> ## Documentation Index
> Fetch the complete documentation index at: https://docs.bijection.com/llms.txt
> Use this file to discover all available pages before exploring further.

# Bijection Auth reference

> Every option, route, function, CLI flag, limit and refusal code of @bijectionhq/library-auth

The [Bijection Auth guide](https://docs.bijection.com/access/authentication/providers/bijection-auth)
explains how to use these. This page lists them.

## `bijectionAuth(options)`

From `@bijectionhq/library-auth`. Returns a subtree to place at `auth` in the app
tree (`app({ auth, … })`); its routes, tables and functions take their paths
there.

| Option | Type | Meaning |
| - | - | - |
| `issuer` | `string` | The site URL followed by `/auth` (or the mounted app's path, then `/auth`). Must equal the native source's `domain`. HTTPS, or `http://localhost:<port>` (passkeys work) or `http://127.0.0.1:<port>` in development. |
| `redirectUris` | `string[]` | Exact browser callback URLs, `<app origin>/connections/callback`. The same list as the source's `browser.redirectUris`. |
| `cli` | `boolean` | Also accept the CLI's loopback callbacks (`http://127.0.0.1:<port>/connections/callback`). |
| `methods` | `Method[]` | The sign-in methods, each once, in page order. At least one. |
| `createUser` | `(ctx, { method, accountId, profile }) => userId` | Creates your user for a newly proved sign-in, in the same transaction; answers its ID. |
| `onSignIn` | `(ctx, { userId, method }) => void` | Optional. Runs in the transaction of every successful sign-in. |
| `signInPage` | `string` | Optional. An exact URL of your own sign-in page; the library appends `?attempt=…`. Default: the deployment's page. |
| `branding` | `{ name?, logoUrl?, accent?, privacyUrl?, termsUrl? }` | Optional. Shown on the sign-in page and in sign-in emails. `name` is 1 to 64 printable characters, URLs are absolute HTTPS, `accent` is `#rgb` or `#rrggbb` (contrast is adjusted to WCAG AA). |
| `installationUrl` | `string` | Optional. The API origin that receives the library's logout events. Default: `BIJECTION_CLOUD_URL`. |

`profile` is `{ name, email, emailVerified, phone, phoneVerified }`, each
`null` (or `false`) when the method did not supply it. Option errors throw a
`TypeError` when the declarations are evaluated, so a deploy refuses them.

### What the subtree holds

| Member | Use |
| - | - |
| `userOf(ctx)` | The signed-in caller's user ID, or `null`. Call it from your own functions. |
| `endSessions(ctx, userId)` | End every session of the user (signed OIDC back-channel logout). |
| `deleteUser(ctx, userId)` | `endSessions`, and remove the user's sign-in methods and passkeys. |
| `session` | The functions a signed-in client calls (below). |
| `keys` | The placed keys `keys.signing` (RS256) and `keys.mac` (HMAC-SHA256). |
| `oidc`, `passkey`, `emailCode`, `github`, `google`, `apple` | The routes. |
| `lifecycle`, `sweep` | Logout delivery, and the minutely cleanup of expired attempts, codes, claims and limits. |

## Methods

| Declaration | Options |
| - | - |
| `passkey()` | None. Relying party ID: the site's host name. Needs a domain-name site. |
| `emailCode(options?)` | `via`: a vendor sender named in code (`resend()`, `postmark()`). `send(ctx, { email, code, url })`: your own delivery. `from`, `replyTo`: the sender of the slot's email. `link`: also email a one-use magic link. With neither `via` nor `send`, codes go out through the `<auth>.mail` slot. |
| `github({ clientId, clientSecret })` | `clientId`: the public OAuth client ID. `clientSecret`: a placed `secret()`. |
| `google({ clientId, clientSecret })` | The same, for a Google OAuth client. |
| `apple({ clientId, teamId, keyId, privateKey })` | `clientId`: the Services ID. `teamId`, `keyId`: from the Apple developer account. `privateKey`: a placed `secret({ alg: "es256" })` holding the `.p8` key. |

### Email senders

| Declaration | Options |
| - | - |
| `resend({ bearer, from, replyTo? })` | `bearer`: a placed `secret()` sent as HTTP Bearer. `from`: `auth@example.com` or `Example <auth@example.com>`, on a domain Resend verified. |
| `postmark({ serverToken, from, replyTo?, messageStream? })` | `serverToken`: a placed `secret()`. `messageStream` defaults to `outbound`. |

With neither `via` nor `send`, codes go out through the library's mail slot,
`<auth>.mail` (`send-mail@1`): the host's managed sender unless
the installation's bindings file binds it to an `endpoint`
([email delivery](https://docs.bijection.com/access/authentication/providers/bijection-auth#email-delivery)).
The managed sender sends from the host's own address: `from` keeps only its
display name, and `replyTo` becomes the Reply-To. A local `http://localhost`
or `http://127.0.0.1` deployment logs the code. A host with no sender
refuses the deploy with `PlacementUnavailable`.

## Native source

The source in `bijection/sign-in.ts` that `bijection auth init` writes:

```ts bijection/sign-in.ts theme={"theme":{"light":"github-light-default","dark":"github-dark-default"}}
import { issuer } from "@bijectionhq/bijection";

const scopes = ["openid", "profile", "email"];

export const bijectionSignIn = issuer.oidc({
  trustVerifiedEmail: true,
  backChannelLogout: true,
  nativeSessions: { renewal: "native" },
  browser: { redirectUris: ["https://app.example.com/connections/callback"], scopes },
  cli: { scopes },
});
```

Place this export in the app tree in `bijection/app.ts`. After deploying, trust
the installation's own issuer for it with
`bijection issuer trust bijectionSignIn --issuer-url https://site.example.com/auth --audience bijection --source-id bijection --trust-verified-email`
(`bijection auth init` prints this command). For an HTTPS
issuer, the library declares the matching token receiver under its
`oidc.exchange` subtree. When the installation advertises the durable
exchange, the native Sessions Task submits the code to that exact URL.

`nativeSessions` also takes `accessTokenLifetimeMs` (120000 to 300000,
default 300000), `idleLifetimeMs` (default 1800000) and `absoluteLifetimeMs`
(default 28800000, at most 86400000), with access ≤ idle ≤ absolute. These
options are the same for every provider.

## Session functions

Called by a signed-in client at `api<typeof App>().auth.session`.

| Function | Arguments | Answers |
| - | - | - |
| `methods` (query) | none | The enabled method names |
| `accounts` (query) | none | `{ id, method, verifiedEmail, verifiedPhone, createdAt }[]` |
| `passkeys` (query) | none | `{ id, name, createdAt, lastUsedAt }[]` |
| `renamePasskey` | `{ passkey, name }` | `null`; names are 1 to 64 characters |
| `removePasskey` | `{ passkey }` | `null`; refuses the last sign-in method |
| `linkStart` | `{ method }` | `{ attempt, url }`: open `url` to prove the method |
| `link` | `{ attempt }` | `null`: adds the proved method |
| `unlink` | `{ account }` | `null`; refuses the last sign-in method |
| `bind` | `{ claim, verifier }` | The user ID. The browser client calls it once per sign-in, before it returns to your page: the one-time claim of the callback and the sign-in's PKCE verifier bind the signed-in person to its user |

## Browser client

From `@bijectionhq/library-auth/client` (non-visual, zero React dependency).

| Export | Use |
| - | - |
| `createAuthSession(installationUrl)` | Reactive session store (`getSnapshot`, `subscribe`, `dispose`) compatible with `useSyncExternalStore` and `useClientAuth`. |
| `listSessions()`, `endSession(sessionId)` | On the session snapshot: the person's live native sessions (every device and CLI) and ending one; ending this browser's signs it out. |
| `browserCredential(installationUrl)` | Low-level IndexedDB credential custody, native renewal, `signIn(options?)`, `signOut(options?)`, `fetchAccessToken`, `httpProof`. |
| `fetchSignInMethods(options)` | Lists enabled sign-in methods for a custom `signInPage` attempt (`{ siteUrl, attempt }`). |
| `passkeySignIn(options)`, `passkeyRegister(options, email?)`, `passkeysSupported()` | WebAuthn passkey ceremonies and feature detection. |
| `sendEmailCode(options, email)`, `verifyEmailCode(options, code)` | Email one-time code and magic-link ceremonies. |
| `oauthAction(options, provider)`, `startOAuth(options, provider)` | GitHub, Google and Apple OAuth form POST helpers. |
| `AuthError` | Typed error with human `message` and stable `code`. |

For visual sign-in and account management components, install `@bijection/sign-in`,
`@bijection/manage-account` and `@bijection/signed-in-devices` from
`ui.bijection.com`.

Pass `bijectionAuth()` from `@bijectionhq/bijection/client` as `token` and
its `httpProof` signer to `connect`. Each browser snapshot reads and renews
credentials for its own session. Its `signOut`, `listSessions`, `endSession`,
and `forget` actions also stay with the session that issued the snapshot.
After an interrupted sign-out, the signed-out snapshot reports
`signOutStatus: "pending"`. Call `signOut()` again to recover the original
request and its original scope. An expired token can recover an existing
receipt. If the deployment reports that the receipt is unavailable, the
snapshot reports `"unconfirmed"`. Call `abandonSignOut()` to explicitly
discard the saved request before starting a new sign-in.

The snapshot uses `null` for a signed-out `sessionId` and `undefined` when
browser custody is unavailable. Credential reads require available custody.
If a provider-renewed session cannot resolve its retained renewal, the
snapshot is signed out and reports
`reauthenticationRequired: "ProviderRenewalIndeterminate"`. Offer
`signIn()` to start a new ceremony after any pending sign-out is resolved.
While subscribed, the store retries an unavailable custody read. Browser
callback restoration retries transient IndexedDB proof-key reads before
the provider exchange, within the original attempt's expiration period.
The store keeps observing custody changes during that wait. An unfinished
callback's error stays visible until it completes or the user starts sign-in
again.

## Routes

Under the issuer, `<site>/auth`.

| Route | Purpose |
| - | - |
| `GET /auth/.well-known/openid-configuration` | Discovery: authorization code flow, S256 PKCE, RS256 ID tokens, no client secret |
| `GET /auth/jwks` | The public half of `auth.keys.signing` |
| `GET /auth/authorize` | Validates the client, exact redirect URI, PKCE, state, nonce and `max_age`; serves the sign-in page |
| `GET /auth/attempt/page`, `GET /auth/attempt/methods` | The hosted page, and the enabled methods for a custom page |
| `POST /auth/attempt/<method>/…` | Method ceremonies |
| `GET /auth/attempt/<method>/callback` (Apple: `POST`) | GitHub, Google and Apple callbacks |
| `GET /auth/attempt/complete` | Issues the one-use authorization code and the one-time person claim, and redirects to the callback with `code`, `state` and `claim` |
| `POST /auth/token` | Code exchange: answers the ID token (`iss`, `sub`, `aud`, `nonce`, `auth_time`, `amr`, `email`, `email_verified`, `phone_number`, `phone_number_verified`) and no refresh token |

`sub` is stable for a person across linking and unlinking.

## Limits and lifetimes

| What | Limit |
| - | - |
| Sign-in attempt | 10 minutes |
| Authorization code | 60 seconds, single use |
| Person claim | 10 minutes, single use, redeemable after its code is exchanged, with the sign-in's PKCE verifier |
| Email code | 6 digits, 10 minutes, 5 tries |
| Magic link | The code's lifetime, single use, bound to the requesting browser by an HttpOnly cookie |
| Code requests | 5 per attempt per 10 minutes, 5 per email address per hour |
| Link starts | 10 per user per minute |
| Passkey ceremonies | 10 per attempt per minute |
| GitHub, Google and Apple starts | 5 per attempt per minute |
| Authorization requests | 200 per minute for the deployment |
| Logout event | Signed for 120 seconds, delivered up to 3 times |

## CLI

`bijection auth init --provider bijection` installs and configures the
library (see the [quick start](https://docs.bijection.com/access/authentication/providers/bijection-auth#quick-start)).

| Flag | Meaning |
| - | - |
| `--web-server-url <url>` | Your app's origin; registers `<url>/connections/callback` |
| `--magic-link` | `emailCode({ link: true })` |
| `--email-provider log\|resend\|postmark`, `--email-from <address>` | How emails are sent: the development log, or a built-in sender (prompts for its key; the sender comes from `AUTH_EMAIL_FROM`) |
| `--brand-name`, `--brand-logo-url`, `--brand-accent`, `--privacy-url`, `--terms-url` | `branding`, validated before anything changes |
| `--provider github\|google\|apple` | Add that method; prints the callback URL and prompts for the client ID and secret |
| `--client-id <id>` | The public client ID (Apple: the Services ID), without a prompt |
| `--apple-team-id`, `--apple-key-id`, `--apple-private-key <file.p8>` | Apple's values; the key is sealed as an `es256` key |

On a terminal, a first setup without choice flags asks how sign-in emails are
sent and whether they carry magic links. Running `auth init` again edits the
existing `auth.ts` in place.

## Refusal codes

Session functions refuse with these codes in the client's `Result`. Method
routes answer `{ ok: false, error, code }` to a JSON caller and show the
message on the page. `/auth/authorize` and `/auth/token` answer the OAuth
`error` format, as OIDC clients expect. Codes are stable; messages may be
reworded. `AUTH_ERRORS` exports the catalog with HTTP statuses and messages.

| Code | When |
| - | - |
| `AuthUnavailable` | The library runs only at the deployment head (not in a preview of an older version) |
| `AuthAttemptExpired` | The sign-in attempt expired or is unknown |
| `AuthMethodDisabled` | The method is not enabled |
| `AuthRateLimited` | Too many requests for this attempt, address or account |
| `AuthEmailInvalid` | Not a valid email address |
| `AuthCodeInvalid` | The code is expired, spent or out of tries |
| `AuthCodeMismatch` | The code did not match |
| `AuthMagicLinkInvalid` | The link is invalid, expired or used |
| `AuthMagicLinkElsewhere` | The link was opened in another browser than the one that asked |
| `AuthPasskeyInvalid` | The passkey ceremony did not verify |
| `AuthPasskeyUnsupported` | The site has no domain name |
| `AuthPasskeyNotFound` | The passkey is not the caller's |
| `AuthPasskeyNameInvalid` | The name is empty or longer than 64 characters |
| `AuthProviderInvalid` | GitHub, Google or Apple answered an invalid response |
| `AuthProviderFailed` | The provider step did not finish |
| `AuthRecoveryUnavailable` | No account has this verified email |
| `AuthSignInRequired` | The function needs a signed-in Bijection Auth user |
| `AuthClaimInvalid` | `bind` got an unknown, spent, expired or not yet exchanged claim, or another browser's verifier |
| `AuthPersonBound` | `bind` was called by a person already bound to another user |
| `AuthLinkRefused` | The method belongs to another user |
| `AuthLinkInvalid` | The link attempt is not the caller's or expired |
| `AuthLinkLimit` | The user has the maximum number of sign-in methods |
| `AuthLastMethod` | Removing the last sign-in method |
| `AuthAccountNotFound` | The linked method is not the caller's |
| `AuthUserAlreadyBound` | `createUser` answered a user that already has sign-in methods |
| `AuthUserStateInvalid` | The user's stored sign-in methods are inconsistent |


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.