Guides Admins & bans without a backend

Admins, roles, and bans without a backend

In a default peer-to-peer room every participant has identical privileges, which works for collaborative tools among friends and breaks down when a game or moderated session needs an authoritative host. Without a backend to enforce access control, peers need a way to agree on which keys hold authority.

Deriving authority from public keys

Every Trystero participant already authenticates a self-certifying 22-character userId derived from an ECDSA P-256 public key. Room authority therefore reduces to agreeing on which userIds count as root admins and verifying their signatures on privileged records. The roles() plugin supports two ways to establish those root keys.

Self-certifying room names

Passing roles({selfAsAdmin: true}) appends ~ and the creator's userId to the room name so the invite URL itself commits to the host's public key digest:

import {joinRoom, roles} from 'trystero'

const room = joinRoom(
  {appId: 'oedipa/friday-trivia', use: [roles({selfAsAdmin: true})]},
  'quiz-night'
)

const {roomId, isAdmin} = await room.getSelf()
// roomId  => "quiz-night~9fX2kLm8pQr7vBn3wZy4xT"
// isAdmin => true

showInviteLink(`${location.origin}/play#${roomId}`)

Guests join that full roomId with use: [roles()] and verify the host's key during the WebRTC handshake without consulting an external server:

import {joinRoom, roles} from 'trystero'

const roomId = location.hash.slice(1)
const room = joinRoom({appId: 'oedipa/friday-trivia', use: [roles()]}, roomId)

const {baseRoomId, isAdmin} = await room.getSelf()
// baseRoomId => "quiz-night", isAdmin => false

room.onUserJoin(({userId, roles}) => {
  if (roles.includes('admin')) showHostBadge(userId)
})

Because browser identities persist in IndexedDB by default (identity: 'local'), the host keeps admin privileges across reloads on that browser profile. Joining a ~<userId> room without loading roles() throws immediately so misconfigured clients fail early.

Pinned admin keys

For fixed room names without a suffix—or rooms with multiple co-owners—pass roles({admins: ['tY8mK3pQvN2xR7wL9jB4cF']}) on both hosts and guests. Any participant proving ownership of a listed key becomes a root 'admin'. Both options can be combined when creating an ad-hoc room that also trusts an additional co-admin.

In Node, Bun, and Deno, identity defaults to ephemeral 'none'. For a server-side admin bot, generate a key once with createUserIdentity(), store the exportUserIdentity() secret, and pass importUserIdentity() as identity; see Running in Node, Bun & Deno.

Authoritative state and actions

Loading roles() changes makeState to default to roles: ['admin']: all peers can read shared state, while only verified admins (or explicitly listed roles) can write it. You can reopen a namespace with roles: '*', delegate write access to custom roles, or restrict makeUserState slots and makeAction channels:

// With roles() loaded, makeState defaults to admin-only writes
const scores = room.makeState('scores', {})

// Allow both 'admin' and granted 'cohost' holders to update round
const round = room.makeState(
  'round',
  {number: 1, prompt: 'Warming up'},
  {roles: ['admin', 'cohost'], validate: next => next.number >= 1}
)

// Restrict a per-user slot to seated players
const answer = room.makeUserState('answer', null, {roles: ['admin', 'player']})

// Reopen a shared state namespace to all participants
const wall = room.makeState('wall', {emoji: '👋'}, {roles: '*'})

await round.set({number: 2, prompt: 'Name the moons of Mars'})
await scores.set(prev => ({...prev, [winnerId]: (prev[winnerId] ?? 0) + 10}))

round.onChange(renderRound, {replay: true})
scores.onChange(renderScoreboard, {replay: true})

Unauthorized set() calls reject locally, and forged packets from a modified client fail signature verification on remote peers. Because every state record carries its author's signature (and role certificate when delegated), remaining peers can cache and sync official state to late joiners even while the host is offline.

Delegating custom roles

Root admins grant and revoke custom roles with grantRole and revokeRole. Grants apply to a userId across all open tabs and reloads, and onRoleChange notifies listeners of updated role sets:

await room.grantRole(friendId, 'cohost')
await room.grantRole(newcomerId, 'player')

room.onRoleChange(({userId, roles, local}) => {
  renderBadges(userId, roles)
  if (local && roles.includes('cohost')) showHostControls()
})

const announce = room.makeAction('announce', {roles: ['admin', 'cohost']})

announce.onMessage((text, {userId, roles}) => {
  showToast(`[${roles.join(', ')}] ${userId}: ${text}`)
})

await room.revokeRole(friendId, 'cohost')
console.log(room.getRoles(friendId)) // => []

grantRole signs an ECDSA P-256 RoleCertificate binding appId, roomId, recipient userId, granted roles, and a monotonic (iat, seq) counter. Promoted peers attach this certificate inline on gated state and action messages so other peers can verify authorization offline after the issuing admin disconnects. Root 'admin' status itself cannot be granted or revoked, and root admins cannot ban one another.

Cooperative bans

room.ban(userId, options) disconnects all of that user's tabs, clears their custom roles, purges every makeState and makeUserState record they authored, and blocks reconnects. Banned clients receive code: 'banned' with any optional reason on room.onError:

await room.ban(disruptiveId, {reason: 'posting answers on the wall'})
room.isBanned(disruptiveId) // => true

await room.unban(disruptiveId)

room.onError(err => {
  if (err.code === 'banned') {
    showBanner('Removed by the host', err.reason)
  }
})

Public signaling relays do not inspect room moderation state; instead, connected peers reject handshakes from banned keys and drop their packets. In multi-hop scale() rooms, direct neighbors verify ban records before forwarding so traffic from a banned key stops at the first hop.

Grants, revocations, and bans (up to 4,096 active bans per room) resolve in a deterministic total order with canonical tie-breakers and reconcile across peers via cursor-paged anti-entropy sync.

Practical boundaries

Bans target a cryptographic userId rather than an IP address or real-world identity. A user who clears site storage or opens a private window with identity: 'none' generates a new keypair and appears as a new participant. For public-facing rooms, combine roles() with a rotatable room password, an advisory maxUsers limit, and controlled invite links. Full method signatures are listed in the API reference.