freertc 0.1.33 → 0.5.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (60) hide show
  1. package/README.md +205 -13
  2. package/bin/freertc.mjs +38 -633
  3. package/migrations/0001_initial.sql +43 -0
  4. package/migrations/0002_kademlia_overlay.sql +32 -0
  5. package/migrations/0003_announcement_role.sql +4 -0
  6. package/package.json +44 -17
  7. package/public/app.js +746 -172
  8. package/public/icon-180.png +0 -0
  9. package/public/icon-192.png +0 -0
  10. package/public/index.html +200 -799
  11. package/public/pigeonlogo.svg +51 -0
  12. package/scripts/d1-schema.sql +36 -0
  13. package/scripts/deploy-cloudflare.mjs +190 -0
  14. package/scripts/dev-server.mjs +54 -7
  15. package/scripts/generate-relay-identity.mjs +14 -0
  16. package/scripts/name-setup.mjs +332 -0
  17. package/scripts/node-relay.mjs +1128 -0
  18. package/scripts/project-bootstrap.mjs +13 -6
  19. package/scripts/wrangler-install-wizard.mjs +21 -11
  20. package/src/client.js +3468 -0
  21. package/src/direct/cert.js +95 -0
  22. package/src/direct/common.js +187 -0
  23. package/src/direct/dial.js +47 -0
  24. package/src/direct/directory.js +230 -0
  25. package/src/direct/listener.js +201 -0
  26. package/src/direct/lookup.js +75 -0
  27. package/src/direct/names.js +150 -0
  28. package/src/direct/node-relay-direct.js +170 -0
  29. package/src/direct/portmap.js +214 -0
  30. package/src/direct/reachable.js +40 -0
  31. package/src/direct/record.js +188 -0
  32. package/src/index.js +1401 -199
  33. package/src/kademlia.js +133 -0
  34. package/src/node/account-sync.js +98 -0
  35. package/src/node/cost-meter.js +92 -0
  36. package/src/node/d1-sqlite.js +108 -0
  37. package/src/node/data-dir.js +66 -0
  38. package/src/node/durable-object.js +58 -0
  39. package/src/node/lan-beacon.js +55 -0
  40. package/src/node/link-crypto.js +99 -0
  41. package/src/node/relay-links.js +385 -0
  42. package/src/node/relay-name.js +193 -0
  43. package/src/node/relay-pq.js +68 -0
  44. package/src/node/relay-stats.js +276 -0
  45. package/src/node/stats-page.js +281 -0
  46. package/src/node/websocket-pair.js +117 -0
  47. package/src/punch/offer.js +143 -0
  48. package/src/punch/rendezvous.js +124 -0
  49. package/src/punch/transport.js +257 -0
  50. package/src/relay-fetch.js +131 -0
  51. package/src/relay-id.js +74 -0
  52. package/src/relay-identity.js +298 -0
  53. package/src/relay-overlay.js +857 -0
  54. package/src/tunnel/client.js +276 -0
  55. package/src/tunnel/frames.js +64 -0
  56. package/src/tunnel/home.js +271 -0
  57. package/wrangler.template.jsonc +34 -9
  58. package/wrangler.workers-dev.jsonc +20 -3
  59. package/scripts/non-cloudflare-server.mjs +0 -433
  60. package/scripts/postinstall-message.mjs +0 -133
package/README.md CHANGED
@@ -1,8 +1,20 @@
1
- # freertc Cloudflare Worker (WebSocket + D1)
1
+ # freertc
2
2
 
3
3
  This project provides a Cloudflare Worker signaling relay for WebRTC peers using the [Peer Signaling Protocol (PSP)](https://github.com/draeder/Peer-Signaling-Protocol-Specification) envelope shape.
4
4
 
5
- ## Install from npm
5
+ ## Deploy your own federated relay
6
+
7
+ [![Deploy to Cloudflare](https://deploy.workers.cloudflare.com/button)](https://deploy.workers.cloudflare.com/?url=https://github.com/draeder/freertc)
8
+
9
+ **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.
10
+
11
+ 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.
12
+
13
+ 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).
14
+
15
+ See [Cloudflare's Deploy Button documentation](https://developers.cloudflare.com/workers/platform/deploy-buttons/) for details about the account and repository flow.
16
+
17
+ ## Install from npm (manual)
6
18
 
7
19
  Local project install:
8
20
 
@@ -19,29 +31,204 @@ npm install -g freertc
19
31
  When you run the CLI from your project directory, `freertc` copies the required worker files into that directory on first run:
20
32
 
21
33
  - `src/index.js`
34
+ - `src/kademlia.js`
35
+ - `src/relay-identity.js`
36
+ - `src/relay-overlay.js`
22
37
  - `public/index.html`
23
38
  - `public/app.js`
39
+ - `migrations/0001_initial.sql`
40
+ - `migrations/0002_kademlia_overlay.sql`
24
41
  - `scripts/d1-schema.sql`
42
+ - `scripts/deploy-cloudflare.mjs`
25
43
  - `wrangler.template.jsonc`
26
44
  - `wrangler.workers-dev.jsonc`
27
45
 
46
+ ## Browser client
47
+
48
+ The package also exports the browser signaling and WebRTC client used by the demo:
49
+
50
+ ```js
51
+ import { createSignalingClient } from "freertc/client";
52
+
53
+ const client = createSignalingClient({
54
+ peerId: crypto.randomUUID(),
55
+ networkId: "my-app",
56
+ roomId: "pairing-room",
57
+ signalUrl: "wss://your-relay.example/ws",
58
+ autoConnect: false,
59
+ onDataMessage: ({ peerId, data }) => {
60
+ console.log("data from", peerId, data);
61
+ },
62
+ });
63
+
64
+ client.connect();
65
+ ```
66
+
67
+ Use `client.initiateConnection(peerId)` to open a WebRTC data channel and
68
+ `client.sendData(data, peerId)` to send an application payload. Calling
69
+ `client.disconnect()` closes signaling and peer connections.
70
+
71
+ ### Relay on demand (opt-in)
72
+
73
+ By default the client keeps its relay socket open for as long as it runs: an announce every 12 s and a
74
+ ping every second. The relay is for meeting the mesh, so a peer that already has a healthy mesh can let
75
+ it go:
76
+
77
+ ```js
78
+ import { createSignalingClient } from "freertc/client";
79
+
80
+ const client = createSignalingClient({
81
+ peerId: crypto.randomUUID(),
82
+ networkId: "my-app",
83
+ roomId: "pairing-room",
84
+ signalUrl: "wss://your-relay.example/ws",
85
+ autoConnect: false,
86
+ onDataMessage: ({ peerId, data }) => {
87
+ console.log("data from", peerId, data);
88
+ },
89
+ // Required for on-demand: a way to carry negotiation frames over the mesh.
90
+ signalTransport: (envelope) => mesh.send(envelope),
91
+ relay: { mode: "on-demand", minMeshPeers: 2, anchors: 3 },
92
+ onRelayStateChange: ({ state }) => console.log("relay", state), // up | idle | waking
93
+ });
94
+
95
+ client.connect();
96
+ ```
97
+
98
+ - A peer with at least `minMeshPeers` live data-channel neighbours withdraws from the relay and closes
99
+ its socket once it has been releasable for `settleMs` (30 s).
100
+ - **Anchors** stay registered so a newcomer still finds a way in: the `anchors` peers (default 3) whose id
101
+ is closest to the room, by SHA-256 on a 256-bit ring. Neighbours tell each other which peers they can
102
+ vouch for with a small `~anchors` frame over the data channel, so each peer works out the same set,
103
+ and an anchor that disappears is replaced as soon as its neighbours stop vouching for it.
104
+ - A released peer wakes the relay when its mesh drops below `minMeshPeers`, when it needs to signal a
105
+ peer the mesh cannot reach, when it asks for discovery (`requestBootstrap`), or on `client.wakeRelay()`.
106
+ It stays up for `lingerMs` (60 s) after a wake.
107
+ - `client.relayIdle` is true while the socket is released on purpose. **A host that watches for a missing
108
+ relay acknowledgement must treat that as healthy**, or it will reopen the socket it was meant to leave
109
+ closed.
110
+ - Without `signalTransport`, `mode: "on-demand"` is ignored, because a released relay is only safe when
111
+ negotiation can travel by mesh.
112
+
113
+ Limits: anchors are chosen among a peer, its live neighbours and the peers they vouch for (two hops), so a
114
+ very large room has more than `anchors` of them, never fewer; a neighbour that lies can make a peer
115
+ release the relay early, and the peer wakes it again as soon as its own mesh degree drops.
116
+
28
117
  ## What this worker does
29
118
 
30
119
  - Accepts WebSocket client connections at `/ws`.
31
- - Validates [PSP](https://github.com/draeder/Peer-Signaling-Protocol-Specification) message envelopes (`psp_version`, `type`, `network`, `from`, `message_id`, `timestamp`).
120
+ - Validates [PSP](https://github.com/draeder/Peer-Signaling-Protocol-Specification) message envelopes (`psp_version`, `type`, `network`, `session_id`, `from`, `message_id`, `timestamp`).
32
121
  - Supports discovery, negotiation, control, and extension message types.
33
122
  - Stores peer announcements in Cloudflare D1 (`psp_announcements`).
34
123
  - Stores directed signaling messages in Cloudflare D1 (`psp_relay`).
35
- - Exposes a simple relay registry at `/api/v1/relays` when D1 is configured.
124
+ - Routes across federated relays through bounded Kademlia buckets when a signed relay identity is configured.
125
+ - Keeps the simple `/api/v1/relays` registry as a compatibility fallback for relays without signing keys.
126
+ - Exposes federation peer lookup at `/api/v1/peers` and message forwarding at `/api/v1/relay`.
36
127
  - Delivers queued relay messages when peers reconnect.
37
128
  - Serves the browser demo from `public/`.
38
129
 
130
+ ## Network and Room scopes
131
+
132
+ The browser UI uses two distinct scopes:
133
+
134
+ - **Network** maps to the PSP envelope `network` and announce `instance_id`.
135
+ - **Room** maps to the PSP envelope `session_id`.
136
+
137
+ 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.
138
+
139
+ 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.
140
+
141
+ ## Local relays
142
+
143
+ A local relay runs the same relay code under Node, on your own machine:
144
+
145
+ ```bash
146
+ node scripts/node-relay.mjs
147
+ ```
148
+
149
+ It federates with the cloud relays by default. Behind NAT it takes a public
150
+ address through a tunnel to a public relay. Clients with WebRTC reach it over a
151
+ punched data channel introduced through that tunnel, instead of through the
152
+ tunnel itself. It also links to other local relays directly, so federation
153
+ between local relays does not pass through the cloud. PeerPigeon clients prefer
154
+ a healthy local relay over a cloud one. See [docs/RELAYS.md](docs/RELAYS.md) for
155
+ the design, the settings, and measured costs.
156
+
157
+ ### Your relay's own name and certificate
158
+
159
+ A local relay can have its own name on your domain and a Let's Encrypt
160
+ certificate, so browsers anywhere reach it as `wss://<name>:8443/ws`. Your
161
+ FreeRTC Worker keeps the name (it holds the only DNS token); the relay asks it.
162
+ On the machine that runs the relay, in this folder, once:
163
+
164
+ ```bash
165
+ npx freertc name --domain example.com
166
+ ```
167
+
168
+ It logs in with wrangler (a browser window, if you are not logged in), finds your
169
+ FreeRTC Worker and the domain, and registers this relay with the Worker. The
170
+ first time for a domain it also opens Cloudflare's API token page, already
171
+ filled in for a token that can only edit DNS on that domain: click Create Token,
172
+ then Copy, and press Enter in the terminal (wrangler's login cannot make
173
+ tokens). Don't paste it: it is read from the clipboard, never shown, and the
174
+ clipboard is emptied. It is checked and stored in the Worker, never on the
175
+ machine. Restart the relay; from then on it
176
+ does the rest:
177
+
178
+ - points `<first 16 characters of its id>.example.com` at your public address,
179
+ and again whenever that changes;
180
+ - gets a certificate from Let's Encrypt by DNS-01 (the Worker writes the
181
+ challenge record; nothing needs to be reachable for it), renews it with 30
182
+ days left;
183
+ - serves `wss://` and `https://` on `FREERTC_TLS_PORT` (8443) and asks the
184
+ router to forward it (UPnP or NAT-PMP);
185
+ - lists `wss://<name>:8443/ws` in the relay directory, which accepts it only if
186
+ DNS for the name points at the relay's own address.
187
+
188
+ Settings: `FREERTC_NAMES=off` turns it off; `FREERTC_ACME_STAGING=1` uses Let's
189
+ Encrypt's staging service (test certificates); `FREERTC_NAMES_URL` points at a
190
+ Worker without running `freertc name`. A Worker with `NAMES_OPEN=1` names any
191
+ relay (a public naming service). The Worker side is `src/direct/names.js`; the
192
+ relay side `src/node/relay-name.js`; the command `scripts/name-setup.mjs`.
193
+
194
+ ## Kademlia relay overlay
195
+
196
+ 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.
197
+
198
+ 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.
199
+
200
+ Kademlia is enabled when D1 and the relay identity secret are present. Both are configured automatically:
201
+
202
+ ```bash
203
+ # Deploy from a cloned repository
204
+ npm run deploy
205
+
206
+ # Deploy an npm-installed project using its production environment
207
+ npx freertc deploy
208
+
209
+ # Local Cloudflare development
210
+ npm run dev:cf
211
+ ```
212
+
213
+ 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.
214
+
215
+ Optional routing settings remain ordinary Wrangler variables:
216
+
217
+ ```jsonc
218
+ "KADEMLIA_BOOTSTRAP_URLS": "wss://peer.ooo/ws,wss://decentralize.ooo/ws",
219
+ "RELAY_CAPACITY": "10000"
220
+ ```
221
+
222
+ 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.
223
+
224
+ 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.
225
+
39
226
  ## Runtime scope
40
227
 
41
228
  - The checked-in Cloudflare Worker runtime is `src/index.js` with Cloudflare D1 (`DB` binding).
42
229
  - The Rust/WASM worker lives in `src/lib.rs` and is optional; the default template now uses the JS worker path.
43
230
  - The built-in browser demo served by the Worker is `public/index.html` + `public/app.js`.
44
- - `src/kv.js` and `demo/src/*` are legacy/experimental code paths and are not used by `wrangler dev` or `wrangler deploy` in the current setup.
231
+ - `demo/src/*` is a legacy/experimental code path and is not used by `wrangler dev` or `wrangler deploy` in the current setup.
45
232
 
46
233
  ## Supported message types
47
234
 
@@ -110,6 +297,8 @@ If you installed the npm package instead of cloning the repo, use `npx freertc w
110
297
 
111
298
  ### 3. Initialize D1 schema
112
299
 
300
+ Normal deploy and `dev:cf` commands perform this step automatically. The following commands are available for manual database maintenance.
301
+
113
302
  Local (for `wrangler dev`):
114
303
 
115
304
  ```bash
@@ -149,7 +338,9 @@ Shortcut alias (same behavior):
149
338
  npm run dev:local
150
339
  ```
151
340
 
152
- You can also choose host/port:
341
+ It listens on `0.0.0.0:8788` by default, so other machines on your network can
342
+ use it at `ws://<this machine's LAN address>:8788/ws`. To keep it to this machine,
343
+ or to pick another port:
153
344
 
154
345
  ```bash
155
346
  HOST=127.0.0.1 PORT=8788 npm run dev:node
@@ -159,7 +350,7 @@ HOST=127.0.0.1 PORT=8788 npm run dev:node
159
350
 
160
351
  - Uses `wrangler.workers-dev.jsonc` automatically when `wrangler.jsonc` is not present.
161
352
  - Only installs `worker-build` and the WebAssembly Rust target when the selected Wrangler config uses a `worker-build` command.
162
- - The checked-in `wrangler.workers-dev.jsonc` now points to `src/index.js`, so standard demo runs do not require Rust/WASM setup.
353
+ - 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.
163
354
 
164
355
  Endpoints:
165
356
 
@@ -188,7 +379,8 @@ freertc deploy
188
379
 
189
380
  Repository-only scripts:
190
381
 
191
- - `npm run build` builds the Rust/WASM worker via `worker-build --release`.
382
+ - `npm run build` bundles and validates the default JavaScript Worker without deploying it.
383
+ - `npm run build:rust` builds the optional Rust/WASM worker via `worker-build --release`.
192
384
  - `npm run deploy:raw` deploys without `--env production`.
193
385
  - `npm run check` runs `cargo check --target wasm32-unknown-unknown` for the Rust worker path.
194
386
  - `npm run dev` runs the standalone local relay (non-Cloudflare).
@@ -216,7 +408,7 @@ Quick checks:
216
408
  Expected `/health` response includes JSON like:
217
409
 
218
410
  ```json
219
- {"ok":true,"version":"0.1.33","protocol_version":"1.0","peers":0}
411
+ {"ok":true,"version":"0.1.32","protocol_version":"1.0","peers":0}
220
412
  ```
221
413
 
222
414
  ## Auto WebRTC two-tab test
@@ -224,7 +416,7 @@ Expected `/health` response includes JSON like:
224
416
  The demo defaults to Auto WebRTC and performs real offer/answer + ICE exchange over this Worker.
225
417
 
226
418
  1. Open `http://127.0.0.1:8787/` in two tabs.
227
- 2. Set both tabs to the same `network` and `session_id`.
419
+ 2. Set both tabs to the same **Network** and **Room**.
228
420
  3. Set opposite peer IDs using random hex strings:
229
421
  - Tab A `from`: `fc2142e44ec5c76f1bd46ccbb1eb2ed48f66f64260a5299c871f37ac742fa0c9`
230
422
  - Tab B `from`: `3e45d44c4ce4f9304a53f42b978fd13d23f85df4d97a88f8eb33ec13a2f8f7b1`
@@ -234,8 +426,9 @@ The demo defaults to Auto WebRTC and performs real offer/answer + ICE exchange o
234
426
 
235
427
  ## Minimal client expectations
236
428
 
237
- - Send `announce` first to bind socket identity (`from`, `network`).
238
- - Include `session_id` for negotiation messages.
429
+ - Send `announce` first to bind socket identity (`from`, `network`, `session_id`).
430
+ - Set announce `body.instance_id` to the same value as `network`.
431
+ - Include the Room as `session_id` on every message.
239
432
  - Include `to` for directed messages.
240
433
  - Use periodic `announce` to refresh presence TTL and receive queued relay messages.
241
434
  - Use `ping` for liveness (`pong`) and keepalive.
@@ -244,4 +437,3 @@ The demo defaults to Auto WebRTC and performs real offer/answer + ICE exchange o
244
437
 
245
438
  - TTL is enforced using `timestamp + ttl_ms` (default 30 seconds, max 120 seconds).
246
439
  - Malformed envelopes produce [PSP](https://github.com/draeder/Peer-Signaling-Protocol-Specification) `error` responses.
247
-