trystero README

README проекта с github.com/dmotz/trystero. Одним файлом markdown: README.md.

✨🤝✨ Trystero

Instant peer-to-peer multiplayer for the web — no server required.

👉 Try it live on trystero.dev 👈

Making your app work with multiple users usually means a detour into setting up servers, auth, billing, databases, etc. — all so two browsers can say hello.

Trystero skips the backend entirely. Import the library, join a room by name, and browsers discover each other automatically and connect directly over fast, end-to-end encrypted WebRTC. Out of the box, you get verified user identities, synced user and room state, host permissions, RPC, chunked file transfers, and live audio/video. The web was meant to be decentralized and Trystero makes it easy to build apps where data flows without middlemen.


Quickstart

Install Trystero from npm:

npm i trystero
(Or skip the build step and import from a script tag)
<script type="module">
  import {joinRoom} from 'https://esm.run/trystero'
</script>

Join a room with a unique app ID and room name and start syncing state. Here's a complete multiplayer cursor canvas in a dozen lines:

import {joinRoom} from 'trystero'

// No API keys, accounts, or backend setup. Just pick a globally unique appId
// (e.g. your app's domain or 'username/app-name') and a room name
const room = joinRoom({appId: 'pixel-party.example.com'}, 'studio-49')

// Give every user their own signed state slot
const cursor = room.makeUserState('cursor', {x: 0, y: 0})

window.addEventListener('pointermove', e =>
  cursor.set({x: e.clientX, y: e.clientY})
)

cursor.onChange((pos, {userId, self, removed}) => {
  if (self) {
    return
  }
  if (removed) {
    removeCursor(userId)
  } else {
    drawCursor(userId, pos)
  }
})

Open your page in two browsers anywhere in the world and watch the cursors move.

Local testing tip: Tabs in the same browser profile share your userId automatically. Open a Private/Incognito window (or pass identity: 'none' in the room config) when simulating a second person on one machine.


What you can build with it

1. Synced user & room state

Most multiplayer apps need two kinds of live state: per-user state that each participant owns (names, avatars, ready flags, cursors) and shared room state for the group (a game board, round timer, or watch-party queue).

Trystero builds both right onto room. Updates apply immediately locally, coalesce rapid writes on the wire, verify who wrote them, and sync automatically to late joiners — even if the person who last updated shared state has already closed their laptop.

// Each player controls only their own signed slot — nobody can overwrite yours
const profile = room.makeUserState('profile', {name: 'Anon', ready: false})
profile.set({name: 'Oedipa', ready: true})

// Snapshot of everyone currently in the room: { [userId]: { name, ready } }
console.log(profile.getAll())

// Shared state for the whole room, synced automatically to latecomers
const track = room.makeState('track', {url: 'chill-beat.mp3', paused: true})

track.onChange((next, {userId}) => {
  syncAudioPlayer(next)
  console.log(`Updated by ${userId}`)
})

await track.set(prev => ({...prev, paused: false}))

Using React? Both makeUserState and makeState plug straight into useSyncExternalStore — no useEffect glue or manual join/leave maps:

import {useSyncExternalStore} from 'react'

function Lobby() {
  const players = useSyncExternalStore(profile.onChange, profile.getAll)
  const nowPlaying = useSyncExternalStore(track.onChange, track.get)
  // render directly from `players` and `nowPlaying`
}

👉 Shared & Per-User State guide →


2. Unforgeable user identity, passwords & room caps

Every participant gets a persistent, cryptographically verified userId out of the box — no login screens or auth servers required. If someone refreshes the page or opens your app in two tabs at once, Trystero recognizes them as the same user automatically. (Want strictly throwaway IDs or keys loaded from your own backend? One config option switches modes.)

Combine password and maxUsers to spin up private, seat-capped matches like a 2-player chess table or a 4-player co-op lobby:

const room = joinRoom(
  {
    appId: 'chess.example.com',
    password: 'knight-takes-f7-secret', // encrypts discovery so outsiders stay out
    maxUsers: 2 // cap this match at 2 unique players (you + 1 opponent)
  },
  'table-7'
)

const {userId} = await room.getSelf()

room.onUserJoin(({userId}) => console.log(`Opponent ${userId} sat down`))
room.onUserLeave(({userId}) => console.log(`Opponent ${userId} left`))

room.onError(err => {
  if (err.code === 'room-full' && Object.keys(room.getPeers()).length === 0) {
    showBanner('Sorry, both seats at this table are taken!')
  }
})

👉 Identity, Presence & Room Access guide →


3. Serverless hosts, custom roles & moderation

In a typical P2P app, everyone is equal — which gets awkward the moment someone opens DevTools in your game and awards themselves a million points.

Import the tree-shakeable roles() plugin to create rooms with mathematically verified admins, custom roles (like 'dj' or 'moderator'), authoritative state that only authorized roles can edit, and peer banning — still with zero backend:

import {joinRoom, roles} from 'trystero'

// Host creates a room where their userId has verified admin authority
const room = joinRoom(
  {appId: 'oedipa/friday-trivia', use: [roles({selfAsAdmin: true})]},
  'quiz-night'
)

// Share `roomId` (e.g. "quiz-night~9fX2kLm...") in an invite link;
// guests join with `use: [roles()]` and automatically verify the host
const {roomId} = await room.getSelf()

// With roles() enabled, makeState defaults to admin-only writes —
// everyone can read `game`, and peers reject forged edits automatically
const game = room.makeState('game', {round: 1, prompt: 'Ready?'})
await game.set({round: 2, prompt: 'Name the moons of Mars'})

// Promote helpers or boot troublemakers
await room.grantRole(friendId, 'cohost')
await room.ban(grieferId, {reason: 'spoiling answers'})

👉 Admins, Roles & Moderation guide →


4. Events, RPC & direct P2P file drop

For ephemeral events, request/response calls, and binary transfers, create typed channels with room.makeAction(). Pass strings, JSON objects, Blobs, Files, or TypedArrays — Trystero handles serialization, chunking, backpressure, metadata headers, and transfer progress automatically, with zero cloud storage bills:

const drop = room.makeAction('file-drop')

// Optionally add a predicate too accept based on max byteLength
drop.onReceive(({byteLength}) => byteLength <= 100 * 1024 ** 2)

// Listen for progress events to show a loading bar
drop.onReceiveProgress((pct, {metadata}) => showDownloadBar(metadata.name, pct))

// When the file is done being received, save it
drop.onMessage((bytes, {userId, metadata}) => saveFile(bytes, metadata.name))

// Send a file to the room with optional metadata
await drop.send(file, {
  metadata: {name: file.name},
  onProgress: pct => showUploadBar(pct)
})

// Create a request action where you ask a peer for something and they provide
// an answer
const roll = room.makeAction('roll-check', {kind: 'request'})

// Respond to roll requests from other peers
roll.onRequest(() => Math.ceil(Math.random() * 20))

// Ask a specific friendId for their roll number
const result = await roll.request(null, {target: friendId, timeoutMs: 2000})

👉 Actions, RPC & File Transfers guide →


5. Voice, video & screen sharing

Drop live audio, webcam video, screen captures, or Web Audio streams into any room, and tag streams with metadata so peers can tell a facecam from a screen share:

const stream = await navigator.mediaDevices.getUserMedia({
  audio: true,
  video: true
})

// Send to everyone here now, plus anyone who joins later
await room.addStream(stream, {metadata: {type: 'webcam'}})
room.onUserJoin(({userId}) =>
  room.addStream(stream, {target: userId, metadata: {type: 'webcam'}})
)

// Add a video when receiving a stream from someone else
room.onPeerStream((remoteStream, {userId, metadata}) =>
  attachVideo(userId, remoteStream, metadata.type)
)

👉 Audio, Video & Screen Sharing guide →


6. Scale to large numbers of peers

Standard WebRTC connects every browser directly to every other browser, which is ideal for smaller hangouts and matches. Building a 100-person collaborative canvas or a crowded party lobby? Opt into the scale() plugin:

import {joinRoom, scale} from 'trystero'

const room = joinRoom({appId: 'canvas.example.com', use: [scale()]}, 'plaza')

Small rooms stay in a fast direct mesh with zero extra overhead. As more people pile in, Trystero automatically forms a multi-hop gossip network so no single browser gets overwhelmed — while your state, action, and media code stays exactly the same.

👉 Scaling Large Rooms guide →


7. Run headless peers in Node, Bun & Deno

Trystero runs outside the browser too. Drop a lightweight peer onto a Raspberry Pi, build a game bot, or run a silent passive: true peer on a tiny box to keep shared room state warm even when every browser tab closes:

import {joinRoom} from 'trystero'
import {RTCPeerConnection} from 'werift'

const room = joinRoom(
  {appId: 'oedipa/synth-jam', rtcPolyfill: RTCPeerConnection, passive: true},
  'room-1'
)

// Silently caches and syncs the latest pattern for newcomers
room.makeState('pattern', {bpm: 120, steps: []})

👉 Running in Node, Bun & Deno guide →


How does Trystero connect users with no backend?

WebRTC lets browsers talk directly to each other, peer-to-peer, without routing traffic through a central server. The one catch with WebRTC has always been signaling: two browsers need a brief introduction to swap connection info before they can link up.

Trystero handles that introduction automatically out of the box using decentralized public relays — nothing to deploy or configure. Once peers connect, your app's data never touches a relay: state, messages, files, and media flow straight from browser to browser, end-to-end encrypted.

Prefer to run your own signaling setup with Nostr, MQTT, BitTorrent, Supabase, Firebase, or a tiny self-hosted WebSocket relay? You can swap strategies with a one-line import change — see the Signaling & Relays guide.

Peek under the hood: how serverless discovery and security work
  • Encrypted signaling: Connection offers (SDPs) are encrypted with AES-256-GCM before touching any relay. Adding a room password derives the key via WebCrypto PBKDF2-SHA256 (600,000 iterations) so outsiders and relay operators can't read handshakes or join the room.
  • Self-certifying identities: Every user (userId) and browser tab (peerId) is derived from a WebCrypto ECDSA P-256 public keypair. During connection setup, peers verify each other's keys against the WebRTC DTLS certificate fingerprint (RFC 8827), preventing spoofing and man-in-the-middle relays.
  • Signed state & roles: Updates to makeUserState, makeState, and roles() carry cryptographic signatures and Hybrid Logical Clock timestamps, allowing peers (including late joiners) to verify who wrote what without a central server.

Documentation

Dive deeper into any feature or browse the full API:

Guide What's inside
Shared & Per-User State makeUserState, makeState, validation rules, late-joiner sync, and React (useSyncExternalStore)
Identity, Presence & Room Access userId vs peerId, multi-tab presence, custom identity keys, room passwords, maxUsers, and onError
Admins, Roles & Moderation roles(), self-certifying rooms, fixed admins, custom roles, authoritative state, and banning
Actions, RPC & File Transfers makeAction, send, request & requestMany, TypeScript types, binary metadata, progress bars, and onReceive
Audio, Video & Screen Sharing addStream, onPeerStream, removeStream, camera/screen switching (replaceTrack), and stream metadata
Scaling Large Rooms Multi-hop routing with scale(), direct media/file promotion, and getTopology()
Signaling & Relays Default zero-config relays, Supabase, Firebase, MQTT, BitTorrent, self-hosted ws-relay, custom strategies, and bundle sizes
Running in Node, Bun & Deno Headless peers, Raspberry Pi / IoT setups, and passive state backup peers
NAT Traversal & Troubleshooting Configuring TURN servers, diagnosing strict firewalls, and ping()
Full API Reference Complete function signatures, TypeScript types, config options, and error codes
Upgrading to 0.27.0 Architectural overview, breaking changes, and before/after migration examples

Trystero by Dan Motzenbecker

trystero (dmotz/trystero)

Ищем в базе…

Что это такое?Trystero — это библиотека на TypeScript для создания многопользовательских веб-приложений без сервера: она позволяет браузерам находить друг друга и соединяться напрямую через WebRTC, а публичные сети вроде BitTorrent или Nostr используются только для поиска участников.
Это библиотека, которую я добавляю в свой код, или облачный сервис?Это фронтенд-библиотека — вы устанавливаете её через пакетный менеджер или подключаете с CDN и импортируете в своё приложение. Регистрироваться ни в каком сервисе не нужно, ничего разворачивать тоже, а живое демо доступно на trystero.dev.
Как заставить два браузера общаться друг с другом?Установите пакет (или используйте CDN), импортируйте его и вызовите joinRoom(config, roomId) с абсолютно уникальным appId — все участники, зашедшие в комнату с одним и тем же ID, автоматически находят друг друга и соединяются.
Нужно ли мне поднимать свой сервер для поиска участников или создавать какие-то аккаунты?По умолчанию ничего не нужно: базовый пакет находит участников через публичную сеть Nostr. Лишь некоторые стратегии требуют своей настройки — Supabase нужен URL вашего проекта, а Firebase — databaseURL в качестве appId.
Прямое соединение между участниками будет работать в любой сети?Некоторые сети с ограничениями блокируют прямые WebRTC-соединения. Задокументированное решение — настроить TURN-сервер как резервный прокси — Cloudflare предлагает бесплатный тариф с 1 000 ГБ трафика в месяц; через него идут только те участники, которые не могут соединиться напрямую.
Данные моего приложения проходят через какой-нибудь сторонний сервер?Данные приложения передаются напрямую между участниками и зашифрованы сквозным шифрованием; сигнальный канал их не касается. Через него передаётся только установка соединения, и она тоже зашифрована по умолчанию — а ещё можно задать общий пароль, чтобы дополнительно защитить комнату.
Какие стратегии поиска участников можно выбрать?Семь, и все за одним API: BitTorrent, Nostr, MQTT, Supabase, Firebase, IPFS и собственный WebSocket-ретранслятор на вашем сервере. Стратегия меняется простым выбором другого пакета для импорта.
Что Trystero берёт на себя по сравнению с чистым WebRTC?Комнаты и рассылку сообщений, автоматическую сериализацию всего, что вы отправляете, автоматическое разбиение больших передач на части и контроль скорости, события прогресса и промисы, метаданные для бинарных данных, а также React-хуки, которые работают сразу из коробки.
Можно ли с её помощью сделать аудио- или видеочат?Да — вы рассылаете свой локальный медиапоток в комнату и получаете потоки других участников через событие, а затем подключаете входящие видеопотоки к video-элементам в DOM.
Можно ли запустить постоянно работающего участника на сервере или Raspberry Pi?Да — тот же синтаксис работает на сервере под Node, Bun и Deno, если импортировать WebRTC-полифилл. Типичные сценарии — всегда включённый участник, который хранит последнее состояние для новичков, или лёгкие участники на встраиваемых устройствах.
Какие есть похожие проекты?webtorrent, yjs, trackerslist, sphere-sdk, gun, webtorrent-desktop, appwrite, rxdb
Автор
dmotz
Размер
4.7 MB
Звёзды
2.9K
Возраст
6 г
Коммиты · 90 дней