# AuthGravity > Hosted passkey (WebAuthn) authentication + relationship-based authorization. Zero-knowledge: the server stores only public keys and a UUID per user — no passwords, no usernames, no email. Your app owns all profile data. ## Start in 60 seconds (local dev — no domain, no DNS) 1. Run the local auth proxy next to your dev server and leave it running: ``` npx @authgravity/cli listen # ✔ Minted sandbox # ▶ Listening on http://localhost:8787 ``` 2. Point your app at it: `PUBLIC_AUTH_ENDPOINT=http://localhost:8787` The CLI mints an ephemeral, isolated sandbox (rpID=localhost) and converts its session into a first-party httpOnly `session_id` cookie on localhost — so the exact same auth code runs in dev and production. Sandbox passkeys are throwaway; promote to a real domain for production (see the end of this file). **Every host publishes its own `/llms.txt`** with its live authz schema and pre-filled endpoint. When integrating a specific app, read *that* host's file — it is the single source for that integration. ## Auth (passkeys) Build the sign-in UI in your app, with `@authgravity/browser` or the raw API below. The UI is two buttons — **"Create Account"** (`register()`) and **"Login"** (`login()`) — in your app's own look, with no redirect out of the app. No username field, no email field, no forms. The passkey label defaults to "Me"; if you offer a custom label keep it client-side (`opts.user.name` before `startRegistration`) — it is never sent to the server. ```typescript // src/lib/auth.ts — identical code in dev and production import { startRegistration, startAuthentication } from '@simplewebauthn/browser'; const ENDPOINT = import.meta.env.PUBLIC_AUTH_ENDPOINT; async function api(path: string, init: RequestInit = {}) { return fetch(ENDPOINT + path, { ...init, credentials: 'include' }); } export async function register() { const opts = await (await api('/v1/register/options')).json(); // PublicKeyCredentialCreationOptionsJSON const cred = await startRegistration({ optionsJSON: opts }); const res = await api('/v1/register/verify', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(cred), // bare RegistrationResponseJSON — no wrapper }); return res.json(); // { verified, user: { id }, last_used } — session_id cookie is now set } export async function login() { const opts = await (await api('/v1/login/options')).json(); // PublicKeyCredentialRequestOptionsJSON const cred = await startAuthentication({ optionsJSON: opts }); const res = await api('/v1/login/verify', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(cred), // bare AuthenticationResponseJSON — no wrapper }); return res.json(); // { verified, user: { id }, last_used } — session_id cookie is now set } // Which button to mark "Last used": the server sets a JS-readable // ag_last_used cookie ("login.webauthn", "register.key", ...) on your domain // after every ceremony. lastUsed() from @authgravity/browser does the same. export function lastUsed(): { action: 'login' | 'register'; method: 'webauthn' | 'device' | 'key' } | null { const m = document.cookie.match(/(?:^|; )ag_last_used=([^;]*)/); const [action, method] = m ? decodeURIComponent(m[1]).split('.') : []; return action === 'login' || action === 'register' ? ({ action, method } as any) : null; } export async function whoami() { const res = await api('/v1/whoami'); return res.ok ? res.json() : null; // { user_id } or null } export async function logout() { await api('/v1/logout', { method: 'POST' }); } ``` HTTP API (spec-shaped WebAuthn JSON — any conforming client library works; always `credentials: 'include'`): - `GET /v1/register/options` → `PublicKeyCredentialCreationOptionsJSON`, unmodified - `POST /v1/register/verify` bare `RegistrationResponseJSON` → `{verified, user:{id}, last_used}`; sets `session_id` cookie - `GET /v1/login/options` → `PublicKeyCredentialRequestOptionsJSON`, unmodified - `POST /v1/login/verify` bare `AuthenticationResponseJSON` → `{verified, user:{id}, last_used}`; sets `session_id` cookie - `GET /v1/whoami` → `{user_id}` or 401. Accepts the cookie or `Authorization: Bearer ` - `POST /v1/logout` → destroys the session, clears the cookie The server keys the pending ceremony by the challenge (inside the signed `clientDataJSON`), so there is no correlation id to carry. ### Multiple passkeys per account An account holds up to 10 credentials. Run the SAME registration ceremony while signed in and the new passkey is ADDED to the session's account instead of creating a new one (`register()` above, with the cookie or Bearer present). The options then carry `excludeCredentials` for the passkeys the account already has, so an authenticator that already holds one refuses with `InvalidStateError` in the browser — never a silent overwrite; if a response for a known credential still reaches the server it answers 409. Any authenticator is accepted (platform passkeys, phones, hardware security keys), so "add a backup passkey" is a one-button feature. - `GET /v1/register/options?label=` — optional owner label (≤64 chars) for the new passkey; otherwise the list shows the provider name derived from the authenticator AAGUID (iCloud Keychain, Google Password Manager, 1Password, YubiKey, …) - `POST /v1/register/verify` → also `credential: {id}` (the row id used by DELETE below); when adding to a signed-in user there is no `last_used` (not a sign-up) - `GET /v1/credentials` → `{amr, credentials: [{id, kind: "webauthn"|"devicekey"|"softkey", label, provider, display, backed_up, transports, created_at, last_used_at, current}]}` — `display` is what to show (label, else provider, else "Passkey"); `current` marks the credential that minted this session - `DELETE /v1/credentials/:id` → `{deleted: true}`; 409 on the last credential (never orphan an account), 403 when the session is weaker than the target (a session from a recovery key cannot remove a passkey — sign in with a passkey first) Zero-UI option: send signed-in users to `/account?return_to=` — a hosted page (like `/login`) that lists credentials, adds a passkey with an optional name, removes one, and offers the 12-word recovery key. In your own UI use `listCredentials(endpoint)` / `removeCredential(endpoint, id)` from `@authgravity/browser`, and this for the add button: ```typescript // Add a passkey to the signed-in account (same ceremony as register(), plus a label). export async function addPasskey(label?: string) { const q = label ? '?label=' + encodeURIComponent(label) : ''; const opts = await (await api('/v1/register/options' + q)).json(); let cred; try { cred = await startRegistration({ optionsJSON: opts }); } catch (e: any) { if (e?.name === 'InvalidStateError') throw new Error('This device already has a passkey for this account'); throw e; } const res = await api('/v1/register/verify', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(cred), }); if (res.status === 409) throw new Error('This device already has a passkey for this account'); return res.json(); // { verified, user: { id }, credential: { id } } } ``` **"Last used" hint.** Every successful ceremony also sets a JS-readable, one-year `ag_last_used` cookie on your domain (not httpOnly, unlike `session_id`) whose value is `.`: action `login` | `register` (only a ceremony that CREATED the account counts as `register`; adding a passkey or recovery key to a signed-in user leaves it alone), method `webauthn` | `device` | `key` | `otp` (the session `amr` vocabulary). Read it on page load and put a small "Last used" pill on the matching button — returning users then see it on **Login**, first-time users see nothing. `lastUsed()` in `@authgravity/browser` parses it (falls back to `localStorage`, which the SDK fills from the `last_used` verify field when the cookie cannot reach your origin, e.g. a sandbox used without `authgravity listen`; the proxy mirrors the cookie onto localhost). Logout keeps the cookie on purpose. It carries no identity — no user id, no credential id. ## Account keys (no-passkey fallback + recovery) For users without passkey support — and as the recovery path for everyone — a client-generated 128-bit secret rendered as `agak1_…` (base32 + checksum) or 12 BIP39 words, from which the client derives a P-256 key pair per tenant. The server stores only the public key, exactly like a passkey. Daily logins should use a silent **device key** (non-extractable WebCrypto key in IndexedDB, registered as an extra credential) so the account key is only typed at setup and recovery. Endpoints (mirror the WebAuthn pair; same session semantics): - `GET /v1/key/register/options` / `GET /v1/key/login/options` → `{challenge, context, tenant}` (single-use, 5 min) - `POST /v1/key/register/verify` `{challenge, public_key, signature, kind: "softkey"|"devicekey", label?}` → `{verified, user:{id}, credential_id, last_used?}`; with a session the credential is ADDED to that user (then no `last_used`) - `POST /v1/key/login/verify` `{challenge, public_key, signature}` → `{verified, user:{id}, last_used}` - `GET /v1/credentials`, `DELETE /v1/credentials/:id` — list/remove every kind (see "Multiple passkeys per account" above for the shape and guards) - `GET /v1/key/wordlist.json` — BIP39 English wordlist Derivation: `priv = (HKDF-SHA256(entropy, salt=utf8(tenant), info="authgravity/softkey/v1", 40 bytes) mod (n-1)) + 1` on P-256; `public_key` = base64url 65-byte uncompressed point; `signature` = base64url 64-byte r||s of ECDSA-SHA256 over utf8 `${context}\n${challenge}\n${tenant}`. The `@authgravity/browser` SDK implements all of this (`mintKey`/`decodeKey`/`registerAccountKey`/`loginWithAccountKey`/`enableDeviceKey`); the full spec + conformance vectors are at https://authgravity.org/llms.txt. Sessions carry `amr` (`webauthn` | `device` | `key` | `otp`, strongest first) in `/v1/whoami` and authz responses, so apps can require passkey-strength sessions for sensitive actions. Adding a credential while signed in never raises the session: an `otp` session that enrolls a device key stays `otp` until the next sign-in. ## Sign in with a code (app-delivered, for people without passkeys) For people who cannot use a passkey — no phone, no platform authenticator, not comfortable with one — your app delivers a 6-digit code over a channel it already owns (a voice call to a landline, an email) and the person types it once per computer. Your backend owns the phone/email and its mapping to an AuthGravity user id; AuthGravity only provisions users and mints/verifies codes. **Accounts are provisioned, not self-served**: codes are minted only for users your backend created, so a stranger cannot trigger calls to arbitrary numbers through AuthGravity. ```typescript // Browser — your "sign in with a phone call" screen. import { startCodeLogin, verifyCode, enableDeviceKey } from '@authgravity/browser'; const ticket = await startCodeLogin(ENDPOINT); // verifier stays in this tab await fetch('/api/send-code', { method: 'POST', body: JSON.stringify({ ticket, phone }) }); // …person types the code they heard… const r = await verifyCode(ENDPOINT, typed); // session_id cookie, amr "otp" if (r.verified) await enableDeviceKey(ENDPOINT); // this computer signs in silently from now on // Backend — /api/send-code (service token stays server-side). import { authgravity } from '@authgravity/server'; const ag = authgravity({ endpoint: ENDPOINT, serviceToken: process.env.AUTHGRAVITY_SERVICE_TOKEN }); const userId = await db.userIdForPhone(phone); // YOUR mapping; AuthGravity never sees the phone if (userId) { const { code } = await ag.mintCode({ ticket, userId }); await placeVoiceCall(phone, code); // or email, or anything } return ok(); // same response whether or not the number is known ``` - `POST /v1/users` (service token) → `{user_id}` — a user with no credentials yet; store the id against their phone/email - `POST /v1/code/start` (browser) → `{ticket, verifier, expires_at}` — send only `ticket` to your backend - `POST /v1/code/mint` `{ticket, user_id}` (service token) → `{code, expires_at}` — 6 digits, valid 10 minutes; calling again is a resend (new code, max 3 per ticket; 5 codes per user per hour) - `POST /v1/code/verify` `{ticket, verifier, code}` (browser) → `{verified, user:{id}, last_used: "login.otp"}`; sets `session_id` with `amr: "otp"`. 5 wrong codes burn the ticket Service tokens (`agk_…`) are minted by the tenant owner in the dashboard; any of the tenant's tokens may provision users and mint codes. Anonymous sandboxes need no token (open pools). The code is bound to the browser that started the ticket (its `verifier`), so a code overheard or left on voicemail is useless elsewhere. **This is not phishing-resistant** (NIST SP 800-63B out-of-band): a scammer who starts a sign-in with the person's number and then asks them to read the code aloud gets in. So: (1) say it in the message — "Never share this code. We will never call and ask for it."; (2) never leave a code on voicemail (use answering-machine detection); (3) tell a family member or the account holder whenever a code is issued; (4) rate-limit your own send-code endpoint and answer identically for unknown numbers; (5) right after a code sign-in, `enableDeviceKey()` so later sign-ins are silent and codes stay rare; (6) gate sensitive actions with `min_amr` — an `otp` session is the weakest. ## Server-side session validation Forward the incoming cookie header to `/v1/whoami` from any backend (Astro, Express, Hono, …): ```typescript const cookie = request.headers.get("cookie"); const res = await fetch(ENDPOINT + "/v1/whoami", { headers: cookie ? { cookie } : {} }); if (!res.ok) return redirectToLogin(); const { user_id } = await res.json(); ``` ## Authorization (relationship-based access control) Optional Zanzibar/SpiceDB-style permissions for your app's resources, served on the same host and session as auth. Subjects are the AuthGravity user UUIDs from `/v1/whoami`. Each host renders its OWN live schema and API in its `/llms.txt` — read that host's file for the real object types. The shape: - Define object types with relations + computed permissions: `PUT /v1/authz/schema`. - Write relationship tuples keyed by user UUIDs: `POST /v1/authz/relationships` `{updates:[{op,object,relation,subject}]}`. - Check on every gated action: `POST /v1/authz/check` `{object, permission}` — omit the subject to use the session user; returns `{allowed, user_id}`. Batch with `{items:[…]}`. - Open sandboxes: any authenticated user may edit the schema and write. Domains: owner-managed — the schema is set in the dashboard and the app backend writes with a service token (`Authorization: Bearer agk_…`). - Do not cache allow/deny across requests; a console lives at `/authz`. ## Person Server (AAuth) This host is also an **AAuth Person Server** (draft-hardt-oauth-aauth-protocol, aauth.dev): it represents each user to AI agents. An agent with its own cryptographic identity asks this host for authorization; the person approves once (passkey session), and the server issues a short-lived signed `aa-auth+jwt` the agent presents to third-party resources. The person picks their PS — this one comes free with every AuthGravity pool. **Instant PS for agent development:** mint a sandbox (`POST /sandbox` on the product endpoint, or `npx @authgravity/cli listen`) and your agent has a live, public https Person Server at `https://sandbox.authgravity.org/` — no domain, no DNS, ready for real cross-server interop. Discovery: `GET https://authgravity./.well-known/aauth-person.json` → issuer, endpoints, JWKS. All signing is Ed25519. ### Agent flow (token) 1. Agent POSTs `{resource_token, justification?}` to `/v1/aauth/token`, RFC 9421-signed (`Signature-Input`/`Signature` + agent token in `Signature-Key: sig=jwt;jwt="…"`; covered components `"@method" "@authority" "@path" "signature-key"`, plus `"authorization"`/`"aauth-mission"` whenever those headers are sent). 2. First time: `202 Accepted` with `Location: /v1/aauth/pending/` and `AAuth-Requirement: requirement=interaction; url="https://authgravity./consent"; code="XXXXXXXX"`. Show the person the consent URL + code — **delivering that link is always the proposing agent's job**; this server never notifies anyone. 3. The person opens `/consent?code=…`, signs in with their passkey, reviews, approves (optionally "remember"). 4. Agent polls the pending URL → `200 {auth_token, expires_in}`. Remembered approvals skip straight to `200` next time. Auth tokens: `aa-auth+jwt`, Ed25519, ≤ 600s, `cnf`-bound to the agent key, verifiable against this host's JWKS. Identity is a per-pool UUID `sub` — never email, never PII. ### Missions, budgets, governance For multi-step or spending work an agent proposes a **mission** at `/v1/aauth/mission`: `{mission: {description, approved_tools?, resources?, budgets?, approver?, expires_in?}}`. Proposals wait for consent up to 7 days (configurable ≤ 30) — approval is asynchronous and may come from a **different person than the proposer** (set `approver` to the intended user's UUID to bind it; without it, holding the code IS the capability — treat the code as a secret). `budgets` entries (AAuth-Budget extension) carry `{resource, amount, currency, models?}` where `resource` is the resource token's `iss`. At consent the person may only **narrow**: lower an amount, restrict models, or drop an entry — never add or increase. The approved blob is hash-committed (`s256`); tokens minted under a budgeted mission carry the granted entry verbatim in a `budget` claim and **no identity at all** (no `sub`). **A budget is a cap + proof of consent, not payment.** Providers gate spend on a funded claim: the token response passes `funded`/`funding_url` through verbatim; until someone claims the mission at `funding_url`, inference returns `402 mission_unfunded`. Relaying that link to a payer is also the agent's job. Governance endpoints (all agent-signed, mission-bound): `POST /v1/aauth/permission` (`{action, mission, …}` → `{permission: "granted"|"denied"}`, auto-granted when the action is in `approved_tools`), `POST /v1/aauth/audit` (fire-and-forget action log → 201), `POST /v1/aauth/interaction` (`{type: "question"|"completion", …}` — questions reach the person; accepted completions close the mission). `GET /v1/aauth/mission/` returns the approved blob + lifecycle status; spend state lives at the resource's own `budget_endpoint`. Lifecycle errors are distinct so a harness learns promptly: `mission_revoked` | `mission_completed` | `mission_expired`. People manage everything themselves on this host: `GET/DELETE /v1/aauth/grants[/:id]`, `GET /v1/aauth/missions`, `POST /v1/aauth/missions/:id/revoke` (kill-switch). ## Your database AuthGravity gives you a stable UUID and stores nothing else. Key your users table by it, create rows on first sight, collect email/name later (e.g. at checkout): ```sql CREATE TABLE users ( id TEXT PRIMARY KEY, -- the AuthGravity UUID email TEXT, name TEXT, -- collected later, nullable created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ); ``` ## Go to production (your own domain) ``` # 1. Create a claim (no auth needed): curl -X POST https://provision.api.authgravity.org/claims \ -H 'Content-Type: application/json' -d '{"domain":"myapp.com"}' # → { "id":"", "cname_name":"authgravity", "cname_target":"cname.authgravity.net" } # 2. Open in a browser for the human (passkey sign-in + DNS via Domain Connect or CNAME): # https://authgravity.org/signup?claim_id= # 3. Poll until claimed: curl https://provision.api.authgravity.org/claims/ # → "status":"claimed" ``` Then set `PUBLIC_AUTH_ENDPOINT=https://authgravity.myapp.com` and deploy under `myapp.com`. Read `https://authgravity.myapp.com/llms.txt` for that host's live guide. ## Notes - rpID = your registrable domain; passkeys work across all its subdomains. - Each domain is an isolated user pool. Only public key material is stored server-side; never private keys, never PII. - Discovery: `GET /.well-known/authgravity` returns this host's endpoint + `llms.txt` URL as JSON. - Auth on this host is provided by AuthGravity (https://authgravity.org); a small credit near your sign-in UI is appreciated, never required. - Powered by the open source Gratos project (AGPLv3): https://github.com/polvi/gratos