@johnhenry/browsermesh-pod 0.1.1 → 0.2.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 +116 -1
- package/package.json +6 -2
- package/src/discovery.mjs +35 -12
- package/src/index.d.ts +78 -3
- package/src/index.mjs +7 -0
- package/src/node-runtime-entry.mjs +51 -0
- package/src/node-runtimes.d.ts +18 -0
- package/src/node-runtimes.mjs +306 -0
- package/src/pod-runtime.mjs +374 -0
- package/src/pod.mjs +95 -11
- package/src/signed-message.mjs +292 -0
- package/src/transport.mjs +12 -0
- package/src/ws-transport.mjs +56 -10
package/src/pod.mjs
CHANGED
|
@@ -11,7 +11,7 @@
|
|
|
11
11
|
* When no adapters are provided, Pod auto-detects: BroadcastChannel in browsers,
|
|
12
12
|
* NullTransport/NullDiscovery in Node.js.
|
|
13
13
|
*
|
|
14
|
-
* Zero
|
|
14
|
+
* Zero host-application imports — depends only on @johnhenry/browsermesh-primitives for identity.
|
|
15
15
|
*/
|
|
16
16
|
|
|
17
17
|
import { PodIdentity } from '@johnhenry/browsermesh-primitives'
|
|
@@ -24,6 +24,7 @@ import {
|
|
|
24
24
|
} from './messages.mjs'
|
|
25
25
|
import { BroadcastChannelTransport, NullTransport } from './transport.mjs'
|
|
26
26
|
import { TransportDiscovery, NullDiscovery } from './discovery.mjs'
|
|
27
|
+
import { MessageSigner, ReplayGuard, verifyMessage, DROP_REASONS } from './signed-message.mjs'
|
|
27
28
|
|
|
28
29
|
const POD_RUNTIME_KEY = Symbol.for('pod.runtime')
|
|
29
30
|
const DEFAULT_HANDSHAKE_TIMEOUT = 1000
|
|
@@ -45,6 +46,12 @@ export class Pod {
|
|
|
45
46
|
#discovery = null
|
|
46
47
|
#messageHandler = null
|
|
47
48
|
#g = null
|
|
49
|
+
#signer = null
|
|
50
|
+
#guard = new ReplayGuard()
|
|
51
|
+
#allowUnsigned = undefined
|
|
52
|
+
#trust = 'untrusted'
|
|
53
|
+
#rx = Promise.resolve()
|
|
54
|
+
#dropped = Object.fromEntries(DROP_REASONS.map((r) => [r, 0]))
|
|
48
55
|
|
|
49
56
|
// ── Getters ──────────────────────────────────────────────────
|
|
50
57
|
|
|
@@ -66,6 +73,14 @@ export class Pod {
|
|
|
66
73
|
/** @returns {PodState} */
|
|
67
74
|
get state() { return this.#state }
|
|
68
75
|
|
|
76
|
+
/**
|
|
77
|
+
* Messages refused so far, by reason (`unsigned`, `unsigned-rpc`, `malformed`,
|
|
78
|
+
* `sender-mismatch`, `bad-signature`, `replay`). Each is also announced as a
|
|
79
|
+
* `message:dropped` event `{ reason, type }`.
|
|
80
|
+
* @returns {Record<string, number>}
|
|
81
|
+
*/
|
|
82
|
+
get dropped() { return { ...this.#dropped } }
|
|
83
|
+
|
|
69
84
|
/** @returns {Map<string, object>} podId → peer info */
|
|
70
85
|
get peers() { return new Map(this.#peers) }
|
|
71
86
|
|
|
@@ -85,6 +100,15 @@ export class Pod {
|
|
|
85
100
|
* @param {number} [opts.handshakeTimeout] - ms to wait for parent ACK
|
|
86
101
|
* @param {number} [opts.discoveryTimeout] - ms to wait for peer responses
|
|
87
102
|
* @param {object} [opts.globalThis] - Override globalThis for testing
|
|
103
|
+
* @param {boolean} [opts.sign=true] - Sign outgoing `pod:message`/`pod:rpc-*` messages with this pod's key.
|
|
104
|
+
* `send()` then returns a promise that settles once the message is on the transport.
|
|
105
|
+
* @param {boolean} [opts.allowUnsigned] - Accept unsigned `pod:message` / `pod:rpc-response`
|
|
106
|
+
* from older peers. Default: `true` when the transport reports `trust === 'same-origin'`
|
|
107
|
+
* (BroadcastChannel, in-process) and for messages posted to the window; `false` for every
|
|
108
|
+
* other transport (WebSocket relay, custom adapters). Unsigned `pod:rpc-request`s are never
|
|
109
|
+
* accepted. A message that carries a signature must verify whatever this is set to.
|
|
110
|
+
* @param {'same-origin'|'untrusted'} [opts.trust] - Overrides the transport's own `trust`.
|
|
111
|
+
* @param {{ maxSenders?: number, maxSessionsPerSender?: number }} [opts.replay] - Bounds of the replay window state.
|
|
88
112
|
*/
|
|
89
113
|
async boot(opts = {}) {
|
|
90
114
|
if (this.#state !== 'idle') {
|
|
@@ -97,6 +121,11 @@ export class Pod {
|
|
|
97
121
|
// Phase 0: Install Runtime
|
|
98
122
|
this._emit('phase', { phase: 0, name: 'install-runtime' })
|
|
99
123
|
this.#identity = opts.identity || await PodIdentity.generate()
|
|
124
|
+
this.#signer = opts.sign !== false && MessageSigner.canSign(this.#identity)
|
|
125
|
+
? new MessageSigner(this.#identity)
|
|
126
|
+
: null
|
|
127
|
+
this.#allowUnsigned = opts.allowUnsigned
|
|
128
|
+
this.#guard = new ReplayGuard(opts.replay)
|
|
100
129
|
this.#kind = detectPodKind(this.#g)
|
|
101
130
|
this.#capabilities = detectCapabilities(this.#g)
|
|
102
131
|
this.#g[POD_RUNTIME_KEY] = {
|
|
@@ -179,8 +208,14 @@ export class Pod {
|
|
|
179
208
|
/**
|
|
180
209
|
* Send a message to a specific peer via the transport.
|
|
181
210
|
*
|
|
211
|
+
* Messages are signed by default (see `signed-message.mjs`), which needs a
|
|
212
|
+
* JSON-compatible payload and makes sending asynchronous: await the
|
|
213
|
+
* returned promise before relying on the message having been handed to the
|
|
214
|
+
* transport.
|
|
215
|
+
*
|
|
182
216
|
* @param {string} targetPodId
|
|
183
217
|
* @param {*} payload
|
|
218
|
+
* @returns {Promise<void>}
|
|
184
219
|
*/
|
|
185
220
|
send(targetPodId, payload) {
|
|
186
221
|
if (this.#state !== 'ready') {
|
|
@@ -189,18 +224,25 @@ export class Pod {
|
|
|
189
224
|
if (!this.#transport) {
|
|
190
225
|
throw new Error('No transport available')
|
|
191
226
|
}
|
|
192
|
-
this
|
|
193
|
-
|
|
194
|
-
)
|
|
227
|
+
const msg = createMessage({ from: this.podId, to: targetPodId, payload })
|
|
228
|
+
const transport = this.#transport
|
|
229
|
+
if (!this.#signer) {
|
|
230
|
+
transport.send(msg)
|
|
231
|
+
return Promise.resolve()
|
|
232
|
+
}
|
|
233
|
+
return this.#signer.sign(msg).then((signed) => {
|
|
234
|
+
if (this.#transport === transport) transport.send(signed)
|
|
235
|
+
})
|
|
195
236
|
}
|
|
196
237
|
|
|
197
238
|
/**
|
|
198
239
|
* Broadcast a message to all peers via the transport.
|
|
199
240
|
*
|
|
200
241
|
* @param {*} payload
|
|
242
|
+
* @returns {Promise<void>}
|
|
201
243
|
*/
|
|
202
244
|
broadcast(payload) {
|
|
203
|
-
this.send('*', payload)
|
|
245
|
+
return this.send('*', payload)
|
|
204
246
|
}
|
|
205
247
|
|
|
206
248
|
// ── Events ───────────────────────────────────────────────────
|
|
@@ -267,7 +309,7 @@ export class Pod {
|
|
|
267
309
|
this.#messageHandler = (event) => {
|
|
268
310
|
const data = event.data
|
|
269
311
|
if (!data || !data.type) return
|
|
270
|
-
this.#handleIncoming(data)
|
|
312
|
+
this.#handleIncoming(data, 'window')
|
|
271
313
|
}
|
|
272
314
|
this.#g.addEventListener('message', this.#messageHandler)
|
|
273
315
|
}
|
|
@@ -342,8 +384,9 @@ export class Pod {
|
|
|
342
384
|
this.#discovery.onPeerLost((info) => {
|
|
343
385
|
this.#removePeer(info.podId)
|
|
344
386
|
})
|
|
345
|
-
this.#
|
|
346
|
-
|
|
387
|
+
this.#trust = opts.trust ?? opts.discovery?.trust ?? this.#transport?.trust ?? 'untrusted'
|
|
388
|
+
this.#discovery.onMessage((msg, meta) => {
|
|
389
|
+
this.#handleIncoming(msg, 'transport', meta)
|
|
347
390
|
})
|
|
348
391
|
|
|
349
392
|
// Run discovery
|
|
@@ -362,7 +405,12 @@ export class Pod {
|
|
|
362
405
|
|
|
363
406
|
// ── Private: message routing ─────────────────────────────────
|
|
364
407
|
|
|
365
|
-
|
|
408
|
+
/**
|
|
409
|
+
* @param {object} data
|
|
410
|
+
* @param {'window'|'transport'} [source]
|
|
411
|
+
* @param {{ peerId?: string }} [meta] - `peerId`: the peer identity the link itself authenticated
|
|
412
|
+
*/
|
|
413
|
+
#handleIncoming(data, source = 'transport', meta) {
|
|
366
414
|
switch (data.type) {
|
|
367
415
|
case POD_HELLO: {
|
|
368
416
|
if (data.podId !== this.podId) {
|
|
@@ -389,14 +437,50 @@ export class Pod {
|
|
|
389
437
|
case POD_RPC_REQUEST:
|
|
390
438
|
case POD_RPC_RESPONSE: {
|
|
391
439
|
if (data.to === this.podId || data.to === '*') {
|
|
392
|
-
|
|
393
|
-
this.
|
|
440
|
+
// Verification is asynchronous; one queue keeps arrival order.
|
|
441
|
+
this.#rx = this.#rx.then(() => this.#receive(data, source, meta)).catch(() => {})
|
|
394
442
|
}
|
|
395
443
|
break
|
|
396
444
|
}
|
|
397
445
|
}
|
|
398
446
|
}
|
|
399
447
|
|
|
448
|
+
/**
|
|
449
|
+
* Decide whether a message that targets this pod is delivered, and as
|
|
450
|
+
* whom. The sender is never read from a field the sender or a relay wrote:
|
|
451
|
+
* it is the identity the link authenticated, or the key that signed.
|
|
452
|
+
*/
|
|
453
|
+
async #receive(data, source, meta) {
|
|
454
|
+
const drop = (reason) => {
|
|
455
|
+
this.#dropped[reason]++
|
|
456
|
+
this._emit('message:dropped', { reason, type: data.type })
|
|
457
|
+
}
|
|
458
|
+
if (this.#state === 'shutdown') return
|
|
459
|
+
|
|
460
|
+
const linkPeer = typeof meta?.peerId === 'string' ? meta.peerId : null
|
|
461
|
+
let delivered
|
|
462
|
+
|
|
463
|
+
if (linkPeer !== null) {
|
|
464
|
+
// The link authenticates the peer: the sender is the link's identity,
|
|
465
|
+
// and a message that claims another one is dropped.
|
|
466
|
+
if (data.from !== linkPeer) return drop('sender-mismatch')
|
|
467
|
+
delivered = { ...data, authenticated: true }
|
|
468
|
+
} else if (data.sig !== undefined || data.pk !== undefined) {
|
|
469
|
+
const verdict = await verifyMessage(data, { guard: this.#guard })
|
|
470
|
+
if (!verdict.ok) return drop(verdict.reason)
|
|
471
|
+
delivered = { ...verdict.message, authenticated: true }
|
|
472
|
+
} else {
|
|
473
|
+
if (data.type === POD_RPC_REQUEST) return drop('unsigned-rpc')
|
|
474
|
+
const allowed = this.#allowUnsigned ?? (source === 'window' || this.#trust === 'same-origin')
|
|
475
|
+
if (!allowed) return drop('unsigned')
|
|
476
|
+
delivered = { ...data, authenticated: false }
|
|
477
|
+
}
|
|
478
|
+
|
|
479
|
+
if (this.#state === 'shutdown') return
|
|
480
|
+
this._onMessage(delivered)
|
|
481
|
+
this._emit('message', delivered)
|
|
482
|
+
}
|
|
483
|
+
|
|
400
484
|
#addPeer(podId, info) {
|
|
401
485
|
if (podId === this.podId) return
|
|
402
486
|
const isNew = !this.#peers.has(podId)
|
|
@@ -0,0 +1,292 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* signed-message.mjs -- sender authenticity for pod messages.
|
|
3
|
+
*
|
|
4
|
+
* A receiver never takes a sender's identity from a field that the sender
|
|
5
|
+
* or a relay wrote. A signed message carries the sender's public key (`pk`)
|
|
6
|
+
* and a signature (`sig`) by that key over a canonical encoding of the whole
|
|
7
|
+
* message, so a receiver checks two things: that `from` equals the pod id
|
|
8
|
+
* derived from `pk` (pod id = base64url(SHA-256(raw public key))), and that
|
|
9
|
+
* `sig` verifies under `pk`. A pod id therefore needs no prior key exchange.
|
|
10
|
+
*
|
|
11
|
+
* Signed bytes: `"browsermesh/pod-message/v1\n"` followed by the canonical
|
|
12
|
+
* JSON (keys sorted, no whitespace) of an object holding exactly the fields
|
|
13
|
+
* listed in `SIGNED_FIELDS` for the message type: sender, recipient, type,
|
|
14
|
+
* body, `sid` (a random session id for this sender, chosen at boot), `seq`
|
|
15
|
+
* (a counter that increases by one per message within that session) and
|
|
16
|
+
* `ts`. A relay that rewrites, re-addresses or adds to a message invalidates
|
|
17
|
+
* the signature; fields outside the list are never delivered.
|
|
18
|
+
*
|
|
19
|
+
* Freshness: `(sid, seq)` is the message id, and the receiver keeps a sliding
|
|
20
|
+
* window of the last `REPLAY_WINDOW` sequence numbers per sender session, so
|
|
21
|
+
* a copy of a message already accepted is refused and mild reordering is
|
|
22
|
+
* tolerated. Clocks are not trusted: `ts` is signed (so it cannot be
|
|
23
|
+
* changed) but never used to decide freshness. The window state is in memory
|
|
24
|
+
* and bounded (`maxSessionsPerSender` sessions for each of `maxSenders`
|
|
25
|
+
* senders): a copy of a message from a session the receiver has forgotten, or
|
|
26
|
+
* sent to a receiver that restarted, is not recognised as a replay. Links
|
|
27
|
+
* that authenticate the peer themselves (see `Pod`) do not rely on this.
|
|
28
|
+
*
|
|
29
|
+
* Browser-safe: WebCrypto only.
|
|
30
|
+
*/
|
|
31
|
+
|
|
32
|
+
import { PodIdentity } from '@johnhenry/browsermesh-primitives'
|
|
33
|
+
import {
|
|
34
|
+
POD_MESSAGE, POD_RPC_REQUEST, POD_RPC_RESPONSE,
|
|
35
|
+
} from './messages.mjs'
|
|
36
|
+
|
|
37
|
+
export const SIGNATURE_DOMAIN = 'browsermesh/pod-message/v1\n'
|
|
38
|
+
|
|
39
|
+
/** Number of sequence numbers behind the highest seen that are still accepted (once each). */
|
|
40
|
+
export const REPLAY_WINDOW = 64
|
|
41
|
+
|
|
42
|
+
/** Fields covered by the signature, per message type. Anything else on a received message is ignored. */
|
|
43
|
+
export const SIGNED_FIELDS = Object.freeze({
|
|
44
|
+
[POD_MESSAGE]: Object.freeze(['type', 'from', 'to', 'payload', 'ts', 'pk', 'sid', 'seq']),
|
|
45
|
+
[POD_RPC_REQUEST]: Object.freeze(['type', 'from', 'to', 'method', 'params', 'requestId', 'ts', 'pk', 'sid', 'seq']),
|
|
46
|
+
[POD_RPC_RESPONSE]: Object.freeze(['type', 'from', 'to', 'requestId', 'result', 'error', 'ts', 'pk', 'sid', 'seq']),
|
|
47
|
+
})
|
|
48
|
+
|
|
49
|
+
/** Why a message was dropped (the `reason` of a drop). */
|
|
50
|
+
export const DROP_REASONS = Object.freeze([
|
|
51
|
+
'unsigned', 'malformed', 'sender-mismatch', 'bad-signature', 'replay', 'unsigned-rpc',
|
|
52
|
+
])
|
|
53
|
+
|
|
54
|
+
// ── Encoding helpers ────────────────────────────────────────────
|
|
55
|
+
|
|
56
|
+
const encoder = new TextEncoder()
|
|
57
|
+
|
|
58
|
+
/** @param {Uint8Array} bytes @returns {string} */
|
|
59
|
+
export function toBase64url(bytes) {
|
|
60
|
+
let bin = ''
|
|
61
|
+
for (let i = 0; i < bytes.length; i++) bin += String.fromCharCode(bytes[i])
|
|
62
|
+
return btoa(bin).replace(/\+/g, '-').replace(/\//g, '_').replace(/=+$/, '')
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
/** @param {string} str @returns {Uint8Array|null} null when not base64url */
|
|
66
|
+
export function fromBase64url(str) {
|
|
67
|
+
if (typeof str !== 'string' || !/^[A-Za-z0-9_-]*$/.test(str) || str.length % 4 === 1) return null
|
|
68
|
+
const bin = atob(str.replace(/-/g, '+').replace(/_/g, '/').padEnd(Math.ceil(str.length / 4) * 4, '='))
|
|
69
|
+
const out = new Uint8Array(bin.length)
|
|
70
|
+
for (let i = 0; i < bin.length; i++) out[i] = bin.charCodeAt(i)
|
|
71
|
+
return out
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
/**
|
|
75
|
+
* Canonical JSON: sorted keys, no whitespace, `undefined` members omitted,
|
|
76
|
+
* finite numbers only, plain objects only.
|
|
77
|
+
*
|
|
78
|
+
* @param {*} value
|
|
79
|
+
* @returns {string}
|
|
80
|
+
*/
|
|
81
|
+
export function canonicalize(value) {
|
|
82
|
+
if (value === null) return 'null'
|
|
83
|
+
switch (typeof value) {
|
|
84
|
+
case 'boolean':
|
|
85
|
+
case 'string':
|
|
86
|
+
return JSON.stringify(value)
|
|
87
|
+
case 'number':
|
|
88
|
+
if (!Number.isFinite(value)) throw new TypeError(`Cannot canonicalize non-finite number: ${value}`)
|
|
89
|
+
return JSON.stringify(value)
|
|
90
|
+
case 'object': {
|
|
91
|
+
if (Array.isArray(value)) {
|
|
92
|
+
return `[${value.map((v) => {
|
|
93
|
+
if (v === undefined) throw new TypeError('Cannot canonicalize undefined array element')
|
|
94
|
+
return canonicalize(v)
|
|
95
|
+
}).join(',')}]`
|
|
96
|
+
}
|
|
97
|
+
const proto = Object.getPrototypeOf(value)
|
|
98
|
+
if (proto !== Object.prototype && proto !== null) throw new TypeError('Can only canonicalize plain objects')
|
|
99
|
+
const keys = Object.keys(value).filter((k) => value[k] !== undefined).sort()
|
|
100
|
+
return `{${keys.map((k) => `${JSON.stringify(k)}:${canonicalize(value[k])}`).join(',')}}`
|
|
101
|
+
}
|
|
102
|
+
default:
|
|
103
|
+
throw new TypeError(`Cannot canonicalize value of type ${typeof value}`)
|
|
104
|
+
}
|
|
105
|
+
}
|
|
106
|
+
|
|
107
|
+
/**
|
|
108
|
+
* The bytes that are signed for a message: domain prefix plus the canonical
|
|
109
|
+
* JSON of its signed fields except `sig`.
|
|
110
|
+
*
|
|
111
|
+
* @param {object} msg
|
|
112
|
+
* @returns {Uint8Array}
|
|
113
|
+
*/
|
|
114
|
+
export function signedBytes(msg) {
|
|
115
|
+
const fields = SIGNED_FIELDS[msg.type]
|
|
116
|
+
if (!fields) throw new TypeError(`Not a signable message type: ${msg.type}`)
|
|
117
|
+
const body = {}
|
|
118
|
+
for (const f of fields) if (msg[f] !== undefined) body[f] = msg[f]
|
|
119
|
+
return encoder.encode(SIGNATURE_DOMAIN + canonicalize(body))
|
|
120
|
+
}
|
|
121
|
+
|
|
122
|
+
/** @param {Uint8Array} raw public key @returns {Promise<string>} pod id */
|
|
123
|
+
export async function podIdOfRawKey(raw) {
|
|
124
|
+
return toBase64url(new Uint8Array(await crypto.subtle.digest('SHA-256', raw)))
|
|
125
|
+
}
|
|
126
|
+
|
|
127
|
+
// ── Signing ─────────────────────────────────────────────────────
|
|
128
|
+
|
|
129
|
+
/**
|
|
130
|
+
* Signs outgoing messages for one pod: owns the session id and counter.
|
|
131
|
+
*/
|
|
132
|
+
export class MessageSigner {
|
|
133
|
+
#identity
|
|
134
|
+
#sid
|
|
135
|
+
#seq = 0
|
|
136
|
+
#pk = null
|
|
137
|
+
|
|
138
|
+
/**
|
|
139
|
+
* @param {{ podId: string, sign: Function, rawPublicKey?: Function }} identity - a `PodIdentity`
|
|
140
|
+
*/
|
|
141
|
+
constructor(identity, { sessionId } = {}) {
|
|
142
|
+
this.#identity = identity
|
|
143
|
+
if (sessionId !== undefined) {
|
|
144
|
+
this.#sid = sessionId
|
|
145
|
+
} else {
|
|
146
|
+
const rnd = new Uint8Array(12)
|
|
147
|
+
crypto.getRandomValues(rnd)
|
|
148
|
+
this.#sid = toBase64url(rnd)
|
|
149
|
+
}
|
|
150
|
+
}
|
|
151
|
+
|
|
152
|
+
/** Whether `identity` can sign (a `{ podId }` stub cannot). */
|
|
153
|
+
static canSign(identity) {
|
|
154
|
+
return !!identity && typeof identity.sign === 'function' && typeof identity.rawPublicKey === 'function'
|
|
155
|
+
}
|
|
156
|
+
|
|
157
|
+
get sessionId() { return this.#sid }
|
|
158
|
+
|
|
159
|
+
/**
|
|
160
|
+
* Add `pk`, `sid`, `seq` and `sig` to a message. The sequence number is
|
|
161
|
+
* assigned before anything is awaited, so messages are numbered in the
|
|
162
|
+
* order `sign()` is called.
|
|
163
|
+
*
|
|
164
|
+
* @template {object} T
|
|
165
|
+
* @param {T} msg - one of the factory-built messages (`createMessage()`, ...)
|
|
166
|
+
* @returns {Promise<T & { pk: string, sid: string, seq: number, sig: string }>}
|
|
167
|
+
*/
|
|
168
|
+
async sign(msg) {
|
|
169
|
+
const seq = ++this.#seq
|
|
170
|
+
this.#pk ??= toBase64url(await this.#identity.rawPublicKey())
|
|
171
|
+
const full = { ...msg, pk: this.#pk, sid: this.#sid, seq }
|
|
172
|
+
const sig = await this.#identity.sign(signedBytes(full))
|
|
173
|
+
return { ...full, sig: toBase64url(sig) }
|
|
174
|
+
}
|
|
175
|
+
}
|
|
176
|
+
|
|
177
|
+
// ── Replay window ───────────────────────────────────────────────
|
|
178
|
+
|
|
179
|
+
/** Sliding window over the sequence numbers of one sender session. */
|
|
180
|
+
export class ReplayWindow {
|
|
181
|
+
#max = 0
|
|
182
|
+
#seen = new Set()
|
|
183
|
+
#size
|
|
184
|
+
|
|
185
|
+
constructor(size = REPLAY_WINDOW) { this.#size = size }
|
|
186
|
+
|
|
187
|
+
/**
|
|
188
|
+
* Record `seq` if it is new and inside the window.
|
|
189
|
+
* @param {number} seq
|
|
190
|
+
* @returns {boolean} false for a repeat, a number too far behind, or a non-counter
|
|
191
|
+
*/
|
|
192
|
+
accept(seq) {
|
|
193
|
+
if (!Number.isSafeInteger(seq) || seq < 1) return false
|
|
194
|
+
if (seq <= this.#max - this.#size) return false
|
|
195
|
+
if (this.#seen.has(seq)) return false
|
|
196
|
+
this.#seen.add(seq)
|
|
197
|
+
if (seq > this.#max) {
|
|
198
|
+
this.#max = seq
|
|
199
|
+
for (const s of this.#seen) if (s <= this.#max - this.#size) this.#seen.delete(s)
|
|
200
|
+
}
|
|
201
|
+
return true
|
|
202
|
+
}
|
|
203
|
+
}
|
|
204
|
+
|
|
205
|
+
/** Bounded replay state for every sender a pod hears from. */
|
|
206
|
+
export class ReplayGuard {
|
|
207
|
+
#senders = new Map()
|
|
208
|
+
#maxSenders
|
|
209
|
+
#maxSessions
|
|
210
|
+
|
|
211
|
+
/**
|
|
212
|
+
* @param {{ maxSenders?: number, maxSessionsPerSender?: number }} [opts]
|
|
213
|
+
*/
|
|
214
|
+
constructor({ maxSenders = 1024, maxSessionsPerSender = 4 } = {}) {
|
|
215
|
+
this.#maxSenders = maxSenders
|
|
216
|
+
this.#maxSessions = maxSessionsPerSender
|
|
217
|
+
}
|
|
218
|
+
|
|
219
|
+
/** Number of senders tracked. */
|
|
220
|
+
get size() { return this.#senders.size }
|
|
221
|
+
|
|
222
|
+
/** Record `(from, sid, seq)`; false if it was seen or is outside the window. */
|
|
223
|
+
accept(from, sid, seq) {
|
|
224
|
+
return this.#sessionOf(from, sid, true).accept(seq)
|
|
225
|
+
}
|
|
226
|
+
|
|
227
|
+
#sessionOf(from, sid, create) {
|
|
228
|
+
let sessions = this.#senders.get(from)
|
|
229
|
+
if (!sessions) {
|
|
230
|
+
if (!create) return null
|
|
231
|
+
sessions = new Map()
|
|
232
|
+
this.#senders.set(from, sessions)
|
|
233
|
+
if (this.#senders.size > this.#maxSenders) this.#senders.delete(this.#senders.keys().next().value)
|
|
234
|
+
} else {
|
|
235
|
+
// most recently used last
|
|
236
|
+
this.#senders.delete(from)
|
|
237
|
+
this.#senders.set(from, sessions)
|
|
238
|
+
}
|
|
239
|
+
let win = sessions.get(sid)
|
|
240
|
+
if (!win) {
|
|
241
|
+
if (!create) return null
|
|
242
|
+
win = new ReplayWindow()
|
|
243
|
+
sessions.set(sid, win)
|
|
244
|
+
if (sessions.size > this.#maxSessions) sessions.delete(sessions.keys().next().value)
|
|
245
|
+
}
|
|
246
|
+
return win
|
|
247
|
+
}
|
|
248
|
+
}
|
|
249
|
+
|
|
250
|
+
// ── Verification ────────────────────────────────────────────────
|
|
251
|
+
|
|
252
|
+
/**
|
|
253
|
+
* Verify a received message against its own claims: shape, that `from`
|
|
254
|
+
* equals the pod id of `pk`, the signature, and freshness.
|
|
255
|
+
*
|
|
256
|
+
* On success the returned `message` holds only the signed fields, which is
|
|
257
|
+
* all a receiver should use.
|
|
258
|
+
*
|
|
259
|
+
* @param {object} msg
|
|
260
|
+
* @param {{ guard?: ReplayGuard }} [opts] - pass a guard to also refuse replays (and to record this message)
|
|
261
|
+
* @returns {Promise<{ ok: true, from: string, message: object } | { ok: false, reason: string }>}
|
|
262
|
+
*/
|
|
263
|
+
export async function verifyMessage(msg, { guard } = {}) {
|
|
264
|
+
if (!msg || typeof msg !== 'object') return { ok: false, reason: 'malformed' }
|
|
265
|
+
const fields = SIGNED_FIELDS[msg.type]
|
|
266
|
+
if (!fields) return { ok: false, reason: 'malformed' }
|
|
267
|
+
if (msg.sig === undefined && msg.pk === undefined) return { ok: false, reason: 'unsigned' }
|
|
268
|
+
if (typeof msg.from !== 'string' || typeof msg.to !== 'string' || typeof msg.sid !== 'string'
|
|
269
|
+
|| typeof msg.pk !== 'string' || typeof msg.sig !== 'string' || !Number.isSafeInteger(msg.seq)) {
|
|
270
|
+
return { ok: false, reason: 'malformed' }
|
|
271
|
+
}
|
|
272
|
+
const raw = fromBase64url(msg.pk)
|
|
273
|
+
const sig = fromBase64url(msg.sig)
|
|
274
|
+
if (!raw || raw.length !== 32 || !sig || sig.length !== 64) return { ok: false, reason: 'malformed' }
|
|
275
|
+
|
|
276
|
+
if ((await podIdOfRawKey(raw)) !== msg.from) return { ok: false, reason: 'sender-mismatch' }
|
|
277
|
+
|
|
278
|
+
let bytes
|
|
279
|
+
try { bytes = signedBytes(msg) } catch { return { ok: false, reason: 'malformed' } }
|
|
280
|
+
let valid = false
|
|
281
|
+
try {
|
|
282
|
+
const key = await crypto.subtle.importKey('raw', raw, 'Ed25519', false, ['verify'])
|
|
283
|
+
valid = await PodIdentity.verify(key, sig, bytes)
|
|
284
|
+
} catch { valid = false }
|
|
285
|
+
if (!valid) return { ok: false, reason: 'bad-signature' }
|
|
286
|
+
|
|
287
|
+
if (guard && !guard.accept(msg.from, msg.sid, msg.seq)) return { ok: false, reason: 'replay' }
|
|
288
|
+
|
|
289
|
+
const message = {}
|
|
290
|
+
for (const f of fields) if (msg[f] !== undefined) message[f] = msg[f]
|
|
291
|
+
return { ok: true, from: msg.from, message }
|
|
292
|
+
}
|
package/src/transport.mjs
CHANGED
|
@@ -24,6 +24,13 @@
|
|
|
24
24
|
* subscribed to the same channel name.
|
|
25
25
|
*/
|
|
26
26
|
export class BroadcastChannelTransport {
|
|
27
|
+
/**
|
|
28
|
+
* Who can put a message on this transport: any script of the same origin.
|
|
29
|
+
* A pod accepts unsigned messages from a `'same-origin'` transport by
|
|
30
|
+
* default; any other value (or none) means signatures are required.
|
|
31
|
+
*/
|
|
32
|
+
get trust() { return 'same-origin' }
|
|
33
|
+
|
|
27
34
|
#channel = null
|
|
28
35
|
#channelName
|
|
29
36
|
#handler = null
|
|
@@ -89,6 +96,9 @@ export class BroadcastChannelTransport {
|
|
|
89
96
|
* const t2 = new EventEmitterTransport(bus)
|
|
90
97
|
*/
|
|
91
98
|
export class EventEmitterTransport {
|
|
99
|
+
/** In-process only: whoever shares the bus. See `BroadcastChannelTransport#trust`. */
|
|
100
|
+
get trust() { return 'same-origin' }
|
|
101
|
+
|
|
92
102
|
#bus
|
|
93
103
|
#handler = null
|
|
94
104
|
#ready = false
|
|
@@ -158,6 +168,8 @@ export class EventEmitterTransport {
|
|
|
158
168
|
* Used when no transport is available or desired.
|
|
159
169
|
*/
|
|
160
170
|
export class NullTransport {
|
|
171
|
+
get trust() { return 'same-origin' }
|
|
172
|
+
|
|
161
173
|
get ready() { return true }
|
|
162
174
|
onMessage(_handler) {}
|
|
163
175
|
async open() {}
|
package/src/ws-transport.mjs
CHANGED
|
@@ -16,7 +16,8 @@
|
|
|
16
16
|
* forwarded by the signaling server as: { type: 'signal', source, envelope }
|
|
17
17
|
* (the signaling server spreads the forwarded payload and injects `source`,
|
|
18
18
|
* so any extra keys like `envelope` survive the hop unchanged)
|
|
19
|
-
* - peers: { type: 'peers', peers: string[] } (signaling only, sent once on registration
|
|
19
|
+
* - peers: { type: 'peers', peers: string[] } (signaling only, sent once on registration,
|
|
20
|
+
* in a frame AFTER `registered`: `open()` can resolve before it is handled)
|
|
20
21
|
* - peer-joined / peer-left: { type: 'peer-joined'|'peer-left', podId } (signaling only)
|
|
21
22
|
* - ping / pong: { type: 'ping' } / { type: 'pong' }
|
|
22
23
|
* - error: { type: 'error', message }
|
|
@@ -56,6 +57,7 @@ export class WebSocketTransport {
|
|
|
56
57
|
#ready = false
|
|
57
58
|
#closed = true
|
|
58
59
|
#knownPeers = new Set()
|
|
60
|
+
#peerJoinedHandlers = new Set()
|
|
59
61
|
|
|
60
62
|
#primaryReconnect = { attempts: 0, timer: null }
|
|
61
63
|
#sigReconnect = { attempts: 0, timer: null }
|
|
@@ -93,6 +95,13 @@ export class WebSocketTransport {
|
|
|
93
95
|
this.#onLog = onLog || (() => {})
|
|
94
96
|
}
|
|
95
97
|
|
|
98
|
+
/**
|
|
99
|
+
* The relay stamps `source` and can rewrite or inject envelopes, so nothing
|
|
100
|
+
* about a message is authenticated by this link. A pod requires signed
|
|
101
|
+
* messages over it unless told otherwise (`allowUnsigned`).
|
|
102
|
+
*/
|
|
103
|
+
get trust() { return 'untrusted' }
|
|
104
|
+
|
|
96
105
|
/** @returns {boolean} true once the primary connection is registered */
|
|
97
106
|
get ready() { return this.#ready }
|
|
98
107
|
|
|
@@ -106,6 +115,19 @@ export class WebSocketTransport {
|
|
|
106
115
|
this.#handler = handler
|
|
107
116
|
}
|
|
108
117
|
|
|
118
|
+
/**
|
|
119
|
+
* Be told about each peer id the server announces (`peers`, `peer-joined`)
|
|
120
|
+
* that this transport did not know yet. `peers` follows `registered` in a
|
|
121
|
+
* later frame, and pods can join at any time, so discovery must react to
|
|
122
|
+
* these rather than assume the list is complete when `open()` resolves.
|
|
123
|
+
* @param {(podId: string) => void} handler
|
|
124
|
+
* @returns {() => void} unsubscribe
|
|
125
|
+
*/
|
|
126
|
+
onPeerJoined(handler) {
|
|
127
|
+
this.#peerJoinedHandlers.add(handler)
|
|
128
|
+
return () => this.#peerJoinedHandlers.delete(handler)
|
|
129
|
+
}
|
|
130
|
+
|
|
109
131
|
/**
|
|
110
132
|
* Connect to the relay server (and, if configured, the signaling server)
|
|
111
133
|
* and complete registration. Resolves once `registered` arrives on the
|
|
@@ -327,6 +349,8 @@ export class WebSocketTransport {
|
|
|
327
349
|
// ── Private: inbound ──────────────────────────────────────────────
|
|
328
350
|
|
|
329
351
|
#handlePrimaryMessage(data) {
|
|
352
|
+
// A signaling server used as the primary connection announces peers on it.
|
|
353
|
+
if (this.#protocol === 'signaling' && this.#handlePeerFrame(data)) return
|
|
330
354
|
switch (data.type) {
|
|
331
355
|
case 'relayed':
|
|
332
356
|
case 'signal': {
|
|
@@ -345,22 +369,41 @@ export class WebSocketTransport {
|
|
|
345
369
|
}
|
|
346
370
|
}
|
|
347
371
|
|
|
348
|
-
|
|
372
|
+
/**
|
|
373
|
+
* Apply a `peers` / `peer-joined` / `peer-left` frame to `knownPeers`.
|
|
374
|
+
* Newly learned peers are announced to `onPeerJoined` handlers.
|
|
375
|
+
* @returns {boolean} true if the frame was one of those three
|
|
376
|
+
*/
|
|
377
|
+
#handlePeerFrame(data) {
|
|
349
378
|
switch (data.type) {
|
|
350
379
|
case 'peers': {
|
|
351
|
-
for (const id of data.peers || [])
|
|
352
|
-
|
|
353
|
-
}
|
|
354
|
-
return
|
|
380
|
+
for (const id of data.peers || []) this.#learnPeer(id)
|
|
381
|
+
return true
|
|
355
382
|
}
|
|
356
383
|
case 'peer-joined': {
|
|
357
|
-
|
|
358
|
-
return
|
|
384
|
+
this.#learnPeer(data.podId)
|
|
385
|
+
return true
|
|
359
386
|
}
|
|
360
387
|
case 'peer-left': {
|
|
361
388
|
if (data.podId) this.#knownPeers.delete(data.podId)
|
|
362
|
-
return
|
|
389
|
+
return true
|
|
363
390
|
}
|
|
391
|
+
default:
|
|
392
|
+
return false
|
|
393
|
+
}
|
|
394
|
+
}
|
|
395
|
+
|
|
396
|
+
#learnPeer(id) {
|
|
397
|
+
if (!id || id === this.#podId || this.#knownPeers.has(id)) return
|
|
398
|
+
this.#knownPeers.add(id)
|
|
399
|
+
for (const handler of this.#peerJoinedHandlers) {
|
|
400
|
+
try { handler(id) } catch { /* a handler error must not break frame handling */ }
|
|
401
|
+
}
|
|
402
|
+
}
|
|
403
|
+
|
|
404
|
+
#handleSignalingMessage(data) {
|
|
405
|
+
if (this.#handlePeerFrame(data)) return
|
|
406
|
+
switch (data.type) {
|
|
364
407
|
case 'ping':
|
|
365
408
|
this.#send(this.#sigWs, { type: 'pong' })
|
|
366
409
|
return
|
|
@@ -374,7 +417,10 @@ export class WebSocketTransport {
|
|
|
374
417
|
|
|
375
418
|
#deliver(source, envelope) {
|
|
376
419
|
if (!this.#handler || !envelope || typeof envelope !== 'object') return
|
|
377
|
-
|
|
420
|
+
// `source` is written by the relay. It is passed on as `relaySource` for
|
|
421
|
+
// diagnostics and is never used as the sender's identity: the envelope's
|
|
422
|
+
// own `from` is a claim too, and a pod checks it against a signature.
|
|
423
|
+
const msg = { ...envelope, relaySource: source }
|
|
378
424
|
this.#handler(msg)
|
|
379
425
|
}
|
|
380
426
|
}
|