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

# Sessions and SSO

> Which tokens make up a session, how long they last, how they are refreshed, ended and revoked, the context switch and SSO between the web apps.

A session has two parts. The device holds the **GoTrue tokens** (Supabase Auth). Calls to horizon-api
use the **Horizon JWT**, an HS256 token signed by the API itself (`lib/jwt.ts`). On the web there is
also a **per-environment SSO cookie** shared by the apps (ADR 0014).

> [!WARNING]
>
> **What does not work as decided yet.** A `profile/me` refresh still extends the session (T-113), and
> the 2FA gate is inert. Each section has the details.

## The tokens

| Token | Issued by | Where it lives | What for |
| - | - | - | - |
| GoTrue `access_token` / `refresh_token` | Supabase Auth | Device (in the login payload as `token_ws` and `refresh_token_ws`) | Session with Supabase |
| Horizon JWT (`token` or `jwt`) | horizon-api, HS256 with `JWT_SECRET` | Device or SSO cookie | `Authorization: Bearer` on every API call |

Every sign-in method (password, provider, magic link) ends in the same `loginCommon` and returns the
same payload. Session-bearing responses are sent with `cache-control: no-store` and
`pragma: no-cache`. In deep links the tokens travel in the fragment (`#access_token=...`), never in the
query.

## Refresh with profile/me

`GET /api/v3/auth/profile/me`, with the JWT as bearer, returns a new JWT and the current payload,
including `has_created_password`. It keeps the `gotrue_sid` and answers `token_ws: ""`: clients keep
their Supabase token. It answers `401` when the JWT is missing, invalid, expired or revoked: a token
revoked by logout or by a revocation marker can never be exchanged for a new one (D-02). Limit: 60 per
hour per user.

> [!NOTE]
>
> **Pending (REQ-109, T-113).** Today `profile/me` issues a new token with a new expiry, so a chain of
> refreshes can extend the session. The decision is that the new token never expires after the one
> presented.

## Lifetime (TTL)

| | Value |
| - | - |
| Decided (D-110, REQ-114) | **30 days** |
| In code | `generateToken` caps `exp` at **30 days** after `iat`, whatever `JWT_EXPIRES_IN` says |
| Task | T-118, done (D-01) |

Tokens issued before the cap keep their one-year expiry. That is why revocation markers are kept for
400 days: they must outlive the longest token.

## Signing out

`POST /api/v3/auth/logout`, with the JWT as bearer and no body, answers `200 { ok: true }`. It is
idempotent: an already revoked session or a JWT without `gotrue_sid` also answers `{ ok: true }`. It
answers `401` only when the bearer is missing or malformed.

> [!WARNING]
>
> **Logout revokes the JWT (D-01).** Besides the bridged GoTrue session, logout blacklists the
> presented JWT's `jti` until its expiry, so the next call with it answers `401`. A JWT issued before
> tokens carried a `jti` stays valid until it expires. On MaihueGO sign-out is still local: the app
> clears its state. Making the app's five logout paths share `clearLocalSession` is T-207, in progress.

### When MaihueGO gets a 401

The app clears the local session **only** when the call carried the stored bearer **and** the body
says the token was rejected («Invalid or expired token», «The token has been revoked», among others).
It never does so on a `403`. It clears session, accounts, plans, profile, courtesy flags and the query
cache, shows the session-expired toast and goes back to `/(auth)/auth`. Several parallel `401`s sign
out once (D-122, D-124).

## Revocation per login

`lib/auth/session/session-revocation.ts` stores one marker per login (`revokeSessionsBefore`): any
token issued before that marker is rejected. When validating a token, the API checks it in Redis
together with the `jti` blacklist. It is used by:

* Changing the password with «Cerrar sesión en los demás dispositivos»: the device that made the
  change receives a new JWT. The same change also ends the login's other GoTrue sessions through the
  `auth_end_login_sessions` function (service role only), so a device that kept its Supabase refresh
  token cannot exchange it for a new Horizon JWT.
* Apple `consent-revoked` and `account-delete` notifications: every session of the login is revoked.
* A login deleted, soft-deleted or banned in Supabase Auth through any channel (Horizon, the Supabase
  dashboard, SQL): a trigger on `auth.users` records the event and the `auth/login-revocation` cron
  writes the marker within about two minutes (D-01).

Routes behind a public permission that read the bearer themselves (`profile/me`, `permissions/me`,
`abandon-registration`) run the same check, so a revoked token is refused there too (D-02).

## Context and organization switch

| Method and path | What it does |
| - | - |
| `GET /api/v3/auth/context` | Returns the person account, the organizations it may act for and the one the token names |
| `POST /api/v3/auth/context` | Body `{ organization }`. Switches organization and **re-issues** the token; `null` goes back to the person context. `403` if not an active member |
| `POST /api/v3/auth/context/staff` | Staff step. With the `account-staff-access` flag it re-issues the token for the staff company keeping its expiry, or answers `403 STAFF_ACCESS_DENIED`. With the flag off it answers `{ enforced: false }` |

`context-switch` limit: 30 per 10 minutes per user.

## SSO between web apps

> [tab] Per-environment cookie
>
> The name comes from `APP_ENV`: `bbrands_session` in production and `bbrands_session_<tier>`
> elsewhere. That way each environment keeps its own session. A non-production environment never
> deletes the unsuffixed cookie.

> [tab] Same site (\*.bbrands.io)
>
> The app calls `GET https://auth.bbrands.io/api/auth/session` with credentials, which answers
> `200 { token }` or `200 { token: null }` (never 4xx), with CORS limited to
> `AUTH_ALLOWED_REDIRECT_HOSTS`. On `null`, the app redirects to `/auth/login?next=...`.

> [tab] Another domain (bbx)
>
> For apps outside `.bbrands.io`, such as the portal on `*.maihuego.com`:
>
> 1. horizon-authenticate signs `bbx` (HS256 with `jwt`, `nonce` and `next`), which expires in
>    **60 s**.
> 2. It redirects to the app with `?bbx=...`.
> 3. The app's `proxy.ts` (`@bbrandslab/auth-sso`, runs only on `?bbx`) calls
>    `POST /api/v3/auth/sso/exchange`.
> 4. The app sets its cookie `HttpOnly; Secure; SameSite=Lax` and redirects to the clean URL.
>
> An expired or reused `bbx`, or a backend that is down, ends in `?sso_error=exchange_failed`.
> Afterwards the app reads its own cookie with its `GET /api/auth/session`; without a session it
> redirects to sign-in once and, if that fails again, shows a retry screen. Logout goes through the
> app's own `/logout`.

`reauth=1` is sent only when the app rejected a cookie that is still valid (a client `401`); a missing
or expired cookie does not carry it (D-223, D-228). Consumer app variables: `APP_ENV`,
`AUTH_HMAC_SECRET` (32 characters or more, same environment), `AUTH_SESSION_COOKIE_DOMAIN` and
`NEXT_PUBLIC_ROUTE_API`.

## 2FA gate

ADR 0134 requires password, provider and magic-link sign-ins to go through the 2FA gate before `next`
on the web. **Today it is inert**: the `authenticate-two-factor-ui` flag is `false` in every environment, the
`auth/2fa/*` pages answer `404` and there is no second-factor backend (it comes with the Better Auth
migration). Sign-in redirects to `auth/2fa/verify` only when the backend answers `requires_2fa`, which
does not happen today.

## MaihueGO session store

The session store persists `hasCreatedPassword`. That value is no longer hardcoded to `true`: it is
refreshed from `profile/me` and decides whether Home shows the «Crea tu contraseña» alert and whether
Settings offers to create or change the password.

## See also

* [Password](https://docs.bbrands.io/maihuego/authentication/password.md)
* [Magic link](https://docs.bbrands.io/maihuego/authentication/magic-link.md)
* [Security and limits](https://docs.bbrands.io/maihuego/authentication/security.md)
* [Operations and maintenance](https://docs.bbrands.io/maihuego/authentication/operations.md)
* [Social login and internal SSO](https://docs.bbrands.io/oauth/social-login.md)


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