@johnhenry/browsermesh-transport 0.5.1 → 0.6.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.
- package/README.md +181 -2
- package/package.json +13 -4
- package/src/channel-relay.mjs +2 -2
- package/src/cross-origin.mjs +3 -3
- package/src/gateway.mjs +3 -3
- package/src/identity-binding.mjs +181 -0
- package/src/index.mjs +8 -0
- package/src/relay.mjs +2 -2
- package/src/silent-catch.mjs +38 -9
- package/src/streams.mjs +3 -3
- package/src/transport.mjs +48 -6
- package/src/webrtc.mjs +236 -25
- package/src/websocket.mjs +23 -16
- package/src/webtransport.mjs +5 -5
- package/src/wisp-client.mjs +5 -5
- package/src/wisp.mjs +4 -4
- package/src/wsh-bridge.mjs +9 -14
- package/src/wsh-frames.mjs +180 -0
- package/src/wsh-in-process.mjs +82 -0
- package/src/wsh-links.mjs +1005 -0
- package/src/wsh-pod-transport.mjs +159 -0
package/README.md
CHANGED
|
@@ -15,7 +15,7 @@ A mesh peer needs to move bytes to another peer, but browsers offer several inco
|
|
|
15
15
|
|
|
16
16
|
## Provenance
|
|
17
17
|
|
|
18
|
-
Extracted from
|
|
18
|
+
Extracted from a private monorepo (previously `packages/browsermesh-transport`), where it was manually published to npm, unscoped, as `browsermesh-transport@0.1.0` (2026-07-17) with no CI ever automating that publish. This is its first release as part of the `@johnhenry/browsermesh` monorepo; the version restarts at `0.0.0` per family convention.
|
|
19
19
|
|
|
20
20
|
|
|
21
21
|
## Modules
|
|
@@ -31,7 +31,11 @@ Extracted from the private `clawser` monorepo (previously `packages/browsermesh-
|
|
|
31
31
|
| gateway | `GatewayNode`, `GatewayDiscovery`, `RouteTable` |
|
|
32
32
|
| streams | `MeshStream`, `StreamMultiplexer` |
|
|
33
33
|
| cross-origin | `CrossOriginBridge`, `CrossOriginHandshake`, `RateLimiter` |
|
|
34
|
-
| wsh-bridge | `MeshWshBridge` |
|
|
34
|
+
| wsh-bridge | `MeshWshBridge` (syncs a `WshKeyStore` with a `MeshIdentityManager`; the link layer does not use it) |
|
|
35
|
+
| wsh-links | `WshPeerLinks`, `WshLink`, `WshLinkError`, `createWshTransportFactory`, `podIdToFingerprint`, `fingerprintToPodId`, `rendezvousId` |
|
|
36
|
+
| wsh-pod-transport | `WshPodTransport` (a `Pod` `TransportAdapter`) |
|
|
37
|
+
| wsh-frames | `encodeFrame`, `FrameDecoder`, `WshFrameError`, `DEFAULT_MAX_FRAME_BYTES` |
|
|
38
|
+
| wsh-in-process (subpath `@johnhenry/browsermesh-transport/wsh-in-process`) | `createInProcessPipeRelay` (tests and examples) |
|
|
35
39
|
| wisp | `WispTransport` |
|
|
36
40
|
| channel-relay | `ChannelRelay` |
|
|
37
41
|
|
|
@@ -61,6 +65,64 @@ parses it (`@johnhenry/browsermesh-apps`' `ctx.onIncomingData()` does). A custom
|
|
|
61
65
|
`WebRTCTransport.send(data, { channel })` takes `'control'` (default) or
|
|
62
66
|
`'bulk'` and falls back to control when the bulk channel is not open.
|
|
63
67
|
|
|
68
|
+
## Binding a WebRTC connection to the pod identities (opt-in)
|
|
69
|
+
|
|
70
|
+
Offer and answer travel through signalling, and a server on that path can swap
|
|
71
|
+
them. Pass `identity` (a `PodIdentity`) to `WebRTCPeerConnection` (or to
|
|
72
|
+
`WebRTCMeshManager`, which hands it to every connection) and each side proves
|
|
73
|
+
possession of its pod key, on the control data channel, over a transcript that
|
|
74
|
+
contains both pod ids and the DTLS fingerprints of **both** session
|
|
75
|
+
descriptions (`identity-binding.mjs`: `extractDtlsFingerprints`,
|
|
76
|
+
`bindingTranscript`, `createBindingProof`, `verifyBindingProof`; signed bytes
|
|
77
|
+
are `"browsermesh/webrtc-binding/v1\n"` plus canonical JSON, with the signer's
|
|
78
|
+
role included so a proof cannot be reflected). The proof carries the public
|
|
79
|
+
key, which must hash to `remotePodId`, the pod id claimed in signalling.
|
|
80
|
+
|
|
81
|
+
- The connection becomes `connected` (and `send()` works) only after the peer's
|
|
82
|
+
proof verified; before that only the proof frame is accepted, and anything
|
|
83
|
+
else is dropped and counted (`droppedUnbound`). `bound` is true afterwards.
|
|
84
|
+
- A proof that does not verify (swapped description, key that is not the claimed
|
|
85
|
+
pod, reflected or replayed proof) closes the connection and reports an
|
|
86
|
+
`identity binding failed: <reason>` error through `onError()`;
|
|
87
|
+
`bindingFailure` holds the reason.
|
|
88
|
+
- A peer that sends no proof is closed after `bindingTimeoutMs` (default
|
|
89
|
+
10000). With `requirePeerBinding: false` such a peer (an older build) is
|
|
90
|
+
accepted unbound (`bound` stays false), while a proof that fails is still
|
|
91
|
+
fatal.
|
|
92
|
+
- Nothing changes without `identity`. An older peer that receives the proof
|
|
93
|
+
frame sees one extra JSON message of type `mesh:bind` on the control channel.
|
|
94
|
+
`createMeshNode()` does not enable this yet.
|
|
95
|
+
|
|
96
|
+
This is verified here with an in-memory duplex and fixed vectors; it has not
|
|
97
|
+
been run over a real `RTCPeerConnection` in a browser (see issue #270).
|
|
98
|
+
|
|
99
|
+
## ICE servers: none by default, and why
|
|
100
|
+
|
|
101
|
+
`DEFAULT_ICE_SERVERS` is empty. With no STUN or TURN server a peer gathers
|
|
102
|
+
host candidates only, which is enough for two devices on the same network and
|
|
103
|
+
contacts nobody. A public STUN server learns the peer's public IP address, and
|
|
104
|
+
that it is about to pair with someone, on every connection attempt; a library
|
|
105
|
+
should not make that choice for an application, so it is opt-in.
|
|
106
|
+
|
|
107
|
+
Peers on different networks (behind NAT) usually need a STUN server, and
|
|
108
|
+
restrictive NATs need TURN. Supply your own:
|
|
109
|
+
|
|
110
|
+
```js
|
|
111
|
+
const mesh = new WebRTCMeshManager({
|
|
112
|
+
localPodId,
|
|
113
|
+
iceServers: [
|
|
114
|
+
{ urls: 'stun:stun.example.com:3478' },
|
|
115
|
+
{ urls: 'turn:turn.example.com:3478', username, credential },
|
|
116
|
+
],
|
|
117
|
+
});
|
|
118
|
+
```
|
|
119
|
+
|
|
120
|
+
If you accept the disclosure, `PUBLIC_STUN_SERVERS` is a ready-made public
|
|
121
|
+
list (`iceServers: [...PUBLIC_STUN_SERVERS]`). An explicit `iceServers: []`
|
|
122
|
+
is honoured as "none". When a connection with no ICE servers fails, a note
|
|
123
|
+
explaining the above is logged once per process (through `onLog` if given,
|
|
124
|
+
otherwise `console.warn`).
|
|
125
|
+
|
|
64
126
|
## TURN-only pods: `iceTransportPolicy`
|
|
65
127
|
|
|
66
128
|
By default a pod that has configured a TURN server still gathers host and
|
|
@@ -106,6 +168,123 @@ padding *inside* the end-to-end seal:
|
|
|
106
168
|
|
|
107
169
|
Constant-rate cover traffic is deliberately not provided.
|
|
108
170
|
|
|
171
|
+
## Sealed peer links over wsh
|
|
172
|
+
|
|
173
|
+
A mesh link can be a [wsh](https://github.com/johnhenry/wsh) session: key login
|
|
174
|
+
in both directions, a host key the dialler pins to the pod id it meant to
|
|
175
|
+
reach, a login bound to the connection, and a session sealed end to end so a
|
|
176
|
+
relay can neither read nor alter it. A pod's Ed25519 key is its wsh identity
|
|
177
|
+
and the pod id a peer claims must be the hash of the key wsh authenticated, so
|
|
178
|
+
the sender of every message on a link is that key. **Off by default**; nothing
|
|
179
|
+
changes for code that does not ask for it. Design and threat model:
|
|
180
|
+
[`docs/design/wsh-peer-link.md`](../../docs/design/wsh-peer-link.md); what is and
|
|
181
|
+
is not protected: [`docs/security.md`](../../docs/security.md).
|
|
182
|
+
|
|
183
|
+
Install the optional peer, `npm install @johnhenry/wsh` (`^0.45.0`). It is
|
|
184
|
+
imported lazily on the first `listen()` / `connect()`, so a page that never
|
|
185
|
+
uses a wsh link loads none of it.
|
|
186
|
+
|
|
187
|
+
Between two browsers neither can listen, so a pod that wants to be reached
|
|
188
|
+
waits at its own rendezvous id on a wsh **pipe relay** (a relay that copies
|
|
189
|
+
bytes and vouches for nothing; `createPipeRelay` in `@johnhenry/wsh/pipe-relay`)
|
|
190
|
+
and a pod that wants to reach it dials that id:
|
|
191
|
+
|
|
192
|
+
```js
|
|
193
|
+
import { PodIdentity } from '@johnhenry/browsermesh-primitives'
|
|
194
|
+
import { WshPeerLinks } from '@johnhenry/browsermesh-transport'
|
|
195
|
+
|
|
196
|
+
const identity = await PodIdentity.generate()
|
|
197
|
+
const links = new WshPeerLinks({
|
|
198
|
+
identity, // or { podId, signer } for a key held elsewhere
|
|
199
|
+
relays: ['wss://relay.example/'], // pipe relay base URL(s)
|
|
200
|
+
authorize: ({ podId }) => allowed.has(podId), // who may link to this pod. Default: nobody
|
|
201
|
+
})
|
|
202
|
+
await links.listen() // be reachable
|
|
203
|
+
await links.connect(otherPodId) // reach a peer; redialled if the link is lost
|
|
204
|
+
links.on('message', ({ from, data }) => { /* `from` is the authenticated pod id */ })
|
|
205
|
+
await links.send(otherPodId, { hello: 'sealed' }) // resolves when the stream accepted it
|
|
206
|
+
```
|
|
207
|
+
|
|
208
|
+
**For a `Pod`**: `WshPodTransport` is a `TransportAdapter`, so a `Pod` uses it
|
|
209
|
+
unchanged. `from` is set to the authenticated key and a message that names
|
|
210
|
+
another sender is dropped.
|
|
211
|
+
|
|
212
|
+
```js
|
|
213
|
+
const transport = new WshPodTransport({ identity, relays, authorize, peers: [otherPodId] })
|
|
214
|
+
await pod.boot({ identity, transport })
|
|
215
|
+
```
|
|
216
|
+
|
|
217
|
+
**For `PeerNode`** (mesh-rpc, mesh-sync, mesh-relay and the rest): use
|
|
218
|
+
`createMeshNode({ wsh: { relays } })` from `@johnhenry/browsermesh-apps`, or
|
|
219
|
+
register the adapter yourself:
|
|
220
|
+
|
|
221
|
+
```js
|
|
222
|
+
negotiator.registerAdapter('wsh', createWshTransportFactory(links)) // endpoint = the peer's pod id
|
|
223
|
+
```
|
|
224
|
+
|
|
225
|
+
### Selection
|
|
226
|
+
|
|
227
|
+
`'wsh'` is a `TRANSPORT_TYPES` member but is in no default preference order.
|
|
228
|
+
Opt in by listing it (`new MeshTransportNegotiator({ preferenceOrder: ['wsh',
|
|
229
|
+
'webrtc'] })`) or by requiring it: `new MeshTransportNegotiator({ require: 'wsh'
|
|
230
|
+
})`, or `negotiate(endpoints, auth, { require: 'wsh' })`. With `require` only
|
|
231
|
+
the wsh adapter is tried and its failure is the failure, **never a fallback to
|
|
232
|
+
an unsealed transport**. There is no setting that makes a wsh link plain:
|
|
233
|
+
sealing is always on and checked after login.
|
|
234
|
+
`TransportFactory.create('wsh', { links, peerPodId })` returns an unconnected
|
|
235
|
+
`WshLink`.
|
|
236
|
+
|
|
237
|
+
### What the link does
|
|
238
|
+
|
|
239
|
+
- **Frames**: `u32 length | u8 kind | payload` on one named endpoint (`mesh`);
|
|
240
|
+
`maxFrameBytes` (default 1 MiB) is checked on the header, before the payload
|
|
241
|
+
is buffered.
|
|
242
|
+
- **Backpressure**: writes wait for the endpoint's credit window; `send()`
|
|
243
|
+
resolves when the stream accepted the frame. Pending sends queue up to
|
|
244
|
+
`maxQueuedBytes` (default 4 MiB), then reject with `WSH_BACKPRESSURE`. A slow
|
|
245
|
+
reader (a handler that returns a promise, or `pause(podId)`) stalls its sender
|
|
246
|
+
at a bounded amount.
|
|
247
|
+
- **Simultaneous dial**: if two pods dial each other at once, exactly one link
|
|
248
|
+
survives, the one the lower pod id initiated; nothing is reported as down.
|
|
249
|
+
- **Liveness and reconnect**: the wsh client pings and closes on a missed pong
|
|
250
|
+
(`keepAlive`); a kept peer is redialled with backoff (`reconnect`), a refusal
|
|
251
|
+
or host key mismatch stops it.
|
|
252
|
+
- **Errors**: `WshLinkError` with a stable `code` (`WSH_HOSTKEY_MISMATCH`,
|
|
253
|
+
`WSH_REFUSED` with `reason`, `WSH_NOT_SEALED`, `WSH_UNREACHABLE`,
|
|
254
|
+
`WSH_SEAL_FAILED`, `WSH_FRAME_TOO_LARGE`, `WSH_BAD_FRAME`, `WSH_BACKPRESSURE`,
|
|
255
|
+
`WSH_CLOSED`, `WSH_UNAVAILABLE`). The listening side gets wsh's `onRefused`
|
|
256
|
+
reasons through the `refused` event (plus `identity-mismatch`).
|
|
257
|
+
|
|
258
|
+
### Testing without a network
|
|
259
|
+
|
|
260
|
+
```js
|
|
261
|
+
import { createInProcessPipeRelay } from '@johnhenry/browsermesh-transport/wsh-in-process'
|
|
262
|
+
const env = await createInProcessPipeRelay() // wsh's real pipe relay, in this process
|
|
263
|
+
new WshPeerLinks({ identity, relays: ['wss://relay.invalid'], WebSocket: env.WebSocket, authorize })
|
|
264
|
+
// env.recorded holds every byte the relay copied; env.tap can alter them; env.dropAll() ends every pipe
|
|
265
|
+
```
|
|
266
|
+
|
|
267
|
+
It is a separate subpath because it imports wsh's pipe relay, which has a
|
|
268
|
+
Node-only listener a browser bundle should not follow.
|
|
269
|
+
|
|
270
|
+
### Bundle size
|
|
271
|
+
|
|
272
|
+
Measured with esbuild (minified, browser, code splitting, `@johnhenry/browsermesh-primitives`
|
|
273
|
+
external), size of what is added:
|
|
274
|
+
|
|
275
|
+
| | raw | gzip |
|
|
276
|
+
| --- | ---: | ---: |
|
|
277
|
+
| a page that imports only `MeshTransportNegotiator` / `WebSocketTransport` (no wsh link): added to the main chunk | +0.56 kB | +0.16 kB |
|
|
278
|
+
| a page that imports `WshPeerLinks`: the link code in the main chunk | 21.1 kB | 7.8 kB |
|
|
279
|
+
| lazy, dialling role (`@johnhenry/wsh` client): shared wsh core + client | 170.6 kB | 52.8 kB |
|
|
280
|
+
| lazy, listening role (`@johnhenry/wsh/memory`): shared wsh core + host | 237.4 kB | 74.5 kB |
|
|
281
|
+
| lazy, both roles | 259.2 kB | 82.9 kB |
|
|
282
|
+
| lazy, only where WebCrypto has no ML-KEM (`@noble/post-quantum`) | +19.2 kB | +7.6 kB |
|
|
283
|
+
|
|
284
|
+
The wsh chunks load on the first `connect()` / `listen()`; a page that never
|
|
285
|
+
links over wsh never fetches them. These are one-off measurements of wsh 0.45.0,
|
|
286
|
+
not a budget this repository enforces.
|
|
287
|
+
|
|
109
288
|
## License
|
|
110
289
|
|
|
111
290
|
MIT
|
package/package.json
CHANGED
|
@@ -1,11 +1,12 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@johnhenry/browsermesh-transport",
|
|
3
|
-
"version": "0.
|
|
4
|
-
"description": "WebSocket, WebRTC, WebTransport, and
|
|
3
|
+
"version": "0.6.0",
|
|
4
|
+
"description": "WebSocket, WebRTC, WebTransport, relay, and sealed wsh peer-link adapters for BrowserMesh",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"main": "./src/index.mjs",
|
|
7
7
|
"exports": {
|
|
8
|
-
".": "./src/index.mjs"
|
|
8
|
+
".": "./src/index.mjs",
|
|
9
|
+
"./wsh-in-process": "./src/wsh-in-process.mjs"
|
|
9
10
|
},
|
|
10
11
|
"files": [
|
|
11
12
|
"src",
|
|
@@ -19,9 +20,17 @@
|
|
|
19
20
|
"directory": "packages/browsermesh-transport"
|
|
20
21
|
},
|
|
21
22
|
"peerDependencies": {
|
|
22
|
-
"@johnhenry/browsermesh-primitives": ">=0.3.0 <1.0.0"
|
|
23
|
+
"@johnhenry/browsermesh-primitives": ">=0.3.0 <1.0.0",
|
|
24
|
+
"@johnhenry/wsh": "^0.45.0"
|
|
25
|
+
},
|
|
26
|
+
"peerDependenciesMeta": {
|
|
27
|
+
"@johnhenry/wsh": {
|
|
28
|
+
"optional": true
|
|
29
|
+
}
|
|
23
30
|
},
|
|
24
31
|
"devDependencies": {
|
|
32
|
+
"@johnhenry/browsermesh-pod": "^0.2.0",
|
|
33
|
+
"@johnhenry/wsh": "^0.45.0",
|
|
25
34
|
"node-datachannel": "^0.33.4"
|
|
26
35
|
},
|
|
27
36
|
"scripts": {
|
package/src/channel-relay.mjs
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { silentCatch } from './silent-catch.mjs'
|
|
2
|
-
//
|
|
2
|
+
// channel-relay.mjs — Channel Relay Plugin
|
|
3
3
|
//
|
|
4
4
|
// Virtual server route for webhooks + BroadcastChannel relay.
|
|
5
5
|
// Normalizes inbound messages via createInboundMessage().
|
|
@@ -107,7 +107,7 @@ export class ChannelRelay {
|
|
|
107
107
|
this.running = false;
|
|
108
108
|
|
|
109
109
|
if (this._bc) {
|
|
110
|
-
try { this._bc.close(); } catch (e) { silentCatch('
|
|
110
|
+
try { this._bc.close(); } catch (e) { silentCatch('channel-relay', 'this._bc.close', e) }
|
|
111
111
|
this._bc = null;
|
|
112
112
|
}
|
|
113
113
|
}
|
package/src/cross-origin.mjs
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
/**
|
|
2
|
-
// STATUS: INTEGRATED — wired into
|
|
3
|
-
*
|
|
2
|
+
// STATUS: INTEGRATED — wired into the `Pod` lifecycle (@johnhenry/browsermesh-pod), proven via E2E testing
|
|
3
|
+
* cross-origin.mjs -- Cross-origin communication bridge.
|
|
4
4
|
*
|
|
5
5
|
* Enables mesh pods running in different browser contexts (iframes,
|
|
6
6
|
* popups, different-origin tabs) to communicate securely using
|
|
@@ -9,7 +9,7 @@
|
|
|
9
9
|
* No browser-only imports at module level.
|
|
10
10
|
*
|
|
11
11
|
* Run tests:
|
|
12
|
-
* node --import ./
|
|
12
|
+
* cd packages/browsermesh-transport && node --import ./test/_setup-globals.mjs --test test/cross-origin.test.mjs
|
|
13
13
|
*/
|
|
14
14
|
|
|
15
15
|
// ---------------------------------------------------------------------------
|
package/src/gateway.mjs
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
/**
|
|
2
|
-
// STATUS: INTEGRATED — wired into
|
|
3
|
-
*
|
|
2
|
+
// STATUS: INTEGRATED — wired into the `Pod` lifecycle (@johnhenry/browsermesh-pod), proven via E2E testing
|
|
3
|
+
* gateway.mjs -- Gateway Node for BrowserMesh.
|
|
4
4
|
*
|
|
5
5
|
* Thin wrapper around relay functionality providing multi-hop routing,
|
|
6
6
|
* route advertisement, and gateway discovery for the mesh network.
|
|
@@ -13,7 +13,7 @@
|
|
|
13
13
|
* No browser-only imports at module level.
|
|
14
14
|
*
|
|
15
15
|
* Run tests:
|
|
16
|
-
* node --import ./
|
|
16
|
+
* cd packages/browsermesh-transport && node --import ./test/_setup-globals.mjs --test test/gateway.test.mjs
|
|
17
17
|
*/
|
|
18
18
|
|
|
19
19
|
// ---------------------------------------------------------------------------
|
|
@@ -0,0 +1,181 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* identity-binding.mjs -- bind a WebRTC connection to the pod identities at
|
|
3
|
+
* its two ends.
|
|
4
|
+
*
|
|
5
|
+
* Signalling (offer/answer through a relay or signalling server) tells each
|
|
6
|
+
* side which pod it is talking to, but a server on that path can swap the
|
|
7
|
+
* session descriptions and sit in the middle. The DTLS certificate
|
|
8
|
+
* fingerprints in the two descriptions identify the certificates that will
|
|
9
|
+
* actually secure the channel, so each side proves possession of its pod key
|
|
10
|
+
* over *both* of them, on the data channel, before any application message is
|
|
11
|
+
* accepted:
|
|
12
|
+
*
|
|
13
|
+
* transcript = "browsermesh/webrtc-binding/v1\n" + canonical JSON of
|
|
14
|
+
* { offerer, answerer, offerFp, answerFp, signer }
|
|
15
|
+
*
|
|
16
|
+
* where `offerer`/`answerer` are the two pod ids, `offerFp`/`answerFp` the
|
|
17
|
+
* sorted, normalised fingerprints of the offer and the answer, and `signer` is
|
|
18
|
+
* `'offerer'` or `'answerer'` (so a proof made by one side cannot be reflected
|
|
19
|
+
* back at it). Each side builds the transcript from the two descriptions *it*
|
|
20
|
+
* applied. If a server changed either description in transit, the two sides
|
|
21
|
+
* build different transcripts and neither proof verifies.
|
|
22
|
+
*
|
|
23
|
+
* The proof carries the signer's public key; the key must hash to the pod id
|
|
24
|
+
* claimed for that peer (pod id = base64url(SHA-256(raw public key))).
|
|
25
|
+
*
|
|
26
|
+
* All functions here are pure apart from the signing call.
|
|
27
|
+
*
|
|
28
|
+
* Browser-safe: WebCrypto only.
|
|
29
|
+
*/
|
|
30
|
+
|
|
31
|
+
export const BINDING_DOMAIN = 'browsermesh/webrtc-binding/v1\n'
|
|
32
|
+
|
|
33
|
+
/** `type` of the proof frame sent on the control data channel. */
|
|
34
|
+
export const BINDING_FRAME_TYPE = 'mesh:bind'
|
|
35
|
+
|
|
36
|
+
const encoder = new TextEncoder()
|
|
37
|
+
|
|
38
|
+
/** @param {Uint8Array} bytes @returns {string} */
|
|
39
|
+
function toBase64url(bytes) {
|
|
40
|
+
let bin = ''
|
|
41
|
+
for (let i = 0; i < bytes.length; i++) bin += String.fromCharCode(bytes[i])
|
|
42
|
+
return btoa(bin).replace(/\+/g, '-').replace(/\//g, '_').replace(/=+$/, '')
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
/** @param {string} str @returns {Uint8Array|null} */
|
|
46
|
+
function fromBase64url(str) {
|
|
47
|
+
if (typeof str !== 'string' || !/^[A-Za-z0-9_-]*$/.test(str) || str.length % 4 === 1) return null
|
|
48
|
+
const bin = atob(str.replace(/-/g, '+').replace(/_/g, '/').padEnd(Math.ceil(str.length / 4) * 4, '='))
|
|
49
|
+
const out = new Uint8Array(bin.length)
|
|
50
|
+
for (let i = 0; i < bin.length; i++) out[i] = bin.charCodeAt(i)
|
|
51
|
+
return out
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
/**
|
|
55
|
+
* The DTLS fingerprints named in an SDP, normalised (`"<algorithm> <hex bytes
|
|
56
|
+
* separated by ':'>"`, lower case) and sorted, without duplicates. A bundled
|
|
57
|
+
* description names one; several are all kept so that none can be swapped.
|
|
58
|
+
*
|
|
59
|
+
* @param {string} sdp
|
|
60
|
+
* @returns {string[]}
|
|
61
|
+
*/
|
|
62
|
+
export function extractDtlsFingerprints(sdp) {
|
|
63
|
+
if (typeof sdp !== 'string') return []
|
|
64
|
+
const found = new Set()
|
|
65
|
+
for (const line of sdp.split(/\r?\n/)) {
|
|
66
|
+
const m = /^a=fingerprint:([A-Za-z0-9-]+)[ \t]+([0-9A-Fa-f]{2}(?::[0-9A-Fa-f]{2})*)[ \t]*$/.exec(line)
|
|
67
|
+
if (m) found.add(`${m[1].toLowerCase()} ${m[2].toLowerCase()}`)
|
|
68
|
+
}
|
|
69
|
+
return [...found].sort()
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
/**
|
|
73
|
+
* Canonical JSON (sorted keys) of the strings, arrays of strings and plain
|
|
74
|
+
* objects used by the transcript.
|
|
75
|
+
* @param {*} v
|
|
76
|
+
* @returns {string}
|
|
77
|
+
*/
|
|
78
|
+
function canonical(v) {
|
|
79
|
+
if (typeof v === 'string') return JSON.stringify(v)
|
|
80
|
+
if (Array.isArray(v)) return `[${v.map(canonical).join(',')}]`
|
|
81
|
+
if (v && typeof v === 'object') {
|
|
82
|
+
return `{${Object.keys(v).sort().map((k) => `${JSON.stringify(k)}:${canonical(v[k])}`).join(',')}}`
|
|
83
|
+
}
|
|
84
|
+
throw new TypeError('unsupported value in transcript')
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
/**
|
|
88
|
+
* The bytes a side signs.
|
|
89
|
+
*
|
|
90
|
+
* @param {object} p
|
|
91
|
+
* @param {string} p.offererPodId
|
|
92
|
+
* @param {string} p.answererPodId
|
|
93
|
+
* @param {string[]} p.offerFingerprints - from `extractDtlsFingerprints(offerSdp)`
|
|
94
|
+
* @param {string[]} p.answerFingerprints
|
|
95
|
+
* @param {'offerer'|'answerer'} p.signer - which side is signing
|
|
96
|
+
* @returns {Uint8Array}
|
|
97
|
+
*/
|
|
98
|
+
export function bindingTranscript({ offererPodId, answererPodId, offerFingerprints, answerFingerprints, signer }) {
|
|
99
|
+
if (!offererPodId || !answererPodId || typeof offererPodId !== 'string' || typeof answererPodId !== 'string') {
|
|
100
|
+
throw new TypeError('both pod ids are required')
|
|
101
|
+
}
|
|
102
|
+
if (!offerFingerprints?.length || !answerFingerprints?.length) {
|
|
103
|
+
throw new TypeError('both descriptions must name a DTLS fingerprint')
|
|
104
|
+
}
|
|
105
|
+
if (signer !== 'offerer' && signer !== 'answerer') throw new TypeError('signer must be offerer or answerer')
|
|
106
|
+
return encoder.encode(BINDING_DOMAIN + canonical({
|
|
107
|
+
offerer: offererPodId,
|
|
108
|
+
answerer: answererPodId,
|
|
109
|
+
offerFp: [...offerFingerprints].sort(),
|
|
110
|
+
answerFp: [...answerFingerprints].sort(),
|
|
111
|
+
signer,
|
|
112
|
+
}))
|
|
113
|
+
}
|
|
114
|
+
|
|
115
|
+
/** @param {Uint8Array} raw @returns {Promise<string>} pod id */
|
|
116
|
+
export async function podIdOfRawKey(raw) {
|
|
117
|
+
return toBase64url(new Uint8Array(await crypto.subtle.digest('SHA-256', raw)))
|
|
118
|
+
}
|
|
119
|
+
|
|
120
|
+
/**
|
|
121
|
+
* Build the proof this side sends.
|
|
122
|
+
*
|
|
123
|
+
* @param {{ podId: string, sign: (data: Uint8Array) => Promise<Uint8Array>, rawPublicKey: () => Promise<Uint8Array> }} identity - a `PodIdentity`
|
|
124
|
+
* @param {Parameters<typeof bindingTranscript>[0]} transcript - `signer` is this side's role
|
|
125
|
+
* @returns {Promise<{ type: 'mesh:bind', v: 1, podId: string, role: string, pk: string, sig: string }>}
|
|
126
|
+
*/
|
|
127
|
+
export async function createBindingProof(identity, transcript) {
|
|
128
|
+
const bytes = bindingTranscript(transcript)
|
|
129
|
+
const [raw, sig] = [await identity.rawPublicKey(), await identity.sign(bytes)]
|
|
130
|
+
return {
|
|
131
|
+
type: BINDING_FRAME_TYPE,
|
|
132
|
+
v: 1,
|
|
133
|
+
podId: identity.podId,
|
|
134
|
+
role: transcript.signer,
|
|
135
|
+
pk: toBase64url(raw),
|
|
136
|
+
sig: toBase64url(new Uint8Array(sig)),
|
|
137
|
+
}
|
|
138
|
+
}
|
|
139
|
+
|
|
140
|
+
/**
|
|
141
|
+
* Verify the peer's proof against the descriptions this side applied.
|
|
142
|
+
*
|
|
143
|
+
* @param {*} proof - the frame received
|
|
144
|
+
* @param {object} p
|
|
145
|
+
* @param {string} p.expectedPodId - the pod id claimed for the peer in signalling
|
|
146
|
+
* @param {'offerer'|'answerer'} p.peerRole - the role the peer has in this connection
|
|
147
|
+
* @param {string} p.offererPodId
|
|
148
|
+
* @param {string} p.answererPodId
|
|
149
|
+
* @param {string[]} p.offerFingerprints
|
|
150
|
+
* @param {string[]} p.answerFingerprints
|
|
151
|
+
* @returns {Promise<{ ok: true } | { ok: false, reason: string }>}
|
|
152
|
+
*/
|
|
153
|
+
export async function verifyBindingProof(proof, { expectedPodId, peerRole, offererPodId, answererPodId, offerFingerprints, answerFingerprints }) {
|
|
154
|
+
if (!proof || typeof proof !== 'object' || proof.type !== BINDING_FRAME_TYPE || proof.v !== 1) {
|
|
155
|
+
return { ok: false, reason: 'malformed' }
|
|
156
|
+
}
|
|
157
|
+
const raw = fromBase64url(proof.pk)
|
|
158
|
+
const sig = fromBase64url(proof.sig)
|
|
159
|
+
if (!raw || raw.length !== 32 || !sig || sig.length !== 64) return { ok: false, reason: 'malformed' }
|
|
160
|
+
if (proof.role !== peerRole) return { ok: false, reason: 'wrong-role' }
|
|
161
|
+
|
|
162
|
+
// The pod id claimed in signalling must be the hash of the key that signed.
|
|
163
|
+
if ((await podIdOfRawKey(raw)) !== expectedPodId || proof.podId !== expectedPodId) {
|
|
164
|
+
return { ok: false, reason: 'wrong-pod-id' }
|
|
165
|
+
}
|
|
166
|
+
|
|
167
|
+
let bytes
|
|
168
|
+
try {
|
|
169
|
+
bytes = bindingTranscript({ offererPodId, answererPodId, offerFingerprints, answerFingerprints, signer: peerRole })
|
|
170
|
+
} catch {
|
|
171
|
+
return { ok: false, reason: 'no-fingerprint' }
|
|
172
|
+
}
|
|
173
|
+
let valid = false
|
|
174
|
+
try {
|
|
175
|
+
const key = await crypto.subtle.importKey('raw', raw, 'Ed25519', false, ['verify'])
|
|
176
|
+
valid = await crypto.subtle.verify('Ed25519', key, sig, bytes)
|
|
177
|
+
} catch {
|
|
178
|
+
valid = false
|
|
179
|
+
}
|
|
180
|
+
return valid ? { ok: true } : { ok: false, reason: 'bad-signature' }
|
|
181
|
+
}
|
package/src/index.mjs
CHANGED
|
@@ -2,12 +2,20 @@
|
|
|
2
2
|
export * from './transport.mjs';
|
|
3
3
|
export * from './websocket.mjs';
|
|
4
4
|
export * from './webrtc.mjs';
|
|
5
|
+
export * from './identity-binding.mjs';
|
|
5
6
|
export * from './webtransport.mjs';
|
|
6
7
|
export * from './relay.mjs';
|
|
7
8
|
export * from './gateway.mjs';
|
|
8
9
|
export * from './streams.mjs';
|
|
9
10
|
export * from './cross-origin.mjs';
|
|
10
11
|
export * from './wsh-bridge.mjs';
|
|
12
|
+
export * from './wsh-frames.mjs';
|
|
13
|
+
export * from './wsh-links.mjs';
|
|
14
|
+
export * from './wsh-pod-transport.mjs';
|
|
15
|
+
// `wsh-in-process.mjs` (the in-process test relay) is deliberately NOT exported
|
|
16
|
+
// here: it imports wsh's pipe relay, which reaches for Node modules, and a
|
|
17
|
+
// bundler would follow that import into every browser build. Use the
|
|
18
|
+
// "@johnhenry/browsermesh-transport/wsh-in-process" subpath.
|
|
11
19
|
export * from './wisp.mjs';
|
|
12
20
|
export * from './channel-relay.mjs';
|
|
13
21
|
export * from './wire-data.mjs';
|
package/src/relay.mjs
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
/**
|
|
2
|
-
*
|
|
2
|
+
* relay.mjs -- Relay Client for Peer Discovery & Signal Forwarding.
|
|
3
3
|
*
|
|
4
4
|
* Two paths:
|
|
5
5
|
* 1. MockRelayServer — in-memory, used by tests and offline scenarios.
|
|
@@ -21,7 +21,7 @@
|
|
|
21
21
|
* {type:'error', message}
|
|
22
22
|
*
|
|
23
23
|
* Run tests:
|
|
24
|
-
* node --import ./
|
|
24
|
+
* cd packages/browsermesh-transport && node --import ./test/_setup-globals.mjs --test test/relay.test.mjs
|
|
25
25
|
*/
|
|
26
26
|
|
|
27
27
|
// ---------------------------------------------------------------------------
|
package/src/silent-catch.mjs
CHANGED
|
@@ -2,41 +2,70 @@
|
|
|
2
2
|
* silent-catch.mjs — debug-gated structured logger for the
|
|
3
3
|
* `try { … } catch { /* ignore *\/ }` pattern.
|
|
4
4
|
*
|
|
5
|
-
*
|
|
6
|
-
* clawser-app imports) so this package doesn't need to reach into web/.
|
|
5
|
+
* Standalone (no other imports) so this package is self-contained.
|
|
7
6
|
*
|
|
8
7
|
* Replaces silent catches with an opt-in inspectable record. Default
|
|
9
8
|
* behaviour is unchanged (silent), so this is a drop-in replacement.
|
|
10
9
|
* Users surface the events by enabling debug mode:
|
|
11
10
|
*
|
|
12
|
-
* localStorage.setItem('
|
|
13
|
-
* // or, in DevTools:
|
|
11
|
+
* localStorage.setItem('browsermesh_debug', 'true') // persistent
|
|
12
|
+
* // or, in DevTools: browsermeshDebug.enable()
|
|
14
13
|
*/
|
|
15
14
|
|
|
15
|
+
/** Primary localStorage key. */
|
|
16
|
+
const DEBUG_KEY = 'browsermesh_debug';
|
|
17
|
+
/** Deprecated alias, kept for compatibility. */
|
|
18
|
+
const LEGACY_DEBUG_KEY = 'clawser_debug';
|
|
19
|
+
|
|
20
|
+
function readFlag() {
|
|
21
|
+
return localStorage.getItem(DEBUG_KEY) === 'true' ||
|
|
22
|
+
localStorage.getItem(LEGACY_DEBUG_KEY) === 'true';
|
|
23
|
+
}
|
|
24
|
+
|
|
16
25
|
let enabled = false;
|
|
17
26
|
try {
|
|
18
27
|
if (typeof localStorage !== 'undefined') {
|
|
19
|
-
enabled =
|
|
28
|
+
enabled = readFlag();
|
|
20
29
|
}
|
|
21
30
|
} catch {
|
|
22
31
|
// localStorage may throw in privacy / sandbox contexts — treat as disabled
|
|
23
32
|
}
|
|
24
33
|
|
|
25
|
-
/** Re-check the localStorage flag; called by
|
|
34
|
+
/** Re-check the localStorage flag; called by browsermeshDebug.enable/disable. */
|
|
26
35
|
export function refreshSilentCatchState() {
|
|
27
36
|
try {
|
|
28
37
|
if (typeof localStorage !== 'undefined') {
|
|
29
|
-
enabled =
|
|
38
|
+
enabled = readFlag();
|
|
30
39
|
}
|
|
31
40
|
} catch {
|
|
32
41
|
enabled = false;
|
|
33
42
|
}
|
|
34
43
|
}
|
|
35
44
|
|
|
45
|
+
const debugApi = {
|
|
46
|
+
enable() {
|
|
47
|
+
try { localStorage.setItem(DEBUG_KEY, 'true'); } catch { /* ignore */ }
|
|
48
|
+
refreshSilentCatchState();
|
|
49
|
+
},
|
|
50
|
+
disable() {
|
|
51
|
+
try {
|
|
52
|
+
localStorage.removeItem(DEBUG_KEY);
|
|
53
|
+
localStorage.removeItem(LEGACY_DEBUG_KEY);
|
|
54
|
+
} catch { /* ignore */ }
|
|
55
|
+
refreshSilentCatchState();
|
|
56
|
+
},
|
|
57
|
+
};
|
|
58
|
+
|
|
59
|
+
if (typeof globalThis !== 'undefined') {
|
|
60
|
+
if (!globalThis.browsermeshDebug) globalThis.browsermeshDebug = debugApi;
|
|
61
|
+
/** Deprecated alias for `browsermeshDebug`, kept for compatibility. */
|
|
62
|
+
if (!globalThis.clawserDebug) globalThis.clawserDebug = globalThis.browsermeshDebug;
|
|
63
|
+
}
|
|
64
|
+
|
|
36
65
|
/**
|
|
37
66
|
* Log a silent-catch event. No-op unless debug mode is enabled.
|
|
38
67
|
*
|
|
39
|
-
* @param {string} module — file/component (e.g. '
|
|
68
|
+
* @param {string} module — file/component (e.g. 'webrtc')
|
|
40
69
|
* @param {string} operation — what was attempted (e.g. 'relay-disconnect')
|
|
41
70
|
* @param {*} error — the caught value
|
|
42
71
|
* @param {object} [context] — extra structured fields
|
|
@@ -51,5 +80,5 @@ export function silentCatch(module, operation, error, context) {
|
|
|
51
80
|
}
|
|
52
81
|
const entry = { module, operation, error: error?.message || String(error) };
|
|
53
82
|
if (context) Object.assign(entry, context);
|
|
54
|
-
console.warn('[
|
|
83
|
+
console.warn('[browsermesh:silent-catch]', entry);
|
|
55
84
|
}
|
package/src/streams.mjs
CHANGED
|
@@ -1,12 +1,12 @@
|
|
|
1
1
|
/**
|
|
2
|
-
// STATUS: INTEGRATED — wired into
|
|
3
|
-
*
|
|
2
|
+
// STATUS: INTEGRATED — wired into the `Pod` lifecycle (@johnhenry/browsermesh-pod), proven via E2E testing
|
|
3
|
+
* BrowserMesh Streams
|
|
4
4
|
*
|
|
5
5
|
* Multiplexed data streaming with credit-based backpressure.
|
|
6
6
|
* Wraps BrowserMesh streaming-protocol.md spec (0x12-0x16 wire codes)
|
|
7
7
|
* with a higher-level application API.
|
|
8
8
|
*
|
|
9
|
-
* @module
|
|
9
|
+
* @module streams
|
|
10
10
|
*/
|
|
11
11
|
|
|
12
12
|
import { MESH_TYPE, MESH_ERROR } from '@johnhenry/browsermesh-primitives';
|