WebRTC: peer-to-peer for the browser
Browsers can exchange CapTP over a WebRTC DataChannel, encrypted with DTLS. The peers use ICE to find a network path, either directly or through a configured TURN relay. They set up the connection by exchanging messages through a capability they can already reach. That exchange is called signaling.
Dial
Zig
const std = @import("std");
const glowcap = @import("glowcap");
const webrtc = @import("webrtc");
// `signaling` carries the offer and each candidate to the peer the locator
// names, over a path you already hold, such as an OCapN capability both peers
// can reach. The answer comes back through `Backend.provideAnswer`.
pub fn example(io: std.Io, allocator: std.mem.Allocator, partner_uri: []const u8, signaling: webrtc.SignalingAuthority) !void {
const partner = try glowcap.ocapn.model.uri.parsePeer(allocator, partner_uri);
defer glowcap.ocapn.model.freePeerLocator(allocator, partner);
var endpoint = try webrtc.Resident.init(.{});
defer endpoint.deinit() catch |err| std.log.err("webrtc endpoint: {s}", .{@errorName(err)});
var resident = try webrtc.CompletionResident.init(
allocator,
try webrtc.Backend.initBound(allocator, &endpoint, signaling, 256, 16 * 1024),
.{},
);
defer resident.deinit();
const residents = [_]glowcap.driver.HostRuntime.ProviderRegistration{
.{ .profile = webrtc.transport_profile, .resident = resident.resident() },
};
const session = try glowcap.driver.connect(
allocator,
io,
.{ .residents = &residents },
partner,
.ephemeral,
.{ .handshake = .{ .ms = 10_000 }, .settle = .{ .ms = 10_000 } },
);
TypeScript
import { Runtime } from "@glowcap/runtime";
import { locator } from "@glowcap/webrtc";
import { provider, type SignalingAuthority } from "@glowcap/webrtc/driver";
// Your signaling carries the offer and each candidate to the peer the locator
// names, over a path you already hold, such as an OCapN capability both peers
// can reach, and brings the answer and the peer's candidates back. In a
// browser, `connector(signaling)` from `@glowcap/webrtc` takes its place.
declare const signaling: SignalingAuthority;
const peerKey = "<64 lowercase hex characters from the peer>";
const partner = locator(peerKey);
await using runtime = await Runtime.open({
providers: [provider(signaling)],
});
Browser
import { connector, locator, type SignalingAuthority } from "@glowcap/webrtc";
import { init } from "@glowcap/web";
declare const signaling: SignalingAuthority;
const web = await init({
wasm: fetch("/glowcap_host.wasm"),
connectors: [connector(signaling)],
});
await using runtime = web.runtime;
const partner = locator("<64 lowercase hex characters from the peer>");
Python
from glowcap import Runtime
from glowcap.webrtc import SignalingAuthority, locator, provider
# Your signaling carries the offer and each candidate to the peer the locator
# names, over a path you already hold, such as an OCapN capability both peers
# can reach, and brings the answer and the peer's candidates back.
signaling: SignalingAuthority
partner = locator("<64 lowercase hex characters from the peer>")
async with Runtime.open(providers=[provider(signaling)]) as runtime:
Rust
use std::rc::Rc;
use glowcap::webrtc::{self, SignalingAuthority};
use glowcap::{Argument, ConnectOptions, PendingWork, Runtime, RuntimeConfig};
// Your signaling carries the offer and each candidate to the peer the locator
// names, over a path you already hold, such as an OCapN capability both peers
// can reach, and brings the answer and the peer's candidates back. Drive the
// runtime from a tokio `LocalSet`: the callbacks run on the thread that steps it.
// Cargo.toml: glowcap = { …, features = ["webrtc"] }
let signaling: Rc<dyn SignalingAuthority> = todo!("your SignalingAuthority");
let partner = webrtc::locator("<64 lowercase hex characters from the peer>");
let runtime =
Runtime::open(RuntimeConfig::providers([webrtc::provider(signaling, webrtc::Config::default())])).await?;
Racket
(require glowcap/glowcap
glowcap/glowcap-webrtc)
;; Your signaling carries the offer and each candidate to the peer the locator
;; names, over a path you already hold, such as an OCapN capability both peers
;; can reach, and brings the answer and the peer's candidates back.
(define signaling
(make-webrtc-signaling
#:offer (lambda (exchange peer sdp) (error "send the offer, return the answer"))
#:answer (lambda (exchange peer sdp) (error "send the answer to an inbound offer"))
#:candidate (lambda (exchange ice) (error "send one candidate"))
#:on-candidate (lambda (exchange peer sink) (error "call sink with each far candidate"))))
(define partner (webrtc-locator "<64 lowercase hex characters from the peer>"))
(define runtime (open-runtime #:providers (list (webrtc-provider signaling))))
Listen
WebRTC has no host-and-port listener. A listener answers the offers your signaling hands it, each with the offerer’s key, and yields a session pinned to that key once the channel opens. In a browser, listener(host, signaling) from @glowcap/webrtc does this. Rust, Python, Racket, and Deno use webrtc.listen, and both take the same signaling object their dial uses.
The channel comes up by signaling
To open a DataChannel, the two peers first trade three things: an SDP offer, an SDP answer (the session descriptions each side sends), and a handful of ICE candidates (the network paths each side can be reached on). glowcap carries that exchange over an ordinary OCapN capability, such as a Rooms room both peers have joined. That object moves opaque strings. It parses no SDP and holds no session.
A bare webrtc locator does not dial on its own: without a signaling reference there is nowhere to send an offer, so the dial refuses. TypeScript configures signaling on the Host, and Zig on the WebRTC backend.
Who the peer is
Like keyed TCP and iroh, a WebRTC peer is named by its Ed25519 public key in canonical hex, not by an address. DTLS encrypts the channel, but nothing in the channel proves that key. The session takes the peer’s identity from the signaling capability that introduced it, so trusting a WebRTC peer means trusting your signaling service.
Optional Rust library
glowcap’s WebRTC DataChannel code is Rust, so it ships as a separate library, libglowcap_net_transport_webrtc (ADR-0035). The base archives stay pure Zig, and building this one needs cargo.
A non-browser endpoint serves many DataChannels from one thread by watching a single file descriptor that signals readiness, the same way iroh does.
In the browser
@glowcap/webrtc drives an RTCPeerConnection and presents the open DataChannel to the wasm Host. It supports two topologies:
- a browser and a non-browser peer hold a keyed session over a DataChannel, and
- two browsers, introduced by a signaling host, bring up a direct DataChannel and hold a keyed session with the host out of the byte path.
STUN, TURN, and staying direct
ICE finds a network path between the peers. The @glowcap/webrtc connector adds no servers unless the application configures some.
- On loopback or a LAN, peers connect directly on host candidates, with no STUN or TURN.
- A browser that must cross a NAT gives the connector a STUN server. Rooms does this by default, using Cloudflare’s public STUN service, and serves the same configuration to both browsers. Setting it explicitly to empty keeps the page free of outside servers.
- A Rooms deployment can also keep a TURN issuer token on its server and give each new browser connection short-lived TURN credentials.
- A peer outside the browser adds no servers either. Its configuration names a STUN or TURN server to cross a NAT, and without one it connects on loopback or a LAN.
When ICE selects a TURN route, the relay forwards DTLS-encrypted traffic. It can observe timing and volume.
Three-party handoff over WebRTC
A handoff over WebRTC works as on any session: the introducer names the object’s host, and the recipient dials that peer on a fresh session to collect it. The redeeming host needs signaling configured.
For peers outside the browser that need discovery or NAT traversal, prefer iroh. Compare the other transports in Choosing a transport.