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

# Tuturuuu session

> Design for one first-party, provider-agnostic session that every Tuturuuu app, Worker, mobile client, the CLI and external apps derive from.

**Status: design, pending independent security review.** Nothing on this page
is implemented or enabled. Implementation lands in reviewed slices behind flags
that default off, and landing a slice does not authorize a flag flip. Database
access, the migration phases, the threat model and the stop fence are in
[Tuturuuu session rollout](https://docs.tuturuuu.com/platform/architecture/tuturuuu-session-rollout.md).

Tuturuuu has one signed-in session for all of `tuturuuu.com`. Tuturuuu issues
and manages it, whichever identity provider authenticated the user. Supabase
Auth is the provider today; Better Auth is next, and a custom provider can
follow. Swapping the provider must not change any app.

This page is the end state of the
[server-held session decision](https://docs.tuturuuu.com/build/devops/start-bridge.md#shared-session-on-the-apex-decision-b-server-held-session).
[HttpOnly session cookie](https://docs.tuturuuu.com/platform/architecture/httponly-session-cookie.md) is
its phase P0. The product rules stay in
[Shared session](https://docs.tuturuuu.com/platform/architecture/shared-session.md).

## Principles

1. **One session authority.** The session service is the only component that
   creates, rotates, refreshes or revokes a session. Other apps and Workers
   consume a derived identity and never see the session secret.
2. **Provider tokens stay in the trusted adapter.** Browsers, mobile, the CLI,
   external apps and mounted app code never receive a Supabase, Better Auth or
   OAuth-provider token.
3. **User IDs are stable.** The Tuturuuu user ID is the existing
   `public.users.id`, today equal to `auth.users.id`. Providers map onto it.
4. **Portable core, thin adapters.** Session logic lives in a framework-free
   package with one adapter per runtime.
5. **Fail closed.** An unknown, expired, revoked, ambiguous or unverifiable
   session is signed out. It never falls back to a weaker credential.
6. **Trusted ingress first.** A host reads first-party identity only after
   every path into it passes through a component that strips client-supplied
   credentials and identity headers.

## Components

| Component | Runs on | Owns |
| - | - | - |
| Session service (Web auth routes, then the `auth` Worker) | Cloudflare Worker, reached only through service-binding entry points with per-entry caller keys | Sign-in flows, the cookie MAC check, the 5-second `read` resolution cache, cookie writes, rotation, step-up grants, revocation, identity assertion signing, provider adapters. Holds every session and signing secret |
| `BrowserDevice` Durable Object, one per device | SQLite-backed Durable Object | The device secret, the device's sessions, the active-account pointer, rotation order |
| `UserSessions` Durable Object, one per user | SQLite-backed Durable Object | The user's device index, revocation epoch, revoke-all fan-out |
| `SessionControl` Durable Object, one per environment | SQLite-backed Durable Object | The durable stop fence |
| Token service | The signer inside the `auth` Worker; its emergency key list comes from a key guard Worker in a separate account | Short-lived ES256 JWTs and the JWKS |
| Gateway (`apps/gateway`) | Cloudflare Worker | The only public ingress: checks the cookie codec, enforces CSRF, classifies ingress, strips credentials, forwards the auth Worker's per-mount identity assertion. Holds no session or signing secret |
| `@tuturuuu/session` | Portable package | Types, cookie codec, expiry policy, assertion verification, runtime adapters |
| Audit sink | Postgres through a Queue | Append-only session and credential events |

```text theme={null}
browser ── __Host-ttr_session ──▶ gateway ──▶ auth Worker ──▶ BrowserDevice DO ──▶ UserSessions DO
                                   │  (MAC check before any DO call)  │
                                   │                                      └─▶ provider adapter
                                   ▼  service binding only
                       mount Worker ── x-ttr-identity (≤ 60 s, aud = mount) ── verify with key source
```

## 1. Session model

### Device cookie

The browser cookie names a **device**, not a user. The active account is a
server-side pointer in the device's Durable Object. A switch moves that pointer
and issues a new generation, so a late response carrying an older generation
cannot restore the superseded account.

| Property | Value | | | |
| - | - | - | - | - |
| Name | `__Host-ttr_session` | | | |
| Attributes | `HttpOnly; Secure; SameSite=Lax; Path=/`, no `Domain` | | | |
| Value | `v1.<dev>.<gen>.<secret>.<mac>` | | | |
| `dev` | 16 random bytes, base64url without padding (22 characters). Addresses the `BrowserDevice` object | | | |
| `gen` | Device generation: canonical decimal (no sign, no leading zero except `0`), from 0 to 2147483647 | | | |
| `secret` | 32 random bytes, base64url without padding (43 characters) | | | |
| `mac` | First 16 bytes of \`HMAC-SHA-256(k, "ttr-session-mac/v1 | " + env + " | " + host + " | " + dev + "." + gen + "." + secret)\`, base64url (22 characters) |
| Stored | `HMAC-SHA-256(TTR_SESSION_PEPPER, secret)` and `gen`. The raw secret exists only in the cookie | | | |
| `Max-Age` | Whole seconds, rounded down, until the latest absolute deadline among the device's live sessions. Zero or less clears the cookie | | | |

Codec invariants, in `@tuturuuu/session`:

* The whole value matches one strict pattern and is at most 128 bytes.
  Base64url must be canonical: no padding and no non-zero trailing bits.
* The codec counts the name across every `Cookie` field value it is given,
  including split headers. More than one `__Host-ttr_session` is
  **ambiguous** and resolves to signed out for every method. The response
  clears the name with `Max-Age=0` and the same attributes.
* **The MAC is an admission filter, not authorization.** It lets the auth
  Worker drop forged or random cookies before any Durable Object call. The device
  secret hash in storage still decides. `k` comes from
  `TTR_SESSION_COOKIE_MAC_KEYS` (HMAC-SHA-256, sign-capable), scoped by
  environment and host through the MAC input. The host is the hostname from
  trusted routing, lowercase, with no port and no trailing dot. Verification accepts the current key and at most one previous key for
  a 24-hour rollover. Emergency retirement removes a key, and its cookies fall
  through to storage-backed checks under the abuse limits.
* `dev` reveals nothing about the user. The cookie carries no claims.
* Adapters pass the `Cookie` field values as received and never fold them
  with commas. Pairs split only on `;`, because browsers allow commas inside
  cookie values, and only spaces and tabs are trimmed.

Pre-authentication state (OAuth `state`, PKCE verifier, WebAuthn challenge,
return target, QR and handoff redemption secrets) lives in a separate
`__Host-ttr_flow` cookie. Each value is bound to one ceremony, lasts at most 10
minutes and is consumed once. It never becomes a session.

### Generations and rotation

The device record keeps one current generation. A new generation (new `gen`,
new secret, the previous secret invalid at once) is issued on:

* every sign-in and account addition, including when the browser already
  sends a cookie, so a planted pre-login cookie dies at login;
* step-up, MFA enrollment or removal, password change and account switch;
* every 24 hours of use.

Only the 24-hour rotation keeps the previous generation for 30 seconds, so
parallel requests from one tab do not sign out. During that window the
previous generation has **read authority only**:

* it resolves with `stale: true` only for routes the effect registry classes
  as `read`, whatever their HTTP method;
* it carries no step-up and cannot use a step-up grant;
* it cannot mint any credential, extend expiry or receive a `Set-Cookie`;
* any other or unknown route with it gets `401 SESSION_ROTATED`, and the client retries
  with the current cookie.

The `BrowserDevice` object serializes every write for its device, so rotation,
account switch, sign-in and logout apply in one order. Each write that emits
`Set-Cookie` carries the new `gen`. A response carrying an older `gen` cannot
win, because any secret with a `gen` below the current one fails resolution
(except the read-only window above). Recovery from an unusable cookie is a
document navigation to Web's sign-in, which keeps the device's saved accounts.

### Session record

Sessions are rows inside their device's object:

| Field | Meaning |
| - | - |
| `sid`, `userId`, `kind` | Identity. `kind` is `browser`, `child`, `mobile`, `cli` or `external_app` |
| `parentSid`, `parentDev` | Set for a child session on a subdomain host |
| `createdAt`, `lastSeenAt`, `idleExpiresAt`, `absoluteExpiresAt` | Expiry clocks. A session is expired when `now >= idleExpiresAt` or `now >= absoluteExpiresAt` |
| `authTime`, `aal`, `amr` | When and how the user authenticated |
| `provider`, `providerSubject`, `upstream` | Adapter name, provider user ID, encrypted upstream grant |
| `epochSeen` | The user's revocation epoch when this session was created |
| `device` | User-agent family, platform, client name and coarse location from the edge |
| `revokedAt`, `revokedReason` | Terminal state |

Saved accounts are sibling sessions on the same device; `activeSid` selects
one. Switching moves the pointer inside one object and issues a new generation.

### Expiry

| Rule | Browser | Mobile and CLI |
| - | - | - |
| Idle expiry | 7 days | 30 days |
| Absolute expiry | 30 days | 90 days |
| Child session | Never longer than its parent; resolution checks the parent | Not applicable |

`lastSeenAt` is written at most once every 5 minutes per session. Expiry is a
pure function of the record and an injected clock.

### Device list and revocation

* **List:** `GET /api/v1/auth/sessions` reads the user's device index from
  `UserSessions` and each device's sessions. It returns device, location,
  `lastSeenAt` and `current: true` for this session, never secrets or grants.
* **Revoke one:** `DELETE /api/v1/auth/sessions/:sid` revokes the row in its
  device object and its children there. It takes effect on the next resolution.
* **Revoke all:** `POST /api/v1/auth/sessions/revoke-all` increments the
  user's epoch in `UserSessions`, then revokes the user's sessions in every
  indexed device object with bounded concurrency, retried by an alarm until
  each one acknowledges. Each device object re-reads the user's epoch when its
  cached copy is older than 30 seconds, so a device the fan-out has not reached
  still stops within 30 seconds. The response reports any device still pending.
* **Upstream:** every revocation calls the adapter's `revokeUpstream` for that
  session's grant, retried through the Queue. A provider failure never undoes
  the first-party revocation.
* Account deletion, an admin "compromised" action and the revoke-all
  endpoint revoke every session on every device, including the caller's.
* Password change, MFA reset, and MFA or passkey removal bump the epoch and
  revoke every other device; the session that made the change stays signed
  in at the new epoch.

Revocation bounds are listed in
[Tuturuuu session rollout](https://docs.tuturuuu.com/platform/architecture/tuturuuu-session-rollout.md#revocation-bounds).

### Step-up grants

A sensitive action needs a **step-up grant**, not a general window. The user
confirms the named action on a Web-owned page with passkey user verification,
or password plus a second factor. The session service then issues a grant
bound to:

* the action name and a hash of its parameters (for example the CLI user code,
  the external client ID and scopes, or the API key name and role);
* the `sid` and the current generation;
* an expiry of 5 minutes.

The action consumes the grant atomically in the device object. Covered actions:
API keys, CLI device approval, QR-login approval, external-app consent, passkey
and MFA changes, email or password change, account deletion and revoke-all.

### Audit events

`session.created`, `session.rotated`, `session.switched`, `session.step_up`,
`session.revoked` (with `reason`), `session.revoked_all`,
`session.reuse_detected`, `identity.linked`, `identity.unlinked`,
`token.issued` (with `class` and `aud`) and `provider.error`.

Events carry IDs, the event type, the actor, a /24 (IPv4) or /48 (IPv6)
prefix, the user-agent family and the time. They never carry secrets, tokens,
raw cookies or full IP addresses. Event IDs are idempotent, and a lost event
never changes a session decision. Users see their own events in the device
list; support access follows the
[data protection standard](https://docs.tuturuuu.com/platform/data-protection-standard.md).

## 2. Identity provider adapters

The session service talks to providers only through this interface, in
`@tuturuuu/session/provider`:

```ts theme={null}
interface IdentityProvider {
  readonly name: 'supabase' | 'better-auth' | (string & {});
  authenticate(input: AuthStep): Effect<AuthOutcome, AuthError>;
  linkIdentity(userId: UserId, proof: LinkProof): Effect<LinkedIdentity, AuthError>;
  unlinkIdentity(userId: UserId, identityId: string): Effect<void, AuthError>;
  refreshUpstream(grant: UpstreamGrant): Effect<UpstreamGrant, UpstreamExpired | UpstreamUnknown>;
  revokeUpstream(grant: UpstreamGrant): Effect<void, ProviderUnavailable>;
  factors(userId: UserId): Effect<FactorSummary[], ProviderUnavailable>;
  // Credential IDs for WebAuthn allowCredentials. Never returns public keys or counters.
  passkeys(userId: UserId): Effect<PasskeySummary[], ProviderUnavailable>;
  enrollFactor(userId: UserId, request: FactorEnrollment): Effect<FactorChallenge, AuthError>;
}

type AuthOutcome =
  | { kind: 'authenticated'; providerSubject: string; userId: UserId;
      aal: 'aal1' | 'aal2'; amr: AuthMethod[]; grant?: UpstreamGrant }
  | { kind: 'challenge'; challenge: MfaChallenge }
  | { kind: 'rejected'; reason: 'invalid' | 'locked' | 'unverified' | 'unprovisioned' };
```

* **Subject mapping.** Each adapter maps its provider subject to a `userId`. A
  missing mapping is `rejected: 'unprovisioned'`.
* **Provisioning.** Through P2, user creation stays with the existing
  `auth.users` triggers. Moving provisioning out of Supabase is a P3 work item
  with its own transactional function; see the rollout page.
* **One refresh owner per grant.** Only the device object that holds a grant
  refreshes it, serialized there. `UpstreamUnknown` (a refresh whose outcome
  was lost) is reconciled by one bounded retry with the same grant, then the
  session is signed out. It is never retried blindly.
* **Grant custody.** `UpstreamGrant` is encrypted with AES-256-GCM under
  `TTR_SESSION_UPSTREAM_KEY`, with `dev` and `sid` as associated data. Only the
  trusted data adapter ([rollout page](https://docs.tuturuuu.com/platform/architecture/tuturuuu-session-rollout.md#5-database-access-and-rls))
  receives a decrypted upstream access token, and only per request.
* **Linking** needs proof of both identities, as
  [OAuth sign-in](https://docs.tuturuuu.com/platform/architecture/authentication.md#oauth-sign-in)
  requires. A matching email alone never links accounts.
* **Uniform controls.** Rate limits, lockouts and MFA assurance are enforced
  in the session service, so they behave the same whichever adapter runs.

**Supabase adapter (P1).** Wraps the provider-thin flow modules in
`apps/web/src/lib/auth`. `providerSubject` equals `userId`. The grant is the
Supabase session, and `revokeUpstream` signs that Supabase session out.

**Better Auth adapter (P3).** Runs Better Auth inside the session service
with its tables in a `better_auth` schema, keyed by the existing UUIDs. Better
Auth sessions stay internal to the adapter.

## 3. App identity

### Principal

```ts theme={null}
type Principal = {
  kind: 'user' | 'api_key' | 'service' | 'external_app';
  userId: UserId | null;
  sessionId: string | null;
  generation: number | null;
  stale: boolean;                // previous-generation read during rotation
  source: 'cookie' | 'bearer' | 'api_key' | 'service_binding';
  aal: 'aal1' | 'aal2';
  authTime: number;
  appId: string | null;          // mount or client the identity was issued for
  scopes: readonly Scope[];
};
```

A `Principal` says who the request is for. Workspace membership and action
permissions stay with the existing permission helpers, and step-up is a grant
(section 1), not a principal field.

### Package layout

| Entry point | Contents | May import |
| - | - | - |
| `@tuturuuu/session` | Types, cookie codec, expiry policy, errors | Effect, Zod, Web Crypto |
| `@tuturuuu/session/verify` | Identity assertion verification with an injected key source and clock | Same |
| `@tuturuuu/session/provider` | The adapter interface | Same |
| `@tuturuuu/session/next` | `getPrincipal()`, `requirePrincipal()`, `requireLiveSession()` | `next/headers` |
| `@tuturuuu/session/worker` | `withPrincipal(handler)` for plain Workers and vinext families | Cloudflare types only |
| `@tuturuuu/session/start` | Middleware for TanStack Start satellites through `@tuturuuu/start-bridge` | Start bridge |

Portable entry points have no framework or Cloudflare runtime imports, no
request globals, no implicit network fetch and no signing keys. A boundary test
parses the module graph reachable from every entry point and enforces it.
An ephemeral-key test issuer lives in `packages/session/src/testing.ts`. It is
not a package entry point, and creating an issuer requires `VITEST=true`. The
boundary test parses every tracked JavaScript and TypeScript file in `apps` and
`packages` whose text matches a `testing` specifier prefilter, and fails if a
non-test file among them imports the issuer. Escaped or computed specifiers can
miss that prefilter. The `VITEST` check guards against accidental use and is not
a security boundary; isolation comes from keeping the issuer out of every entry
point and from verifiers trusting only configured keys. Only the verifier can mark an object as a verified assertion, and
`principalFromAssertion` accepts nothing else.

Supabase and Better Auth code live only in the session service.

### Trusted ingress

A mount Worker trusts `x-ttr-identity` only when the request arrived through
the gateway's service binding:

* **No public ingress.** A mount whose reader flag is `shadow` or
  `first-party` has no zone route, custom domain, `workers.dev` or preview
  URL. A CI check on the app's Worker configuration enforces it. Today some
  apex paths are zone routes straight to their Worker; those move behind the
  gateway before that app's reader leaves `supabase`.
* **Exact routing.** The gateway dispatches from an exact host and route
  allowlist, rejects unknown hosts, and handles assets and WebSocket upgrades
  on the same path.
* **Header hygiene.** The gateway deletes every client-sent `x-ttr-*` header
  and the session cookie before dispatch, and before logging.
* **Bridge backstop.** `packages/start-bridge` runs with
  `unknownHost: 'reject'`. On every request it strips `__Host-ttr_session`,
  drops any app `Set-Cookie` for that name, and deletes `x-ttr-identity` that
  fails verification. The P0 Supabase-cookie fences stay in force during
  dual-run.
* **Subdomain hosts.** A subdomain app holding child sessions gets the same
  gateway in front of it before its reader leaves `supabase`.

### Resolution

1. The gateway checks the cookie's codec without any key and, for an unsafe
   method with a cookie, enforces CSRF (see the rollout page); a failed check
   means no assertion. It classifies ingress and calls the auth Worker's
   `GatewayEntry.resolveForMount` with its caller key.
2. The auth Worker checks the cookie MAC before any Durable Object call, then
   resolves the device, its active session and the user's epoch. It may cache
   a successful resolution of a `read` route for up to 5 seconds in its own
   isolate, keyed by the SHA-256 of the cookie value and the host. It never
   caches a failure or any other route class. On every cache hit it re-runs
   the route's class and expected-account checks from its current registry
   and signs a new assertion for the requesting mount, so a cached entry
   never skips `account_mismatch`.
3. The auth Worker signs `x-ttr-identity` for this mount and request, and the
   gateway forwards it.
4. The mount's adapter verifies it with `verifyIdentityAssertion` and builds a
   `Principal`. Sensitive operations, and anything that mints a credential, also
   call `requireLiveSession()`, which asks the session service and fails closed.
5. A bearer request (`Authorization: Bearer`) skips the cookie path. The gateway
   or the app verifies the access token or resolves the workspace API key, and
   ignores cookies.

No runtime may resolve a session outside the gateway path, and that is a
precondition, not a property of today's gateway, which still forwards some
paths to `WEB_ORIGIN` and leaves some apex paths on direct zone routes.
Before any reader leaves `supabase`, APEX confirms that no session-bearing app
has a direct zone route and that no session-bearing path reaches `WEB_ORIGIN`.
Web family Workers that own auth routes call the auth Worker's `WebEntry` over
a service binding with their own caller key; see
[Tuturuuu session auth Worker](https://docs.tuturuuu.com/platform/architecture/tuturuuu-session-auth-worker.md).

### Identity assertion profile

The header and claims sets are closed: any member not listed here is rejected.

| Member | Type and rule |
| - | - |
| Header `alg` | Exactly `ES256`. The signature is the 64-byte JWS `r‖s` form, verified with a public P-256 ECDSA key |
| Header `typ` | Exactly `ttr+identity` |
| Header `kid` | String matching `[A-Za-z0-9_-]{1,64}`. Keys come only from the injected key source for the identity class |
| `iss` | String, equal to the verifier's configured issuer |
| `env` | `production`, `staging` or `local`, equal to the verifier's environment |
| `aud` | One string `mount:<appId>`, equal to the verifier's mount. Arrays are rejected |
| `sub` | Lowercase canonical UUID |
| `sid`, `jti` | 16 bytes in canonical base64url (22 characters) |
| `gen` | Integer from 0 to 2147483647 |
| `src` | `cookie` or `bearer` |
| `stale` | Boolean |
| `aal` | `aal1` or `aal2` |
| `amr` | Array of 1 to 8 distinct values from `pwd`, `otp`, `totp`, `passkey`, `oauth`, `sso`, `device_approval`, `qr` |
| `auth_time`, `iat`, `exp` | Non-negative safe integers in seconds. `auth_time <= iat < exp`, `exp - iat <= 60`, `iat <= now + 5`, and `now < exp` with no tolerance past `exp` |
| `ipp` | Optional. An IPv4 `/24` with a zero last octet, or an IPv6 `/48` with zero host bits in canonical RFC 5952 form. Never a full address |
| Encoding | At most 4 KiB, three canonical base64url segments, JSON objects only, duplicate member names rejected (including escaped spellings), `__proto__` treated as an ordinary member. Numbers must be canonical decimal safe integers: no fraction, exponent or `-0` |

The auth Worker caps `exp` at the earliest of the session's idle, absolute and
parent deadlines, and for a `stale` assertion at the end of the grace window.
No tolerance extends a deadline.

Assertions are not single use. They only travel from the auth Worker
through the gateway to the mount over service bindings, so an outside party cannot present one. A mount that misuses
its own assertion is already inside its own boundary, and `aud` keeps it from
using that assertion at another mount.

```ts theme={null}
// @tuturuuu/session/verify
type KeySource = {
  get(kid: string): Promise<
    | { key: CryptoKey; class: TokenClass; notBefore: number; notAfter: number }
    | null
    | 'unavailable'
  >;
};

function verifyIdentityAssertion(
  token: string,
  options: {
    issuer: string;
    environment: 'production' | 'staging' | 'local';
    audience: `mount:${string}`;
    keys: KeySource;          // injected; trusted keys only, never from the token
    now: () => number;        // seconds
  }
): Promise<
  | { ok: true; assertion: VerifiedAssertion }
  | { ok: false; reason: 'malformed' | 'header' | 'signature' | 'issuer' | 'environment'
      | 'audience' | 'type' | 'time' | 'claims' | 'unknown_key' | 'key_type'
      | 'keys_unavailable' }
>;
```

A successful result proves only that a trusted identity-class key signed these
claims, for this issuer, environment and mount, and that the verifier's clock
is inside the accepted window. It does not prove how the request arrived, that
the session is still live, or that the action is authorized.

The function never throws for a bad token, makes no network call and needs no
signing key. A key source that returns `null` gives `unknown_key`. A key source
that returns `'unavailable'` or throws gives `keys_unavailable`. A key that is
not a public P-256 ECDSA verification key gives `key_type`. A key of another
class, or a token with `iat` before the key's `notBefore` or verified at or
after its `notAfter`, gives `unknown_key`. Every failure is a rejection.

## 4. Service tokens and credential families

### Token service

| Property | Rule |
| - | - |
| Algorithm | ES256 (P-256) |
| Keys | Private keys only in the auth Worker's secrets (`TTR_TOKEN_SIGNING_KEYS`), one active key per class family. The cookie MAC keys, the pepper and the upstream grant key are auth Worker secrets too; the gateway's only session secret is its caller key, beside its existing `TRUSTED_PROXY_ORIGIN_SECRET` for Web's visitor IP proof. Verifiers get public keys through an injected key source |
| JWKS | `https://tuturuuu.com/.well-known/jwks.json` for external verifiers, `Cache-Control: public, max-age=300`. Internal Workers receive keys through configuration, not a runtime fetch |
| Rotation | Every 90 days. A new key is published 7 days before it signs. A retired key stays published for the longest token lifetime plus 1 day |
| Compromise | Remove the `kid` from every key source and the JWKS, then rotate. Verifiers reject that `kid` within the JWKS cache bound (5 minutes) or at once for configuration-fed Workers |
| Claims | `iss`, `env`, `sub`, `aud`, `iat`, `exp`, `jti`, and a `typ` header per class. Verifiers reject any other `typ` |

| Class (`typ`) | Holder | Lifetime | `aud` |
| - | - | - | - |
| `ttr+identity` | Gateway to mount, per request | ≤ 60 s | `mount:<appId>` |
| `ttr+s2s` | Worker to Worker over HTTP | 5 min | `service:<name>` |
| `ttr+realtime` | Browser, one topic | ≤ 60 s for channels, ≤ 10 min for meet and chat joins | `realtime:<service>` plus a `topic` claim |
| `ttr+access` | Mobile, CLI, external app | 5 min | The resource server, `https://tuturuuu.com/api`. The client is `azp` |
| `ttr+stepup` | A Worker that must check a step-up offline, such as the secrets vault share service | ≤ 5 min | `stepup:<service>`, a prefix no other class uses. Carries `act` (the action), `nonce` (a single-use nonce the receiving service issued for its stored challenge), `sid`, `gen`, `amr` and `auth_time`. The receiving service enforces single use of `jti` and `nonce` until `exp`. Registered `act` value: `vault.pin-eval` |

Refresh tokens are never JWTs. They are opaque, single-use secrets stored as
HMACs in the session row and rotated on every use. Reusing a rotated refresh
token revokes the whole session family.

### Credential families

| Family | Design |
| - | - |
| **Satellite child session** (subdomain hosts) | The destination host starts a handoff: it sets a `__Host-ttr_flow` nonce on its own host and sends the nonce's hash with its registered origin and callback. Web, after its own CSRF and session checks, issues a code bound to the nonce hash, the exact origin and callback, the parent `sid`, generation and epoch, valid 60 s. The destination redeems it server to server with the nonce from its own cookie. Redemption consumes the code and creates the child row in the parent's device object in one serialized step, after checking the parent is live. The child cookie is host-only, its expiry never exceeds the parent's, and every resolution checks the parent. Child logout revokes only the child; the upstream grant belongs to the parent. The app-only logout marker and explicit re-entry rules stay as in [Shared session](https://docs.tuturuuu.com/platform/architecture/shared-session.md#logout-confirmation-and-app-scope). A same-origin mount needs no handoff |
| **External apps** | OAuth 2.0 authorization code with S256 PKCE only, exact registered redirect URIs, the existing hashed client secret, and atomic one-time code consumption. Consent needs a step-up grant bound to the client and scopes. `ttr+access` has `aud` = the API and `azp` = the client. Every refresh re-checks client status, consent, user membership, scopes and `allowedWorkspaceIds`, intersecting with the current values rather than copying the original grant. Resource handlers check scopes and workspace restrictions on each request |
| **CLI** | Device authorization (RFC 8628). The CLI holds a secret `device_code`. The user enters an 8-character `user_code` on Web. Codes last 10 minutes; polling has an interval with `slow_down`; wrong `user_code` attempts are limited per account and per IP prefix. The approval page shows the client name, the device name it reported and the request's coarse location, then asks for explicit confirmation and a step-up grant bound to that `user_code`. Redemption is one time and bound to that approval. The CLI gets `ttr+access` and a rotating refresh in a `cli` session |
| **Mobile** | The existing native sign-in endpoints return `ttr+access` and a rotating refresh in a `mobile` session; the app stops calling Supabase directly. The refresh is bound to the device approval key registered through the existing attested enrollment. Each refresh sends a JWS proof over the method, URL, refresh family, refresh token hash, `iat` and `jti`. `iat` must be within 60 s and `jti` is single use, stored in the device object. If the same old refresh token and key arrive within 30 s after a successful rotation, the object returns the same new pair it stored (encrypted) instead of treating it as reuse, so a lost response does not advance the family twice. Replacing the device key needs a fresh sign-in and revokes the old family |
| **QR login** | A separate challenge type for browsers. The browser that creates the challenge gets a redemption secret in `__Host-ttr_flow`; the QR shows only the challenge ID and an approval number. A signed-in phone approves with its device approval key after showing the origin, browser and number, using a step-up grant. Only the initiating browser, presenting its flow secret, can redeem it. Redemption is atomic and ends in a server-set `__Host-ttr_session`. Browser challenges have no native-poller redemption path |
| **Realtime** | `ttr+realtime` tickets verified through the realtime Workers' key source. Admission and every lease renewal check the session's live state. A lease ends at most 5 minutes after the ticket's `iat`, so a revoked session disconnects within 5 minutes of its ticket's issue, and the realtime Worker closes the connection when the lease ends |
| **Workspace API keys** | Unchanged (`ttr_<hex>`, scrypt). They resolve to a principal of kind `api_key` |

### Mapping the existing credentials

Every family except Supabase's own JWT signs today with a shared symmetric
secret (HS256 or HMAC-SHA-256), and Tuturuuu publishes no JWKS. With one
asymmetric token service, a verifier never holds a key that can mint.

| Today | Where | Becomes |
| - | - | - |
| Supabase cookie `sb-<ref>-auth-token*` | `packages/supabase/src/next/*` | `__Host-ttr_session`. The Supabase session becomes the upstream grant |
| Cross-app handoff token (opaque, single use, at most 300 s) | `public.cross_app_tokens`, `generate-app-tokens`, `cross-app/server.ts` | The child-session handoff above |
| Satellite app session (`tuturuuu_app_session*`, `ttr_app_` HS256, 8 h and 30 d) | `app-coordination-token.ts`, `app-session-core.ts` | The child session plus `ttr+identity`. The app-coordination secret retires once no reader accepts `ttr_app_` |
| External-app exchange (PKCE, `ttr_app_secret_`, 8 h bearer) | `api/v1/auth/app-token/exchange`, `external-app*.ts`, `refresh-family.ts` | The external-app OAuth flow above |
| CLI tokens (`cli:access` 8 h, `cli:refresh` 90 d) | `cli-session.ts`, `api/cli/auth/*` | The device authorization flow above |
| Mobile Supabase session in Keychain or Keystore | `apps/mobile/lib/data/*`, `api/v1/auth/mobile/*` | The mobile flow above |
| QR login (120 s challenge, magic-link session) | `lib/auth/qr-login.ts`, `public.qr_login_challenges` | The browser QR challenge above |
| Realtime tickets (HMAC per service) | `packages/realtime/src/*/token.ts`, `*-realtime` Workers | `ttr+realtime`. The per-service HMAC secrets retire |
| Saved-account vault (AES-GCM Supabase sessions per device) | `lib/auth/multi-account/*`, `private.web_account_*` | Sibling sessions in the `BrowserDevice` object |
| Session list RPCs over `auth.sessions` | `/api/v1/users/sessions` | `/api/v1/auth/sessions`, with the old route as a shim during P2 |
| Refresh replay sets in Redis | `refresh-replay.ts`, `cli:refresh:used` | Refresh state in the device object |

Rate limits use the existing `apps/abuse-guard` Durable Objects. Sign-out,
password change, MFA reset, MFA or passkey removal, account deletion, the
admin "compromised" action and revoke-all keep revoking AI temporary auth
tokens and outstanding handoff codes.


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