Guides Self-certifying identities

Self-certifying identities: public keys as user IDs

In a client-server game, a session cookie and database lookup prevent one player from submitting moves on behalf of another. In a peer-to-peer room with no central database or auth server, each browser must verify peer identities directly on the connection.

Deriving IDs from public keys

A self-certifying identifier embeds its own verification rule: generate an asymmetric keypair, derive the ID deterministically from the public key, and prove ownership by signing a challenge with the private key. Any peer can check that the signature is valid and that the public key hashes to the claimed ID without querying a central directory.

Trystero generates an ECDSA P-256 keypair via Web Crypto for each user. The userId is a 22-character Base62 encoding of sha256("trystero:uid:v1:" || x || "." || y) mod 6222 (~131 bits), where x and y are the public key coordinates. Each open browser tab also generates an ephemeral endpoint keypair whose peerId is a 20-character Base62 digest using the domain prefix trystero:pid:v1:.

Separate domain prefixes prevent cross-type hash collisions, and the 22-vs-20 character lengths let target parameters distinguish userId from peerId automatically:

import {joinRoom} from 'trystero'

const room = joinRoom(
  {appId: 'chess.example.com', maxUsers: 2}, // counts unique userIds rather than tabs
  'table-7'
)

const me = await room.getSelf()
console.log(me.userId) // 22 chars, persistent across tabs and reloads
console.log(me.peerId) // 20 chars, ephemeral per tab
console.log(me.identityPersistence) // 'local' by default in browsers

let opponentId = null
room.onUserJoin(({userId}) => {
  opponentId = userId
})

const move = room.makeAction('move')

onLocalMove(san => move.send(san))

move.onMessage((san, {userId}) => {
  // userId was cryptographically verified during the admission handshake
  if (userId !== opponentId) return
  applyOpponentMove(san)
})

Because Trystero verifies key ownership before admitting a peer to the room, the userId delivered to every action, state, and stream callback can be compared directly for authorization checks.

Binding identity to the DTLS channel

Signing a challenge proves someone holding Alice's private key is online, but if signaling traverses an untrusted relay, a man-in-the-middle could attempt to forward Alice's signature onto a connection terminated by the relay or replay an older proof.

Trystero prevents this using the DTLS fingerprint binding approach from RFC 8827. Every WebRTC connection establishes a DTLS session with per-endpoint certificate fingerprints. Before emitting join events, peers exchange random nonces over the data channel and sign a canonical transcript containing appId, roomId, both peerIds, both userIds, both nonces, and both DTLS certificate fingerprints.

Random nonces block replay, DTLS fingerprints bind the proof to that exact encrypted transport, and appId / roomId prevent cross-room transcript reuse. Any verification mismatch aborts admission and emits 'handshake-failed' on room.onError.

Users vs. tabs

When Alice opens your app in two tabs, each tab creates its own WebRTC connection and peerId while authenticating with the same userId:

Action 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

Use userId for rosters, permissions, and state ownership. Passing a userId as target to action.send() or room.addStream() fans out to all of that user's open tabs, while action.request() and room.ping() route to a single tab. maxUsers also counts distinct userIds so refreshing does not consume a second seat. Use peerId when targeting a specific tab or reading RTCPeerConnection diagnostics from room.getPeers().

Key storage and portability

The identity option on joinRoom() controls how identity keys are stored:

  • 'local' (browser default): stores a non-extractable Web Crypto CryptoKey per appId in IndexedDB, coordinated across concurrent first-time tabs with navigator.locks. Scripts can sign with the key without reading raw private key bytes.
  • 'none' (Node, Bun, and Deno default): generates an in-memory keypair per tab, reload, or process start without persisting anything to disk.
  • UserIdentity or async loader: supplies key material created with createUserIdentity(), serialized to a trystero_uk_... string via exportUserIdentity(), and restored with importUserIdentity().

Custom loaders let an authenticated user keep the same userId across devices by storing the exported key in your backend:

import {
  joinRoom,
  createUserIdentity,
  exportUserIdentity,
  importUserIdentity
} from 'trystero'

const room = joinRoom(
  {
    appId: 'oedipa/dungeon-crawl',
    identity: async ({appId}) => {
      const saved = await fetchKeyFromYourBackend(appId)
      if (saved) return importUserIdentity(saved) // 'trystero_uk_...' string

      const fresh = await createUserIdentity()
      await saveKeyToYourBackend(appId, exportUserIdentity(fresh))
      return fresh
    }
  },
  'tavern-1'
)

const {userId} = await room.getSelf()

The same helpers give server-side bots a stable identity across process restarts: generate an identity once, store the trystero_uk_... secret in an environment variable, and pass await importUserIdentity(process.env.BOT_SECRET_KEY) to joinRoom(). Note that exportUserIdentity() rejects browser 'local' identities because their IndexedDB CryptoKeys are marked non-extractable.

Resetting browser identity

To rotate a stored 'local' identity, leave active rooms and call clearUserIdentity(appId):

import {clearUserIdentity} from 'trystero'

await room.leave()
await clearUserIdentity('chess.example.com')

Local testing: open a private window or pass identity: 'none' when simulating multiple users on the same machine.

Scope and limitations

A verified userId guarantees key continuity across reloads and cryptographic authorship of messages and state records. It does not tie a key to a real-world person or prevent Sybil identities: generating a fresh keypair takes milliseconds, so a banned user can clear site storage or open an incognito window to return under a new userId unless the room also requires a password. Conversely, clearing browser storage in 'local' mode permanently discards that userId unless keys were backed up via a custom identity loader.

Pair userId with makeUserState for human-readable display names:

const profile = room.makeUserState('profile', {name: 'Anon'})
profile.set({name: 'Oedipa'})

room.onUserJoin(({userId}) => {
  addPlayer(userId, profile.get(userId).name)
})

profile.onChange((value, {userId, removed}) => {
  if (removed) removePlayer(userId)
  else renamePlayer(userId, value.name)
})

Because two users can choose the same display name, key internal state by userId and render a short key suffix or deterministic color when disambiguating players in the UI. For room-level permissions, roles() builds directly on these keys by encoding the root admin's userId in the room name or a pinned admins list.