# Integrating OAuthMC

This guide shows how a platform connects to OAuthMC, chooses between code mode and link mode, builds a safe confirmation page, polls ticket status, and handles errors.

OAuthMC's HTTP API is server-to-server only. Never send an API key from `OAUTHMC_API_KEYS` to browser code or a mobile client.

## Verification flow

```mermaid
sequenceDiagram
    participant Platform
    participant OAuthMC
    participant Player

    Platform->>OAuthMC: POST /v1/tickets {name, mode, link_url?}
    OAuthMC-->>Platform: 201 {id, address, mode, status: "pending", expires_at}
    Platform-->>Player: Show server address (and code input in code mode)
    Player->>OAuthMC: Minecraft Login Start (username)
    Note over OAuthMC: Check open ticket + per-IP rate limit<br/>RSA + AES-128-CFB8 + Mojang hasJoined
    alt Code mode (or Minecraft < 1.21.6)
        OAuthMC-->>Player: Login Disconnect with code (XXXX-XXXX)
        Player->>Platform: Enter code in signed-in session
    else Link mode (Minecraft >= 1.21.6)
        OAuthMC-->>Player: Configuration Show Dialog (Open link + Copy code)
        Player->>Platform: Click Open link -> confirm POST in signed-in session
    end
    Platform->>OAuthMC: POST /v1/tickets/{id}/redeem {code}
    OAuthMC-->>Platform: 200 {uuid, name}
    opt Link mode
        OAuthMC-->>Player: Configuration Disconnect ("verified" message)
    end
```

## Code mode vs link mode

- **Code mode** (`mode: "code"`, the default) works on every supported Minecraft version (tested across 1.8.9–26.1). OAuthMC disconnects the player during Login with an 8-character code (`XXXX-XXXX`). The player types or pastes that code into your platform's form.
- **Link mode** (`mode: "link"` with `link_url`) targets Minecraft 1.21.6 and later (protocol `>= 771`). OAuthMC transitions the client to Configuration and displays a native dialog with **Open link** and **Copy code** buttons while holding the connection open. As soon as your platform redeems the ticket, OAuthMC disconnects the player with the `verified` message.

Players on versions older than 1.21.6—or joining when `OAUTHMC_MAX_HELD`, `OAUTHMC_MAX_HELD_PER_IP`, or mixed-tenant isolation triggers—receive a code-mode disconnect even for a link-mode ticket. Keep a manual code input on your platform alongside link mode so every player can finish verification.

## Building the link-mode confirmation page

Link mode shifts the code from manual typing to a browser navigation. That navigation is only safe when your platform enforces three rules:

1. **Put `{ticket}` and `{code}` in the URL fragment, not the query string.**
   Use a `link_url` such as:

   ```text
   https://example.com/account/minecraft/verify#ticket={ticket}&code={code}
   ```

   Browsers do not send URL fragments in HTTP requests, so the ticket ID and code never appear in reverse proxy logs, application logs, or `Referer` headers. Read `window.location.hash` on the client, keep `{ticket, code}` in `sessionStorage` if you need to redirect through sign-in, and clear the fragment immediately with `window.history.replaceState(null, '', '/account/minecraft/verify')`. Also send `Referrer-Policy: no-referrer` on the verification page.

2. **Bind every redeem to the authenticated session that created the ticket.**
   Store the active ticket ID against the signed-in user in your platform's database (for example, `minecraft_join_tickets(user_id, ticket_id, name)`). When the player opens the confirmation page, require an authenticated session and check that the ticket ID from the link matches the ticket owned by that session's user. Reject mismatches with `404` or `403` and never call `/redeem` on a ticket belonging to another user. See [Security model](https://docs.sculk.network/nightly/oauthmc/security.md#link-mode-requires-session-binding-on-the-platform) for the attack this prevents.

3. **Never redeem on `GET`.**
   Render a confirmation view showing the Minecraft username and the signed-in platform account, and perform the redeem on an explicit `POST` action protected by your platform's session and CSRF checks. Link previews, browser prefetchers, and accidental clicks must never complete account linking.

If your development environment runs on plain `http://` (so OAuthMC rejects `link_url` with `422 invalid_link_url`), catch `invalid_link_url` or `unsupported_mode` and fall back to creating a `mode: "code"` ticket instead of enabling `OAUTHMC_ALLOW_HTTP_LINKS` in production.

## TypeScript SDK example

The zero-dependency [`oauthmc`](https://docs.sculk.network/nightly/oauthmc/sdk/js.md) package works in Node.js 18+, Deno, Bun, and Cloudflare Workers.

```ts
import { OAuthMC, OAuthMCError, isValidMinecraftName } from 'oauthmc';

const oauthmc = new OAuthMC({
  baseUrl: process.env.OAUTHMC_URL ?? 'http://oauthmc:8080',
  apiKey: process.env.OAUTHMC_API_KEY!,
  timeoutMs: 5_000,
});

// 1. Start verification for a signed-in user.
export async function startVerification(userId: string, playerName: string) {
  if (!isValidMinecraftName(playerName)) {
    throw new Error('Invalid Minecraft username');
  }

  let ticket;
  try {
    ticket = await oauthmc.createTicket({
      name: playerName,
      mode: 'link',
      linkUrl: 'https://example.com/account/minecraft/verify#ticket={ticket}&code={code}',
      ttlSeconds: 900,
      maxAttempts: 5,
      metadata: { userId },
    });
  } catch (err) {
    if (err instanceof OAuthMCError && err.status === 422 && err.code === 'invalid_link_url') {
      ticket = await oauthmc.createTicket({
        name: playerName,
        mode: 'code',
        ttlSeconds: 900,
        maxAttempts: 5,
        metadata: { userId },
      });
    } else {
      throw err;
    }
  }

  // Persist { userId, ticketId: ticket.id, name: ticket.name } in your database.
  return ticket;
}

// 2. Redeem from a POST handler after verifying the signed-in user owns ticketId.
export async function completeVerification(
  userId: string,
  ownedTicketId: string,
  expectedName: string,
  submittedCode: string,
) {
  const result = await oauthmc.redeem(ownedTicketId, submittedCode);
  if (result.ok) {
    // Defense in depth: confirm canonical username matches the ticket.
    if (result.name.toLowerCase() !== expectedName.toLowerCase()) {
      throw new Error('Username mismatch');
    }
    // Always store result.uuid and result.name returned by OAuthMC.
    return { ok: true as const, uuid: result.uuid, name: result.name };
  }
  return result; // wrong_code | not_redeemable | not_found
}
```

## Raw HTTP example

Any language with an HTTP client can integrate directly against the [HTTP API](https://docs.sculk.network/nightly/oauthmc/api.md) or generate a client from [openapi.yaml](https://docs.sculk.network/nightly/oauthmc/openapi.md).

Create a link-mode ticket:

```sh
curl -sS -X POST http://127.0.0.1:8080/v1/tickets \
  -H "Authorization: Bearer $API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "name": "HatsuneMiku",
    "mode": "link",
    "link_url": "https://example.com/account/minecraft/verify#ticket={ticket}&code={code}"
  }'
```

```json
{"address":"verify.example.com","exclusive":false,"expires_at":"2026-11-26T10:32:10Z","id":"tkt_cf7711bb913524ba2b17e16370a52105","max_attempts":5,"metadata":null,"mode":"link","name":"HatsuneMiku","status":"pending"}
```

Poll ticket status:

```sh
curl -sS http://127.0.0.1:8080/v1/tickets/tkt_cf7711bb913524ba2b17e16370a52105 \
  -H "Authorization: Bearer $API_KEY"
```

```json
{"attempts_left":5,"expires_at":"2026-11-26T10:32:10Z","id":"tkt_cf7711bb913524ba2b17e16370a52105","metadata":null,"mode":"link","name":"HatsuneMiku","status":"joined"}
```

Redeem the code once the player confirms on your page:

```sh
curl -sS -X POST http://127.0.0.1:8080/v1/tickets/tkt_cf7711bb913524ba2b17e16370a52105/redeem \
  -H "Authorization: Bearer $API_KEY" \
  -H "Content-Type: application/json" \
  -d '{"code":"7DQ8-AM76"}'
```

```json
{"name":"HatsuneMiku","uuid":"a0c4b8c5-a04f-4a6f-9d02-1dea6154a9f6"}
```

Cancel a pending ticket when a user abandons or restarts verification:

```sh
curl -sS -i -X DELETE http://127.0.0.1:8080/v1/tickets/tkt_cf7711bb913524ba2b17e16370a52105 \
  -H "Authorization: Bearer $API_KEY"
```

```text
HTTP/1.1 204 No Content
date: Thu, 26 Nov 2026 10:17:12 GMT
```

## Polling ticket status

Poll `GET /v1/tickets/{id}` from your backend (for example, every 2–3 seconds while the verification modal is open) to update the UI when the player joins or when the ticket transitions to a terminal state:

| `status` | Meaning | UI action |
| --- | --- | --- |
| `pending` | Waiting for the player to join in Minecraft. | Keep showing the server address. |
| `joined` | Player authenticated with Mojang and received a code/dialog. | Focus the code input or prompt the player to click **Open link**. |
| `redeemed` | Ticket was redeemed (for example, in another tab via link mode). | Refresh the account state and stop polling. |
| `expired` | Ticket TTL elapsed. | Show an expired notice with a button to start a new ticket; stop polling. |
| `locked` | Wrong codes exhausted `max_attempts`. | Show a locked notice with a button to start a new ticket; stop polling. |

If `GET /v1/tickets/{id}` returns `404 not_found`, the ticket was deleted, swept after `OAUTHMC_EXPIRED_GRACE_SECONDS`, or lost on an OAuthMC restart. Clear the local ticket record and let the user start a new verification.

## Error handling

Handle expected redeem outcomes explicitly instead of treating them as server crashes:

- `422 wrong_code`: display the remaining `attempts_left`. If `attempts_left` is `0`, the ticket is now `locked`.
- `409 not_redeemable`: inspect `status`:
  - `pending`: the player submitted a code before joining in Minecraft.
  - `redeemed`: already completed (for example, double submit or redeemed in another tab).
  - `expired` or `locked`: prompt the player to start a new ticket.
- `404 not_found`: ticket no longer exists; clear your stored ticket row.
- `503 ticket_limit`: OAuthMC reached `OAUTHMC_MAX_TICKETS` or `OAUTHMC_MAX_TICKETS_PER_KEY`. Rate-limit ticket creation per user on your platform and delete displaced tickets when a user starts a new one.
- Network errors, timeouts, or `5xx`: return a temporary-unavailable error to the user without deleting their local ticket so they can retry.

## Multi-tenant API keys

Pass multiple comma-separated keys in `OAUTHMC_API_KEYS` to share one OAuthMC instance across several platforms or environments (for example, staging and production):

- Each key is an isolated tenant on `/v1/*`. Tickets created by key A return `404 not_found` to key B.
- If two tenants hold open tickets for the same Minecraft username at the same time, OAuthMC ignores per-ticket `messages` overrides and falls back to code mode using server templates. Both tenants' tickets still receive the code hash so either can redeem the code.

## Message overrides

You can override in-game text at two levels:

- **Instance-wide** via `OAUTHMC_MESSAGES` (JSON file path). Overrides any of the 14 templates, including pre-ticket messages (`no_ticket`, `rate_limited`, `shutdown`).
- **Per-ticket** via the `messages` field on `POST /v1/tickets` (for localization or per-platform branding). Overrides any of the 11 ticket-scoped templates (`code`, `unverified`, `dialog_title`, `dialog_code`, `link`, `open_link`, `copy_code`, `verified`, `expired`, `locked`, `replaced`), up to 512 bytes each.

Per-ticket overrides apply only when every open ticket for that username belongs to the same tenant. See [Configuration](https://docs.sculk.network/nightly/oauthmc/configuration.md#message-templates) for every key, default string, and placeholder.
