Gating a route
import { requireAuth } from "@pithy-sh/auth";
app.get("/notes", requireAuth(), (c) => c.json({ userId: c.var.auth.userId }));That is the whole integration for most applications — protecting a route walks it with the failure cases.
c.var.auth carries the resolved identity — the user id, plus the session and device ids. It is null until a verification strategy sets it, and the middleware turns that null into a 401 before your handler runs, so inside the handler it is not null.
The type narrows with it. A handler chained after requireAuth() on the same route reads c.var.auth as a filled AuthContext, so c.var.auth.userId needs no ?.. A separate app.use(path, requireAuth()) refuses the same requests and narrows nothing. A function that takes the handler’s context types it Context<PithyHonoEnv & SignedInEnv>, and a route that has to hand c to one taking plain Context<PithyHonoEnv> stacks requireAuthUnnarrowed(), the same check with no narrowing. Protecting a route has both.
Test it signed in. signInTestUser from @pithy-sh/auth/src/test-utils/signIn signs a user in inside the Workers test pool with a real session and hands back the bearer headers and the cookie to send. Test your backend has the details.
Every other capability gates the same way, reading the same seam. None of them validates a token.
A route that can do lasting harm can ask for a recent sign-in too. requireRecentSignIn({ maxAgeSeconds, purpose }), from @pithy-sh/auth/src/http/recentSignIn, passes a session signed in within the window the route names and refuses any other with 403 auth/recent_sign_in_required, audited as auth/recent_sign_in_refused with the purpose. A rotation keeps the original sign-in time, so only a fresh sign-in passes. Require a recent sign-in has the rest.
Signing somebody in
await fetch("/auth/sign-in/magic-link", {
method: "POST",
headers: { "content-type": "application/json" },
body: JSON.stringify({ email, callbackURL: "/" }),
});The route enqueues a durable mail job and returns — it does not send inline, so the response comes back in milliseconds whether or not the message has left.
The one-time-code flow is the same shape with a code they type instead of a link they click.
Choosing the email methods
Magic link and the one-time code are both on by default. methods turns either off, and a method that is off is not composed at all: its routes answer 404, its paths leave the OpenAPI document and the MCP tools, and no mail is sent for it. Hiding a form only hides a form.
import { auth } from "@pithy-sh/auth/src/capability";
import { compositionEnvironment } from "@pithy-sh/core/src/env/ambient";
// Apple and Google only, with email in dev so an emulator can sign in before the OAuth clients exist.
const dev = compositionEnvironment() === "dev";
auth({
baseURL: PUBLIC_ORIGIN,
apple: { enabled: true },
google: { enabled: true },
methods: { magicLink: dev, emailOtp: dev },
}),compositionEnvironment() reads the ENVIRONMENT var pithy init stamps into each environment of the Worker’s wrangler.jsonc, and answers undefined where none was stamped, so the branch above leaves email off anywhere it was not told dev.
The screens follow. The client projection carries methods, and the scaffolded web and React Native sign-in screens offer a link where one is composed, a code where only that is, and the provider buttons alone with neither. Each front end’s projection is taken from the config as evaluated for its own environment — @pithy-sh/vite sets ENVIRONMENT to the bundle’s environment while it loads pithy.config.ts, and pithy ui add and pithy ui sync evaluate it once per environment for an Expo app — so a dev-only branch shows the email form in dev alone.
Three consequences of switching email off:
- With neither method, a provider is the only way in, so Better Auth’s refusal to unlink a person’s last provider stands. With either, every account can reach its own address, and unlinking every provider is allowed.
- A Microsoft work or school address Entra ID did not verify is verified by magic link before it links. With
magicLink: falseit cannot link; add thexms_edovclaim. - The remedy for a refused provider sign-in is to sign in by email and connect the provider from the account. Without email, that remedy is gone: set
allowSignUpon the providers you offer.
The session on mobile
Web gets a session cookie automatically, and can stop there.
Mobile reads the raw session token from the sign-in answer’s body, { "token": "…", "user": { … } }, stores it in secure device storage, and sends it on every request:
Authorization: Bearer <session token>Not the JWT. /auth/token and /auth/token/rotate hand back a short-lived JWT access token too, and the kit’s routes do not accept it; it is for a service outside your Worker. A redirect sign-in hands the session to the app through a one-time code it trades at POST /auth/handoff. createBearerSession in @pithy-sh/auth/src/client/bearer does all of this, and sign in on iOS and Android is the walkthrough.
Rotate before the session expires, not on a 401 — by then there is nothing left to trade — and single-flight it. POST /auth/token/rotate spends the token it is shown, and a second rotation of the same one is refused.
A rotation can answer 403, with auth/account_suspended or auth/account_deleted. That is not an expired session, and signing in again cannot help: stop rotating and send the reader to the screen for that state. Suspended and deleted accounts has both codes.
Devices
Opt in per request by sending device metadata headers at sign-in. Only the id is required; every other header is best-effort, and a later sign-in that leaves one out never erases what an earlier one recorded:
| Header | Meaning |
|---|---|
x-pithy-device-id | A client-generated stable id, at most 128 characters. The same physical device maps to one row across re-logins. Required — no id, no registration |
x-pithy-platform | ios, android or web |
x-pithy-device-name | A human label |
x-pithy-device-model | The hardware model |
x-pithy-os-version | The operating system’s version |
x-pithy-app-version | Your app’s version |
x-pithy-push-token | The push token, stored for later routing |
The session binds to the device, and two routes follow: list my devices, and revoke one. Sign me out on that lost phone is a single call.
Generate the stable id once and keep it. It is what makes the device one row rather than a new one per sign-in. createBearerSession sends four of these headers for you — the id, the platform, the name and the model. A client that wants the other three recorded sends them on its own sign-in request.
Letting somebody delete their account
await fetch("/auth/account", {
method: "DELETE",
headers: { "content-type": "application/json", authorization: `Bearer ${sessionToken}` },
body: JSON.stringify({ confirm: true }),
});The App Store and Google Play require it of an app that lets people create an account, so put it behind a button in your settings screen and send confirm: true once the person has confirmed. It is a soft deletion on the configured window, every session ends, and the deletion-scheduled mail tells them how to get the account back before the purge.
A suspended person can still leave. When a sign-in answers auth/account_suspended, offer a delete button: sign in again with the header x-pithy-intent: delete-account, which gives a session that opens this route and nothing else, then call it. Deleting your own account has the rest.
Giving players a public handle
auth({
baseURL: PUBLIC_ORIGIN,
handles: true, // or { minLength, maxLength, cooldownHours }
}),A handle is the name other players see beside a score, one per account, unique across the Worker. It is off by default, and with it off nothing changes: no table, no migration, no route. On, it adds one migration, three routes, and fills core’s c.var.publicIdentity seam, which resolves a batch of user ids to their handles in one call. A capability reads handles through that seam and never through auth: leaderboard returns them beside each entry with include=handle.
GET /auth/handle → { handle, changeableAt }
PUT /auth/handle { handle } → { handle, changeableAt }
POST /auth/handles/lookup { handle } → { handle, held }, or 404 core/not_foundThe rule. 3 to 20 characters unless you configure the range: ASCII letters, digits, _ and -, starting with a letter or a digit. A handle outside the length is auth/handle_length, with params.minLength and params.maxLength, and a character outside the rule is auth/handle_charset. minLength may not exceed maxLength, and neither may exceed 32.
Unique after folding. Case folds, and so do the ASCII look-alikes: 0 reads as o; 1, l and i as one; rn and m as one; vv and w as one, wherever they fall. So Bob and b0b cannot both be held, and a taken one is auth/handle_taken (409). Everyone sees the handle as its owner typed it.
Checked by the text moderator. Every write goes through c.var.moderator as a handle, so a moderation block in your Worker’s config applies to it. reject is auth/handle_rejected, with the moderator’s reason in params.reason. review leaves the handle as it was and answers auth/handle_in_review, so the client asks for another. Moderation has what the default checks.
A cooldown, and a hold. The first set is free. After it, a handle changes at most once per cooldown, 24 hours unless you set cooldownHours, and a change inside it is auth/handle_cooldown (409), with params.changeableAt; GET /auth/handle answers the same time ahead of asking. The handle a change gives up is held for the cooldown: its previous owner can take it back inside the hold at any time, and nobody else can claim it. A take-back undoes the change and nothing more, so the handle it gives up is held for nobody and cannot be taken back in turn. A handle freed by an account’s erasure is held for the same window with no owner.
The lookup is public, and a POST. It folds as uniqueness does. A hit answers the handle as its owner shows it with held: false, or the handle as asked with held: true when it is held and nobody shows it; a miss is 404 core/not_found. It never answers a user id. A handle is something a person typed, and a URL is written to every log between the client and the Worker, so it goes in the body. It is limited to 30 per minute per client address, through its own Workers Rate Limiting binding, ROUTE_RATE_LIMIT_30_PER_60S: run pithy worker sync after turning handles on, or auth’s routes fail with an error naming the missing binding rather than serve the lookup unlimited.
Exported and erased with the account. The account export carries the handle, when it was first set and last changed, and the handles held for the account. The purge erases the handle, holds it for nobody until the cooldown ends, and turns every hold the account had into one with no owner, so no row names the person after it. Suspended and deleted accounts has the rest of the purge.
Once the migration has run, keep handles on. pithy migrate refuses a migration set that no longer names a migration it applied.
Composing more Better Auth plugins
import { organization } from "better-auth/plugins/organization";
auth({
baseURL: PUBLIC_ORIGIN,
plugins: [organization()],
}),The kit’s own are composed first and are fixed: bearer, JWT, and the magic link and one-time code methods leaves on. A config naming one of the four in plugins is refused by name, even one methods switched off.
They are fixed because the rest of the kit depends on them and cannot see your config. Magic link and one-time code are the passwordless email sign-in this product promises, which methods can leave out but never hands to another plugin. JWT mints the key set every Worker verifies against, and it is what the control-plane seam is built on. Bearer is how a mobile client presents its credential.
Removing one is not a preference; it is breaking a contract several packages away. And because plugin endpoints merge by id with the later registration winning, adding one of the four would silently redefine it — which is why a duplicate is refused rather than ignored.
Two plugins sharing an id are refused the same way.
A plugin’s tables are created by migrate
A plugin brings schema. The capability asks the plugin what schema your list implies, subtracts what the fixed four already imply, and contributes one ordinary migration per plugin — with a tested rollback, beside the initial one.
Nothing new was added to the migration model: your plugin list is in the config file migrate already imports.
Three things about the derivation:
A column added to an existing table is nullable, whatever the plugin declares — SQLite refuses otherwise on a table with rows. The plugin writes the value on every insert it makes, so the constraint holds where the plugin enforces it.
Foreign keys are omitted, matching the rest of the kit — the database does not enforce them without a per-connection setting. Linkage is by indexed id columns, and the plugin’s declared indexes are created.
A plugin’s table names are the plugin’s own, not prefixed. They are your tables now. A collision with a table you already own is renamed through the plugin’s own option; a collision with the kit’s is refused at composition time with both names.
Removing a plugin needs the same care as removing a capability
Roll back first, while the plugin is still composed, then take it out of the config.
Otherwise its migration disappears from the set while its row is still in the ledger, and the migrator refuses a chain it cannot account for.
The client half is separate
The client is built from its own plugin list. The server’s type never crosses into a browser bundle — so composing a plugin on the server is half of it, and the matching client plugin goes beside it.
The kit’s own sign-in plugins have client halves too, in the same list. Nothing about the client is inherited from the server.
The one thing that does need the server’s type is the helper that teaches the client about extra user and session fields, and the instance type is parameterized for exactly that.
Composed plugins are reported
pithy doctor prints every composed plugin and the tables it introduced.
A plugin has no package manifest for the capability listing to name it from, and it adds both routes and tables — so it gets a line of its own rather than living only in the source of your config.
The management surface
Thirteen routes for a dashboard’s user panes — named in the reference — each behind its own scope, and every one default-denied: with the control-plane seam not composed they all answer controlplane/not_connected, and no app session opens any of them whatever it carries.
requireAuth() never appears on one — the seam leaves the identity null on purpose, so an auth gate there would deny every legitimate management call forever, and there would be no user to sign in as that could fix it.
Every listing is cursor-paginated, never offset: people sign up while somebody is paging through, and offset would shift rows under them.
Responses are projections, never rows. A session’s token never leaves the Worker — it is the credential. A device’s push token never leaves — it is a capability to reach somebody’s phone. Provider tokens are never even loaded.