# tensile-auth: the full recipe
> The agent skill for tensile.tools/auth at v0.4.1, word for word. Start at https://auth.tensile.tools/llms.txt.
# tensile-auth
Passkey and email and password sign-in for a Go web app in one call. The library owns every sign-in route, the browser client, and the drop-in elements; you wire three things: the service, the routes, and a page. Don't write your own sign-in, sign-up, or session handlers: `authroutes.Mount` already has them, each with its security rule.
For an app in another language, see [Not a Go app? Run the server and use the SDK](#not-a-go-app-run-the-server-and-use-the-sdk).
## Recipe: working sign-in
1. Add the module:
```sh
go get tensile.tools/auth@latest
```
2. Build the server. This is the whole Go side; change only the origin, the RP name, and where your own routes go:
```go
import (
"context"
"crypto/rand"
"encoding/hex"
"errors"
"log/slog"
"os"
auth "tensile.tools/auth"
"tensile.tools/auth/authhttp"
"tensile.tools/auth/authroutes"
"tensile.tools/auth/memstore"
"tensile.tools/auth/passkey"
"tensile.tools/auth/password"
"tensile.tools/auth/ratelimit"
)
// The exact origin the browser uses. Use localhost, not 127.0.0.1:
// a passkey's RPID must be a domain, and passkey.New refuses an IP.
const origin = "http://localhost:8080"
// newServer builds the server. ctx must live as long as the server:
// svc.Run seals the audit log until it ends.
func newServer(ctx context.Context) (http.Handler, error) {
store := memstore.New() // pgstore.New(db) in production, after pgstore.Migrate(ctx, db)
limiter, err := ratelimit.New(ratelimit.NewMemory(), ratelimit.DefaultRules())
if err != nil {
return nil, err
}
// The logger also gets every 500 that authhttp writes.
// 32 random bytes kept for the life of the audit log, for example
// from `openssl rand -hex 32`. The password package needs it. Keep it
// in your secret store, outside the repository; a new key breaks
// the link between old and new audit events for every address.
auditKey, err := hex.DecodeString(os.Getenv("AUTH_AUDIT_KEY"))
if err != nil {
return nil, err
}
svc, err := auth.New(store, auth.WithLimiter(limiter), auth.WithAuditKey(auditKey), auth.WithLogger(slog.Default()))
if err != nil {
return nil, err
}
go svc.Run(ctx) // seals the audit log and writes failure summaries once a minute
pk, err := passkey.New(svc, store, passkey.Config{RPID: "localhost", RPName: "My app", Origins: []string{origin}})
if err != nil {
return nil, err
}
pw, err := password.New(svc, store, password.Config{
Mailer: password.MailerFunc(sendMail),
// Called on email sign-up, with the confirmed address.
// Passkey sign-up calls authroutes.Config.NewUser instead.
NewUser: func(context.Context, password.NewUser) (auth.UserID, error) {
// Create the row in your users table and store this ID in it:
// every session names the user by it.
return auth.UserID("usr_" + rand.Text()), nil
},
})
if err != nil {
return nil, err
}
mux := authhttp.NewMux(svc, authhttp.WithClientIP(), authhttp.WithOrigins(origin))
authroutes.Mount(mux, authroutes.Config{Passkeys: pk, Passwords: pw})
// Your routes: every one declares authhttp.Public or authhttp.Need(...).
mux.HandleFunc("GET /{$}", authhttp.Public, servePage)
if err := mux.Check(); err != nil {
return nil, err // the message names each problem and its fix
}
return mux, nil
}
// sendMail queues m with your email provider and returns at once. Show
// m.Code.Reveal(), the typed code, in large type, with m.CodePurpose()
// and password.NeverShare beside it, say how long it works with
// m.ValidFor(), and add the link m.Link.Reveal() (set
// password.Config.Links). Never log either. A notice, such as
// MessageAccountExists when someone signs up with a taken address,
// has no code, and CodePurpose() is empty: write a short message for
// each m.Kind instead.
func sendMail(ctx context.Context, m password.Message) error {
return errors.New("sendMail: connect your email provider")
}
```
Email and password sign-in is on unless you set `authroutes.Config{PasskeyOnly: true}` instead of `Passwords`; `Mount` panics unless exactly one is set. `RPID` is the host name without a port: `localhost` locally, `app.example.com` in production. `origin` includes the scheme and port.
There are two sign-up hooks, one for each way to sign up. `password.Config.NewUser` runs when someone confirms an email sign-up, and gets the address. `authroutes.Config.NewUser` runs when someone signs up with a passkey, and gets only the name they typed; its default makes a random ID. If your users table needs an email address, set `methods: 'password'` on the elements in step 3, so nobody signs up with a passkey alone. People can add a passkey after they sign in.
The typed code in a sign-up or reset email works only in the browser that started the flow, which holds a binding cookie. To test sign-up with `curl`, keep cookies between requests with `-c` and `-b`, or use the link code, which works anywhere.
Keep `go svc.Run(ctx)`: until it seals an audit event, a change to that event is undetectable, and `svc.VerifyAudit` covers only sealed events. `svc.UnsealedAudit` counts the rest. `auth.WithLogger` also configures `authhttp`'s logging; pass `authhttp.WithLogger` to `NewMux` only to log `authhttp` somewhere else. An error from `auth.New`, `passkey.New`, `password.New`, or `mux.Check` is a setup error: its message names the field and the fix, so return or log it as it is, and never pass it to `auth.Describe`.
3. Add the page. Use the elements instead of a hand-written page: the Go server serves them with the client, so there is no build step:
```html
```
For the account page and approvals, see [Use the drop-in elements instead of hand-written pages](#use-the-drop-in-elements-instead-of-hand-written-pages).
`GET /auth/me` answers the signed-in session as JSON, or 401.
4. Verify, in this order:
1. `go vet ./...` passes.
2. Starting the server doesn't fail in `mux.Check()`.
3. `curl -s -o /dev/null -w '%{http_code}' http://localhost:8080/auth/client/elements/index.js` prints `200`.
4. `curl -s -X POST http://localhost:8080/auth/passkey/sign-in/begin` prints JSON with `publicKey`.
`examples/quickstart` is the same server with `PasskeyOnly: true`, as a running app.
## Not a Go app? Run the server and use the SDK
For a Node, Bun, or Deno app, run `tensile-auth-server`, the library as one binary, and use `@tensile-tools/auth`. The app proxies `/auth/` to the server, so sessions stay in `__Host-` cookies on the app's own origin, and checks each request with the server in one call, `POST /v1/check`. With Next.js 16 and the App Router:
```ts
// lib/auth.ts
import { tensile } from '@tensile-tools/auth/next'
export const auth = tensile({ url: process.env.TENSILE_AUTH_URL!, appKey: process.env.TENSILE_AUTH_APP_KEY!, signIn: '/sign-in' })
// app/auth/[...path]/route.ts
import { auth } from '@/lib/auth'
export const { GET, POST } = auth.proxy
// app/settings/page.tsx (imports auth the same way)
export default async function Settings() {
const p = await auth.require({ action: 'settings.view', human: true })
return Signed in as {p.user}
}
```
Follow `docs/guide-node.md` step by step: it starts the server with `migrate`, `app-key create`, and `serve`, adds `auth.gate` in `proxy.ts`, and covers step-up, agents, and approvals. `tensile-auth-server dev` serves no `/v1/` API, so the SDK can't use it. Express and Hono use `@tensile-tools/auth/express` and `@tensile-tools/auth/hono` with the same server. Operators read `docs/server.md`.
## Protect your routes
Declare what each route needs; the library enforces, records, and explains refusals:
```go
mux.HandleFunc("GET /repos/{id}", authhttp.Need(auth.Need{Human: true}), showRepo)
mux.HandleFunc("DELETE /repos/{id}", authhttp.Need(auth.Need{Assurance: auth.AssuranceMulti, Within: 10 * time.Minute, Human: true}), deleteRepo)
```
In a handler, `p, _ := auth.FromContext(r.Context())` is the caller. Send every library error to the client with `authhttp.Error(w, r, err)`. In the browser, use `auth.fetch(path, init)`: it confirms with a passkey when a route needs a recent check, and retries once.
**An agent's `p.User` is the human it acts for.** Scopes alone let an agent do anything its human can within them. Every route that uses the user's identity for something only the person should do, such as accepting an invitation, creating an account-level resource, or listing everything the person has, must refuse agents: declare it with `authhttp.Need(auth.Need{Human: true})`, or check `p.IsAgent()` in the handler and answer `authhttp.Error(w, r, svc.Require(r.Context(), p, auth.Need{Action: "invite.accept", Human: true}))`.
## Use the drop-in elements instead of hand-written pages
The elements are framework-free Web Components that handle every outcome, focus, and the live region. Import `index.js` once to define them all:
```html
```
- Sign-in: `` and ``.
- Account page: ``, ``, ``, ``, ``, and ``.
- Approvals: `` at the path that `auth.WithApprovalURL` names.
- Before a sensitive action: ``.
Set options with `configure({appName, methods, theme, accent, text})`, a property, or an attribute, and theme them with `--tensile-*` properties and `::part()`. Each element dispatches DOM events, such as `signed-in`, `approved`, and `revoked`. Behind the SDK's proxy, the same path works, because the server serves the client under `/auth/client/`. Every option and event is in `client/src/elements/README.md`.
## Agents asking for approval
To let an agent ask its human for one action, wrap the route with `authhttp.Approvable`. The agent gets 403 `human_required` with `challenge.approval`, which holds `id`, `url`, and `wait_hint`. The agent then:
1. Shows the person `approval.url`.
2. Retries the same request once, with the headers `Tensile-Approval: ` and `Prefer: `, for example `Prefer: wait=60`. The app holds the retry until the person approves or declines, for at most that many seconds, and the route runs once. Without `wait_hint`, the app holds no retry: the agent retries after `Retry-After` while it answers `approval_pending`.
The agent doesn't poll and doesn't ask again: asking again for the same action before the person decides returns the same approval. An agent holds at most 4 waits at once. A Go app holds a retry for up to 60 seconds; behind a proxy with a shorter idle timeout, cap it with `authhttp.WithApprovalWait(25 * time.Second)`. Give your `http.Server` a `WriteTimeout` above the cap, or none, for these routes.
On the server side:
- Set `auth.WithApprovalURL("https://app.example/approve/")`, so the challenge carries an absolute link, and serve `` at that path.
- Pass `authhttp.WithSignInPage("/signin")` to `authhttp.NewMux`, so a person who opens the link signed out signs in and comes back to the approval.
- Add `auth.WithApprovalNotifier(func(ctx context.Context, a auth.Approval, url string) error {…})` to email or message the person. It runs once for each new approval, in its own goroutine, at most 32 at a time, with a 30-second timeout, and never for a repeated request. Treat `a.Action.Summary` as text: it may hold what the agent sent.
- Set `Need.ApprovalTTL`, from 1 minute to 24 hours, for an agent that runs in the background. The default is 5 minutes.
- Approvals work with `auth.WithNeeds`: an agent needs the floor's scopes to ask, and the approving person meets the whole floor. Outside `Approvable`, check the agent with `svc.RequireAgentPart(ctx, p, need)`.
With the SDK, use `auth.approvable(need, describe, handler)`, and set `approvalTtl` on the need. The SDK holds the agent's retry for up to `approvalWait` seconds: 50 by default on a long-running server, and 0 on a detected serverless platform. On Vercel, set `approvalWait: 25` and `export const maxDuration = 30`, and keep `maxDuration >= approvalWait + 5`; a route can pass `{ wait }` instead. `examples/agents` runs the whole loop.
## Agents that sign themselves up
To let an agent arrive with no human and be claimed later, pass `auth.WithSignup(auth.SignupPolicy{Scopes: sandbox})`, then serve three routes: sign-up (`authhttp.Public`, calls `svc.RegisterAgent`, returns the token, a claim link, and `auth.PairingWords(code)`), a claim page for a signed-in person (`svc.PeekClaim`, then `svc.ClaimAgent`), and pickup (`authhttp.Public`, calls `svc.CollectClaimWait`). The agent sends its old token to pickup in the request body, never in `Authorization`: the claim revoked it, so the mux answers `unauthenticated` before your handler runs. See `docs/guide.md`, section 8, and `docs/design/agent-signup.md`.
## Leaving or arriving
To move every person to another install, another store, or another product, or to bring people in from Auth0, Clerk, or Supabase, follow `docs/export.md`. `tensile-auth-server export` writes addresses, password hashes, passkeys, TOTP secrets, recovery codes, identities, and agents to one age-encrypted file, and `tensile-auth-server import`, with `--from auth0`, `--from clerk`, or `--from supabase` for another product's files, signs them in as the same users. A Go app that embeds the library calls `authexport.Export` and `authexport.Import`, or `authexport.ReadAuth0`, `ReadClerk`, or `ReadSupabase` and then `Plan.Import`, instead.
## Add more
- TOTP and recovery codes: pass `TOTP` and `Recovery` to `authroutes.Config`. The client answers `needs_factor`; finish with `auth.verifyTOTP(code)`.
- Email and password pages: `auth.signInWithPassword({email, password})`, `auth.signUpWithPassword({email, password})`, `auth.forgotPassword(email)`, and on the pages your links open, `auth.confirmEmail()` and `auth.resetPassword({password})`. Both read the code from the link's `#code=…` fragment; to pass it yourself, use an object: `auth.confirmEmail({code})`, never `auth.confirmEmail(code)`. Use `` and allow paste. To refuse breached passwords, set `password.Config.Breached` to `pwned.New(pwned.Options{})`.
- Your users table: set both sign-up hooks to create the row and return its ID, and store that ID in the row; `p.User` is that ID. `password.Config.NewUser` runs on email sign-up, and `authroutes.Config.NewUser` on passkey sign-up. Set `Scopes` to give sessions their scopes.
- SQLite: `sqlitestore.Open(ctx, "auth.db")`. It uses the `ncruces/go-sqlite3` driver (`sqlite3`). An app that also uses `modernc.org/sqlite` works, but use `sqlitestore.DSN` only for the store's database.
- Tokens and agents: `svc.CreatePAT`, `svc.CreateAgent`, and `svc.Delegate`. A delegated token gets only scopes that both the parent and `AgentSpec.Scopes` allow. For approvals, see [Agents asking for approval](#agents-asking-for-approval).
- MCP: register the MCP route beside the `authhttp.Mux` on a parent `http.ServeMux` (`protector.Register(root, "/mcp", server, nil)`, then `root.Handle("/", mux)`). Behind the Mux, MCP tokens get 401 unless `authhttp.WithResource(uri)` lists the MCP resource, which also lets them call your routes. MCP clients use the authorization code flow: the device flow refuses `resource` with `invalid_target`.
- Tests: `authtest.Routes(t, mux)` fails if any route serves a caller its declared rule excludes. It can't tell whether a rule is too loose, and it skips `Public` routes, so also test each sensitive route as an agent and as another user, and compare `authtest.PublicRoutes(mux)` with the list you expect.
## Don't
- Don't write handlers for sign-in, sign-up, step-up, or sign-out, or put tokens in `localStorage`: the session is an `HttpOnly` cookie the client never sees.
- Don't hand-write sign-in, sign-up, approval, sessions, or activity pages, in Go or in a Node app: use the elements, which handle every outcome, focus, and the live region.
- Don't register routes on a plain `http.ServeMux`: `authhttp.Mux` makes each route declare its rule and checks the setup at start.
- Don't write your own password hashing, reset links, or email codes: `password` has them. Don't sign anyone in from an email link or an SMS code: a code from an email only confirms an address or resets a password.
- Don't tell people whether an address has an account: sign-up and forgot-password answer the same for every address, and every failed sign-in is the same `factor_rejected`.
- Don't catch `mux.Check()` errors to continue: each one is a real security gap.
- Don't pass setup errors to `auth.Describe` or `authhttp.Error`: they are for request errors.
- Don't treat `p.User` as proof that a person is acting: check `p.IsAgent()`, or need `Human: true`.
- Don't key your user rows by anything but the ID that `NewUser` returns: every session names the user by it.
- Don't skip `go svc.Run(ctx)`: without it, no audit event is sealed, and `svc.VerifyAudit` can't detect a change.
- Don't serve an MCP server behind the `authhttp.Mux`: register it beside the Mux, or MCP tokens get 401.
- Don't check an agent with `svc.Require(ctx, p, auth.AgentPart(need))`: call `svc.RequireAgentPart(ctx, p, need)`, which `authhttp.Approvable` uses.
- Don't let an agent poll an approval or ask again: it retries once with `Tensile-Approval` and the `Prefer` value from `wait_hint`, and polls after `Retry-After` only when there is no `wait_hint`. Don't approve from a notification or a chat message: only the person's passkey on `` grants it.
- In a Node app, don't read or verify the session cookie yourself, and don't put the app key in a `NEXT_PUBLIC_` variable or anywhere the browser sees it: check every request with the SDK. Answer a `TensileError`, which means the server couldn't decide, with 503, never 401.
- Don't write your own migration script, reset everyone's password, or export to plain text when you move people: `export` and `import` keep passwords, passkeys, and second factors, and always encrypt.
Every error code a client can see, with its fix, is in `docs/errors.md`. The full guide is `docs/guide.md`.
## Docs pages, as Markdown
The docs describe v0.4.1-3-ga4e7747, at commit a4e7747.
### Get started
- [Documentation](https://auth.tensile.tools/docs/index.md): Sign-in for people and the agents that act for them: a Go library, or a server with a TypeScript SDK for any other backend.
- [Quickstart for Go](https://auth.tensile.tools/docs/get-started/quickstart-go.md): Add passkey and email and password sign-in to a Go web app with one call, then check it in four steps.
- [Quickstart for Next.js](https://auth.tensile.tools/docs/get-started/quickstart-nextjs.md): Run the tensile-auth server, proxy its routes through a Next.js app, and protect a page with the TypeScript SDK.
- [How it works](https://auth.tensile.tools/docs/get-started/how-it-works.md): People, agents, sessions as a tree, needs, and approvals: the five ideas the rest of the docs build on.
### Guides
- [Service and routes](https://auth.tensile.tools/docs/guides/service-and-routes.md): Create the service, declare a rule for every route, and mount every sign-in route in one call.
- [Passkeys](https://auth.tensile.tools/docs/guides/passkeys.md): Usernameless passkey sign-up and sign-in, with the session cookie set for you.
- [Email, passwords, and presets](https://auth.tensile.tools/docs/guides/email-and-passwords.md): Email and password sign-in held to OWASP ASVS 5.0 Level 2, and the four versioned presets that configure it in one line.
- [Second factors and recovery](https://auth.tensile.tools/docs/guides/second-factors.md): TOTP, pending sign-ins, recovery codes, and undoing a recovery sign-in that the person didn't make.
- [Needs and step-up](https://auth.tensile.tools/docs/guides/needs.md): Declare what an operation needs; the library decides, enforces, records, and explains each refusal.
- [Sessions and devices](https://auth.tensile.tools/docs/guides/sessions.md): A session tree people can read, revocation, and sessions bound to a key in the device's hardware.
- [Tokens and agents](https://auth.tensile.tools/docs/guides/tokens-and-agents.md): Personal access tokens, agents, and delegated tokens that only narrow what the person can do.
- [Approvals](https://auth.tensile.tools/docs/guides/approvals.md): Let an agent ask its person for one risky action, notify the person, and run the route once after they approve.
- [MCP servers](https://auth.tensile.tools/docs/guides/mcp.md): Protect an MCP server with tokens bound to it, connect Claude Code, or verify the JWTs your own sign-in issues.
- [OAuth and the device flow](https://auth.tensile.tools/docs/guides/oauth.md): Run the server as an OAuth 2.0 and OpenID Connect provider, for a CLI that signs in with the device flow or for an MCP client.
- [Browser client](https://auth.tensile.tools/docs/guides/browser-client.md): One entry point with honest outcomes, step-up that retries once, and no session token in the page.
- [Drop-in elements](https://auth.tensile.tools/docs/guides/elements.md): Framework-free Web Components for sign-in, step-up, approvals, sessions, and activity, served with no build step.
### Server
- [Install the server](https://auth.tensile.tools/docs/server/install.md): Run tensile-auth-server from the signed image or the binary, with Postgres or SQLite.
- [Configure](https://auth.tensile.tools/docs/server/configure.md): Every setting, from flags, environment variables, a TOML file, or defaults, and how secrets stay out of process lists.
- [Reverse proxy](https://auth.tensile.tools/docs/server/reverse-proxy.md): The paths, cookies, headers, and timeouts the app's proxy forwards, and how the server finds the client's address.
- [Keys and rotation](https://auth.tensile.tools/docs/server/keys.md): The master key that wraps every stored key, and how to rotate each kind of key without downtime.
- [Hooks and webhooks](https://auth.tensile.tools/docs/server/webhooks.md): Signed hooks that decide sign-ups and scopes before the server acts, and events delivered at least once after it does.
- [Admin](https://auth.tensile.tools/docs/server/admin.md): Invite the first administrator, and keep the admin API to your own networks.
- [Operate the server](https://auth.tensile.tools/docs/server/operate.md): Back up and restore, upgrade with zero downtime, and watch the health endpoints and alerts.
- [Troubleshooting](https://auth.tensile.tools/docs/server/troubleshooting.md): Every startup refusal and run-time symptom, with its cause and fix.
### TypeScript SDK
- [SDK core](https://auth.tensile.tools/docs/sdk/core.md): Check each request with the server in one call, act for a person, and verify webhooks, from Node, Bun, or Deno.
- [Next.js adapter](https://auth.tensile.tools/docs/sdk/nextjs.md): The App Router adapter: a proxy route, `require` in pages and actions, approvable handlers, and `gate` in proxy.ts.
- [Express adapter](https://auth.tensile.tools/docs/sdk/express.md): Express 5 middleware: the proxy, `authenticate`, `need`, and `approvable`.
- [Hono adapter](https://auth.tensile.tools/docs/sdk/hono.md): Hono 4 middleware: the proxy, `authenticate`, `need`, and `approvable`, on Node, Bun, Deno, and Workers.
- [Cache checks](https://auth.tensile.tools/docs/sdk/cache.md): Serve allowed checks from memory for up to 30 seconds, cleared within 100 milliseconds of a revocation.
### Migrate
- [Export and import](https://auth.tensile.tools/docs/migrate/export.md): Move every person to another install in one encrypted file, or leave for another product.
- [Import from another product](https://auth.tensile.tools/docs/migrate/import.md): The rules every importer follows: kept IDs, no matching by address, and a stop at any field it doesn't know.
- [Import from Auth0](https://auth.tensile.tools/docs/migrate/auth0.md): Bring Auth0 users across from the password hash export and the bulk user export.
- [Import from Clerk](https://auth.tensile.tools/docs/migrate/clerk.md): Bring Clerk users across from the dashboard's CSV export.
- [Import from Supabase](https://auth.tensile.tools/docs/migrate/supabase.md): Bring Supabase users across from one COPY statement against your project's database.
- [Export file format](https://auth.tensile.tools/docs/migrate/format.md): The documented JSON Lines format inside every export, and the rules for programs that read it.
### Reference
- [Error catalog](https://auth.tensile.tools/docs/reference/errors.md): Every problem code a client can see, with its HTTP status, its title, and the fix to show the person.
- [HTTP API](https://auth.tensile.tools/docs/reference/api.md): Every route the server serves: the app API, the browser routes, the server's own routes, and the admin API.
- [App API](https://auth.tensile.tools/docs/reference/api/app.md): The routes under /v1/ that the app's backend calls with its app key. The SDK wraps them, for example check is POST /v1/check.
- [Browser routes](https://auth.tensile.tools/docs/reference/api/browser.md): The routes under /auth/ that the browser client and the elements call on the app's origin, through the app's proxy.
- [Server routes](https://auth.tensile.tools/docs/reference/api/server.md): The routes the server adds under /auth/ for agents, tokens, claims, OAuth, and devices.
- [Admin API](https://auth.tensile.tools/docs/reference/api/admin.md): The routes under /admin/v1/ that administrators call, with a second factor, to inspect and revoke users, sessions, and agents.
- [Elements reference](https://auth.tensile.tools/docs/reference/elements.md): Every option, event, custom property, and part of the drop-in elements.
- [OWASP ASVS 5.0](https://auth.tensile.tools/docs/reference/asvs.md): The library's self-assessment against OWASP ASVS 5.0: what it meets, where it deviates and why, and what the application owns.
- [Cryptography](https://auth.tensile.tools/docs/reference/cryptography.md): Every cryptographic algorithm the library, the server, and the packages use, what each protects, and the post-quantum migration plan.
- [Security invariants](https://auth.tensile.tools/docs/reference/invariants.md): The security rules the library holds, each one with the tests that hold it.