Identity, presence & room access
Trystero assigns every participant a cryptographically verified
userId without an account system, separates user-level
presence from individual browser tabs, and supports room passwords and
seat limits.
Self-certifying user IDs
Each participant gets a 22-character userId derived from an
ECDSA P-256 public key and verified during the WebRTC handshake. Because
ownership is proven by signing a handshake transcript bound to the DTLS
connection, peers cannot spoof or claim another user's ID.
import {joinRoom} from 'trystero'
const room = joinRoom({appId: 'tabletop.example.com'}, 'room-49')
const {userId, peerId, identityPersistence} = await room.getSelf()
console.log(`user ${userId} on tab ${peerId} (${identityPersistence})`)Identity persistence modes
identity | Behavior |
|---|---|
'local' (browser default) | Stored per appId in IndexedDB and shared across tabs and reloads on that browser profile until clearUserIdentity(appId) or site storage is cleared. |
'none' (Node/Bun/Deno default) | Ephemeral. Every reload, tab, or process start generates a new userId with nothing written to storage. |
UserIdentity or async loader | Loads an exported key from your own storage or account system so a user keeps the same userId across devices or server restarts. |
Ephemeral identities
const room = joinRoom(
{appId: 'oedipa/sketchpad', identity: 'none'},
'canvas-1'
)Clearing stored identity
import {clearUserIdentity} from 'trystero'
await room.leave()
await clearUserIdentity('tabletop.example.com')Portable identities across devices
To persist a userId across devices or across Node restarts,
use createUserIdentity, exportUserIdentity, and
importUserIdentity. Exported keys are compact
trystero_uk_… strings containing private key material and
should be stored with the same care as any signing secret.
import {
joinRoom,
createUserIdentity,
exportUserIdentity,
importUserIdentity
} from 'trystero'
const room = joinRoom(
{
appId: 'rpg.example.com',
identity: async ({appId}) => {
const savedKey = await fetchKeyFromYourBackend(appId)
if (savedKey) return importUserIdentity(savedKey)
const fresh = await createUserIdentity()
await saveKeyToYourBackend(appId, exportUserIdentity(fresh))
return fresh
}
},
'tavern-1'
) Local testing: 'local' shares one
userId across tabs in the same browser profile. Open an
incognito window or set identity: 'none' when testing
multi-user flows on one computer.
Users vs. tabs
When a user opens your app in two tabs, each tab establishes its own
WebRTC connection and peerId while sharing the same
userId:
-
room.onUserJoinfires when a user's first tab connects and does not fire again when they open additional tabs. -
room.onUserLeavefires only when their last open tab disconnects. -
room.getUsers()returns remote users keyed byuserId:{[userId]: {peerIds, roles}}. -
Passing a
userIdastargettosend()oraddStream()delivers to all of that user's open tabs, whilerequest()andping()route to a single tab so you receive one response.
// Sends to all of Alice's open tabs
dm.send('Hey Alice', {target: aliceUserId})
// Routes to one of Alice's tabs and awaits a single reply
const stats = await getStats.request(null, {target: aliceUserId})
For per-tab control, every callback context also includes
peerId, onPeerJoin and onPeerLeave
fire per connection, room.getPeers() lists all endpoints with
their hop count and RTCPeerConnection, and target
accepts a peerId directly.
| Event | onUserJoin / onUserLeave | onPeerJoin / onPeerLeave |
|---|---|---|
| Alice opens tab 1 | onUserJoin | onPeerJoin |
| Alice opens tab 2 | No event | onPeerJoin |
| Alice closes tab 1 | No event | onPeerLeave |
| Alice closes tab 2 | onUserLeave | onPeerLeave |
Subscriptions and teardown
All on* methods return an unsubscribe function and accept
replay, once, and signal options.
Joining an (appId, roomId) pair that is already active throws
an error; call await room.leave() before rejoining.
const controller = new AbortController()
const unsub = room.onUserJoin(({userId}) => console.log(`${userId} online`), {
replay: true, // emit users already in the room immediately
once: false, // set true to unsubscribe after the first call
signal: controller.signal // unsubscribe on controller.abort()
})
unsub()
await room.leave()Password-protected rooms
WebRTC media and data channels are always encrypted end to end. During
discovery, signaling payloads are encrypted with AES-256-GCM using a key
derived from appId and roomId, keeping plaintext
SDP out of relay logs, though anyone who knows both strings can derive
that key and join. Pass password to require a shared secret
during signaling:
const room = joinRoom(
{
appId: 'oedipa/late-night-poker',
password: 'correct-horse-battery-staple'
},
'back-room'
)
Peers must supply the same password to decrypt connection
offers. A common pattern is placing a random secret in the URL fragment
(#secret), which browsers omit from HTTP requests.
Room capacity limits
Set maxUsers to cap how many distinct users can occupy a
room, such as a two-player game or four-person call.
const room = joinRoom(
{
appId: 'example.com/battleship',
maxUsers: 2 // advisory cap of 2 unique users
},
'match-99'
)
room.onError(err => {
if (err.code === 'room-full' && Object.keys(room.getPeers()).length === 0) {
showModal('This match already has two players.')
}
})- Counted per user, not per tab. Refreshing or opening a second tab reuses an existing user's seat.
- Enforced during admission. Extra users are rejected
during the handshake before
onUserJoinfires on seated participants. - Seats reopen on disconnect when a user's last tab leaves.
- Checking
getPeers()on'room-full'. Each peer evaluates capacity from its own view, so an already-seated player can also observe'room-full'if a peer they meet saw a full room. Zero connected peers indicates that the local client was turned away.
maxUsers is advisory: peers enforce it locally during
handshakes and never evict themselves or existing connections if another
peer claims the room is full.
Room error events
Direct operations (send(), request(),
state.set()) reject their returned promises on failure.
Asynchronous signaling, admission, and moderation failures emit on
room.onError with a typed err.code:
room.onError(err => {
switch (err.code) {
case 'room-full':
if (Object.keys(room.getPeers()).length === 0) showBanner('Room is full.')
break
case 'banned':
showBanner(`Removed by host${err.reason ? `: ${err.reason}` : ''}`)
break
case 'decrypt-failed':
showBanner('Incorrect room password.')
break
case 'peer-connect-failed':
console.warn('Direct WebRTC connection failed; check turnConfig:', err)
break
case 'relay-failed':
console.warn('Could not reach signaling relays:', err.message)
break
}
})
All nine RoomError codes and their properties are documented
in the API reference.
For 'peer-connect-failed', see
TURN & troubleshooting.
Storage and verification
- Domain-separated Base62 IDs. Each tab generates an
ephemeral ECDSA P-256 endpoint keypair (20-character
peerId, domain tagtrystero:pid:v1:) alongside the user's ECDSA P-256 identity keypair (22-characteruserId, domain tagtrystero:uid:v1:, ~131 bits of entropy). The distinct lengths allowtargetto distinguishuserIdfrompeerIdunambiguously. - DTLS-bound handshake (RFC 8827). Before presence events
fire, peers exchange random nonces over the data channel and sign a
transcript binding
appId,roomId, bothpeerIds, bothuserIds, and both WebRTC DTLS certificate fingerprints. This prevents replay attacks and stops a relay from splicing an identity proof onto another connection. - Non-extractable IndexedDB keys. In
'local'mode, initial key generation is synchronized across tabs withnavigator.locksand stored in IndexedDB as a non-extractable Web CryptoCryptoKey. - PBKDF2 signaling keys. When
passwordis set, Trystero derives a 256-bit master secret with PBKDF2-SHA256 (600,000 iterations, salted withappIdandroomId) and subkeys via HKDF-SHA256 to encrypt offers, answers, and ICE candidates with AES-256-GCM. Mismatched passwords emit'decrypt-failed'before a data channel opens.