# Authentication

> Register your app once, then connect users with browser sign-in or the device flow.

Public reads need no authentication. The Protected API (`/account`,
`/notifications` and `/relationships`) acts for one Mediux user and needs an
access token that user approved. Mediux uses standard OAuth,
so any OAuth library works.

## The short version

1. [Register your app](#register-your-app) once and copy its client ID.
2. Pick the recipe that fits where your app runs:

   | Your app                                                          | Recipe                                              |
   | ----------------------------------------------------------------- | --------------------------------------------------- |
   | A website or service you host                                     | [Browser sign-in](#browser-sign-in)                 |
   | A CLI or desktop tool on the same computer as the browser         | [Browser sign-in](#browser-sign-in), on `localhost` |
   | A tool on a server, in Docker, on a TV, or a self-hosted web page | [Device flow](#device-flow)                         |
   | Your own script                                                   | [Device flow](#device-flow)                         |

3. Send the access token as `Authorization: Bearer ACCESS_TOKEN`.

Run the flow and your API calls from your server or app, not from a web page's
JavaScript. Keep tokens out of source control and logs.

## Register your app

Register at [Account → Apps](https://mediux.io/account/apps/) with a verified
email. You do this once: everyone who uses your app connects their own account
to it.

- **Name, description and homepage** are shown to people when they connect.
- **Callback URLs** are for browser sign-in. Use an HTTPS URL for a website, or a
  `localhost` / `127.0.0.1` URL (or a reverse-domain app URL such as
  `com.example.app:/callback`) for a tool on the user's own computer. Register
  the exact URL, including the port.
- **Enable device flow** for tools that can't receive a callback.

An app can use both. Mediux gives you a **client ID**, which isn't secret: you
can ship it in your code, including open source. If every callback URL is an
HTTPS website and device flow is off, you also get a **client secret** to keep on
your server; you can regenerate it at any time without disconnecting anyone. Forks
and redistributions of an open-source tool must register their own app.

The issuer is `https://mediux.io/api/auth`; its
[metadata document](https://mediux.io/api/auth/.well-known/oauth-authorization-server)
lists every endpoint.

## Browser sign-in

Send the user's browser to Mediux, then exchange the code it brings back.

1. Create a random `state` and a PKCE verifier, and keep both for the callback.
2. Redirect the browser to the authorization endpoint:

   ```text
   https://mediux.io/api/auth/oauth2/authorize?response_type=code&client_id=CLIENT_ID&redirect_uri=https%3A%2F%2Fapp.example%2Fcallback&resource=https%3A%2F%2Fapi.mediux.io&scope=lists%3Aread%20offline_access&code_challenge=BASE64URL_SHA256_OF_VERIFIER&code_challenge_method=S256&state=STATE
   ```

3. The user signs in and approves. At your callback, check `state` matches and
   there is no `error`, then exchange the code:

   ```sh
   curl --request POST \
     https://api.mediux.io/api/auth/oauth2/token \
     --user "$CLIENT_ID:$CLIENT_SECRET" \
     -H 'Content-Type: application/x-www-form-urlencoded' \
     --data-urlencode 'grant_type=authorization_code' \
     --data-urlencode "client_id=$CLIENT_ID" \
     --data-urlencode "code=$CODE" \
     --data-urlencode "redirect_uri=$REDIRECT_URI" \
     --data-urlencode "code_verifier=$CODE_VERIFIER" \
     --data-urlencode 'resource=https://api.mediux.io'
   ```

   Apps without a secret leave out the `--user` line.

**A local CLI or desktop tool** does the same with a `localhost` callback: start
a small listener on the registered port, open the authorization URL in the
user's browser, and read the code when the browser comes back. The user just
approves; there's nothing to type.

## Device flow

For tools whose browser is somewhere else: a server, Docker, a TV, or a
self-hosted web page at an address like `http://192.168.1.20:8080`.

1. Ask for a code:

   ```sh
   curl --request POST \
     https://api.mediux.io/api/auth/device/code \
     -H 'Content-Type: application/x-www-form-urlencoded' \
     --data-urlencode "client_id=$CLIENT_ID" \
     --data-urlencode 'scope=lists:read offline_access' \
     --data-urlencode 'resource=https://api.mediux.io'
   ```

2. Show the user where to go. The response has `verification_uri`
   (`https://mediux.io/link`), `user_code` (such as `BCDFGHJK`; show it as
   `BCDF-GHJK`), and `verification_uri_complete`, which carries the code:

   - On a screen or in a log, show _Go to mediux.io/link and enter BCDF-GHJK_,
     plus `verification_uri_complete` as a link or QR code.
   - In a self-hosted web page, open `verification_uri_complete` in a new tab
     for them, so they don't type anything.

   Codes last ten minutes and work once.

3. While the user approves, poll from your server every `interval` seconds:

   ```sh
   curl --request POST \
     https://api.mediux.io/api/auth/oauth2/token \
     -H 'Content-Type: application/x-www-form-urlencoded' \
     --data-urlencode 'grant_type=urn:ietf:params:oauth:grant-type:device_code' \
     --data-urlencode "client_id=$CLIENT_ID" \
     --data-urlencode "device_code=$DEVICE_CODE"
   ```

   Keep polling on `authorization_pending`, wait longer on `slow_down`, and stop
   on `access_denied` or `expired_token`. Success returns your tokens.

### Example: your own script

Register an app with device flow on, then:

```js
const API = "https://api.mediux.io";
const CLIENT_ID = "YOUR_CLIENT_ID";
const form = (body) => ({
  method: "POST",
  headers: { "Content-Type": "application/x-www-form-urlencoded" },
  body: new URLSearchParams(body),
});

const code = await (
  await fetch(
    `${API}/api/auth/device/code`,
    form({
      client_id: CLIENT_ID,
      scope: "lists:read offline_access",
      resource: `${API}`,
    }),
  )
).json();
console.log(`Open ${code.verification_uri_complete}`);

let tokens;
while (!tokens) {
  await new Promise((done) => setTimeout(done, code.interval * 1000));
  const result = await (
    await fetch(
      `${API}/api/auth/oauth2/token`,
      form({
        grant_type: "urn:ietf:params:oauth:grant-type:device_code",
        client_id: CLIENT_ID,
        device_code: code.device_code,
      }),
    )
  ).json();
  if (result.access_token) tokens = result;
  else if (result.error !== "authorization_pending")
    throw new Error(result.error);
}

const me = await fetch(`${API}/account`, {
  headers: { Authorization: `Bearer ${tokens.access_token}` },
});
console.log(await me.json());
```

## Permissions

Ask only for what your app needs. Each scope is independent:

| Scope                  | Access                                                                      |
| ---------------------- | --------------------------------------------------------------------------- |
| `relationships:read`   | Read follows and hides.                                                     |
| `relationships:manage` | Read and manage follows and hides (includes read).                          |
| `lists:read`           | Read the user's Lists, including private and subscribed Lists.              |
| `lists:write`          | Create and edit Lists, add and remove items, and subscribe (includes read). |
| `notifications:read`   | Read the user's notifications and mark them read.                           |

Add `offline_access` to get a refresh token. Apps can't upload or change artwork, Sets, Boxsets or
Loadouts, delete Lists, change Likes or manage the account: owners do those on
mediux.io. Apps can unfollow and unhide. Any token can call [`GET /account`](https://docs-preview.mediux.io/api/reference/account-identity/get.md) for the
user's ID and username.

The user sees your app's name, developer and permissions, a note that Mediux
hasn't reviewed the app, and a warning on permissions with lasting effects. Check
the `scope` in the token response: it lists what the user approved. To ask for
more later, connect again.

## Tokens

- Access tokens last one hour.
- Refresh tokens rotate: each refresh returns a new one, which you save before
  using. A connection lasts until the user disconnects it, or until it goes 90
  days without a refresh.
- Two refreshes a few seconds apart get the same result. Reusing an old refresh
  token later revokes the connection.

```sh
curl --request POST \
  https://api.mediux.io/api/auth/oauth2/token \
  -H 'Content-Type: application/x-www-form-urlencoded' \
  --data-urlencode 'grant_type=refresh_token' \
  --data-urlencode "client_id=$CLIENT_ID" \
  --data-urlencode "refresh_token=$REFRESH_TOKEN"
```

To disconnect from your side, revoke the refresh token at
`/api/auth/oauth2/revoke` with `token` and `token_type_hint=refresh_token`. Apps
with a secret add `--user "$CLIENT_ID:$CLIENT_SECRET"` to token and revoke calls.

## When a connection ends

People can disconnect your app in Account → Apps, and Mediux can disable an app
that misuses the API. Either way, refreshes and writes stop straight away and
reads stop within 60 seconds. Treat a `401` or `403` as the end of the
connection and offer to connect again.

## Endpoints

| Purpose                                 | URL                                                                 |
| --------------------------------------- | ------------------------------------------------------------------- |
| Metadata                                | `https://mediux.io/api/auth/.well-known/oauth-authorization-server` |
| Browser sign-in                         | `https://mediux.io/api/auth/oauth2/authorize`                       |
| Device code                             | `https://api.mediux.io/api/auth/device/code`                        |
| Code entry for people                   | `https://mediux.io/link`                                            |
| Tokens (exchange, refresh, device poll) | `https://api.mediux.io/api/auth/oauth2/token`                       |
| Revoke                                  | `https://api.mediux.io/api/auth/oauth2/revoke`                      |
