Adds game-specific Better Auth patterns: player/moderator/admin roles, session checks on game routes and WebSocket handshakes, and separating auth sessions from game sessions.
Ships in game-dev. Installing the plugin adds it to Claude Code.
What the skill costs in Claude's context, stage by stage
Name and description: Claude knows it exists.
SKILL.md joins the conversation and stays.
Read when SKILL.md points to them.
Use the better-auth-best-practices skill if it is installed, otherwise https://www.better-auth.com/docs. This skill covers only what a game adds on top: the role matrix, the WebSocket handshake, and the split between who a player is and which match they are in.
postgres-game-schemaInstall the packages: bun add better-auth @better-auth/drizzle-adapter. Import the adapter with import { drizzleAdapter } from '@better-auth/drizzle-adapter'. If the project uses Drizzle Relations v2, import from @better-auth/drizzle-adapter/relations-v2 instead.
Add the admin plugin with the game roles from templates/role-definitions.ts: admin({ ac, roles, defaultRole: 'player' }) on the server and adminClient({ ac, roles }) on the client. Without defaultRole: 'player', new users get the plugin's default role user, which the game matrix does not define, and every permission check fails.
Add the staffGuard() plugin from templates/staff-guard.ts after admin(): plugins: [admin({ ... }), staffGuard()]. A plugin hook does not take the single user-level hooks.before slot, and its place relative to bearer() does not matter. If a project must call guardStaffTargets(ctx) from its own hooks.before instead, await it as the first statement, do not catch its error, and do not rewrite the body of /admin/* requests in any hook.
Do not add a role field through additionalFields. The admin plugin adds role (plus banned, banReason, banExpires) to the user table.
Generate the auth schema, then migrate it with Drizzle Kit. Better Auth's migrate command works only with its built-in Kysely adapter.
bunx auth@latest generate
bunx drizzle-kit generate
bunx drizzle-kit migrate
Mount the Better Auth handler in the game server and guard routes. For Elysia, follow https://www.better-auth.com/docs/integrations/elysia, and use the elysiajs skill if it is installed for the Elysia version the project runs.
| Role | May do |
|---|---|
| player | join and create matches, send chat, file reports |
| moderator | player actions; list and view users; ban, unban and revoke all sessions of players only; end matches, delete chat, read and resolve reports, read game config and analytics |
| admin | every admin-plugin action (including changing roles), every game action, update game config |
user and session resources. Unban checks user: ['ban']. Changing a role checks user: ['set-role'].user: ['ban'] could ban an admin. staffGuard denies by default: on every /admin/* path outside its allow list (list-users, get-user, has-permission, stop-impersonating), a caller who is not an admin must name a target user whose every role is player (no role counts as the plugin's defaultRole). Any other role, a new staff role included, is refused.adminUserIds as admins when they call and as staff when they are the target. It reads a bearer-token caller the way the endpoint will.sessionToken for revoke-user-session, userId for the rest), coerces userId the way the endpoints do, and rejects a request whose target it cannot find. Server code that calls auth.api.createUser({ body }) with no headers passes, as the plugin allows.auth.api.* calls but not for writes through internalAdapter. Game code that acts on another user calls auth.api.* with the acting moderator's own request headers, never with an admin or service session and never through internalAdapter, or it applies the same player-only target check itself.session: ['list']. /admin/list-user-sessions returns each session's token, and a token is a login. Moderators revoke a player's sessions with /admin/revoke-user-sessions, which needs only session: ['revoke'].user.role holds a comma-separated list when a user has several roles. rolesOf in role-definitions.ts splits it without trimming, as the plugin does, and treats a missing role as defaultRole. can() and staffGuard both use it, so the two never read a role differently. Pass can() the same defaultRole you gave the plugin (it defaults to player).returned: false, a moderator can still test their values through the filterField query of /admin/list-users.can(session.user.role, { chat: ['delete'] }) when you already hold the session, or with auth.api.userHasPermission({ body: { userId, permissions } }) when you only have the id.session.user.id === ownerId.Validate the session once, when the client upgrades the connection, from the upgrade request's headers.
const session = await auth.api.getSession({
headers: request.headers,
query: { disableCookieCache: true },
});
if (!session) return new Response('Unauthorized', { status: 401 });
// Store session.user.id and session.user.role on the socket; never read them from client messages.
disableCookieCache: true makes the server read the session from the database. With session.cookieCache enabled and no such flag, a revoked session can pass until the cache cookie expires.
A direct auth.api call skips Better Auth's origin checks, even with the browser's headers. Reject an upgrade whose Origin header is not in your trusted origins before you read the session.
Browsers send Origin on every WebSocket upgrade, so they are checked by Origin plus the session cookie. Native clients (the game-godot and game-unity skills) send no Origin: RFC 6455 says only browser clients must send Origin (section 4.1), and that the check is not meant to keep non-browsers out (section 10.2). Check them by a bearer session instead: a request with no Origin passes only with Authorization: Bearer <token> that getSession accepts, and is 403 otherwise. A client-set Origin proves nothing, so an untrusted Origin is 403 even with a valid token. game-backend-architecture has this as authorizeUpgrade in its server boilerplate.
This needs the bearer() plugin. In 1.7.23 it is import { bearer } from 'better-auth/plugins' and plugins: [admin({ ... }), staffGuard(), bearer({ requireSignature: true })]. The plugin reads Authorization: Bearer <token> in a before hook, also for auth.api.getSession({ headers }), and turns a valid token into the session cookie for that call. Sign-in and sign-up responses carry the token in the set-auth-token header. requireSignature: true refuses an unsigned token; that is this skill's choice, since the header gives the signed value (default false).
bearer() is app-wide, and it changes two things for web clients. First, every response that sets the session cookie, a browser sign-in included, also returns the token in a set-auth-token header and adds that header to Access-Control-Expose-Headers. Page JavaScript can read it, unlike the httpOnly cookie, so an XSS bug would hand over a reusable session token. Web clients must never read or store set-auth-token. Second, every Better Auth route now accepts Authorization: Bearer with no Origin, so a stolen token works on every route. CSRF is unchanged: a cross-site page cannot send that header without a preflight. The plugin has one option, requireSignature. It cannot limit which routes send the header or which clients get it, so keep the token out of web code and protect it where it is stored.
The bearer token is a session credential: whoever holds it is logged in as the player. A native client keeps it in the OS secure store (Keychain on iOS and macOS, Android Keystore, or the platform's credential store on desktop; this skill's rule, the plugin docs only say "store this token securely"). It never goes in a URL or query string, and never in a log, crash report or analytics event. Send it only in the Authorization header. The server reads it from that header alone.
Origin to identify a native client, or taking a session token from the query string.isAdmin boolean instead of roles.auth.api calls made by the server.staffGuard(). They can then ban or log out admins and each other.staffGuard. It denies by default, but its allow list, its reading of userId and sessionToken, and its bearer handling match 1.7.23. Check both against any admin endpoint a new version adds.staffGuard reads the caller only from cookies or bearer(), so it refuses those callers until you replay that hook the way it replays bearer().trustedOrigins and CORS when the game client runs on another origin. Better Auth rejects auth requests from origins it does not trust.templates/role-definitions.ts: read when you set up roles or add a game permission.templates/staff-guard.ts: read when you give moderators ban or session powers.references/sources.md: read when you need the documentation page behind a claim in this skill.postgres-game-schema for the player tables that reference the auth usergame-backend-architecture for the server and the WebSocket endpointredis-game-patterns for game session statestripe-game-payments for payments tied to an authenticated playerWhat SKILL.md sets; muted values are Claude Code's defaults
Three short reads, in order
/game-dev:betterauth-integrationfrom game-dev
npx claudepluginhub fcsouza/agent-skills --plugin game-dev39 skills in this plugin
/bullmq-game-queuesBackground job design for game backends on BullMQ and Redis: one queue per game domain, idempotent reward fulfilment, and cron schedulers for daily rewards and season ends. Use when a game needs matchmaking requests, reward grants, match results, notifications or analytics processed off the request path, or recurring and timed jobs such as daily login rewards, leaderboard snapshots and season rollovers./character-design-narrativeCovers designing game characters: NPCs, companions, antagonists, player avatars, character bibles and branching dialogue. Use when a game needs a new character written, an NPC feels flat or interchangeable, or dialogue needs a branching format with conditions and effects./ci-cd-gameGitHub Actions pipeline rules for a Bun game backend on Neon and Fly.io: migrations before deploy, one Neon database branch per pull request, a smoke test after deploy, and a pinned Bun version. Use when a game project needs CI, a deploy workflow, preview databases for pull requests, or a safe order for schema migrations and server deploys./elevenlabs-sound-musicCovers generating game audio with ElevenLabs (voice lines, sound effects, music) and Google Lyria 2 (instrumental music clips), and playing it in the browser through an audio state machine with crossfades, per-layer volume and an unlock on the first user input. Use when a game needs sound effects, NPC voice lines or a soundtrack, when music must follow game state (menu, exploration, combat, boss) without hard cuts, when audio stays silent on a phone until the player taps, or when choosing between ElevenLabs and Lyria for music./game-anti-cheatCovers how a developer defends their own online game against cheating: server-side input validation, withholding hidden state, lag-compensation limits, dupe-proof transfers, detection from server data and reports, and enforcement with delayed bans, appeals and refunds to victims. Use when a multiplayer game has speed hacks, wallhacks, aimbots, bots, item or currency dupes, real-money trading, boosting or win trading, or when planning how to detect and ban cheaters./game-architectInterviews the user about a new game, researches reference games and genre conventions, then writes an MVP plan (`docs/mvp-first-draft.md`) and starter project files. Use when starting a game project from scratch and there is no plan yet.Other plugins' skills for the same job