# Browser client

> One entry point with honest outcomes, step-up that retries once, and no session token in the page.

From `docs/guide.md`, `client/README.md` in tensile-tools/tensile-auth at commit `e66760d` (v0.4.1-7-ge66760d). The HTML page is https://auth.tensile.tools/docs/guides/browser-client.

```ts
import { createAuthClient } from '@tensile-tools/auth-client'
const auth = createAuthClient()
const r = await auth.enter() // ok | no_passkey_or_cancelled | already_registered | unsupported | throttled | problem
await auth.fetch('/repos/x/secrets', { method: 'PUT', body, stepUpFirst: true })
```

`me()` itself sends `session-lost` when it answers 401, so don't call `me()` from a `session-lost` listener; [`client/README.md`](/docs/guides/browser-client) shows the pattern. Methods that take options take an object, for example `confirmEmail({code})` and `resetPassword({password})`. In development, `auth.WithDevTools()` with `authhttp.DevTools` and the client's `mountDevTools` let you make a session stale or switch to recovery mode in one click.

## Use it

```ts
import { createAuthClient } from '@tensile-tools/auth-client'

const auth = createAuthClient()

const r = await auth.enter()
switch (r.outcome) {
  case 'ok':                      break // signed in
  case 'no_passkey_or_cancelled': showEntryOptions(); break // create one, use a phone, or a recovery code
  case 'throttled':               showWait(r.retryAfter); break
  case 'problem':                 show(r.problem.title, r.problem.fix); break
  case 'unsupported':             showFallback(); break
}
```

- `signIn`, `signUp({name})`, `addPasskey({label})`, and `stepUp({for})` return the same `Outcome`.
- `signInWithPassword({email, password})`, `signUpWithPassword({email, password})`, `forgotPassword(email)`, `stepUpWithPassword(password)`, `changePassword`, `addPassword`, `removePassword`, `changeEmail`, `resendVerification`, and `passwordStatus` call the email and password routes that `authroutes.Mount` serves with `Config.Passwords`. A failed sign-in is always the same `factor_rejected` problem. Use `<input type="password">` and allow paste.
- `confirmEmail()` and `resetPassword({password})` read the code from the link's URL fragment (`#code=…`), which browsers don't send to servers or in `Referer`, remove it from the address bar, and post it once. Build the link that way, for example `https://app.example/confirm#code=…`. Both take an object: to pass a code you already have, call `confirmEmail({code})` or `resetPassword({code, password})`, never `confirmEmail(code)`. When `confirmEmail` answers the `confirm_sign_in` problem, call it again with `{password}`.
- `enter()` is one "Continue" button. It uses immediate mediation where the browser has it, so a person without a passkey goes straight to sign-up with no failed prompt.
- `autofill()` offers passkeys in an input with `autocomplete="username webauthn"`. Any other ceremony cancels it first, which otherwise fails without a word.
- `fetch(path, init)` steps up when a response is a `step_up_required` or `stronger_factor_required` challenge that a passkey can meet, for the challenge's purpose if it has one, and retries once. It throws a `ProblemError` for any other refusal.
- `syncPasskeys()` calls the WebAuthn Signal API, so iCloud Keychain, Google Password Manager, and 1Password stop offering removed passkeys. A rejected sign-in never signals a passkey as unknown, because a rejection can mean an expired ceremony as well as a removed passkey.
- `onSessionChange(fn)` hears sign-in, sign-out, step-up, and a lost session from every tab through `BroadcastChannel`.
- A 401 `unauthenticated` answer to `fetch`, or to an account call that goes through it, such as `me()`, `sessions()`, or `approvals()`, sends `session-lost` to every tab. So a listener that calls `me()` on every event loops while the person is signed out: `me()` answers 401, which sends `session-lost`, which calls `me()` again. Call `me()` only after `signed-in` and `stepped-up`, and treat `signed-out` and `session-lost` as signed out:

  ```ts
  let user: string | undefined
  async function refresh() {
    const r = await auth.me()
    user = r.outcome === 'ok' ? r.data.user : undefined
    render()
  }
  auth.onSessionChange(e => {
    if (e.type === 'signed-out' || e.type === 'session-lost') { user = undefined; render() }
    else void refresh() // signed-in or stepped-up
  })
  void refresh()
  ```
- `capabilities()` reports platform authenticators, phone sign-in, autofill, PRF, and immediate mediation.
- `freshUntil` says until when the session passes step-up checks, from `authhttp.WithFreshHeader`, and `fetch(path, {stepUpFirst: true})` confirms first when it has passed.
- `approvals()`, `approval(id)`, `approve(id)`, and `deny(id)` read and decide the approvals agents ask the person for; `approve` runs a passkey ceremony whose signature covers the exact action. `sessions()`, `revokeSession(id)`, and `signOutOthers()` manage the session tree; each session's `kind` is `device`, `agent`, `token`, `app`, or `other`, which [session kinds](/docs/guides/sessions#session-kinds) maps to the `/v1/` names. Signing out doesn't end an OAuth client's grant; see [OAuth grants](/docs/guides/sessions#oauth-grants). `activity({before})` reads the person's audit events and the chain state. `recoverySignIns()` and `undoRecovery(session)` back "That wasn't me". `totpStatus()` answers whether the authenticator app is on, locked, or not set up, and `removeTOTP()` removes it. `enrollTOTP()`, `confirmTOTP(code)`, `generateRecoveryCodes()`, and `confirmRecoveryCodes(code)` set up two-step codes. Each answers an `Outcome`, and steps up first when the server asks.
- `mountDevTools(client)` shows the session and offers "Make stale" and "Recovery mode" against `authhttp.DevTools`, on a server with `auth.WithDevTools` only.
- `deriveKey(prfOutput, purpose)` turns a passkey's PRF output into a non-extractable AES-GCM key, or `'unsupported'`.

## Server routes

The client calls the routes in `defaultEndpoints`, which `endpoints` overrides. Each begin route answers the WebAuthn options that `passkey.Passkeys` returns (`{"publicKey": …}`); each finish route takes the credential JSON and answers JSON or nothing. Refusals must be problem details, as `authhttp.Error` writes them. The credentials route answers `passkey.Passkeys.AcceptedCredentials`, optionally with `name` and `displayName`.
