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),引入它,然后用一个完全唯一的 appId 调用 joinRoom(config, roomId)——加入同一个房间 ID 的节点会自动互相发现并建立连接。
我需要自己架设匹配服务器或注册任何账号吗?默认都不需要:默认的包通过公共的 Nostr 网络来完成节点发现。只有部分策略需要你自己的配置——Supabase 需要你的项目 URL,Firebase 需要把你的 databaseURL 作为 appId。
点对点连接在所有网络下都能用吗?一些限制严格的网络会封锁直接的 WebRTC 连接。文档给出的解决办法是配置一台 TURN 服务器作为中转兜底——Cloudflare 提供每月 1,000 GB 流量的免费额度——而且只有无法直连的节点才会经过它。
我应用的数据会经过第三方服务器吗?应用数据直接点对点传输并采用端到端加密,绝不经过信令媒介。信令媒介上只交换连接建立的信息,而且默认就是加密的——你还可以设置共享密码来进一步保护房间。
节点发现策略有哪几种可以选?七种,而且都共用同一个 API:BitTorrent、Nostr、MQTT、Supabase、Firebase、IPFS,以及自建的 WebSocket 中继。只要换一下引入的包,就能切换策略。
除了原生 WebRTC,Trystero 还帮我处理了哪些事?房间和广播、对你发送的所有内容自动序列化、对大文件传输自动分块和限速、进度事件和 Promise、二进制数据的元数据,以及开箱即用的 React hooks。
能用它做语音或视频聊天室吗?可以——你把本地的媒体流广播到房间里,并通过事件接收其他节点的流,然后把收到的视频流挂到 DOM 里的 video 元素上。
我能在服务器或树莓派上跑一个常驻节点吗?可以——只要引入一个 WebRTC polyfill,同样的代码就能在 Node、Bun 和 Deno 上以服务端方式运行。常见用法是跑一个常驻节点为新加入的人保存最近的状态,或者在嵌入式设备上跑轻量节点。
作者
dmotz
大小
4.7 MB
星标
2.9K
时长
6年
提交 · 90 天