Trivia night with a verified host
A quiz room where the host's browser acts as the referee. Only the verified host can publish questions and update scores, while players submit answers over request/response RPC.
Host: room creation and grading
Passing roles({selfAsAdmin: true}) appends
~ and the host's 22-character userId to the room
name. Anyone joining that full roomId with
use: [roles()] verifies the admin's public key from the room
name itself. With roles() active, makeState
defaults to admin-only writes.
import {joinRoom, roles} from 'trystero'
const code = codeInput.value.trim().toLowerCase() // e.g. 'tuesday'
const room = joinRoom(
{appId: 'oedipa/trivia-night', use: [roles({selfAsAdmin: true})]},
'quiz-' + code
)
// roomId ends in ~<hostUserId>; guests verify the host from that suffix
const {roomId} = await room.getSelf()
showInviteLink(`${location.origin}/play#${roomId}`)
// With roles() loaded, makeState defaults to admin-only writes
const question = room.makeState('question', null)
const scores = room.makeState('scores', {})
const notice = room.makeState('notice', '', {roles: ['admin', 'cohost']})
const player = room.makeUserState('player', {name: 'Anon'})
const answer = room.makeAction('answer', {kind: 'request'})
let current = null
const ask = index => {
const {prompt, choices, correct} = QUESTIONS[index]
current = {index, correct, closesAt: Date.now() + 20_000, answered: new Set()}
return question.set({index, prompt, choices, closesAt: current.closesAt})
}
// Host grades incoming answers; throwing rejects the caller's request()
answer.onRequest(({index, choice}, {userId}) => {
if (!current || index !== current.index || Date.now() > current.closesAt) {
throw new Error('Question is closed')
}
if (current.answered.has(userId)) throw new Error('Already answered')
current.answered.add(userId)
const correct = choice === current.correct
const points = correct ? Math.ceil((current.closesAt - Date.now()) / 1000) : 0
if (points) {
scores.set(prev => ({...prev, [userId]: (prev[userId] ?? 0) + points}))
}
return {correct, points}
})
player.onChange(() => renderPlayers(player.getAll(), scores.get()))
scores.onChange(next => renderPlayers(player.getAll(), next))
nextButton.onclick = () => ask((current?.index ?? -1) + 1)
noticeInput.onchange = () => notice.set(noticeInput.value)
promoteButton.onclick = () => room.grantRole(selectedUserId(), 'cohost')
kickButton.onclick = () =>
room.ban(selectedUserId(), {reason: 'spoiling answers'})
Faster correct answers earn more points, duplicate or expired submissions
throw inside onRequest (rejecting the caller's
request() with that message), and the host's default
'local' IndexedDB identity preserves admin authority across
page reloads.
Players: joining and submitting answers
Players join using the full roomId from the invite link.
Joining a ~userId room without use: [roles()]
throws immediately. Both host and guest declare the same state namespaces
and roles configurations so every peer verifies incoming
signatures against the same rules.
import {joinRoom, roles} from 'trystero'
// Full self-certifying roomId from the invite link
const roomId = location.hash.slice(1)
const room = joinRoom(
{appId: 'oedipa/trivia-night', use: [roles()]},
roomId
)
const question = room.makeState('question', null)
const scores = room.makeState('scores', {})
const notice = room.makeState('notice', '', {roles: ['admin', 'cohost']})
const player = room.makeUserState('player', {name: 'Anon'})
const answer = room.makeAction('answer', {kind: 'request'})
player.set({name: nameInput.value || 'Anon'})
let askedBy = null
question.onChange((q, {userId}) => {
askedBy = userId
renderQuestion(q)
}, {replay: true})
scores.onChange(next => renderScoreboard(next, player.getAll()), {replay: true})
notice.onChange(showNotice, {replay: true})
choiceList.onclick = async e => {
const choice = Number(e.target.dataset.choice)
if (Number.isNaN(choice) || !question.get() || !askedBy) return
try {
const {correct, points} = await answer.request(
{index: question.get().index, choice},
{target: askedBy, timeoutMs: 5000}
)
flash(correct ? `+${points}` : 'Incorrect')
} catch (err) {
flash(err.message)
}
}
room.onRoleChange(({roles, local}) => {
if (local) toggleNoticeEditor(roles.includes('cohost'))
})
room.onError(err => {
if (err.code === 'banned') {
showBanner(`Removed by host${err.reason ? ': ' + err.reason : ''}`)
}
})
Each player sends their answer directly to the userId that
published the question. Unauthorized calls to question.set()
or scores.set() reject locally, and forged packets from a
modified client fail signature verification on remote peers.
Keeping scores in admin-owned state
Display names belong in makeUserState('player') because each
participant should control their own name. Putting scores in
makeUserState('score') would let any player sign an arbitrary
score for their own slot.
Storing the scoreboard in makeState('scores') keeps writes
restricted to 'admin'. Every update carries the host's
signature, peers cache and relay it to late joiners intact, and because
only the host writes to scores, there are no concurrent
multi-writer conflicts on the map.
Co-hosts and bans
grantRole(userId, 'cohost') issues a signed role certificate
that persists across that user's tabs and reloads. Because
notice is configured with
roles: ['admin', 'cohost'], promoted co-hosts can update the
banner while question and scores remain
admin-only. onRoleChange notifies the promoted client when
local is true.
room.ban() disconnects all of a user's tabs, revokes their
custom roles, purges any state records they authored, and blocks
reconnection across honest peers. Banned clients receive
code: 'banned' on room.onError.