# Sessions and tokens
Source: https://sovaria.in/docs/sessions-and-tokens

How a signed-in session works: access and refresh tokens, automatic refresh and rotation, auth events in your app, devices, signing out everywhere, verifying tokens on your server and the session settings.

Signing in gives the app a **session**: a short-lived **access token** sent with every request, and a **refresh token** the SDK uses to get new access tokens. The SDKs handle all of this; this page explains what they do so you can reason about it.

(Diagram: A session over time)

## Access and refresh tokens

|  | Access token | Refresh token |
|---|---|---|
| Lives | 15 minutes by default (at most 60) | 7 days by default |
| Sent | With every request: `Authorization: Bearer …` | Only to `POST /api/v1/auth/refresh` |
| Format | A signed JWT (ES256) with `sub`, `email`, `role`, `app_roles`, `aal`, `exp` | Opaque |
| When used | — | Replaced on every refresh (rotation): each refresh token works once |

Rotation means a stolen refresh token is useful only until the real app refreshes; using an old refresh token fails. Signing out revokes the refresh token and the current access token at once: every server refuses that access token within 3 seconds. A normal refresh does not revoke the access token it replaces: that one keeps working until it expires, so requests already in flight (or a long Sovariq build acting as you) are not signed out.

**A session belongs to one environment.** A user who signs in to a staging environment (or a test account seeded there) gets a token for that environment only, and a refresh keeps it there. Used against production or another environment of the project, the request is refused with `403 TOKEN_ENVIRONMENT_MISMATCH` (realtime connections are refused the same way): sign in again in that environment. A request that names no environment runs in the token's own. Production accounts are project-wide, as before: they can sign in to a staging environment, and that sign-in gives a staging session.

## React to sign-in and sign-out

JavaScript:
```js
const stop = sovaria.auth.onAuthStateChange((event, session) => {
  // INITIAL_SESSION (right away), SIGNED_IN, TOKEN_REFRESHED, SIGNED_OUT
  if (event === 'SIGNED_OUT') router.push('/login')
  else setUser(session?.user ?? null)
})

const session = sovaria.auth.getSession()   // current session or null, no network call
// later: stop()

// supabase-js style works too:
const { data: { subscription } } = sovaria.auth.onAuthStateChange(handler)
subscription.unsubscribe()
```

Python:
```python
sub = sovaria.auth.on_auth_state_change(lambda event, session: print(event))
sub.unsubscribe()
```

`updateUser()` fires `USER_UPDATED`.

In browsers the session is kept in storage and survives reloads; a session that can't be refreshed (revoked, expired, user banned) fires `SIGNED_OUT`.

## Sessions and devices

A signed-in user can see and end their own sessions:

JavaScript:
```js
const sessions = await sovaria.auth.sessions.list()      // device, IP, last used
await sovaria.auth.sessions.revoke(sessionId)              // one
await sovaria.auth.sessions.revokeOthers()                 // everywhere but here
```

REST:
```bash
curl -s "$URL/api/v1/auth/sessions" -H "Authorization: Bearer $TOKEN"
curl -s -X POST "$URL/api/v1/auth/sessions/revoke-others" -H "Authorization: Bearer $TOKEN"
```

- Changing or resetting the password signs the user out on every other device.
- Banning or deleting a user ends all their sessions ([Users and app roles](https://sovaria.in/docs/users-and-roles)).
- Mobile apps register each device; signing a device out also stops its push notifications ([Sign-in for mobile apps](https://sovaria.in/docs/mobile-auth)).

## Session settings

Under **Authentication › Sessions**: access and refresh token lifetimes, a **time-box** (sessions end after a fixed time whatever happens), an **inactivity timeout** and **single session** (signing in elsewhere ends the old session). The last three need a paid plan.

|  | Free | Pro | Ultra | Team | Enterprise |
|---|---|---|---|---|---|
| Session time-box, inactivity timeout and single session | ✓ | ✓ | ✓ | ✓ | ✓ |

## Check a token on your own server

To accept Sovaria users in your own API, verify the access token with the project's public keys. Never decode it without checking the signature.

Node (jose):
```js
import { createRemoteJWKSet, jwtVerify } from 'jose'

const JWKS = createRemoteJWKSet(new URL('https://<project-ref>.sovarias.in/auth/v1/.well-known/jwks.json'))

export async function userFrom(req) {
  const token = req.headers.authorization?.replace(/^Bearer /, '')
  const { payload } = await jwtVerify(token, JWKS, { algorithms: ['ES256'] })
  return { id: payload.sub, email: payload.email, roles: payload.app_roles ?? [] }
}
```

Python (PyJWT):
```python
import jwt

jwks = jwt.PyJWKClient("https://<project-ref>.sovarias.in/auth/v1/.well-known/jwks.json")

def user_from(token: str) -> dict:
    key = jwks.get_signing_key_from_jwt(token)
    claims = jwt.decode(token, key.key, algorithms=["ES256"], options={"verify_aud": False})
    return {"id": claims["sub"], "email": claims.get("email"), "roles": claims.get("app_roles", [])}
```

> **Tip:** A verified token proves who the user is; it does not check revocation in real time. For actions that must respect a sign-out instantly, call `GET /api/v1/auth/me` with the token instead.

## Rotate the signing key

App-user tokens are signed with your project's own key, published at `/auth/v1/.well-known/jwks.json` on your project URL. Under **Project settings › API keys › App-user signing keys** (or `sov auth-keys`): **Publish standby key** adds the next key to the key set first, so backends that cache it pick it up; **Rotate** makes it sign new tokens while the old key keeps verifying for 24 hours; **Revoke** removes a standby or retired key from the key set at once (tokens it signed stop verifying). The active key can't be revoked.

CLI:
```bash
sov auth-keys standby        # publish the next key
sov auth-keys rotate --yes   # sign with it from now on
sov auth-keys revoke p.<project>.<kid> --yes
```
