oauthmc
Zero-dependency TypeScript client for the OAuthMC HTTP API.
CautionServer-side only. Never bundle this package into browser code or expose your
OAUTHMC_API_KEYSbearer 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:
npm install oauthmcUntil the first release, build and pack a tarball from a checkout of this repository and install the generated .tgz file:
# From the repository root (pnpm workspace)
pnpm --filter oauthmc pack
# Or directly inside crates/oauthmc/sdk/js
npm packThen install the resulting tarball in your project:
npm install /path/to/oauthmc-0.1.0.tgzQuick start (code mode)#
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). Onlynameis 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}). Returnsnullon404. 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}). Returnstrueon204andfalseon404so retries converge.health(): Promise<boolean>— ProbesGET /healthzwithout authentication. Returnstrueonly on HTTP200with{"ok": true},falseotherwise.
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 whenmodeis'link'; template URL mapped tolink_urlcontaining{ticket}and{code}.ttlSeconds(number, optional): Ticket lifetime in seconds.maxAttempts(number, optional): Maximum redeem attempts before locking.exclusive(boolean, optional): Reject with409 name_busywhen 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 ongetTicket.
See docs/api.md for the server's defaults, caps, validation rules, and multi-tenant message isolation rules.
Helper#
isValidMinecraftName(name: string): boolean— Checks whethernamematches^[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:
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:
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.tsdirectly via native type stripping) - Deno
- Bun
- Cloudflare Workers