Docs Admins, roles & moderation

Admins, roles & moderation

By default every peer in a room has equal permissions. When an application needs a host to advance rounds, a DJ to control playback, or a moderator to remove disruptive users, load the optional roles() plugin.

Loading roles()

Pass roles() in use: […] on joinRoom() to enable verified admins, custom role grants, role-gated state and actions, and peer bans. Applications that do not import roles tree-shake the module out of their bundle (~4.7 KB compressed when included).

Establishing root admins

1. Self-certifying room IDs: selfAsAdmin

For ad-hoc rooms created from a button click, pass roles({selfAsAdmin: true}). Trystero appends ~ followed by the creator's 22-character userId to the room name. Guests joining that full roomId with use: [roles()] derive who the root admin is directly from the suffix and verify it against the host's public key on connect.

import {joinRoom, roles} from 'trystero'

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

const {roomId} = await hostRoom.getSelf()
// => "friday-quiz~9fX2kLm8pQr7vBn3wZy4xT"
// Share roomId in your invite URL
const guestRoom = joinRoom(
  {appId: 'oedipa/trivia-night', use: [roles()]},
  roomId
)
  • Because browser identities persist in IndexedDB by default (identity: 'local'), the host retains admin status across reloads and reconnects on that browser profile.
  • Joining a <baseRoomId>~<userId> room without use: [roles()] throws immediately so a misconfigured client cannot ignore room authority rules.
  • In Node, Bun, or Deno, where identity defaults to 'none', pass a saved UserIdentity so restarting the process preserves the admin keypair.

2. Pinned admin IDs: admins

For fixed room names like 'main-stage' without a ~userId suffix—or rooms with multiple root admins—pass an array of trusted userId strings. Hosts and guests run the same configuration:

import {joinRoom, roles} from 'trystero'

const ADMINS = ['tY8mK3pQvN2xR7wL9jB4cF', '9fX2kLm8pQr7vBn3wZy4xT']

const room = joinRoom(
  {appId: 'town-hall.example.com', use: [roles({admins: ADMINS})]},
  'main-stage'
)

Both options can be combined: roles({selfAsAdmin: true, admins: [CO_HOST_ID]}) creates a self-certifying room while trusting an additional root admin.

Role-gated state

When roles() is present, room.makeState() defaults to roles: ['admin']. Every peer can read the value, while only root admins (or the roles you specify) can write to it.

// Only 'admin' or 'host' can update round; all peers can read it
const round = room.makeState(
  'round',
  {number: 1, phase: 'lobby'},
  {roles: ['admin', 'host'], validate: next => next.number >= 1}
)

// Opt a shared state namespace back into open writes
const reactions = room.makeState('wall', {latestEmoji: '👋'}, {roles: '*'})

// Restrict a per-user slot so only seated players can submit bets
const bet = room.makeUserState('bet', 0, {roles: ['admin', 'player']})

Admins do not need to remain connected for late joiners to receive authoritative state. Each record carries the writer's signature and role certificate, allowing remaining peers to cache and forward the latest value without being able to alter it.

Role-gated actions

Pass roles to makeAction() to restrict which roles may send messages or issue requests on that channel. Verified sender roles are included on the handler context.

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

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

await announce.send({text: 'Final round starts in 10 seconds'})

Unauthorized send() or request() calls reject locally, and peers verify signatures and role certificates on incoming frames so modified clients are dropped on arrival.

Granting roles and banning users

Root admins can grant custom roles such as 'moderator', 'dj', or 'player', revoke them later, and ban or unban users.

room.onRoleChange(({userId, roles, previousRoles, local}) => {
  console.log(`${userId}: ${previousRoles} -> ${roles} (self=${local})`)
})

// Grant roles (root 'admin' only)
await room.grantRole(friendUserId, 'dj')
await room.grantRole(helperUserId, ['moderator', 'dj'])

console.log(room.getRoles(friendUserId)) // => ['dj']
console.log(room.getRoles()) // => ['admin']

// Revoke one role, or omit the role name to clear all granted roles
await room.revokeRole(friendUserId, 'dj')

// Ban and unban across the room (root 'admin' only)
await room.ban(disruptiveUserId, {reason: 'spamming soundboard'})
console.log(room.isBanned(disruptiveUserId)) // => true

await room.unban(disruptiveUserId)

Operational rules

  • Root 'admin' is fixed. Only the self-certifying room creator and userIds listed in roles({admins}) hold 'admin' and may call grantRole, revokeRole, ban, or unban. Root admins cannot grant or revoke 'admin' or ban one another.
  • User-scoped enforcement. Role grants apply across all of a user's open tabs and reloads. Banning a userId disconnects all of their tabs, clears their granted roles, purges every makeState and makeUserState record they authored, and rejects reconnect attempts.
  • Banned client notification. Banned peers receive {code: 'banned', reason} via room.onError.
  • Cooperative enforcement. Public signaling relays do not inspect room permissions; peers enforce bans directly across WebRTC handshakes, multi-hop forwarding, and state/action verification.

Verification and sync

  • Signed role certificates. grantRole() produces an ECDSA P-256 RoleCertificate binding appId, roomId, the recipient's userId, granted roles, and a monotonic (iat, seq) pair. Promoted peers attach this certificate inline on gated actions and state writes so other peers can verify authorization even after the issuing admin leaves.
  • Deterministic convergence. Role grants, revocations, and bans (up to 4,096 active bans per room) resolve in a deterministic total order with canonical tie-breakers, tolerating up to 60 seconds of clock skew and syncing via anti-entropy reconciliation.
  • Edge filtering. Role certificates and ban records only traverse encrypted WebRTC data channels. In scale() rooms, direct neighbors verify permissions and ban lists before forwarding packets.