freertc
v0.5.0
Published
WebRTC browser client and Cloudflare Worker signaling relay with D1 storage.
Maintainers
Readme
freertc
This project provides a Cloudflare Worker signaling relay for WebRTC peers using the Peer Signaling Protocol (PSP) envelope shape.
Deploy your own federated relay
This is the fastest installation path. The button creates the Worker and D1 database in your Cloudflare account, applies every D1 migration, generates an UnSEA relay identity, installs it directly as an encrypted Worker secret, and deploys the relay to your own <worker>.<account>.workers.dev address. The private identity is never printed or added to the generated repository.
Immediately after deployment, the install script requests the new Worker's /health endpoint. The Worker derives wss://<worker>.<account>.workers.dev/ws from that request and joins the Kademlia overlay through its seed relays. No custom domain is required. Cloudflare lets you customize the Worker and database names before deployment.
There is no hub. Every one-click relay joins the network through the seeds in KADEMLIA_BOOTSTRAP_URLS, asking one at a time in random order; the seed answers with the relays closest to the newcomer's own ID, and the newcomer carries on from those. Any relay can be a seed for the next, and /health lists the seeds a relay was given. Each federated relay's PSP sender ID is its relay ID: the SHA-256 of its signing key, the same ID it has in the overlay and in its tunnel address (a relay without a signing key uses the SHA-256 of its domain).
See Cloudflare's Deploy Button documentation for details about the account and repository flow.
Install from npm (manual)
Local project install:
npm install freertcGlobal install:
npm install -g freertcWhen you run the CLI from your project directory, freertc copies the required worker files into that directory on first run:
src/index.jssrc/kademlia.jssrc/relay-identity.jssrc/relay-overlay.jspublic/index.htmlpublic/app.jsmigrations/0001_initial.sqlmigrations/0002_kademlia_overlay.sqlscripts/d1-schema.sqlscripts/deploy-cloudflare.mjswrangler.template.jsoncwrangler.workers-dev.jsonc
Browser client
The package also exports the browser signaling and WebRTC client used by the demo:
import { createSignalingClient } from "freertc/client";
const client = createSignalingClient({
peerId: crypto.randomUUID(),
networkId: "my-app",
roomId: "pairing-room",
signalUrl: "wss://your-relay.example/ws",
autoConnect: false,
onDataMessage: ({ peerId, data }) => {
console.log("data from", peerId, data);
},
});
client.connect();Use client.initiateConnection(peerId) to open a WebRTC data channel and
client.sendData(data, peerId) to send an application payload. Calling
client.disconnect() closes signaling and peer connections.
Relay on demand (opt-in)
By default the client keeps its relay socket open for as long as it runs: an announce every 12 s and a ping every second. The relay is for meeting the mesh, so a peer that already has a healthy mesh can let it go:
import { createSignalingClient } from "freertc/client";
const client = createSignalingClient({
peerId: crypto.randomUUID(),
networkId: "my-app",
roomId: "pairing-room",
signalUrl: "wss://your-relay.example/ws",
autoConnect: false,
onDataMessage: ({ peerId, data }) => {
console.log("data from", peerId, data);
},
// Required for on-demand: a way to carry negotiation frames over the mesh.
signalTransport: (envelope) => mesh.send(envelope),
relay: { mode: "on-demand", minMeshPeers: 2, anchors: 3 },
onRelayStateChange: ({ state }) => console.log("relay", state), // up | idle | waking
});
client.connect();- A peer with at least
minMeshPeerslive data-channel neighbours withdraws from the relay and closes its socket once it has been releasable forsettleMs(30 s). - Anchors stay registered so a newcomer still finds a way in: the
anchorspeers (default 3) whose id is closest to the room, by SHA-256 on a 256-bit ring. Neighbours tell each other which peers they can vouch for with a small~anchorsframe over the data channel, so each peer works out the same set, and an anchor that disappears is replaced as soon as its neighbours stop vouching for it. - A released peer wakes the relay when its mesh drops below
minMeshPeers, when it needs to signal a peer the mesh cannot reach, when it asks for discovery (requestBootstrap), or onclient.wakeRelay(). It stays up forlingerMs(60 s) after a wake. client.relayIdleis true while the socket is released on purpose. A host that watches for a missing relay acknowledgement must treat that as healthy, or it will reopen the socket it was meant to leave closed.- Without
signalTransport,mode: "on-demand"is ignored, because a released relay is only safe when negotiation can travel by mesh.
Limits: anchors are chosen among a peer, its live neighbours and the peers they vouch for (two hops), so a
very large room has more than anchors of them, never fewer; a neighbour that lies can make a peer
release the relay early, and the peer wakes it again as soon as its own mesh degree drops.
What this worker does
- Accepts WebSocket client connections at
/ws. - Validates PSP message envelopes (
psp_version,type,network,session_id,from,message_id,timestamp). - Supports discovery, negotiation, control, and extension message types.
- Stores peer announcements in Cloudflare D1 (
psp_announcements). - Stores directed signaling messages in Cloudflare D1 (
psp_relay). - Routes across federated relays through bounded Kademlia buckets when a signed relay identity is configured.
- Keeps the simple
/api/v1/relaysregistry as a compatibility fallback for relays without signing keys. - Exposes federation peer lookup at
/api/v1/peersand message forwarding at/api/v1/relay. - Delivers queued relay messages when peers reconnect.
- Serves the browser demo from
public/.
Network and Room scopes
The browser UI uses two distinct scopes:
- Network maps to the PSP envelope
networkand announceinstance_id. - Room maps to the PSP envelope
session_id.
Peers are discoverable and relay messages are deliverable only when both Network and Room match. The relay domain is not an isolation boundary: peer.ooo and decentralize.ooo can federate peers that deliberately use the same Network and Room.
A peer can say what it is with capabilities.role in its announce (a short lowercase word, such as storage). Relays store it and list it with the peer, and list peers with a role before the rest, so a scope where many plain peers look for a few servers never cuts the servers from a list. Most peers have no role; relays without migration 0003 simply leave it out.
Local relays
A local relay runs the same relay code under Node, on your own machine:
node scripts/node-relay.mjsIt federates with the cloud relays by default. Behind NAT it takes a public address through a tunnel to a public relay. Clients with WebRTC reach it over a punched data channel introduced through that tunnel, instead of through the tunnel itself. It also links to other local relays directly, so federation between local relays does not pass through the cloud. PeerPigeon clients prefer a healthy local relay over a cloud one. See docs/RELAYS.md for the design, the settings, and measured costs.
Your relay's own name and certificate
A local relay can have its own name on your domain and a Let's Encrypt
certificate, so browsers anywhere reach it as wss://<name>:8443/ws. Your
FreeRTC Worker keeps the name (it holds the only DNS token); the relay asks it.
On the machine that runs the relay, in this folder, once:
npx freertc name --domain example.comIt logs in with wrangler (a browser window, if you are not logged in), finds your FreeRTC Worker and the domain, and registers this relay with the Worker. The first time for a domain it also opens Cloudflare's API token page, already filled in for a token that can only edit DNS on that domain: click Create Token, then Copy, and press Enter in the terminal (wrangler's login cannot make tokens). Don't paste it: it is read from the clipboard, never shown, and the clipboard is emptied. It is checked and stored in the Worker, never on the machine. Restart the relay; from then on it does the rest:
- points
<first 16 characters of its id>.example.comat your public address, and again whenever that changes; - gets a certificate from Let's Encrypt by DNS-01 (the Worker writes the challenge record; nothing needs to be reachable for it), renews it with 30 days left;
- serves
wss://andhttps://onFREERTC_TLS_PORT(8443) and asks the router to forward it (UPnP or NAT-PMP); - lists
wss://<name>:8443/wsin the relay directory, which accepts it only if DNS for the name points at the relay's own address.
Settings: FREERTC_NAMES=off turns it off; FREERTC_ACME_STAGING=1 uses Let's
Encrypt's staging service (test certificates); FREERTC_NAMES_URL points at a
Worker without running freertc name. A Worker with NAMES_OPEN=1 names any
relay (a public naming service). The Worker side is src/direct/names.js; the
relay side src/node/relay-name.js; the command scripts/name-setup.mjs.
Kademlia relay overlay
FreeRTC uses Kademlia between federated relays—not between browser peers. Relay IDs, scope keys, and exact-peer keys are deterministic 256-bit SHA-256 values produced by UnSEA. Relay and provider records are signed with stable UnSEA P-256 identities before they are accepted or replicated.
The overlay keeps at most 20 contacts per XOR-distance bucket, performs lookups three relays at a time with a 24-query ceiling, and replicates provider records to the five closest relays. Discovery queries at most eight load-ranked providers for a Network + Room; directed signaling forwards to at most two providers for the exact destination peer. These bounds replace federation-wide fanout as the relay population grows.
Kademlia is enabled when D1 and the relay identity secret are present. Both are configured automatically:
# Deploy from a cloned repository
npm run deploy
# Deploy an npm-installed project using its production environment
npx freertc deploy
# Local Cloudflare development
npm run dev:cfProduction deployment applies pending remote migrations, deploys the Worker, then checks for an existing relay identity. Existing identities are preserved. On the first deployment, a new UnSEA identity is held only in process memory and streamed directly to Wrangler's bulk-secret command. Local development stores its automatically generated identity in the git-ignored .dev.vars file and applies local migrations before starting Wrangler.
Optional routing settings remain ordinary Wrangler variables:
"KADEMLIA_BOOTSTRAP_URLS": "wss://peer.ooo/ws,wss://decentralize.ooo/ws",
"RELAY_CAPACITY": "10000"Every bootstrap URL must point to a FreeRTC relay with Kademlia enabled. List several: a joining relay asks one at a time, in a random order, and stops at the first that answers; relays it has learned of are tried only when every seed is down. Nothing is a default hub, and a relay with no seeds simply runs standalone. GLOBAL_RELAY_URL is still read as one more seed for compatibility, and, only when it is set and the relay has no signing keys, it names the hub for the legacy registry. Legacy deployments using separate RELAY_SIGNING_PUBLIC_KEY and RELAY_SIGNING_PRIVATE_KEY values continue to work during migration. npx freertc relay:keygen remains available only for manual identity recovery or migration.
A relay's peer ID is the SHA-256 of the domain it is deployed on (wss://peer.ooo/ws → sha256("peer.ooo")). It is derived, not configured: there is no RELAY_PEER_ID setting, and an old one left in a Wrangler config is ignored.
Runtime scope
- The checked-in Cloudflare Worker runtime is
src/index.jswith Cloudflare D1 (DBbinding). - The Rust/WASM worker lives in
src/lib.rsand is optional; the default template now uses the JS worker path. - The built-in browser demo served by the Worker is
public/index.html+public/app.js. demo/src/*is a legacy/experimental code path and is not used bywrangler devorwrangler deployin the current setup.
Supported message types
- Discovery:
announce,withdraw,discover,peer_list,redirect - Negotiation:
connect_request,connect_accept,connect_reject,offer,answer,ice_candidate,ice_end,renegotiate - Control:
ping,pong,bye,error,ack - Extension:
ext
Wrangler install wizard (recommended)
Use the interactive wizard from the project directory where you want the worker files and Wrangler config to live:
npx freertc wizardThe default command runs full setup mode (both):
npx freertcYou can also preselect full setup mode explicitly:
npx freertc setupGlobal install flow:
freertc wizard
freertcAfter install, freertc prints a quick-start reminder with the exact next command.
The wizard can:
- Copy the worker runtime files into your current project when they are missing.
- Verify Wrangler CLI.
- Create
wrangler.jsoncfromwrangler.template.jsoncif needed. - No domain? No problem. Press Enter at the domain prompt to deploy on a free
workers.devsubdomain. - Set Worker name automatically to
freertc-<your-domain>when a domain is provided. - Initialize local D1 schema for
wrangler dev. - Initialize remote D1 schema for deploy.
- Detect Rust build configs and install
worker-build/WASM target automatically when required. - Check existing Wrangler auth and only run
wrangler loginwhen needed. - Optionally run
npm run dev:cfandnpm run deploy.
Manual setup
1. Install dependencies
npm installIf you installed the npm package instead of cloning the repo, use npx freertc wizard instead of the repository scripts below.
2. Configure Wrangler
- If needed, copy
wrangler.template.jsonctowrangler.jsonc. - Set your Worker name, route(s), and D1 database values.
- Ensure
d1_databases[0].bindingisDB.
3. Initialize D1 schema
Normal deploy and dev:cf commands perform this step automatically. The following commands are available for manual database maintenance.
Local (for wrangler dev):
npm run d1:init:localRemote (for production):
npm run d1:init:remoteIf your database name is not freertc-signal, use Wrangler directly:
wrangler d1 execute <your-db-name> --local --file scripts/d1-schema.sql
wrangler d1 execute <your-db-name> --remote --file scripts/d1-schema.sqlLocal development
npm run devnpm run dev now runs the non-Cloudflare local runtime (plain Node.js + WebSocket).
Cloudflare/Wrangler runtime:
npm run dev:cfShortcut alias (same behavior):
npm run dev:localIt listens on 0.0.0.0:8788 by default, so other machines on your network can
use it at ws://<this machine's LAN address>:8788/ws. To keep it to this machine,
or to pick another port:
HOST=127.0.0.1 PORT=8788 npm run dev:nodenpm run dev:cf checks local Rust Worker prerequisites automatically:
- Uses
wrangler.workers-dev.jsoncautomatically whenwrangler.jsoncis not present. - Only installs
worker-buildand the WebAssembly Rust target when the selected Wrangler config uses aworker-buildcommand. - The checked-in
wrangler.workers-dev.jsoncuses generic local-development values and points tosrc/index.js, so standard demo runs do not require Rust/WASM setup.
Endpoints:
- WebSocket:
ws://127.0.0.1:8788/ws(npm run dev) - Health:
http://127.0.0.1:8788/health(npm run dev) - Demo UI:
http://127.0.0.1:8788/(npm run dev)
Cloudflare/Wrangler endpoints (default):
- WebSocket:
ws://127.0.0.1:8787/ws(npm run dev:cf) - Health:
http://127.0.0.1:8787/health(npm run dev:cf) - Demo UI:
http://127.0.0.1:8787/(npm run dev:cf) - Relay registry:
http://127.0.0.1:8787/api/v1/relays(GET/POST, when D1 is configured)
Deploy
npx freertc deployIf you installed freertc globally:
freertc deployRepository-only scripts:
npm run buildbundles and validates the default JavaScript Worker without deploying it.npm run build:rustbuilds the optional Rust/WASM worker viaworker-build --release.npm run deploy:rawdeploys without--env production.npm run checkrunscargo check --target wasm32-unknown-unknownfor the Rust worker path.npm run devruns the standalone local relay (non-Cloudflare).npm run dev:cfruns Wrangler/Cloudflare local dev.npm run dev:noderuns a standalone local relay without Cloudflare/Wrangler.npm run dev:localis a no-env shortcut for the standalone local relay.
Troubleshooting custom domain deploys
If your custom domain returns:
{"error":"API key is missing"}that error is usually from Cloudflare routing/auth config, not from this Worker runtime.
Quick checks:
- Compare
https://<workers-subdomain>/healthandhttps://<custom-domain>/health. - Confirm your route/custom domain points to this Worker.
- Review Cloudflare Access/API Shield/WAF rules on the custom hostname.
- If deploying with
--env production, verify that environment is the one bound to the route.
Expected /health response includes JSON like:
{"ok":true,"version":"0.1.32","protocol_version":"1.0","peers":0}Auto WebRTC two-tab test
The demo defaults to Auto WebRTC and performs real offer/answer + ICE exchange over this Worker.
- Open
http://127.0.0.1:8787/in two tabs. - Set both tabs to the same Network and Room.
- Set opposite peer IDs using random hex strings:
- Tab A
from:fc2142e44ec5c76f1bd46ccbb1eb2ed48f66f64260a5299c871f37ac742fa0c9 - Tab B
from:3e45d44c4ce4f9304a53f42b978fd13d23f85df4d97a88f8eb33ec13a2f8f7b1
- Tab A
- Set each tab
toto the other tabfrom, or leavetoempty for auto-discovery. - Connect both sockets and click Start Auto Handshake in both tabs.
- When DataChannel is open, send chat messages.
Minimal client expectations
- Send
announcefirst to bind socket identity (from,network,session_id). - Set announce
body.instance_idto the same value asnetwork. - Include the Room as
session_idon every message. - Include
tofor directed messages. - Use periodic
announceto refresh presence TTL and receive queued relay messages. - Use
pingfor liveness (pong) and keepalive.
Notes
- TTL is enforced using
timestamp + ttl_ms(default 30 seconds, max 120 seconds). - Malformed envelopes produce PSP
errorresponses.
