# Multi-factor authentication
Source: https://sovaria.in/docs/mfa

Let app users protect their account with an authenticator app or SMS codes and one-time backup codes: enrolment, signing in with a second factor, recovery, lockouts and turning it off.

With MFA on, signing in needs a password (or link, or provider) **and** something the user has. Sovaria supports **authenticator apps** (TOTP — Google Authenticator, 1Password, Authy…), **SMS codes**, **security keys** (FIDO2 / WebAuthn: YubiKey, Touch ID, Windows Hello) and **backup codes**. A user can have several factors, each with a friendly name. MFA for app users is available on every plan.

|  | Free | Pro | Ultra | Team | Enterprise |
|---|---|---|---|---|---|
| Multi-factor authentication for app users | ✓ | ✓ | ✓ | ✓ | ✓ |
| Hardware-key MFA | ✓ | ✓ | ✓ | ✓ | ✓ |

## Factors (Supabase-style API)

Each factor is enrolled, challenged and verified (supabase's `auth.mfa` names in every SDK, from `@sovaria/sdk` 0.7.0; TypeScript calls resolve to `{ data, error }`). The same calls finish a sign-in that asked for a second step. Over HTTP they are `/api/v1/auth/mfa/factors` (or `/auth/v1/factors` on your project URL).

TypeScript:
```ts
// Add an authenticator app (or factorType 'phone' with phone: '+15551234567', or 'webauthn')
const { data: factor, error } = await sovaria.auth.mfa.enroll({ factorType: 'totp', friendlyName: 'Work phone' })
showQrCode(factor.totp.qr_code)              // or let the user type factor.totp.secret

// Confirm it: the session becomes two-factor (aal2); the first factor also returns backup codes once
const { data } = await sovaria.auth.mfa.challengeAndVerify({ factorId: factor.id, code })
showOnce(data.backup_codes)

// Later: two steps when you need the challenge id (a phone factor is texted a code at challenge)
const { data: challenge } = await sovaria.auth.mfa.challenge({ factorId: factor.id })
await sovaria.auth.mfa.verify({ factorId: factor.id, challengeId: challenge.id, code })

const { data: { all, totp, phone } } = await sovaria.auth.mfa.listFactors()
const { data: aal } = await sovaria.auth.mfa.getAuthenticatorAssuranceLevel()   // { currentLevel, nextLevel }
await sovaria.auth.mfa.unenroll({ factorId: factor.id })                       // a verified factor needs an aal2 session
```

Python:
```python
factor = await sovaria.auth.mfa.enroll({"factor_type": "totp", "friendly_name": "Work phone"})
show_qr(factor["totp"]["qr_code"])
await sovaria.auth.mfa.challenge_and_verify({"factor_id": factor["id"], "code": code})
levels = await sovaria.auth.mfa.get_authenticator_assurance_level()   # {"current_level", "next_level"}
await sovaria.auth.mfa.unenroll({"factor_id": factor["id"]})
```

Swift:
```swift
let factor = try await sovaria.auth.mfa.enroll(factorType: "totp", friendlyName: "Work phone")
let qr = (factor["totp"] as? [String: Any])?["qr_code"] as? String
let session = try await sovaria.auth.mfa.challengeAndVerify(factorId: factor["id"] as! String, code: code)
let aal = try await sovaria.auth.mfa.getAuthenticatorAssuranceLevel()   // .currentLevel, .nextLevel
try await sovaria.auth.mfa.unenroll(factorId: factor["id"] as! String)
```

Kotlin:
```kotlin
val factor = sovaria.auth.mfa.enroll("totp", friendlyName = "Work phone")
val qr = factor["totp"].asMap()["qr_code"]
val session = sovaria.auth.mfa.challengeAndVerify(factor["id"].toString(), code)
val aal = sovaria.auth.mfa.getAuthenticatorAssuranceLevel()       // currentLevel, nextLevel
sovaria.auth.mfa.unenroll(factor["id"].toString())
```

Dart:
```dart
final factor = await sovaria.auth.mfa.enroll(friendlyName: 'Work phone');
final qr = (factor['totp'] as Map)['qr_code'];
final session = await sovaria.auth.mfa.challengeAndVerify(factorId: '${factor['id']}', code: code);
final aal = await sovaria.auth.mfa.getAuthenticatorAssuranceLevel();   // currentLevel, nextLevel
await sovaria.auth.mfa.unenroll('${factor['id']}');
```

| Call | Returns | Errors |
|---|---|---|
| `enroll({ factorType, friendlyName?, phone? })` | The unverified factor: `id`, `type`, for TOTP `totp.qr_code` / `secret` / `uri`, for a phone the masked number | `403 MFA_REQUIRED` (adding a factor when one is verified needs aal2), `422 TOO_MANY_FACTORS` |
| `challenge({ factorId })` | `{ id, type, expires_at }` (5 minutes); a phone factor is texted a code | `404` no such factor, `429` too many texts |
| `verify({ factorId, challengeId, code })` | A new two-factor (`aal2`) session, saved by the SDK; `backup_codes` the first time | `400 MFA_INVALID_CODE` (wrong code; a challenge is single-use, so start a new one or use `challengeAndVerify`), `400 CODE_ALREADY_USED`, `400 CHALLENGE_EXPIRED`, `423 MFA_LOCKED` |
| `listFactors()` | `{ all, totp, phone, webauthn }` (verified ones by type) | — |
| `getAuthenticatorAssuranceLevel()` | `{ currentLevel, nextLevel }`: ask for a code when next is `aal2` and current is `aal1` | — |
| `unenroll({ factorId })` | `{ id }` | `403` without an aal2 session for a verified factor |

- Adding a second factor needs an `aal2` session (verify an existing one first), so a stolen one-factor session can't plant its own authenticator.
- Verifying the first factor signs the user out of every other session and returns backup codes once.
- Security keys as a second factor need **Security keys (WebAuthn)** on under Auth › Multi-factor (plan key `auth.hardware_mfa`) and your passkey domain and origins set under Auth › Passkeys.
- Your **MFA attempt hook** sees every code (valid or not) and can refuse even a correct one ([Blocking hooks (before create, before sign-in)](https://sovaria.in/docs/auth-blocking-hooks)).

## Turn on an authenticator app

1. **Start enrolment** — For the signed-in user, `enroll` returns a secret, an `otpauth://` URI to show as a QR code, and **backup codes**.
```js
const { totp_uri, secret, backup_codes } = await sovaria.auth.mfa.enroll()
showQrCode(totp_uri)          // or let the user type `secret`
showOnce(backup_codes)        // they are never shown again
```
2. **Confirm with a code** — The user enters the 6-digit code from their app.
```js
await sovaria.auth.verifyMfa(code)
```
3. **Done** — `sovaria.auth.mfa.status()` now reports MFA on. Future sign-ins ask for a code.

## Sign in with a second factor

JavaScript:
```js
const result = await sovaria.auth.signIn(email, password)
if (result.mfa_required) {
  const code = await askForCode()                  // authenticator, SMS or a backup code
  await sovaria.auth.verifyMfa(code)               // 'totp' (default) or verifyMfa(code, 'phone')
}
// signed in, with a two-factor (aal2) session
```

After the password step the client holds only a short challenge token; nothing else works until the code is verified. A verified session is marked `aal2` in its token (`auth.jwt() ->> 'aal'`), so you can require it for sensitive actions.

## SMS codes

Users can add a phone number as a factor (`POST /api/v1/auth/mfa/phone/enroll`, then `verify-enrollment` with the code they receive). At sign-in, `POST /api/v1/auth/mfa/phone/challenge` sends a code and `verifyMfa(code, 'phone')` checks it. Codes are rate-limited per user to stop abuse and SMS costs.

## Backup codes and recovery

- Each backup code works once, in place of an authenticator code. Show them only at enrolment; Sovaria stores only hashes.
- `GET /api/v1/auth/mfa/backup-codes` reports how many are left; `POST /api/v1/auth/mfa/backup-codes/regenerate` issues a new set (the old set stops working).
- A user who lost their phone and codes can't pass MFA. Your team can **reset MFA** for them from the Users page after checking who they are.

## Built-in protection

- **Lockout:** 5 wrong codes within 5 minutes lock the factor for a while (`423` with `Retry-After`) — per user, so rotating IPs doesn't help an attacker.
- **No replay:** a code that was accepted can't be used again (`401 CODE_ALREADY_USED`).
- Turning MFA off needs a current code: `sovaria.auth.mfa.disable(code)`.

## Require MFA for every user

Turn on **Require MFA** under **Project Settings › Security** to make a second factor mandatory. A user who hasn't added one still signs in, but gets an **enroll-only session** (`mfa_enrollment_required: true`, no refresh token, 15 minutes) that can do one thing: set a factor up and verify it, which gives the full two-factor session. Every other request answers `403 MFA_ENROLLMENT_REQUIRED`. Anonymous users are never asked. The SDKs emit `MFA_ENROLLMENT_REQUIRED` from `onAuthStateChange`.

JavaScript:
```js
sovaria.auth.onAuthStateChange(async (event) => {
  if (event === 'MFA_ENROLLMENT_REQUIRED') {
    const { data: factor } = await sovaria.auth.mfa.enroll({ factorType: 'totp' })
    showQrCode(factor.totp.qr_code)
    await sovaria.auth.mfa.challengeAndVerify({ factorId: factor.id, code: await askForCode() })   // now fully signed in
  }
})
```

Passkey sign-ins that used the device’s fingerprint, face or PIN already count as two factors and pass ([Passkeys](https://sovaria.in/docs/passkeys)).

## Require a two-factor session for sensitive data

You can also leave MFA optional and require it only where it matters. A session that passed a second factor (or a passkey) carries `aal: "aal2"` in its token; one that didn't carries `aal1`. Check it in row-level security:

SQL:
```sql
-- Payouts can only be read and changed from a two-factor session
create policy "payouts need aal2" on payouts
  as restrictive
  for all
  to authenticated
  using ((auth.jwt() ->> 'aal') = 'aal2');
```

A **restrictive** policy is combined with your other policies using AND, so the owner check you already have still applies. In your app, send a user with an `aal1` session to the code prompt before showing those screens ([Row-level security and access](https://sovaria.in/docs/row-level-security), [Auth helpers in SQL](https://sovaria.in/docs/auth-helpers)).

## Project settings

Under **Users › Multi-factor** choose which second factors your users can add (authenticator apps are on by default; SMS is off until you turn it on and connect an SMS provider) and how many factors one user may have (10 by default).
