# oauthmc

Zero-dependency TypeScript client for the [OAuthMC](https://github.com/YellowUmbrellaDev/sculk.network/blob/main/crates/oauthmc/README.md) HTTP API.

> [!CAUTION]
> **Server-side only.** Never bundle this package into browser code or expose your `OAUTHMC_API_KEYS` bearer token to a client. Anyone with the API key can create, inspect, redeem, and delete tickets for your tenant. Keep OAuthMC on a private network (loopback or internal container network) and call it exclusively from your backend.

## Install

`oauthmc` is not published on npm yet. Once published, install it with:

```sh
npm install oauthmc
```

Until the first release, build and pack a tarball from a checkout of this repository and install the generated `.tgz` file:

```sh
# From the repository root (pnpm workspace)
pnpm --filter oauthmc pack

# Or directly inside crates/oauthmc/sdk/js
npm pack
```

Then install the resulting tarball in your project:

```sh
npm install /path/to/oauthmc-0.1.0.tgz
```

## Quick start (code mode)

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

const client = new OAuthMC({
  baseUrl: process.env.OAUTHMC_URL ?? 'http://oauthmc:8080',
  apiKey: process.env.OAUTHMC_API_KEY!,
  // Optional: custom fetch implementation (defaults to globalThis.fetch)
  // Optional: request timeout in milliseconds (default 10_000)
  timeoutMs: 10_000,
});

// 1. Validate input (optional helper; the server always validates) and create a ticket.
if (!isValidMinecraftName(playerName)) {
  throw new Error('Invalid Minecraft username');
}

const ticket = await client.createTicket({
  name: playerName,
  metadata: { userId: currentUser.id },
});

// Store ticket.id in the user's server-side session.
// Show ticket.address and ticket.expiresAt to the user so they can join in Minecraft.
console.log(`Join ${ticket.address} before ${ticket.expiresAt.toISOString()}`);

// 2. (Optional) Poll ticket status while waiting for the player to join.
// getTicket() returns null on 404 and never returns the player's UUID.
const state = await client.getTicket(ticket.id);
if (state?.status === 'joined') {
  console.log(`Player joined; ${state.attemptsLeft} attempts left`);
}

// 3. When the user submits the code shown on the Minecraft kick screen, redeem it on the server.
const result = await client.redeem(ticket.id, submittedCode);

if (result.ok) {
  // Always trust and persist result.uuid and result.name returned by redeem().
  // Never accept a UUID supplied by the browser or client request.
  await linkMinecraftAccount(currentUser.id, result.uuid, result.name);
} else if (result.reason === 'wrong_code') {
  // Normal outcome (HTTP 422 wrong_code): prompt the user to retry.
  console.log(`Wrong code, ${result.attemptsLeft} attempts left`);
} else if (result.reason === 'not_redeemable') {
  // Normal outcome (HTTP 409 not_redeemable): status is pending, redeemed, expired, or locked.
  console.log(`Ticket cannot be redeemed (status: ${result.status})`);
} else {
  // result.reason === 'not_found' (HTTP 404)
  console.log('Ticket not found');
}

// 4. Cancel/clean up a ticket if needed. Returns true when deleted, false on 404 (idempotent).
await client.deleteTicket(ticket.id);
```

## API

### `new OAuthMC(options)`

| Option | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `baseUrl` | `string` | yes | — | Base URL of the OAuthMC HTTP API (trailing slash optional) |
| `apiKey` | `string` | yes | — | Tenant bearer token from `OAUTHMC_API_KEYS` |
| `fetch` | `typeof fetch` | no | `globalThis.fetch` | Custom Fetch API implementation |
| `timeoutMs` | `number` | no | `10_000` | Per-request timeout via `AbortSignal.timeout` |

### Methods

- `createTicket(options): Promise<Ticket>` — Creates a verification ticket (`POST /v1/tickets`). Only `name` is required. Unset optional fields are omitted from the request body so server defaults apply.
- `getTicket(id): Promise<TicketState | null>` — Fetches ticket status (`GET /v1/tickets/{id}`). Returns `null` on `404`. Never includes a UUID.
- `redeem(id, code): Promise<RedeemResult>` — Redeems a one-time verification code (`POST /v1/tickets/{id}/redeem`). Returns a discriminated union for normal outcomes (`ok: true`, `wrong_code`, `not_redeemable`, `not_found`).
- `deleteTicket(id): Promise<boolean>` — Deletes a ticket (`DELETE /v1/tickets/{id}`). Returns `true` on `204` and `false` on `404` so retries converge.
- `health(): Promise<boolean>` — Probes `GET /healthz` without authentication. Returns `true` only on HTTP `200` with `{"ok": true}`, `false` otherwise.

### Per-ticket options

`createTicket` accepts:

- `name` (`string`, required): 1–16 characters matching `[A-Za-z0-9_]`.
- `mode` (`'code' | 'link' | 'auto'`, optional): Verification mode (server defaults to `'code'` and decides which modes it accepts).
- `linkUrl` (`string`, optional): Required when `mode` is `'link'`; template URL mapped to `link_url` containing `{ticket}` and `{code}`.
- `ttlSeconds` (`number`, optional): Ticket lifetime in seconds.
- `maxAttempts` (`number`, optional): Maximum redeem attempts before locking.
- `exclusive` (`boolean`, optional): Reject with `409 name_busy` when another open ticket exists for the same username.
- `messages` (`TicketMessages`, optional): Per-ticket kick/dialog/disconnect message template overrides (`code`, `unverified`, `dialogTitle`, `dialogCode`, `link`, `openLink`, `copyCode`, `verified`, `expired`, `locked`, `replaced`).
- `metadata` (`Record<string, unknown>`, optional): Opaque JSON object echoed on `getTicket`.

See [docs/api.md](https://github.com/YellowUmbrellaDev/sculk.network/blob/main/crates/oauthmc/docs/api.md#post-v1tickets) for the server's defaults, caps, validation rules, and multi-tenant message isolation rules.

### Helper

- `isValidMinecraftName(name: string): boolean` — Checks whether `name` matches `^[A-Za-z0-9_]{1,16}$`. Exported as a convenience helper; the SDK does not block requests client-side.

## Error handling

Expected redemption outcomes (`wrong_code`, `not_redeemable`, `not_found`) are returned as a discriminated union from `redeem()` instead of throwing:

```ts
type RedeemResult =
  | { ok: true; uuid: string; name: string }
  | { ok: false; reason: 'wrong_code'; attemptsLeft: number }
  | { ok: false; reason: 'not_redeemable'; status: TicketStatus }
  | { ok: false; reason: 'not_found' };
```

Unexpected API errors (`401 unauthorized`, `409 name_busy`, `422` validation errors, `503 ticket_limit`, `5xx`), malformed or incomplete responses (`invalid_response`), timeouts (`timeout`), and network errors (`network`) throw `OAuthMCError`:

```ts
try {
  await client.createTicket({ name: playerName, exclusive: true });
} catch (err) {
  if (err instanceof OAuthMCError) {
    // err.status: HTTP status code, or null for network/timeout errors
    // err.code: server error code (e.g. 'name_busy', 'ticket_limit') or 'network' | 'timeout' | 'invalid_response'
    // err.message: human-readable message (API key is never included in message or cause)
    if (err.code === 'name_busy') {
      // Another verification is already in progress for this player.
    }
  }
  throw err;
}
```

## Runtime support

Built strictly on standard Web APIs (`fetch`, `AbortSignal.timeout`, `URL`, `JSON`) with zero runtime dependencies.

- Node.js 18+ (Node.js 22.18+ can import `src/index.ts` directly via native type stripping)
- Deno
- Bun
- Cloudflare Workers

## License

[MIT](https://github.com/YellowUmbrellaDev/sculk.network/blob/main/crates/oauthmc/sdk/js/LICENSE)
