> ## 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

> Passkeys, email codes and social sign-in served by your own deployment, with no identity vendor to set up

Bijection Auth is sign-in that works out of the box. Your deployment serves
it: passkeys, email codes and magic links, and GitHub, Google and Apple
sign-in, with your users in your own table and every session handled by
Bijection's native sessions. There is no vendor account, dashboard or API key
to paste.

It is a convenience, not a replacement for an identity provider. If your app
needs enterprise SSO (SAML), organizations, MFA policies, a user
administration console or passwords, [bring your own provider](https://docs.bijection.com/access/authentication#choose-a-provider):
WorkOS AuthKit, Clerk, Auth0 or any OIDC issuer. Everything after sign-in
(roles, grants, labels, invitations, native sessions) works the same with
either choice, and [switching later](#switch-to-your-own-provider) keeps your
users.

## Quick start

From your application root, with a development deployment selected:

```sh theme={"theme":{"light":"github-light-default","dark":"github-dark-default"}}
bijection auth init --provider bijection
```

It registers your app's sign-in callback on its development origin
(`http://localhost:5173` for a Vite app, `http://localhost:3000` otherwise);
pass `--web-server-url <origin>` when the app is served elsewhere, and always
for a production deployment. The command:

1. installs `@bijectionhq/library-auth`: the copy pinned in your CLI release, else
   the matching version from npm (`workspace:*` inside the Bijection
   monorepo);
2. writes `bijection/auth.ts` with passkeys and email codes, places it at
   `auth` in your app tree, and adds `bijection/auth.settings.ts`, which reads
   the site URL and your app's origin;
3. generates the library's signing and MAC keys and seals them on the
   deployment (`auth.keys.signing`, `auth.keys.mac`); the material never
   leaves the host;
4. registers the deployment's own issuer, `<site URL>/auth`, in
   `bijection/sign-in.ts`, with native renewal, OIDC back-channel logout
   and trusted verified email turned on.

Then subscribe to the browser session store and connect the client with its
adapter:

```tsx src/main.tsx theme={"theme":{"light":"github-light-default","dark":"github-dark-default"}}
import { useState, useSyncExternalStore } from "react";
import { createAuthSession } from "@bijectionhq/library-auth/client";
import { bijectionAuth, connect } from "@bijectionhq/bijection/client";
import { Bijection, useClientAuth } from "@bijectionhq/bijection/react";
import { createRoot } from "react-dom/client";
import type app from "../bijection/app";

const installationUrl = import.meta.env.VITE_BIJECTION_URL;
const authSession = createAuthSession(installationUrl);
const auth = bijectionAuth();
const client = connect(installationUrl, {
  contract: "discover",
  token: auth,
  httpProof: auth.httpProof,
});

function App() {
  const state = useSyncExternalStore(authSession.subscribe, authSession.getSnapshot);
  const ready = useClientAuth(auth, state);
  const [actionError, setActionError] = useState<string>();
  const [pending, setPending] = useState(false);
  const notice = actionError ?? state.error?.message;

  async function run(action: () => Promise<void>) {
    setPending(true);
    setActionError(undefined);
    try {
      await action();
    } catch (error) {
      setActionError(error instanceof Error ? error.message : "The session action failed.");
    } finally {
      setPending(false);
    }
  }

  if (state.isLoading || !ready) return <p>Restoring sign-in…</p>;
  return (
    <>
      {notice && <p role="alert">{notice}</p>}
      {state.isAuthenticated ? (
        <Bijection client={client}>
          <button disabled={pending} onClick={() => void run(state.signOut)}>Sign out</button>
        </Bijection>
      ) : (
        <>
          {state.signOutStatus === "pending" && (
            <button disabled={pending} onClick={() => void run(state.signOut)}>Retry sign-out</button>
          )}
          {state.signOutStatus === "unconfirmed" && <p>The deployment could not confirm the original sign-out.</p>}
          {state.signOutStatus ? (
            <button disabled={pending} onClick={() => void run(state.abandonSignOut)}>Discard saved sign-out request</button>
          ) : (
            <button disabled={pending} onClick={() => void run(state.signIn)}>Sign in</button>
          )}
        </>
      )}
    </>
  );
}

createRoot(document.getElementById("root")!).render(<App />);
```

Serve this page at `/connections/callback` too: the provider finishes
sign-in there and returns to the page that started it. Run `bijection dev`,
open the app and choose **Sign in**. A local deployment serves its site on
`http://localhost:<port>`, which browsers treat as secure, so passkeys work
there as they do on every hosted deployment. Email codes work too: a local
deployment's code sender writes the code to its log
(`bijection list sys.logs`). Open the app on `localhost` as well (Vite's default), not
`127.0.0.1`: a passkey belongs to a host name, and an IP address is never one.

> [!TIP]
>
> Setting this up with a coding agent? Give it this page and a prompt such as
> "add sign-in with passkeys and email codes and private per-user notes". The
> [Bijection Auth example](https://github.com/bijectionhq/bijection/tree/main/examples/authentication-bijection)
> is the finished result.

## Your users

Bijection Auth keeps its own records (sign-in methods, passkeys, codes,
attempts) in private library tables that your functions cannot read. Your
users live in your table. `createUser` runs in the same transaction that
records a newly proved sign-in and answers your fact's ID:

```ts bijection/auth.ts theme={"theme":{"light":"github-light-default","dark":"github-dark-default"}}
import { bijectionAuth, emailCode, passkey } from "@bijectionhq/library-auth";
import { t, table } from "@bijectionhq/bijection";
import { authIssuer, authRedirectUris } from "./auth.settings.js";

export const users = table({ name: t.maybe(t.string), email: t.maybe(t.string) });

export const auth = bijectionAuth({
  issuer: authIssuer,
  redirectUris: authRedirectUris,
  cli: true,
  methods: [passkey(), emailCode()],
  createUser: (ctx, { profile }) =>
    ctx.insert(users, { name: profile.name, email: profile.emailVerified ? profile.email : null }),
});
```

`profile` is `{ name, email, emailVerified, phone, phoneVerified }`, with
`null` for what the method did not supply. A failure in `createUser` leaves
nothing behind. `onSignIn(ctx, { userId, method })` runs the same way on
every successful sign-in.

In any function, `await auth.userOf(ctx)` answers the signed-in caller's user
ID, or `null`:

```ts bijection/account.ts theme={"theme":{"light":"github-light-default","dark":"github-dark-default"}}
import { query, role } from "@bijectionhq/bijection";
import { auth, users } from "./auth.js";

export const me = query({ allow: [role.signedIn] }, async (ctx) => {
  const userId = await auth.userOf(ctx);
  return userId === null ? null : ctx.get(users(userId));
});
```

Bijection Auth knows the caller the way any app knows a user of any
provider: by principal. The host gives each signed-in person a random
`person:…` principal and never shows functions the provider's subject. When a
sign-in completes, the callback carries a one-time claim next to the code;
the browser client, once signed in, redeems it with the sign-in's PKCE
verifier (`auth.session.bind`) and that binds the person to its user. Only
the browser that started the sign-in holds the verifier, so a claim or code
taken from the redirect binds nothing. A person who has not bound, such as a
first sign-in from the CLI, is nobody's user: `userOf` answers `null` until
that person signs in once in the browser.

Use the user ID for your relationships and business data. Use
[roles, grants and labels](https://docs.bijection.com/access) for what the person may do: signing in
holds `role.signedIn` and nothing more.

### Private per-user notes

Per-user privacy is a label family and a grant, not a filter on an owner
field. Each author gets a member of an `authors` family and the `author` role
under it; a notes table labelled with the family puts every note in its
author's member, so the host refuses a read across authors. The code is the
same with any provider: the
[Bijection Auth example](https://github.com/bijectionhq/bijection/tree/main/examples/authentication-bijection)
and the [AuthKit example](https://github.com/bijectionhq/bijection/tree/main/examples/authentication-authkit)
share their `notes.ts`, `access.ts` and `roles.ts`. See [Labels](https://docs.bijection.com/access/labels.md)
for the model.

## Sign-in methods

List the methods in `methods`, each once. The sign-in page offers them in
that order.

| Method | Declaration | Proves |
| - | - | - |
| Passkeys | `passkey()` | A WebAuthn credential (discoverable, user verification required) |
| Email codes | `emailCode({ via? })` | Control of an email address: six digits, ten minutes |
| Magic links | `emailCode({ via?, link: true })` | The same, with a one-use link in the email |
| GitHub | `github({ clientId, clientSecret })` | A GitHub account and its verified primary email |
| Google | `google({ clientId, clientSecret })` | A Google account, from its verified ID token |
| Apple | `apple({ clientId, teamId, keyId, privateKey })` | An Apple ID; private-relay addresses count as verified |

### Passkeys

`passkey()` registers and uses discoverable WebAuthn credentials (ES256 and
RS256), with user verification required and the origin and relying party
(the site's host name) checked exactly. A sign count that goes backwards is
refused. A new passkey may carry an optional email, which stays unverified
until an email ceremony confirms it. Passkeys need a site with a host name:
every hosted deployment, and a local one on `http://localhost:<port>` (only
non-production deployments accept an HTTP issuer). A site on an IP address,
such as `http://127.0.0.1`, offers email codes instead.

### Email codes and magic links

`emailCode()` sends a six-digit code that expires within ten minutes and
allows five tries. With `link: true`, the email also carries a one-use link
bound to the attempt and to the browser that asked for it. Opened in another
browser, it spends nothing and asks for the code on the device where sign-in
started. Codes and links share the same lifetime and rate limits. See
[Email delivery](#email-delivery).

### GitHub, Google and Apple

These methods send the person to the provider and back to
`<site>/auth/attempt/<method>/callback`, which you register with the
provider. Client IDs are public values; client secrets and Apple's private
key are placed `secret()`s that only the host opens:

```sh theme={"theme":{"light":"github-light-default","dark":"github-dark-default"}}
bijection auth init --provider github     # or google, or apple
```

The command adds the method, prints the callback URL, and asks for the client
ID and secret (for Apple: the team ID, key ID and `.p8` key file). Each prompt
has a non-interactive flag; see the [reference](https://docs.bijection.com/access/authentication/providers/bijection-auth/reference.md#cli).

* GitHub's token exchange is a `capture` operation: the host seals GitHub's
  access token as a bearer that only the profile request presents, and the
  flow retracts it once the profile is read. Only the verified primary email
  counts.
* Google's identity comes from its verified ID token, including
  `phone_number` and `phone_number_verified`.
* Apple's client secret is a short-lived JWT the host signs with your
  `es256` key. Apple sends the person's name only on the first sign-in; it
  reaches `createUser` as `profile.name`.

## Email delivery

Choose how codes and links are delivered:

* **`emailCode()`** (optionally `emailCode({ from, replyTo })`) renders a
  branded, accessible HTML and plain-text email and sends it through the
  library's mail [slot](https://docs.bijection.com/operate/placement.md), `auth.mail` (`send-mail@1`).
  Code never says who sends it. Unbound, the host's managed sender does; to
  use your own relay, bind it in the installation's bindings file:

  ```ts bindings.ts theme={"theme":{"light":"github-light-default","dark":"github-dark-default"}}
  import { placement } from "@bijectionhq/bijection";
  import app from "./bijection/app";
  const { bind, endpoint, env, bindings } = placement;

  export default bindings([
    bind(app.auth.mail, endpoint({
      url: env("AUTH_MAIL_URL"), hosts: ["mail-relay.example.com"], credential: "auth.mail.token",
    })),
  ]);
  ```

  Where the host offers no sender and the slot is unbound, deploy refuses
  with `PlacementUnavailable` (`NotOffered`), which names both fixes, rather
  than dropping codes silently. On a local `http://localhost` or
  `http://127.0.0.1` deployment, the code is written to the deployment log.
* **A vendor named in code**: `emailCode({ via: resend({ bearer, from }) })`
  or `emailCode({ via: postmark({ serverToken, from }) })` renders the same
  email and submits it to that provider. The key is a placed secret: set it
  with `bijection secret set`. Use a sender address your mail provider has
  verified.

  ```ts bijection/auth.ts theme={"theme":{"light":"github-light-default","dark":"github-dark-default"}}
  import { emailCode, passkey, resend } from "@bijectionhq/library-auth";
  import { secret } from "@bijectionhq/bijection";

  export const resendApiKey = secret();   // bijection secret set resendApiKey

  export const methods = [
    passkey(),
    emailCode({ via: resend({ bearer: resendApiKey, from: "sign-in@example.com" }) }),
  ];
  ```
* **Your own code**: `emailCode({ send })` hands you `(ctx, { email, code, url })`
  in the transaction that accepts the request, so you can submit to your own
  [target](https://docs.bijection.com/functions/effects.md) atomically with it.

`bijection auth init --provider bijection --email-provider resend --email-from "Acme <sign-in@acme.example>"`
writes a vendor delivery for you, with the sender in `AUTH_EMAIL_FROM` and the
key in a placed secret it asks for. Add `--magic-link` for links.

Which identity providers may sign people in is not placement: issuers are
trust facts changed by an audited trust act, never by a deploy
([switch providers](https://docs.bijection.com/access/authentication/switch-provider.md)).

## The sign-in page

The deployment serves the sign-in page itself at `<site>/auth/authorize`. It
is server-rendered, mobile-first, light and dark, and accessible (labels,
focus, contrast, reduced motion, announced errors). Email codes work without
JavaScript, and the page is served with a strict content security policy.
Pass these options as `branding` to `bijectionAuth`:

```ts theme={"theme":{"light":"github-light-default","dark":"github-dark-default"}}
import type { Branding } from "@bijectionhq/library-auth";

export const branding: Branding = {
  name: "Acme",
  logoUrl: "https://acme.example/logo.svg",
  accent: "#4f46e5",
  privacyUrl: "https://acme.example/privacy",
  termsUrl: "https://acme.example/terms",
};
```

URLs must be absolute HTTPS and the accent `#rgb` or `#rrggbb`; text on the
accent is adjusted to meet WCAG AA contrast. A wrong value refuses at deploy,
not at sign-in. The same branding appears in sign-in emails.

To sign in inside your own app instead, set `signInPage` to the exact URL of
a page of your app, install `@bijection/sign-in` from `ui.bijection.com`, and
wire its callbacks to the helpers in `@bijectionhq/library-auth/client`:
`fetchSignInMethods`, `passkeySignIn`, `passkeyRegister`, `sendEmailCode`,
`verifyEmailCode` and `startOAuth`. Each takes `{ siteUrl, attempt }` and
reports failures as `AuthError` with a stable `code`. Passkeys run on the
deployment site's origin, so a page on another origin hands the passkey step to
the deployment's page.

## Accounts and recovery

Install `@bijection/manage-account` and `@bijection/signed-in-devices` from
`ui.bijection.com` and connect them to `api<typeof App>().auth.session` with
`useWatch` and `useMutation` from `@bijectionhq/bijection/react`. Passkeys
(add one on this device, rename, remove) and linked sign-in methods (add,
remove) come from the session functions below; the signed-in devices list
reads `listSessions()` and ends one with `endSession(sessionId)` from the
`createAuthSession` snapshot, which covers every device and CLI signed in to
the person's account:

| Function | Does |
| - | - |
| `methods()` | The enabled sign-in methods |
| `accounts()` | The caller's linked methods: `{ id, method, verifiedEmail, verifiedPhone, createdAt }` |
| `passkeys()` | The caller's passkeys: `{ id, name, createdAt, lastUsedAt }` |
| `renamePasskey({ passkey, name })`, `removePasskey({ passkey })` | Manage one passkey |
| `linkStart({ method })` answers `{ attempt, url }`; then `link({ attempt })` | Prove another method and add it |
| `unlink({ account })` | Remove a linked method |

A person always keeps at least one way to sign in: removing the last one is
refused. Linking needs the person signed in *and* a fresh proof of the new
method. Two accounts with the same email are never linked automatically.
Adding a passkey on a new device is `linkStart({ method: "passkey" })`.

**Recovery.** The sign-in page offers recovery to a person who lost their
passkey: they enter a verified email address of their account and the code
sent to it. The code signs in to the account that verified that address
(never one where the address was only typed with a passkey), and the page
offers to create a new passkey on this device before continuing. Keep
`emailCode()` beside `passkey()` (the scaffold does) so recovery is always
possible.

## Sessions and lifecycle

After sign-in the session is Bijection's native session, the same one every
provider gets: a sender-bound access token (each request is signed with a
browser key the page cannot export), renewed by the deployment within its
idle and absolute lifetimes, revocable and audited. The issuer returns no
refresh token: the source's `nativeSessions: { renewal: "native" }` lets the
deployment renew without calling it.

* `signOut()` ends this browser's session. `signOut({ allSessions: true })`
  ends every session of the person. A pending sign-out withdraws application
  access and retains its exact request. If the bearer expires, retry sign-out
  to check the original receipt and renew the credential if needed to finish.
  A temporary renewal refusal preserves that pending request. If sign-out
  could never be sent and renewal is unavailable, the browser clears its
  unusable session.
* `listSessions()` (on the `createAuthSession` snapshot from `@bijectionhq/library-auth/client`)
  lists the person's live sessions, newest first: `{ sessionId, current, issuer,
  client, createdAt, expiresAt, idleExpiresAt }`, times in epoch milliseconds.
  `endSession(sessionId)` ends one of them (this browser's is a sign-out).
  Install `@bijection/signed-in-devices` from `ui.bijection.com` to render the
  list. Both use the deployment's native session inventory
  (`GET /api/bijection/identity/sessions`, and `POST
  /api/bijection/identity/session/end` with `session`), which every provider's
  native sessions share; `bijection auth sessions` shows the same list in the
  CLI.
* `signIn({ reauthenticate: true })` forces a fresh ceremony (OIDC
  `max_age=0`); `auth_time` is that ceremony's time.
* `await auth.endSessions(ctx, userId)` in your mutation ends all of a
  user's sessions. `await auth.deleteUser(ctx, userId)` also removes their
  sign-in methods and passkeys; delete your own user fact in the same
  mutation.

Both send a signed OIDC back-channel logout event to the deployment's own
logout receiver, exactly as an external provider would (the source sets
`backChannelLogout: true`). Check that the caller may manage the user first;
the example's `account.deleteMe` lets people delete only themselves.

## Owners and invitations

Declare the owner in the app's [founder roles](https://docs.bijection.com/access/grants.md#initial-owner)
and name the founder at installation creation. When nominated by email,
the first matching verified app sign-in receives the role. A signed-in owner
can use `team.invite` to issue additional invitations.

## Security model

* **Same interfaces as any provider.** The library is an OIDC issuer at
  `<site>/auth` (discovery, authorization code with S256 PKCE, JWKS). The
  native layer verifies it like an external issuer. The library never writes
  native session, grant or membership state, and authorization never reads
  its tables.
* **Keys stay in the host.** The RS256 signing key and the HMAC key are
  `secret({ alg })` keys: functions ask the host to sign or MAC and never
  hold the material. Email codes and authorization codes are stored only as
  MACs and compared in constant time.
* **Private credential tables.** Every Bijection Auth table (accounts,
  passkeys, email codes, attempts, authorization codes, rate limits) is
  declared `private: true`. Your app places them when it places `auth`, but
  only the library's own functions read or write them: a function of your
  app that reads one is refused `LibraryTableReaderRequired`, and one that
  writes one is refused at commit, whoever calls it (a signed-in user, a
  client or an administrator). Read accounts through `auth.userOf(ctx)` and
  the `auth.session` entries. Any library can keep its tables private the
  same way.
* **Short, single-use credentials.** Attempts expire after ten minutes;
  authorization codes after 60 seconds, spent on exchange; email codes within
  ten minutes, after at most five tries.
* **Rate limits** per attempt, per email address and per account, with the
  counters in a private table.
* **Exact redirects.** Only the registered `/connections/callback` URLs (and
  loopback CLI callbacks with `cli: true`) receive codes. There is no open
  redirect.
* **Honest assurance.** The ID token's `amr` names the ceremony that proved
  the sign-in, and `auth_time` its time; PKCE verifiers are compared in
  constant time.
* **Hardened pages.** A nonce-based content security policy, no framing
  (`X-Frame-Options`), no caching of ceremony replies, and refusals with
  stable codes and human messages
  ([refusal codes](https://docs.bijection.com/access/authentication/providers/bijection-auth/reference.md#refusal-codes)).
* **No silent linking.** A matching email never merges accounts.
* **Sender-bound person binding.** The claim that ties a signed-in person to
  a user is single use, lasts ten minutes, is redeemable only after its code
  was exchanged and only with the sign-in's PKCE verifier. A person bound to
  one user is never rebound to another (`AuthPersonBound`).

## Test your sign-in

The example ships an end-to-end suite you can copy. Playwright drives email
codes, passkeys (with a virtual WebAuthn authenticator), renewal, sign-out
and account deletion against a real deployment. See the
[example README](https://github.com/bijectionhq/bijection/tree/main/examples/authentication-bijection#end-to-end-tests).

## Switch to your own provider

Nothing in your app depends on Bijection Auth beyond `auth.ts`, the
`auth.userOf(ctx)` calls and the React provider:

1. Add the new provider's source to `bijection/sign-in.ts` and its
   client adapter (for example `authkit()`), keeping the Bijection Auth
   source during the move.
2. For each existing user, record the principal (`ctx.frame.as.id`) the
   new provider's sign-in opens. Use verified email only to find the
   candidate fact, and confirm the match (a sign-in with the old method, or
   an administrator).
3. Replace `auth.userOf(ctx)` with a lookup through that association, and
   grant roles to the new principals.
4. Remove the `auth` subtree, its source and `@bijectionhq/library-auth`.

[Switch identity providers](https://docs.bijection.com/access/authentication/switch-provider.md) covers
each step.


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