# Sign in with hematite: OAuth for apps

How an app signs people in with hematite: OAuth 2.1 with PKCE, the scopes it can ask for, token lifetimes, one refresh at a time, and revoking tokens.

hematite is an OAuth 2.1 server. An app sends a person to hematite, they sign in and allow what the app asked for, and the app gets tokens that act as them, for those things only. The app never sees their password, and they can take it back.

> **Note: Your own app**
>
> An app needs a client id first: [create an app](https://hematite.gg/docs/developers/create-an-app) in
> Settings → Developers, with its return addresses, and come back here for the
> flow it sends people through.

## Try it here

Every endpoint in the [API reference](https://hematite.gg/docs/developers/reference/images) has a **Try it** tab. **Sign in to try**, in the bar, signs you in with the flow below, asking only to read; an endpoint that writes asks for its scope when you try it, and hematite shows you that scope marked **New**. It's your real account: a request that deletes something asks first. The tokens stay in that browser tab, and **Sign out** gives them up.

## The flow

The authorization code flow with PKCE, the only one hematite takes:

1. **Make a verifier and its challenge.** The verifier is a random secret the app keeps: 32 random bytes in base64url, 43 characters. The challenge is the base64url SHA-256 of it. PKCE is required, with `S256` only.
2. **Send the person to hematite's authorization page** with the request in its query. They sign in if they aren't, and see what the app asks for.
3. **They come back** to the app's `redirect_uri` with a `code`, the app's `state` and `iss`. Check that `state` is the one you sent and `iss` is hematite's API.
4. **Trade the code** at [`POST /oauth/token`](https://hematite.gg/docs/developers/reference/oauth#post-oauth-token), form-encoded, with the verifier. A code works once, within a minute.
5. **Call the API** with the access token: `Authorization: Bearer <token>`.

```text label="Authorization request"
https://hematite.gg/oauth/authorize
  ?client_id=your-app
  &redirect_uri=https%3A%2F%2Fyourapp.example%2Fcallback
  &response_type=code
  &scope=images%3Aread%20users%3Aread
  &state=k3Jx9Qe2pV7mZ0aT1bYw4g
  &code_challenge=E9Melhoa2OwvFrEMTJguCHaoeK1t8URWbuGJSstw-cM
  &code_challenge_method=S256
```

- `redirect_uri` has to be exactly one the app registered: another path, port or query is another address, and hematite sends nobody there ([return addresses](https://hematite.gg/docs/developers/create-an-app#return-addresses)).
- `scope` is the [scopes](#scopes) it asks for, separated by spaces.
- `state` is the app's own random value; hematite hands it back untouched, so the app knows the answer is for its request.
- `prompt=consent` shows the page even when it could be skipped ([asking again](#asking-again-and-for-more)).

Then the code, with the verifier:

```bash
curl -X POST https://api.hematite.gg/v1/oauth/token \
  --data-urlencode "grant_type=authorization_code" \
  --data-urlencode "code=$CODE" \
  --data-urlencode "redirect_uri=https://yourapp.example/callback" \
  --data-urlencode "code_verifier=$CODE_VERIFIER" \
  --data-urlencode "client_id=your-app"
```

```json title="200 OK"
{
  "access_token": "hmo_live_eTt4LxD0hR2mA9cQ_…",
  "token_type": "Bearer",
  "expires_in": 3600,
  "refresh_token": "hmr_live_Vq81sNbZ3kWfG6yP_…",
  "scope": "images:read users:read"
}
```

The tokens are in [hematite's format](https://hematite.gg/docs/developers/authentication#what-a-token-looks-like): `hmo_` an access token, `hmr_` a refresh token, each named by its public id. The token endpoint answers in OAuth's shape, not the API's envelope: the tokens at the top, or an `error` and `error_description` when it says no (`invalid_grant` for a code that's used, expired or not this app's). An app in a browser or on a phone sends no secret: PKCE proves it's the one that asked. An app on a server sends [its secret](https://hematite.gg/docs/developers/create-an-app#its-secret) too, with HTTP Basic or as `client_secret`.

## Scopes

A token can do what its scopes allow and nothing else. Each resource has a read and a write; `email` is a scope of its own, and without it the person's profile comes without their address or when they confirmed it. Each endpoint in the [API reference](https://hematite.gg/docs/developers/reference/images) says the scope it needs, under **App scope**.

| Scope | Lets an app |
|---|---|
| `images:read` | See your images and their details, private ones too |
| `images:write` | Upload images, and edit and delete yours |
| `folders:read` | See your folders and what's in them, private ones too |
| `folders:write` | Create folders, and edit and delete yours |
| `shares:read` | See your share links |
| `shares:write` | Change your share links |
| `comments:read` | Read comments, yours and on your images and folders |
| `comments:write` | Comment as you, and edit and delete your comments |
| `likes:read` | See what you've liked |
| `likes:write` | Like and unlike things as you |
| `notifications:read` | Read your notifications |
| `notifications:write` | Mark your notifications read and delete them |
| `users:read` | See your profile, upload settings and storage, and look up other users |
| `users:write` | Change your username, bio, picture and upload settings (never your email, password or privacy settings) |
| `email` | See your email address |

No app can change a person's password, email or privacy settings (whether their page is hidden, who sees their upload stats), or get at their sessions, upload tokens, billing or domains, whatever it was allowed; nor admin tools, or OAuth itself. With `users:read` it can still read those settings on the person's profile. An endpoint like that says **Not open to apps** under **App scope**, with the reason.

A request the token's scopes don't cover answers `403` with the code `OAUTH_INSUFFICIENT_SCOPE`, the scope it needs in `data.scope` and in the `WWW-Authenticate` header. An endpoint no app may call answers `403` with `OAUTH_ROUTE_DENIED` ([errors](https://hematite.gg/docs/developers/errors)). And some take a field from a person but not from an app: a profile update's `email`, `profile.hideProfile` and `profile.activityVisibility`, a user search filtering by `email`. The reference marks those fields **Apps can't send it**, and a request with one answers `403` with `OAUTH_FIELD_DENIED`, the fields in `data.fields`.

## Asking again, and for more

hematite remembers what a person allowed an app. A request for nothing beyond that skips the page and comes straight back with a code. One that asks for more shows the page, with the new scopes marked **New**. `prompt=consent` always shows it. Ask for every scope the app needs each time: the tokens of a sign-in carry the scopes that request asked for.

## Tokens

- **The access token** lives an hour. Send it as `Authorization: Bearer <token>`.
- **The refresh token** gets the next access token when that one runs out. It lives 30 days and works once, with [a short leeway](#one-refresh-at-a-time): each refresh hands out a new refresh token with the new access token, good for another 30 days.

```bash
curl -X POST https://api.hematite.gg/v1/oauth/token \
  --data-urlencode "grant_type=refresh_token" \
  --data-urlencode "refresh_token=$REFRESH_TOKEN" \
  --data-urlencode "client_id=your-app"
```

### One refresh at a time

Refresh tokens rotate. One used a second time was copied somewhere on its way, so hematite revokes that whole sign-in: every token of it stops working, and the person signs in again. So an app keeps one refresh in flight at a time, across browser tabs too: it holds a lock while refreshing (the Web Locks API), and the other tabs take the new tokens instead of refreshing again.

```ts title="refresh.ts"
// One refresh at a time across this browser's tabs. The tokens are read where every
// tab sees the newest, or handed round on a BroadcastChannel.
async function freshToken(stale: string): Promise<Tokens> {
  return navigator.locks.request("hematite-refresh", async () => {
    const current = await readTokens();
    // Another tab refreshed while this one waited for the lock.
    if (current.accessToken !== stale) return current;
    const next = await refresh(current.refreshToken);
    await saveTokens(next);
    return next;
  });
}
```

There's one leeway, for a tab that missed the new tokens by a moment (a duplicated tab still loading, a message that came late) and refreshes with the refresh token it has: one your app shows again within 30 seconds of its first use is exchanged once more. That refresh gets a pair of its own and the sign-in stays; the refresh token the first refresh gave stays valid too, and each rotates on its own from there. Only once: a third use, or a second one after 30 seconds, revokes the sign-in as above. Nor does it cover a tab the browser froze for minutes (kept in the back/forward cache, or paused in the background) that wakes up and refreshes with a token used long before: that still ends the sign-in. These docs' **Try it** tabs work this way too; after that, **Sign in to try** again.

A refresh that's refused (`invalid_grant`) means the sign-in is over: revoked, expired, or the person reset their password. Drop the tokens and sign in again.

## Revoking

[`POST /oauth/revoke`](https://hematite.gg/docs/developers/reference/oauth#post-oauth-revoke) gives a token up (RFC 7009). A refresh token takes its whole sign-in with it; an access token only itself. It answers `200` whether or not it knew the token, so it can't be used to test tokens. An app's sign out should revoke its refresh token.

```bash
curl -X POST https://api.hematite.gg/v1/oauth/revoke \
  --data-urlencode "token=$REFRESH_TOKEN" \
  --data-urlencode "token_type_hint=refresh_token" \
  --data-urlencode "client_id=your-app"
```

A password reset disconnects every app a person allowed, and so does a password change when they tick **Disconnect your apps too**.

## The server's metadata

Everything above, for an OAuth library to read, is at [`GET /.well-known/oauth-authorization-server`](https://hematite.gg/docs/developers/reference/oauth#get-well-known-oauth-authorization-server) (RFC 8414) on the API's origin: the authorization page, the token and revocation endpoints, the scopes, and what's supported.

```bash
curl https://api.hematite.gg/.well-known/oauth-authorization-server
```
