# @kaarel/auth documentation > Framework-agnostic, server-only auth for TypeScript apps: sessions, passwords, Google and GitHub in one config file. You keep your own pages. No client SDK, no runtime dependencies. --- # Introduction `@kaarel/auth` is server-only auth for TypeScript apps. It runs inside your app, on any framework, and stores its data in your Postgres database. - **No UI.** Your app keeps its own login, sign-up and settings pages. The package gives you functions and error codes. - **No client SDK.** You call the package from server code: server functions, loaders, API routes. - **No runtime dependencies.** It uses only what Bun and Node have built in: `node:crypto`, `fetch` and argon2id. - **One file of config.** Methods, access rules, e-mails and pages are in one `createAuth()` call. - **Any framework.** The core works on a web `Request`. TanStack Start and Next.js have adapters; Hono, Bun.serve, SvelteKit, React Router and the others use `auth.withRequest(request)`. ## What you get | Part | Contents | | --- | --- | | Core | Cookie sessions, Google, GitHub, e-mail and password, e-mail verification, password reset, access rules, rate limits, account settings | | `twoFactor` | TOTP codes (any authenticator app) and recovery codes | | `workspaces` | Workspaces, members, roles, invites by e-mail | | `tokens` | API tokens for scripts, CLIs and MCP clients | ## How it works 1. Your page posts a form to your own server code: a server function, a server action, or a POST route. 2. That code calls `auth.password.signIn(data)`. 3. The package checks the password, sets an `HttpOnly` session cookie, and returns `{ ok: true }` or `{ ok: false, error: "invalid_credentials" }`. 4. Your page shows the error in its own words and its own look. Google and GitHub use redirects, so the package serves a few routes under `/auth/*`: the start of the login, the callback, the e-mail links and sign-out. These routes only redirect. They never render a page. ## Requirements - Bun 1.2+ or Node 24.7+. Both have argon2id built in. - PostgreSQL 13+. - Any framework that gives you a web `Request`. TanStack Start and Next.js (15+) have adapters. ## Design choices - **Sessions live on the server.** The cookie holds a random token. The database holds only its SHA-256 hash. Sign-out and "sign out everywhere" work at once. - **Results, not exceptions.** Functions that change something return `{ ok, error }`. `error` is a typed union, so your editor lists every case. - **Each app has its own users.** There is no central auth server. Each app has its own Google project, so the Google screen shows the app's own name. --- # Getting started The package works with any framework that gives you a web `Request`. Steps 1–3 are the same everywhere. Step 4 connects your framework. ## 1. Install ```sh bun add @kaarel/auth ``` ## 2. Add the env vars ```sh AUTH_SECRET= # bunx kaarel-auth secret BASE_URL=http://localhost:3000 DATABASE_URL=postgres://localhost/myapp GOOGLE_CLIENT_ID= GOOGLE_CLIENT_SECRET= RESEND_API_KEY= ``` ## 3. Create the config Put it in a server-only module. The name and folder are up to you: `src/auth.ts`, `lib/auth.ts`, `server/auth.ts`. ```ts import { createAuth, google, password, resend } from "@kaarel/auth"; export const auth = createAuth({ url: process.env.BASE_URL!, secret: process.env.AUTH_SECRET!, db: process.env.DATABASE_URL!, // Bun. On Node: db: pg(pool) appName: "Leads", methods: [ password(), google(process.env.GOOGLE_CLIENT_ID, process.env.GOOGLE_CLIENT_SECRET), ], email: { from: "Leads ", send: resend(process.env.RESEND_API_KEY) }, pages: { signIn: "/login", afterSignIn: "/app" }, // framework: tanstackStart() or nextjs(), see step 4 }); ``` The tables go into a Postgres schema called `auth`. The package creates them on first use. Every path in `pages` and the `/auth` mount path (`basePath`) is yours to choose. ## 4. Connect your framework Each framework needs three things: the `/auth/*` routes, a place to call the API (a POST handler), and a guard for signed-in pages. ### TanStack Start ```ts // in createAuth: framework: tanstackStart() (import from "@kaarel/auth/tanstack") // routes/auth.$.ts — the /auth/* routes export const Route = createFileRoute("/auth/$")({ server: { handlers: auth.routes } }); // TanStack Start 1.131: export const ServerRoute = createServerFileRoute("/auth/$").methods(auth.routes); // a server function — POST for every change export const signIn = createServerFn({ method: "POST" }) .validator((data: { email: string; password: string; next?: string }) => data) .handler(({ data }) => auth.password.signIn(data)); export const currentUser = createServerFn().handler(() => auth.user()); // guard: in the layout route of signed-in pages beforeLoad: async ({ location }) => { const user = await currentUser(); if (!user) throw redirect({ to: "/login", search: { next: location.href } }); return { user }; }, ``` Never name a file `src/server.ts`: TanStack Start uses that name for its server entry. ### Next.js (App Router) ```ts // in createAuth: framework: nextjs() (import from "@kaarel/auth/next") // app/auth/[...auth]/route.ts — the /auth/* routes export const GET = auth.handler; export const POST = auth.handler; // app/actions.ts — server actions for every change "use server"; export async function signIn(email: string, password: string, next?: string) { return auth.password.signIn({ email, password, next }); } // guard: in a server component of a signed-in page const user = await auth.requireUser({ next: "/app" }); ``` Server components only read (`auth.user()`, `auth.session()`, `requireUser`). Sign-in, sign-up and settings go in server actions, because only actions and route handlers can set cookies. ### Hono ```ts // no framework option: Hono gives a web Request app.all("/auth/*", (c) => auth.handler(c.req.raw)); app.post("/api/sign-in", async (c) => { const api = auth.withRequest(c.req.raw); const result = await api.password.signIn(await c.req.json()); return c.json(result, { headers: api.headers }); // headers carry the session cookie }); // guard app.use("/app/*", async (c, next) => { if (!(await auth.withRequest(c.req.raw).user())) return c.redirect(`/login?next=${encodeURIComponent(c.req.path)}`); await next(); }); ``` ### Any other framework Bun.serve, SvelteKit, React Router, Astro, Elysia and others all give a web `Request`: 1. Send every request under `/auth/*` to `auth.handler(request)` and return its `Response`. 2. In a POST handler, call `auth.withRequest(request)`, use its API, and copy `api.headers` (the `Set-Cookie` lines) onto your response. 3. Guard pages with `await auth.withRequest(request).user()`. See [Frameworks](https://auth.kaarel.dev/docs/frameworks.md) for more, and how to write an adapter. ## 5. Build the login page The page is yours. It posts e-mail and password to your POST handler from step 4 and shows the result: ```tsx import type { AuthError } from "@kaarel/auth/errors"; const text: Partial> = { invalid_credentials: "Wrong e-mail or password.", email_not_verified: "Confirm your e-mail. We sent a new link.", rate_limited: "Too many attempts. Try again later.", oauth_denied: "Google sign-in was cancelled.", }; // after the call: if (result.ok) location.assign(result.redirectTo); // "/app", or the two-factor page else showError(text[result.error] ?? "Something went wrong."); ``` - The Google button is a plain link: `Continue with Google`. - Redirect flows send errors back as `?error=`, so read `error` from the query string too. - A verification link opened in another browser lands on `/login?verified=1`: show "E-mail confirmed, sign in". - Sign-out is a form: `
`. - Pages import from `@kaarel/auth/errors` only. `@kaarel/auth` is server code. ## 6. Check the setup ```sh bunx --bun kaarel-auth doctor ``` It finds the config file, checks the secret, the URL and the database, and prints the exact Google redirect URI to paste into the Google Cloud console: `https:///auth/google/callback`. --- # Install with AI The docs are written so a coding agent can follow them. Open the **[install builder](https://auth.kaarel.dev/install)**, tick what you need, and copy the prompt or download it as `install.md`: - your framework: TanStack Start, Next.js, Hono, or any framework with a web `Request`; - your database driver; - sign-in methods, access rules and modules; - extras: a settings page, dev login, tests. Give the prompt to Claude Code, Cursor or any agent that can read URLs and edit files. A builder link keeps your choices in the URL, so you can share a setup. ## What the agent reads | File | Contents | | --- | --- | | [`/llms.txt`](https://auth.kaarel.dev/llms.txt) | A short index of the docs with links | | [`/llms-full.txt`](https://auth.kaarel.dev/llms-full.txt) | Every docs page in one plain-text file | | `node_modules/@kaarel/auth/AGENTS.md` | The API reference and the rules, shipped with the package | Every docs page also has a Markdown version: add `.md` to its URL. --- # Configuration ```ts const auth = createAuth({ url, secret, db, methods, // required appName, framework, access, email, pages, schema, basePath, session, cookie, trustedOrigins, ip, rateLimit, migrate, devLogin, onUserCreated, twoFactor, workspaces, tokens, // modules }); ``` ## Required | Option | Type | Notes | | --- | --- | --- | | `url` | `string` | The app's public URL. Cookies are `Secure` and `__Host-` when it is https. | | `secret` | `string` | At least 32 characters. Encrypts the OAuth flow cookie and TOTP secrets. `bunx kaarel-auth secret` makes one. | | `db` | `string \| Db` | A Postgres URL (Bun only), or an adapter. See [Database](https://auth.kaarel.dev/docs/database.md). | | `methods` | `Method[]` | Any of `password()`, `google()`, `github()`. | ## Methods ```ts password({ verifyEmail: true, minLength: 10, legacyVerify }) google(clientId, clientSecret, { scopes, prompt }) // prompt default "select_account" github(clientId, clientSecret, { scopes }) ``` - `verifyEmail` (default `true`): users must open the link in the verification e-mail before they can sign in with a password. With it off, nobody proves they own the e-mail: do not combine it with a domain allowlist. `doctor` warns about this. - `legacyVerify(hash, password)`: checks hashes from an old system. A match signs in and replaces the hash with argon2id. See [Migrating](https://auth.kaarel.dev/docs/migrating.md). - A Google or GitHub method with an empty client ID or secret is off. Its routes redirect with `error=method_disabled`. `doctor` warns about it. ## Access ```ts access: "open" // default: anyone can sign up access: "closed" // nobody signs up; create users with auth.users.create() access: allowlist(process.env.ADMIN_EMAILS) // "me@x.dev, @team.dev" access: async (email) => isEmployee(email) // your own rule ``` A function or allowlist applies to sign-up and to every sign-in. A user that the rule no longer allows gets `access_denied`. ## Pages The package links and redirects to your pages. It never renders them. | Page | Default | Used for | | --- | --- | --- | | `signIn` | `/login` | `requireUser()` redirects here with `?next=` | | `afterSignIn` | `/` | After sign-in, when there is no `next` | | `afterSignOut` | `/` | After `POST /auth/sign-out` | | `error` | `signIn` | Redirect flows send errors here as `?error=` | | `verified` | `afterSignIn` | After the user opens a verification link | | `resetPassword` | `/reset-password` | The reset e-mail links here with `?token=` | | `twoFactor` | `/login/two-factor` | The code form, when the user has 2FA on | | `acceptInvite` | `/invite` | The invite e-mail links here with `?token=` | ## Other options | Option | Default | Notes | | --- | --- | --- | | `appName` | the URL's host name | Shown in e-mails and the authenticator app | | `framework` | none | `tanstackStart()` or `nextjs()`. Without it, use `auth.withRequest(request)`. See [Frameworks](https://auth.kaarel.dev/docs/frameworks.md). | | `email` | console outside production | `{ from, send, templates }`. See [E-mails](https://auth.kaarel.dev/docs/emails.md). | | `schema` | `"auth"` | Postgres schema for the tables | | `basePath` | `"/auth"` | Where you mount `auth.routes` | | `session.days` | `30` | Sessions used in their second half get a new full period | | `cookie.name` | `"auth"` | Cookie names become `__Host-auth_session` etc. | | `trustedOrigins` | `[]` | Extra origins allowed to call sign-in and other changes | | `ip` | last `x-forwarded-for`, then `x-real-ip`, then the socket address from the adapter | Client IP for rate limits. Per-IP limits are skipped when no IP is known. Set it when your proxy chain is longer than one hop (for example Cloudflare in front of Caddy). | | `rateLimit` | `true` | Turn off only in tests | | `migrate` | `"auto"` | `"manual"` to run `kaarel-auth migrate` yourself | | `devLogin` | none | An e-mail. `/auth/dev` signs in as it, only outside production on `localhost`, `*.localhost` or `*.test`. | | `onUserCreated` | none | `(user, tx) => Promise`. Runs in the same transaction as the user insert. Throw to cancel the sign-up. | ## Modules ```ts twoFactor: true, // or { issuer: "Acme" } workspaces: { roles: ["owner", "admin", "member"] }, // highest first; the first is the owner tokens: true, // or { prefix: "acme" } → tokens look like acme_… ``` `auth.twoFactor`, `auth.workspaces` and `auth.tokens` exist only when their module is on. TypeScript knows this from the config. --- # E-mail and password Turn it on with `password()` in `methods`. Passwords are hashed with argon2id (19 MiB, 2 passes), the OWASP minimum. ## Sign up ```ts const result = await auth.password.signUp({ email, password, name }); ``` | Result | Meaning | | --- | --- | | `{ ok: true, next: "verify_email" }` | Show "Check your inbox". The e-mail has a link to `/auth/verify`. | | `{ ok: true, next: "signed_in" }` | Only with `verifyEmail: false`. The session cookie is set. | | `{ ok: false, error }` | `invalid_email`, `weak_password`, `password_too_long`, `email_taken`, `signup_closed`, `rate_limited`, `forbidden_origin` | With `verifyEmail` on, sign-up with an e-mail that already has an account also returns `verify_email`. The owner gets a "you already have an account" e-mail. So nobody can use the sign-up form to test which e-mails have accounts. `email_taken` comes only with `verifyEmail: false`. The verification link works once and for 24 hours. Opened in the browser that signed up, it signs the user in and redirects to `pages.verified`. Opened anywhere else (another device, a forwarded e-mail), it only verifies the e-mail and redirects to `pages.signIn?verified=1`; show "E-mail confirmed, sign in" there. ## Sign in ```ts const result = await auth.password.signIn({ email, password, next: "/app/deals" }); if (result.ok) navigate({ href: result.redirectTo }); ``` | Result | Meaning | | --- | --- | | `{ ok: true, next: "signed_in", redirectTo }` | Signed in. `redirectTo` is `next` when it is a path on this site, else `pages.afterSignIn`. | | `{ ok: true, next: "two_factor", redirectTo }` | The user has 2FA on. `redirectTo` is `pages.twoFactor`. See [Two-factor](https://auth.kaarel.dev/docs/two-factor.md). | | `{ ok: false, error }` | `invalid_credentials`, `email_not_verified`, `access_denied`, `rate_limited`, `forbidden_origin` | - A wrong password and an unknown e-mail both give `invalid_credentials`. Both take the same time. - `email_not_verified` comes only after the right password. It also sends a new link (at most 3 per hour). - Limits: 10 failed attempts per e-mail and 50 attempts per IP in 15 minutes. The right password still works while someone guesses, until the 10th failure. ## Password reset Two pages in your app: "forgot password" and "new password". ```ts // Forgot password page await auth.password.requestReset({ email }); // always { ok: true } // New password page, at pages.resetPassword?token=… const result = await auth.password.reset({ token, password }); ``` - `requestReset` always answers `{ ok: true }`, so it does not show which e-mails have accounts. - Each link works once and for 1 hour. A new request does not cancel older links, so a stranger cannot cancel the owner's link. At most 3 reset e-mails per hour go to one address. - `reset` errors: `invalid_token`, `link_expired`, `weak_password`, `password_too_long`. - A reset signs out every session, deletes every API token and cancels pending e-mail changes. Send the user to the login page after it. - A reset also marks the e-mail as verified, because the link reached that inbox. ## Resend the verification e-mail ```ts await auth.password.resendVerification({ email }); // always { ok: true } ``` ## Users without a password A user who signed up with Google has no password. They can set one with [`auth.account.changePassword({ next })`](https://auth.kaarel.dev/docs/account.md) or with a password reset. --- # Google and GitHub ```ts methods: [ google(process.env.GOOGLE_CLIENT_ID, process.env.GOOGLE_CLIENT_SECRET), github(process.env.GITHUB_CLIENT_ID, process.env.GITHUB_CLIENT_SECRET), ] ``` A login button is a plain link: ```tsx Continue with Google Continue with GitHub ``` The flow: 1. `/auth/google` stores the flow state in an encrypted cookie and redirects to Google. 2. Google redirects back to `/auth/google/callback`. 3. The package checks the answer, finds or creates the user, sets the session cookie and redirects to `next`. 4. On an error it redirects to `pages.error?error=`. ## Set up Google 1. Open [Google Cloud console → Google Auth Platform](https://console.cloud.google.com/auth/overview). Make one project per app, so the consent screen shows that app's name and logo. 2. Under **Branding**, set the app name, logo and support e-mail. 3. Under **Clients**, create a **Web application** client. 4. Add the redirect URI that `bunx kaarel-auth doctor` prints: `https:///auth/google/callback`. For local development also add `http://localhost:3000/auth/google/callback`. 5. Under **Audience**, publish the app ("In production"). In "Testing", only the listed test users can sign in. 6. Put the client ID and secret in `GOOGLE_CLIENT_ID` and `GOOGLE_CLIENT_SECRET`. ## Set up GitHub 1. Open **GitHub → Settings → Developer settings → OAuth Apps → New OAuth App**. 2. Set **Authorization callback URL** to `https:///auth/github/callback`. 3. Create a client secret. Put both values in `GITHUB_CLIENT_ID` and `GITHUB_CLIENT_SECRET`. ## Which user signs in | Case | Result | | --- | --- | | The Google/GitHub account is already linked | That user signs in. | | A user has the same e-mail, verified | The account is linked to that user, who signs in. | | A user has the same e-mail, never verified | The provider proves who owns the e-mail. Everything that gives access to that user is removed: password, sessions, API tokens, other linked accounts, 2FA. Then the account is linked. This stops someone who signed up with another person's e-mail. | | No user has the e-mail | A new user is created, if `access` allows sign-up. | | The provider says the e-mail is not verified | `oauth_email_unverified`. GitHub uses only the primary e-mail. | Errors from the callback: `oauth_denied` (the user cancelled), `oauth_failed`, `oauth_email_unverified`, `signup_closed`, `access_denied`, `method_disabled`, `rate_limited`. ## Link an account to the signed-in user On the settings page: ```tsx Connect Google ``` After the link, the user returns to `next`, and gets an e-mail that a provider was connected. On a problem they return to `next?error=`: - `account_linked_elsewhere`: that Google account belongs to another user. - `reauth_required`: the session is older than 15 minutes. Ask for the password with `auth.account.reauthenticate({ password })`, or have the user sign in again, then retry. - `email_not_verified`: the user's own e-mail is not verified yet. ```ts const { hasPassword, accounts } = await auth.account.linked(); await auth.account.unlink({ provider: "google" }); // error last_sign_in_method if it is the only way in ``` ## What the package checks - `state` (CSRF), PKCE with S256, and for Google a `nonce`. - The flow cookie is encrypted with AES-256-GCM and works for 10 minutes, in the browser that started the login. - The Google ID token comes straight from Google's token endpoint over TLS, with the client secret. OIDC Core 3.1.3.7 allows TLS server validation in place of the signature check in this case. The package still checks `iss`, `aud`, `exp`, `nonce` and `email_verified`. --- # Sessions ## Read the user ```ts const user = await auth.user(); // User | null const current = await auth.session(); // { user, session, scopes? } | null const signedIn = await auth.requireUser(); // redirects to pages.signIn?next= when signed out await auth.requireUser({ next: "/app" }); // give next yourself where the framework cannot tell the page ``` ```ts type User = { id: string; email: string; emailVerified: boolean; name: string | null; image: string | null; hasPassword: boolean; createdAt: Date; }; type Session = { id: string; userId: string; method: "password" | "google" | "github" | "email_link" | "dev" | "token"; workspaceId: string | null; ip: string | null; userAgent: string | null; createdAt: Date; lastSeenAt: Date; expiresAt: Date; }; ``` The package reads the session once per request, so several calls cost one query. ## Sign out ```tsx
``` The route redirects to `pages.afterSignOut`. Send `Accept: application/json` to get `204` instead. From a POST server function: `await auth.signOut()`. ## Devices These need a browser session; API tokens get `forbidden`. ```ts const sessions = await auth.sessions.list(); // each has `current: boolean` await auth.sessions.revoke({ id }); await auth.sessions.revokeOthers(); // "sign out everywhere else" ``` ## The cookie - Name `__Host-auth_session` on https, `auth_session` on http. - `HttpOnly`, `Secure` (https), `SameSite=Lax`, `Path=/`, no `Domain`. - The value is 32 random bytes. The database stores its SHA-256 hash, so a database leak gives no usable sessions. - 30 days by default (`session.days`). A session used in its second half gets a full new period. ## Cross-site requests Functions that change something (sign-in, sign-up, settings, …) answer `forbidden_origin` when: - the request is a GET or HEAD (SameSite=Lax cookies still go with cross-site links, so changes must be POST); - its `Origin` is not `url` or one of `trustedOrigins`; - it has `Sec-Fetch-Site: cross-site`. POST requests without an `Origin` header (server to server) pass. --- # Account settings Build the settings page in your app. Call these from server functions. ```ts await auth.account.reauthenticate({ password }); await auth.account.changePassword({ current, next }); await auth.account.changeEmail({ email, password }); await auth.account.linked(); // { hasPassword, accounts: [{ provider, email, createdAt }] } await auth.account.unlink({ provider: "github" }); await auth.account.delete({ password }); ``` | Function | Notes | Errors | | --- | --- | --- | | `reauthenticate` | Checks the password and opens a new 15-minute window for sensitive changes. | `invalid_credentials`, `reauth_required` (the user has no password: sign in again) | | `changePassword` | `current` is needed when the user has a password. A Google-only user sets a first password without it, but needs a recent sign-in. Signs out the other sessions, cancels pending e-mail changes, and e-mails a notice. | `invalid_credentials`, `reauth_required`, `weak_password`, `password_too_long`, `rate_limited` | | `changeEmail` | Needs a recent sign-in or `password`. Sends a link to the new address. The e-mail changes when that link is opened in a browser signed in as this user; then the old address gets a notice. | `email_taken`, `invalid_email`, `invalid_credentials`, `reauth_required`, `rate_limited` | | `unlink` | Needs a recent sign-in or `password`. Refuses to remove the last way to sign in. | `last_sign_in_method`, `reauth_required` | | `delete` | Needs a recent sign-in or `password`. Deletes the user and their data in the `auth` schema. Workspaces where they are the only member go too. | `invalid_credentials`, `reauth_required`, `transfer_ownership_first` | ## Recent sign-in Some changes add a new way into the account, or remove the owner's. A stolen session cookie must not be enough for them, so they need a sign-in in the last 15 minutes: - `changeEmail`, `unlink`, `delete`, and `changePassword` without `current`; - linking Google or GitHub, `tokens.create`, `twoFactor.setup`. Each of these also takes an optional `password`. A right password counts as a fresh sign-in. On `reauth_required`, ask for the password and call `reauthenticate` (or pass `password` to the same call). A user without a password signs in again with their provider. All of them return `not_signed_in` without a session, and `forbidden` for a request with an API token. ## Your own user data Keep app data in your own tables and point to `auth.users(id)`: ```sql create table profiles ( user_id uuid primary key references auth.users(id) on delete cascade, plan text not null default 'free' ); ``` To create rows when a user signs up, use `onUserCreated`. It runs in the same transaction: ```ts onUserCreated: async (user, tx) => { await tx.query("insert into profiles (user_id) values ($1)", [user.id]); }, ``` ## Admin and scripts `auth.users` needs no request: ```ts const owner = await auth.users.create({ email: "me@example.com", password: "…" }); await auth.users.byEmail("me@example.com"); await auth.users.get(id); await auth.users.setPassword(id, "…"); // also ends their sessions, API tokens and pending e-mail changes await auth.users.delete(id); ``` --- # E-mails ```ts import { resend } from "@kaarel/auth"; email: { from: "Leads ", send: resend(process.env.RESEND_API_KEY), templates: { /* optional overrides */ }, } ``` - `send(message)` gets `{ from, to, subject, html, text }`. Write your own for any provider. - `resend(apiKey)` calls the Resend HTTP API with `fetch`. - Without `email`, e-mails print to the console outside production. In production, a missing `email` is an error when the package needs to send one. - E-mails go out in the background, after the function has answered. So the answer time does not show whether an account exists. Send errors are logged with `console.error`. In tests, `await auth.settled()` waits for them. ## When the package sends e-mails | Template | Sent when | Link | | --- | --- | --- | | `verifyEmail` | Sign-up, and sign-in before verification | `/auth/verify?token=` (24 hours) | | `accountExists` | Sign-up with an e-mail that has an account | `pages.signIn` | | `resetPassword` | `requestReset` | `pages.resetPassword?token=` (1 hour) | | `passwordChanged` | `changePassword` | none | | `changeEmail` | `changeEmail`, to the new address | `/auth/verify?token=` (24 hours) | | `emailChanged` | The new address was confirmed, to the old address | none | | `accountLinked` | Google or GitHub was linked to the user | none | | `tokenCreated` | An API token was created | none | | `invite` | `workspaces.invite` | `pages.acceptInvite?token=` (7 days) | ## Your own templates Each template gets data and returns `{ subject, html, text }`: ```ts templates: { resetPassword: ({ appName, url, email, name }) => ({ subject: `Uus parool – ${appName}`, html: `

Tere${name ? `, ${name}` : ""}!

Vali uus parool

`, text: `Vali uus parool: ${url}`, }), }, ``` | Template | Data | | --- | --- | | all | `appName`, `url`, `email`, `name` | | `emailChanged` | also `newEmail` | | `passwordChanged` | no `url` | | `accountLinked` | also `provider` ("Google", "GitHub"); no `url` | | `tokenCreated` | also `tokenName`; no `url` | | `invite` | also `workspace`, `invitedBy`, `role` | Escape values you put into HTML. The default templates do. Keep user-written text (workspace names, user names) out of the subject line: the default invite subject has only the app name. --- # Errors Functions that change something never throw for expected problems. They return: ```ts { ok: true, ...data } | { ok: false, error: AuthError } ``` Functions that only read (`user()`, `sessions.list()`, `workspaces.members()`, …) return data. Without a session they throw `AuthException` with `code: "not_signed_in"`. Mistakes in the config throw `AuthConfigError`. Redirect flows (Google, GitHub, e-mail links) send the code to `pages.error` as `?error=`. ## Show them in your app's words ```ts import type { AuthError } from "@kaarel/auth/errors"; const text: Record = { /* … your app's language … */ }; ``` Import from `@kaarel/auth/errors` in pages. It has no server code. `@kaarel/auth` itself pulls `node:crypto` into the browser bundle and breaks the page. A full `Record` makes TypeScript list every missing code. English defaults are in `messages.en`: ```ts import { messages } from "@kaarel/auth/errors"; messages.en.invalid_credentials; // "Wrong e-mail or password." ``` A thrown `AuthException` that crosses a server function boundary arrives in the browser as a plain `Error`. Its `message` is the code, for example `"forbidden"`. ## All codes | Code | When | | --- | --- | | `invalid_input` | A field has the wrong type or format | | `invalid_email` | The e-mail is not valid | | `weak_password` | Shorter than `minLength` (default 10) | | `password_too_long` | Longer than 256 characters | | `invalid_credentials` | Wrong e-mail or password, or a wrong current password | | `email_not_verified` | Sign-in before the e-mail is verified (a new link was sent), or linking or inviting by an unverified user | | `email_taken` | Sign-up without verification, or an e-mail change, to a used e-mail | | `signup_closed` | `access` does not allow sign-up for this e-mail | | `access_denied` | `access` does not allow this user to sign in | | `rate_limited` | Too many attempts | | `forbidden_origin` | The request came from another site | | `not_signed_in` | The function needs a session | | `reauth_required` | A sensitive change needs a sign-in in the last 15 minutes, or the password | | `invalid_token` | The link or token is not valid, or was used | | `link_expired` | The link is too old | | `oauth_failed` | The provider login failed (wrong state, bad answer) | | `oauth_denied` | The user cancelled at the provider | | `oauth_email_unverified` | The provider has no verified e-mail for the user | | `account_linked_elsewhere` | That provider account belongs to another user | | `last_sign_in_method` | Unlinking would leave no way to sign in | | `method_disabled` | The method or module is not on | | `invalid_code` | Wrong two-factor or recovery code | | `two_factor_not_enabled` | 2FA is off for this user | | `two_factor_already_enabled` | 2FA is already on | | `challenge_expired` | The two-factor step timed out or had too many wrong codes | | `not_found` | The workspace, member or token does not exist for this user | | `forbidden` | The role is too low, or an API token tried an account change | | `already_member` | The invited e-mail is already a member | | `invite_email_mismatch` | The invite is for another e-mail | | `owner_cannot_leave` | The owner must transfer ownership first | | `transfer_ownership_first` | Account deletion while owning a shared workspace | --- # Two-factor ```ts createAuth({ /* … */ twoFactor: { issuer: "Leads" } }); // or twoFactor: true ``` Codes are TOTP (RFC 6238): 6 digits, 30 seconds, SHA-1. They work with Google Authenticator, 1Password, Authy and the others. The secret is stored encrypted with AES-256-GCM. ## Turn it on (settings page) ```ts const started = await auth.twoFactor.setup(); // { ok: true, secret: "JBSW…", uri: "otpauth://totp/Leads:me@x.dev?…" } ``` `setup` needs a recent sign-in or `{ password }` (see [Account settings](https://auth.kaarel.dev/docs/account.md)). Show `uri` as a QR code (your app draws it) and `secret` for manual entry. Then ask for a code: ```ts const result = await auth.twoFactor.enable({ code }); // { ok: true, recoveryCodes: ["ABCDE-FGHIJ", …10] } | { ok: false, error: "invalid_code" } ``` Show the recovery codes once and ask the user to save them. `enable` signs out the user's other sessions. ## Sign in with a code When a user with 2FA on signs in, `password.signIn` returns `{ ok: true, next: "two_factor", redirectTo: pages.twoFactor }`. Google and GitHub redirect to `pages.twoFactor` too. No session exists yet; a short `challenge` cookie (10 minutes) remembers the first step. On your code page: ```ts const result = await auth.twoFactor.verify({ code }); if (result.ok) navigate({ href: result.redirectTo }); // errors: invalid_code, challenge_expired ``` - The code can be a TOTP code or a recovery code. - Each TOTP code and each recovery code works once. - After 5 wrong codes the challenge ends with `challenge_expired`. The user signs in again. - Across all challenges, a user gets at most 10 code attempts in 15 minutes and 30 a day (`rate_limited`), so new sign-ins do not give an attacker more guesses. ## Manage it ```ts await auth.twoFactor.status(); // { enabled, recoveryCodesLeft } await auth.twoFactor.regenerateRecoveryCodes({ code }); // new codes; the old ones stop working await auth.twoFactor.disable({ code }); ``` `disable` and `regenerateRecoveryCodes` need a current code or a recovery code. --- # Workspaces ```ts createAuth({ /* … */ workspaces: { roles: ["owner", "admin", "member"] }, pages: { acceptInvite: "/invite" }, }); ``` - `roles` go from highest to lowest. The first role is the owner. Each workspace has one owner. - The second role (here `admin`) and up may invite, rename and manage members. Change it with `manage: "member"`. - `auth.workspaces` is typed with your roles, so `role: "admni"` is a type error. ## The active workspace Each session has an active workspace. A new session opens in the user's first workspace. ```ts const current = await auth.workspaces.current(); // { workspace, role } | null const all = await auth.workspaces.list(); // [{ workspace, role }] await auth.workspaces.switch({ workspaceId }); ``` ## Protect a route or a server function ```ts const { user, workspace, role } = await auth.workspaces.requireMember({ role: "admin" }); ``` - Signed out: redirects to `pages.signIn` with a framework adapter. Without one it throws `AuthException("not_signed_in")`. - Not a member, or below `role`: throws `AuthException` with `forbidden` (or `not_found` for a given `workspaceId`). - Leave out `role` to allow any member. Store your app data with a `workspace_id` that points to `auth.workspaces(id)`, and filter by `workspace.id`. With an API token, `requireMember`, `current`, `list`, `members` and `invites` work, but only in the token's workspace when it has one. Every change (create, invite, roles, delete, …) needs a browser session. The package does not check token scopes: check `session().scopes` yourself. ## Create, rename, delete ```ts const created = await auth.workspaces.create({ name: "Acme" }); // the creator is the owner; the session switches to it await auth.workspaces.rename({ name: "Acme Ltd" }); await auth.workspaces.delete(); // owner only ``` Every function acts on the active workspace. Pass `workspaceId` to act on another one. ## Members ```ts await auth.workspaces.members(); // [{ user, role, joinedAt }], highest role first await auth.workspaces.setRole({ userId, role: "admin" }); await auth.workspaces.removeMember({ userId }); await auth.workspaces.leave(); // owner_cannot_leave for the owner await auth.workspaces.transferOwnership({ userId }); // the old owner gets the second role ``` Nobody can give a role above their own, change the owner's role, or remove the owner. ## Invites ```ts await auth.workspaces.invite({ email: "ann@example.com", role: "member" }); await auth.workspaces.invites(); // pending invites await auth.workspaces.revokeInvite({ email }); ``` The e-mail links to `pages.acceptInvite?token=…`, valid for 7 days. A new invite to the same e-mail replaces the old one. Only users with a verified e-mail can invite. A user can send 50 invites an hour, and a workspace 100 a day. On your invite page: ```ts // Works signed out: show what the invite is for. const info = await auth.workspaces.inviteInfo({ token }); // { ok: true, email: string, role: string, workspace: string, invitedBy: string | null } // | { ok: false, error: "link_expired" } // After the user signs in or signs up with that e-mail: const result = await auth.workspaces.acceptInvite({ token }); // { ok: true, workspace: { id, name, createdAt }, role } | errors: invalid_token, link_expired, invite_email_mismatch ``` The signed-in user's verified e-mail must match the invite. A new user can sign up with Google, or with a password and the verification link, and then accept. --- # API tokens ```ts createAuth({ /* … */ tokens: { prefix: "leads" } }); // tokens look like leads_… ``` ## Create and manage (settings page) ```ts const created = await auth.tokens.create({ name: "CLI", scopes: ["deals:read"], expiresInDays: 90 }); // { ok: true, token: "leads_…", apiToken: { id, name, prefix, scopes, … } } ``` Show `token` once. Only its SHA-256 hash is stored. Creating a token needs a recent sign-in or `{ password }`, and e-mails the user a notice. ```ts await auth.tokens.list(); // never includes the token itself await auth.tokens.revoke({ id }); ``` Options: `scopes` (strings you define), `expiresInDays` (1–3650, default never), `workspaceId` (ties the token to one workspace). ## Use a token Clients send `Authorization: Bearer leads_…`. `auth.user()` and `auth.session()` accept it like a cookie: ```ts // src/routes/api/deals.ts GET: async ({ request }) => { const current = await auth.withRequest(request).session(); if (!current) return new Response("Unauthorized", { status: 401 }); if (!current.scopes?.includes("deals:read")) return new Response("Forbidden", { status: 403 }); return Response.json(await listDeals(current.user.id)); }, ``` - `session.method` is `"token"`, and `scopes` holds the token's scopes. - `session.workspaceId` is the token's workspace, or null. - A token can read: `user()`, `session()`, and the workspace reads (`requireMember`, `current`, `list`, `members`, `invites`), only in its own workspace when it has one. - A token cannot change anything through the package: account, sessions, 2FA, tokens and every workspace change return `forbidden`. Your own API routes decide what a token may do in your app. - The package does not check `scopes`. Check them in your routes. - A password reset and `auth.users.setPassword` delete all of the user's tokens. ## MCP servers An MCP server over HTTP can use the same check: read the bearer token, and answer 401 when `session()` is null. OAuth 2.1 for MCP clients is planned as a separate module. --- # Frameworks The core of the package works on a web `Request` and gives back a `Response` or cookie headers. Nothing in it depends on a framework. There are two ways to call it: | Way | Use it with | Calls look like | | --- | --- | --- | | An adapter (`framework` option) | TanStack Start, Next.js | `auth.user()`, `auth.password.signIn(data)` | | `auth.withRequest(request)` | Hono, Bun.serve, SvelteKit, React Router, Astro, Elysia, … | `auth.withRequest(request).user()` | Both give the same API, types and errors. The package does not guess the framework: you choose the adapter, or none. In every framework, mount `auth.handler` (or `auth.routes`) on `/*`, default `/auth/*`. Those routes handle the Google and GitHub redirects, e-mail links, sign-out and dev login. ## TanStack Start ```ts import { tanstackStart } from "@kaarel/auth/tanstack"; createAuth({ /* … */ framework: tanstackStart() }); ``` The adapter reads the request and sets cookies through TanStack Start. It works with 1.131+ (`getWebRequest`) and 1.160+ (`getRequest`). ```ts // TanStack Start 1.160+ export const Route = createFileRoute("/auth/$")({ server: { handlers: auth.routes } }); // TanStack Start 1.131 export const ServerRoute = createServerFileRoute("/auth/$").methods(auth.routes); ``` - Call auth functions only on the server: in server functions and server routes. - In `beforeLoad`, call a server function that calls `auth.user()`. `beforeLoad` also runs in the browser. - `requireUser()` and `workspaces.requireMember()` throw a TanStack `redirect` when signed out. Inside a server function, `next` comes from the page (the `Referer`), not from the server function URL. - Make every server function that changes something `method: "POST"`. The package refuses changes over GET. ## Next.js (App Router) ```ts import { nextjs } from "@kaarel/auth/next"; createAuth({ /* … */ framework: nextjs() }); ``` ```ts // app/auth/[...auth]/route.ts export const GET = auth.handler; export const POST = auth.handler; ``` The adapter builds the request from `headers()` and sets cookies with `cookies()`. It needs Next.js 15 or newer. - **Server actions** change things: sign-in, sign-up, reset, settings. They are POST requests, so the package accepts them. - **Server components** only read: `auth.user()`, `auth.session()`, `auth.requireUser({ next: "/app" })`. A server component cannot see its own path, so pass `next` yourself. A server component also cannot set cookies; a session refresh then waits for the next action or route handler. - **Route handlers** can use the adapter too, or `auth.withRequest(request)`. - `requireUser()` throws Next's `redirect` when signed out. ## Any other framework Use `auth.withRequest(request)`. It binds the API to one request. Cookies collect in `headers`; copy them to your response. ```ts async function signIn(request: Request) { const api = auth.withRequest(request); const result = await api.password.signIn(await request.json()); return Response.json(result, { headers: api.headers }); } ``` ```ts // Bun.serve Bun.serve({ fetch(request) { if (new URL(request.url).pathname.startsWith("/auth/")) return auth.handler(request); // … }, }); // Hono app.all("/auth/*", (c) => auth.handler(c.req.raw)); // SvelteKit: src/routes/auth/[...path]/+server.ts export const GET = ({ request }) => auth.handler(request); export const POST = ({ request }) => auth.handler(request); // React Router / Remix: app/routes/auth.$.ts export const loader = ({ request }) => auth.handler(request); export const action = ({ request }) => auth.handler(request); ``` Without an adapter, `requireUser()` throws `AuthException("not_signed_in")` instead of redirecting. Catch it and redirect the way your framework does. ## Rules for every framework - Changes over GET are refused (`forbidden_origin`). Use POST handlers, actions or server functions for them. - Browser code imports only `@kaarel/auth/errors` (types and messages). `@kaarel/auth` is server code. - The paths are yours: the config file can live anywhere, `pages` holds your page paths, and `basePath` moves `/auth/*`. ## Write an adapter An adapter has three functions and one optional one: ```ts import type { FrameworkAdapter } from "@kaarel/auth"; const adapter: FrameworkAdapter = { getRequest: () => currentRequest(), // may be async; return the same object within one request setCookie: (name, value, options) => setResponseCookie(name, value, options), // may be async redirect: (to) => { throw frameworkRedirect(to); }, getIP: () => socketAddress(), // optional: used when no proxy header gives the client IP }; ``` --- # Database The package needs PostgreSQL 13 or newer. It has no ORM and no driver of its own. It uses yours. | Driver | Config | | --- | --- | | Bun (built in) | `db: process.env.DATABASE_URL` or `db: bunSql(Bun.sql)` | | node-postgres | `db: pg(pool)` | | postgres.js | `db: postgresJs(sql)` | | Drizzle | `db: pg(drizzle.$client)` or `postgresJs(drizzle.$client)` | | Prisma | Use the URL on Bun, or a `pg` pool with the same URL | Any other driver works through the `Db` interface: ```ts interface Db { query(sql: string, params?: unknown[]): Promise; // $1, $2, … placeholders transaction(fn: (tx: Db) => Promise): Promise; } ``` ## Tables All tables are in the `auth` schema (change it with `schema`): | Table | Contents | | --- | --- | | `users` | id (uuid), email, email_verified_at, name, image, password_hash | | `accounts` | Google/GitHub accounts linked to users | | `sessions` | SHA-256 of the token, user, method, active workspace, IP, user agent, expiry | | `email_tokens` | Hashes of verification, reset and e-mail change links | | `challenges` | Two-factor sign-in steps | | `rate_limits` | Counters, keyed by a hash | | `two_factor`, `recovery_codes` | Encrypted TOTP secrets, hashed recovery codes | | `workspaces`, `members`, `invites` | Workspaces module | | `api_tokens` | Hashes of API tokens | Point your tables at `auth.users(id)` and `auth.workspaces(id)` with `on delete cascade`. ## Migrations With `migrate: "auto"` (the default), the package applies its migrations on first use. A Postgres advisory lock makes this safe when several app instances start at once. With `migrate: "manual"`, run them in your deploy step: ```sh bunx kaarel-auth migrate # loads src/auth.ts bunx kaarel-auth migrate server/auth.ts ``` or from code: `await auth.migrate()`. The package never changes your own tables, and migrations only add to the `auth` schema. --- # Testing and dev login ## In tests ```ts import { signInAs } from "@kaarel/auth/testing"; import { auth } from "~/auth"; test("the deals page needs a session", async () => { const { user, cookie, request } = await signInAs(auth, "ann@example.com"); const response = await app.fetch(request("/app/deals")); expect(response.status).toBe(200); }); ``` - `signInAs` creates the user when the e-mail is new, and a session for it. - `request(path, init)` returns a `Request` with the session cookie, and a same-origin `Origin` header for non-GET requests. - `cookie` is the `Cookie` header value, for other HTTP clients. Use `rateLimit: false` in tests that sign in many times. Use a separate `schema` per test file to keep tests apart. E-mails go out in the background: `await auth.settled()` before you read them. ## Local development ```ts devLogin: process.env.DEV_LOGIN, // e.g. "me@example.com" ``` Open `http://localhost:3000/auth/dev?next=/admin` to sign in as that e-mail. It creates the user when needed. Use it when Google login cannot work locally, for example on a review proxy. Dev login works only when all of these hold: - `NODE_ENV` is not `production`; - the `url` host is `localhost`, `127.0.0.1`, `*.localhost` or `*.test`. In every other case `/auth/dev` answers 404. `doctor` warns while it is on. --- # Security | Threat | Protection | | --- | --- | | Stolen database | Sessions, API tokens and e-mail links are stored as SHA-256 hashes. Recovery codes are an HMAC with a key from `secret`, so the short codes cannot be brute-forced from a dump alone. Passwords use argon2id. TOTP secrets are encrypted with AES-256-GCM. | | XSS reading the session | The cookie is `HttpOnly`. | | Cookie set by a subdomain | On https the cookie is `__Host-`: bound to this host, `Secure`, `Path=/`, no `Domain`. | | CSRF | `SameSite=Lax`, plus an `Origin` check (and `Sec-Fetch-Site`) on every function that changes something and on sign-out. Changes over GET are refused. | | OAuth CSRF and code theft | `state`, PKCE (S256) and a Google `nonce`, kept in an encrypted cookie that works for 10 minutes. | | Open redirects | `next` must be a path on this site. `//host`, `https://app//host`, `\`, control characters and other origins fall back to the default page. | | Account pre-registration | A Google/GitHub login with a verified e-mail takes over an unverified account with that e-mail, and removes everything that gave access to it: password, sessions, tokens, linked accounts, 2FA. Unverified users cannot link providers. A verification link signs in only the browser that signed up. | | Stolen session cookie | Adding a way back in (linking a provider, an API token, an e-mail change, a first password, a new authenticator) needs a sign-in in the last 15 minutes or the password. Linking and new tokens e-mail the user. An e-mail change applies only when opened while signed in as the user. A password reset ends sessions, tokens and pending e-mail changes. | | User enumeration | Same answer and timing for wrong passwords and unknown e-mails. Reset and resend always answer ok. With verification on, sign-up answers the same for new and used e-mails. E-mails go out in the background, so their sending time does not show in the answer. | | Brute force | Rate limits per e-mail and per IP, stored in Postgres so they hold across instances. 5 tries per two-factor step, and 10 per user in 15 minutes across steps. | | Lockout | Only failed sign-ins count per e-mail, so the owner can sign in while someone guesses. New reset requests do not cancel older links. | | Replayed codes and links | Each TOTP code, recovery code and e-mail link works once. A new verification or e-mail change link makes the older one stop working. | | Leaked API token | Tokens only read through the package, and only in their own workspace when they have one. They cannot change the account, sessions, 2FA, tokens or workspaces. They can expire and be revoked. | | Dev login in production | Off when `NODE_ENV=production` and on any public host name. | ## Rate limits | Action | Limit | | --- | --- | | Sign-in | 10 failures per e-mail and 50 per IP in 15 min | | Sign-up | 10 per IP per hour | | Reset and verification e-mails | 3 per e-mail per hour | | OAuth callbacks | 30 per IP in 5 min | | Password confirmation in settings | 10 per user in 15 min | | Two-factor settings | 10 per user in 15 min | | Two-factor codes at sign-in | 5 per step; 10 per user in 15 min; 30 per user a day | | Invites | 50 per user per hour; 100 per workspace a day | The client IP comes from the last `x-forwarded-for` entry (the one your nearest proxy added), then `x-real-ip`, then the socket address from the adapter. When no IP is known, per-IP limits are skipped rather than shared by everyone, and the package logs a warning once in production. Set `ip` when your proxy chain has more than one hop, or when your proxy passes client headers through unchanged. ## Cryptography Only built-in primitives: `node:crypto` (randomBytes, SHA-256, HMAC, HKDF, AES-GCM, timingSafeEqual) and argon2id from Bun or Node. Each purpose gets its own key, derived from `secret` with HKDF. ## What you do - Keep `secret` secret and long (`bunx kaarel-auth secret`). Changing it ends running OAuth flows and makes saved TOTP secrets unreadable. - Serve the app over https. - Set `trustedOrigins` only for origins you control. --- # Migrating ## Users and passwords Copy users into `auth.users`. Keep the old password hashes and check them with `legacyVerify`. Each user's hash becomes argon2id at their next sign-in. ```ts import { timingSafeEqual, scryptSync } from "node:crypto"; password({ legacyVerify: (hash, password) => { // Example: "scrypt$$" const [, salt, hex] = hash.split("$"); const key = scryptSync(password, salt!, 64); return timingSafeEqual(key, Buffer.from(hex!, "hex")); }, }); ``` Argon2id hashes in the standard `$argon2id$…` format (for example from `Bun.password`) verify without `legacyVerify`. better-auth's default scrypt hashes (`:`) and bcrypt hashes need a `legacyVerify` that checks that format. `auth.users.id` is a uuid. When your old ids are not uuids (better-auth ids are not), let Postgres make new ones and keep the mapping: ```sql create table old_user_ids (old_id text primary key, user_id uuid not null references auth.users(id)); with inserted as ( insert into auth.users (email, email_verified_at, name, image, password_hash, created_at) select lower(u.email), case when u.email_verified then u.created_at end, u.name, u.image, a.password, u.created_at from old_users u left join old_accounts a on a.user_id = u.id and a.provider_id = 'credential' returning id, email ) insert into old_user_ids (old_id, user_id) select u.id, i.id from inserted i join old_users u on lower(u.email) = i.email; ``` Then update your own tables to point at the new ids. ## Google and GitHub accounts ```sql insert into auth.accounts (provider, provider_user_id, user_id, email) select a.provider_id, a.account_id, m.user_id, null from old_accounts a join old_user_ids m on m.old_id = a.user_id where a.provider_id in ('google', 'github'); ``` If you skip this, users still sign in: a provider login with a verified e-mail links to the user with that e-mail. ## Sessions Old sessions do not carry over. Users sign in once after the switch. ## From better-auth | better-auth | @kaarel/auth | | --- | --- | | `authClient.signIn.email()` in the browser | your server function calls `auth.password.signIn()` | | `authClient.signIn.social({ provider })` | a link to `/auth/google` | | `auth.api.getSession({ headers })` | `auth.user()` / `auth.session()` | | `tanstackStartCookies()` plugin | `framework: tanstackStart()` | | schema CLI | the package's own migrations | | organization plugin | `workspaces` | | twoFactor plugin | `twoFactor` | | apiKey plugin | `tokens` |