End-to-end encryption in peer-to-peer web apps
When browsers discover each other through public relays you do not operate, security depends on three distinct layers: transport encryption on the WebRTC link, signaling encryption during discovery, and cryptographic identity verification once connected.
Three security layers
1. WebRTC transport (DTLS and SRTP)
WebRTC mandates encryption on every connection. Data channels run SCTP over DTLS, while audio and video streams use SRTP keyed from the same DTLS handshake. Session keys are negotiated directly between the two endpoints. Once connected, all Trystero state records, actions, binary transfers, and media streams travel inside that encrypted tunnel.
Even when restrictive firewalls force traffic through a TURN relay, TURN merely forwards encrypted DTLS/SRTP packets without access to the session keys.
2. Signaling discovery
Before DTLS begins, peers exchange SDP descriptions and ICE candidates over a signaling relay. Trystero protects signaling in two steps:
First, topic names are hashed: instead of subscribing to a cleartext room
name, clients subscribe to the SHA-256 digest of
trystero:<appId>:<roomId>. Hashing keeps plain
room names out of relay logs, though anyone who knows both
appId and roomId can compute the same topic.
Second, every SDP offer, answer, and ICE candidate is encrypted with AES-256-GCM before transmission:
- Without
password: the AES-256-GCM key is derived via HKDF-SHA256 fromappIdandroomId. Relay operators who do not know those strings cannot read SDP payloads, while anyone who knows yourappIdand room name can derive the key and join. - With
password: Trystero derives a 256-bit master key using PBKDF2-SHA256 (600,000 iterations, salted withappIdandroomId) and expands subkeys with HKDF-SHA256. Each message uses a random 12-byte IV and binds the signal type, senderpeerId, andofferIdas additional authenticated data (AAD), preventing relays from replaying or splicing ciphertext across handshakes.
Mismatched passwords fail AES-GCM authentication before a data channel
opens and emit 'decrypt-failed' on room.onError
with peerId and stage
('offer' or 'answer').
3. Peer identity binding
Transport encryption alone does not prevent a malicious signaling relay from substituting its own DTLS certificate fingerprint in the SDP to mount a man-in-the-middle attack—at least in rooms without a secret password.
Trystero closes this by deriving every userId and
peerId from an ECDSA P-256 public key. Before emitting join
events, peers exchange fresh nonces over the data channel and sign a
transcript binding appId, roomId, both
peerIds, both userIds, and both DTLS certificate
fingerprints (RFC 8827). A relay substituting its own DTLS session cannot
forge the victim's ECDSA signature over the altered fingerprint, causing
verification to fail with 'handshake-failed'; see
Self-certifying identities.
Using room passwords
Passing a high-entropy token in the URL fragment (#...) keeps
the secret out of HTTP requests, server logs, and Referer
headers:
import {joinRoom} from 'trystero'
if (!location.hash) {
location.hash = crypto.randomUUID()
}
const password = location.hash.slice(1)
const room = joinRoom(
{appId: 'oedipa/late-night-poker', password, maxUsers: 6},
'back-room'
)
// URL fragments after '#' are never sent to HTTP servers
showInviteLink(location.href)
Prefer generated random secrets such as crypto.randomUUID()
(122 bits of entropy) over user-chosen passphrases. Note that a room
password gates room entry equally for everyone holding the link; combine
it with maxUsers for seat limits and
roles() for host permissions.
Two groups using the same roomId with different passwords
share the same hashed signaling topic and will emit
'decrypt-failed' when encountering each other's offers.
Include a per-session random ID in roomId as well.
Because seated participants also see 'decrypt-failed' when an
outsider with an invalid link attempts to join, check whether the local
client has zero connected peers before displaying an error banner:
room.onError(err => {
if (err.code !== 'decrypt-failed') return
if (Object.keys(room.getPeers()).length === 0) {
showBanner('Invalid or expired invite link.')
}
})Multi-hop rooms with scale()
When the experimental scale()
plugin is active and a room grows past maxDirectPeers + 1
peers, intermediate browsers forward overlay frames across hops. Each peer
generates ephemeral ECDSA P-256 signing and ECDH P-256 encryption keys:
targeted unicast messages are encrypted end to end between sender and
recipient via ECDH + AES-256-GCM so forwarding hops only see ciphertext,
while broadcasts, link descriptors, and leave notices are signed and
replay-checked. Media streams and binary transfers over 16 KiB promote to
direct 1-hop WebRTC connections instead of traversing the overlay.
Because overlay forwarding is cooperative, a participant running a
modified client can still drop packets routed through it. Pair
scale() with password and roles()
when running moderated rooms.
Threat summary
| Observer / participant | Can observe or do | Cannot do |
|---|---|---|
| Signaling relay operator |
Hashed topics, announcing peerIds, ciphertext timing
and sizes, client IP addresses
|
Decrypt handshakes without appId + roomId
(and password when set), or see WebRTC data/media
|
Knows appId + roomId (no password) | Derive the default signaling key and join under their own key |
Impersonate an existing userId or forge signed state
|
Holds the room password | Join the room and read broadcasts and shared state | Forge another user's identity or bypass roles() checks |
| Room member with a modified client |
Read room broadcasts, send arbitrary inputs, drop packets routed
through them in scale() rooms
|
Forge another user's signatures or decrypt targeted unicast frames
between other peers in scale() rooms
|
| TURN server operator | Endpoint IP addresses, packet timing, and byte volume | Read media or data payloads (forwards DTLS/SRTP ciphertext) |
What encryption does not hide
Traffic metadata
Signaling relays still observe when clients subscribe to a topic hash, how many peers announce, and which IP addresses connect. Encryption protects handshake and data contents rather than network-level metadata.
Peer IP addresses
Direct WebRTC connections exchange public (and sometimes local) IP candidates with connected peers. When participants should not learn one another's IP addresses, force TURN-only transport so peers only see the TURN server's address:
import {joinRoom} from 'trystero'
const room = joinRoom(
{
appId: 'review.your-domain.example',
password: inviteSecret,
// Force relay-only candidates so peers do not exchange direct IP addresses
rtcConfig: {iceServers: [], iceTransportPolicy: 'relay'},
turnConfig: [
{
urls: [
'turn:turn.your-domain.example:3478?transport=udp',
'turns:turn.your-domain.example:5349?transport=tcp'
],
username: turnUser,
credential: turnPassword
}
]
},
reviewId
)Application invariants
Authenticated room members can still send malformed or out-of-range
payloads from their own key. Validate incoming action payloads and state
updates in application logic, and gate large binary transfers with
onReceive:
const bet = room.makeAction('bet')
bet.onMessage((amount, {userId}) => {
if (!Number.isInteger(amount) || amount <= 0 || amount > stacks[userId]) {
return
}
applyBet(userId, amount)
})
const pot = room.makeState('pot', 0, {
validate: next => Number.isInteger(next) && next >= 0
})