npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2026 – Pkg Stats / Ryan Hefner

freertc

v0.5.0

Published

WebRTC browser client and Cloudflare Worker signaling relay with D1 storage.

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

Deploy to Cloudflare

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 freertc

Global install:

npm install -g freertc

When you run the CLI from your project directory, freertc copies the required worker files into that directory on first run:

  • src/index.js
  • src/kademlia.js
  • src/relay-identity.js
  • src/relay-overlay.js
  • public/index.html
  • public/app.js
  • migrations/0001_initial.sql
  • migrations/0002_kademlia_overlay.sql
  • scripts/d1-schema.sql
  • scripts/deploy-cloudflare.mjs
  • wrangler.template.jsonc
  • wrangler.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 minMeshPeers live data-channel neighbours withdraws from the relay and closes its socket once it has been releasable for settleMs (30 s).
  • Anchors stay registered so a newcomer still finds a way in: the anchors peers (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 ~anchors frame 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 on client.wakeRelay(). It stays up for lingerMs (60 s) after a wake.
  • client.relayIdle is 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/relays registry as a compatibility fallback for relays without signing keys.
  • Exposes federation peer lookup at /api/v1/peers and 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 network and announce instance_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.mjs

It 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.com

It 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.com at 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:// and https:// on FREERTC_TLS_PORT (8443) and asks the router to forward it (UPnP or NAT-PMP);
  • lists wss://<name>:8443/ws in 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:cf

Production 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.js with Cloudflare D1 (DB binding).
  • The Rust/WASM worker lives in src/lib.rs and 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 by wrangler dev or wrangler deploy in 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 wizard

The default command runs full setup mode (both):

npx freertc

You can also preselect full setup mode explicitly:

npx freertc setup

Global install flow:

freertc wizard
freertc

After 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.jsonc from wrangler.template.jsonc if needed.
  • No domain? No problem. Press Enter at the domain prompt to deploy on a free workers.dev subdomain.
  • 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 login when needed.
  • Optionally run npm run dev:cf and npm run deploy.

Manual setup

1. Install dependencies

npm install

If 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.jsonc to wrangler.jsonc.
  • Set your Worker name, route(s), and D1 database values.
  • Ensure d1_databases[0].binding is DB.

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:local

Remote (for production):

npm run d1:init:remote

If 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.sql

Local development

npm run dev

npm run dev now runs the non-Cloudflare local runtime (plain Node.js + WebSocket).

Cloudflare/Wrangler runtime:

npm run dev:cf

Shortcut alias (same behavior):

npm run dev:local

It 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:node

npm run dev:cf checks local Rust Worker prerequisites automatically:

  • Uses wrangler.workers-dev.jsonc automatically when wrangler.jsonc is not present.
  • Only installs worker-build and the WebAssembly Rust target when the selected Wrangler config uses a worker-build command.
  • The checked-in wrangler.workers-dev.jsonc uses generic local-development values and points to src/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 deploy

If you installed freertc globally:

freertc deploy

Repository-only scripts:

  • npm run build bundles and validates the default JavaScript Worker without deploying it.
  • npm run build:rust builds the optional Rust/WASM worker via worker-build --release.
  • npm run deploy:raw deploys without --env production.
  • npm run check runs cargo check --target wasm32-unknown-unknown for the Rust worker path.
  • npm run dev runs the standalone local relay (non-Cloudflare).
  • npm run dev:cf runs Wrangler/Cloudflare local dev.
  • npm run dev:node runs a standalone local relay without Cloudflare/Wrangler.
  • npm run dev:local is 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:

  1. Compare https://<workers-subdomain>/health and https://<custom-domain>/health.
  2. Confirm your route/custom domain points to this Worker.
  3. Review Cloudflare Access/API Shield/WAF rules on the custom hostname.
  4. 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.

  1. Open http://127.0.0.1:8787/ in two tabs.
  2. Set both tabs to the same Network and Room.
  3. Set opposite peer IDs using random hex strings:
    • Tab A from: fc2142e44ec5c76f1bd46ccbb1eb2ed48f66f64260a5299c871f37ac742fa0c9
    • Tab B from: 3e45d44c4ce4f9304a53f42b978fd13d23f85df4d97a88f8eb33ec13a2f8f7b1
  4. Set each tab to to the other tab from, or leave to empty for auto-discovery.
  5. Connect both sockets and click Start Auto Handshake in both tabs.
  6. When DataChannel is open, send chat messages.

Minimal client expectations

  • Send announce first to bind socket identity (from, network, session_id).
  • Set announce body.instance_id to the same value as network.
  • Include the Room as session_id on every message.
  • Include to for directed messages.
  • Use periodic announce to refresh presence TTL and receive queued relay messages.
  • Use ping for liveness (pong) and keepalive.

Notes

  • TTL is enforced using timestamp + ttl_ms (default 30 seconds, max 120 seconds).
  • Malformed envelopes produce PSP error responses.