# API keys
Source: https://sovaria.in/docs/api-keys

The anon, service role and custom keys: what each can do, where to use it, and how to rotate and revoke keys.

Every request carries either an **API key** or a signed-in user's **session**. Keys belong to one project; using a key against another project is refused.

## Key types

| Key | Use it in | Access |
|---|---|---|
| Anon (publishable) | Browsers, mobile apps, public clients | An anonymous visitor: `auth.uid()` is empty and your policies decide everything. |
| Service role | Your servers and CI only | Full access; **bypasses row-level security** and the default rules (only a DENY rule you write stops it). Treat it like a database password. |
| Custom | One integration or job | A role you choose (admin, editor, or viewer — read-only) and an optional expiry; row-level security treats it as `anon`. |

> **Warning:** Anyone with the service role key can read and change all of the project's data. Never put it in frontend code, a mobile app or a repository. If it leaks, rotate it immediately.

## Sending a key

Use `apikey: <key>` or `Authorization: Bearer <key>`. The SDKs do this for you from the second argument of `createClient`.

## Create, rotate and revoke

- The full value of a new key is shown **once** — copy it into your secret store straight away.
- **Rotate** creates a replacement and revokes the old key; apps still using the old one stop working, so deploy the new value first.
- Owners and admins get an email whenever a key is created or revoked.

CLI:
```bash
sov keys list
sov keys create --name ci-deploy --role admin   # printed once
sov keys revoke <key-id>
```

cURL:
```bash
curl https://<project-ref>.sovarias.in/api/v1/apikeys \
  -H "Authorization: Bearer $ACCESS_TOKEN"
```

## Server code and CI

On a server, pass the service role (or a custom) key as the second argument of `createClient`. The key already names its project, so no org or project ids are needed. In CI, give the CLI the key through an environment variable instead of `sov login`; saved logins and linked projects are ignored while a key is set.

Node:
```js
import { createClient } from '@sovaria/sdk'

const sovaria = createClient(process.env.SOVARIA_URL, process.env.SOVARIA_SERVICE_ROLE_KEY)
const { rows } = await sovaria.data.sql('select count(*) from notes')
```

Python:
```python
import os
from sovaria import create_client

sovaria = create_client(os.environ["SOVARIA_URL"], os.environ["SOVARIA_SERVICE_ROLE_KEY"])
result = await sovaria.sql_query("select count(*) from notes")
```

CLI in CI:
```bash
# GitHub Actions: store the key as a repository secret
export SOVARIA_API_KEY="${{ secrets.SOVARIA_SERVICE_ROLE_KEY }}"
sov db migrations push                                  # apply pending .sql migrations
sov fn deploy ./functions/send-receipt --name send-receipt
```

`SOVARIA_ACCESS_TOKEN` works the same way for a short-lived user session token. Every HTTP route is also available as `sovaria.api.<area>.<method>` in both SDKs; both are generated from one API description, so they send identical requests.

## How Sovaria stores keys and passwords

- Service role and custom keys are stored only as a keyed hash (HMAC-SHA-256 with a server-side secret). Nobody, including Sovaria staff, can read them back; a lost key must be rotated.
- The anon key is public by design, so it is also kept encrypted (AES-256-GCM) so the console can show it again.
- User passwords are hashed with bcrypt (cost 12) and never stored or logged in plain text. MFA secrets are encrypted with AES-256-GCM; backup codes are bcrypt-hashed.
- OAuth provider secrets, function secrets and database credentials are encrypted at rest and never returned by the API after you save them.

## Verifying user sessions in your own backend

App-user access tokens are JWTs signed with your project's own key (**ES256**, P-256). Verify them in your own API with the public key set at `https://<project-ref>.sovarias.in/auth/v1/.well-known/jwks.json` — no call to Sovaria per request needed. Tokens last 15 minutes; the SDK refreshes them for you.

| Claim | Value |
|---|---|
| `iss` | `https://<project-ref>.sovarias.in/auth/v1` — check it, so a token from another project is refused. |
| `aud` | `authenticated` |
| `sub` | The app user's id (the same value as `auth.uid()` in SQL). |
| `role`, `app_roles`, `email` | The user's role and the app roles you assigned under **Authentication → Users**. |
| `exp`, `iat`, `jti` | Expiry, issue time and a unique token id. |

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

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

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

Python (PyJWT):
```python
import jwt

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

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