@johnhenry/browsermesh-core 0.2.3 → 0.2.5
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/package.json +1 -1
- package/src/group-keys.mjs +59 -4
- package/src/handshake.mjs +229 -48
package/package.json
CHANGED
package/src/group-keys.mjs
CHANGED
|
@@ -386,18 +386,73 @@ export class GroupKeyManager {
|
|
|
386
386
|
* Used when adding a member (existing key is fine, but new epoch
|
|
387
387
|
* ensures clean key lifecycle) or periodically for key freshness.
|
|
388
388
|
*
|
|
389
|
+
* By default this self-generates a fresh random key for the new epoch
|
|
390
|
+
* (unchanged, original behavior). Pass `{ epoch, key }` to instead
|
|
391
|
+
* *adopt* a specific, externally-agreed key rather than generating one —
|
|
392
|
+
* see the "Adopt-path calling convention" note below.
|
|
393
|
+
*
|
|
394
|
+
* ## Adopt-path calling convention
|
|
395
|
+
*
|
|
396
|
+
* This exists for callers that run a distributed agreement protocol
|
|
397
|
+
* (e.g. PBFT/consensus) over *when* to rotate and *who* the members are,
|
|
398
|
+
* without letting the actual key bytes anywhere near that agreement
|
|
399
|
+
* payload — broadcasting raw key material to every participant of a
|
|
400
|
+
* consensus round (rather than just the intended group members) would be
|
|
401
|
+
* a security regression relative to the per-recipient envelope
|
|
402
|
+
* mechanism this package already provides (`wrapKeyForMember` /
|
|
403
|
+
* `unwrapKeyForMember`, used by `broadcastDistribute()` /
|
|
404
|
+
* `wireTransport()`'s `GROUP_KEY_DISTRIBUTE` handler).
|
|
405
|
+
*
|
|
406
|
+
* The intended shape of that split:
|
|
407
|
+
* 1. Consensus agrees ONLY on `{ epoch, members }` — never key bytes.
|
|
408
|
+
* 2. Exactly one designated party (the proposer/leader) generates the
|
|
409
|
+
* real key and distributes it to each member individually via the
|
|
410
|
+
* existing secure envelope mechanism (`wrapKeyForMember` on the
|
|
411
|
+
* sender, `unwrapKeyForMember` — or the `GROUP_KEY_DISTRIBUTE`
|
|
412
|
+
* handler wired by `wireTransport()`, which calls
|
|
413
|
+
* `unwrapKeyForMember` internally — on each recipient).
|
|
414
|
+
* 3. Once a caller has BOTH the consensus-agreed epoch number AND the
|
|
415
|
+
* real `CryptoKey` obtained locally from that envelope decrypt (not
|
|
416
|
+
* exported/wire bytes — `unwrapKeyForMember` already hands back a
|
|
417
|
+
* live `CryptoKey`, the same shape `acceptEpoch()` accepts), it
|
|
418
|
+
* calls `rotate(members, { epoch, key })` to install that exact key
|
|
419
|
+
* as this manager's active state for that epoch, instead of calling
|
|
420
|
+
* plain `rotate(members)` (which would self-generate a different,
|
|
421
|
+
* non-agreed key).
|
|
422
|
+
*
|
|
423
|
+
* `key` is deliberately a `CryptoKey`, not exported/serialized bytes:
|
|
424
|
+
* this path is for in-process callers on the same JS runtime (e.g. a
|
|
425
|
+
* PBFT `applyBlock()` dispatch handing off to this manager) that already
|
|
426
|
+
* hold a real key locally — it is not a wire format and must never be
|
|
427
|
+
* put on the wire itself.
|
|
428
|
+
*
|
|
389
429
|
* @param {string[]} [newMembers] - Updated member list; defaults to current members
|
|
430
|
+
* @param {object} [adopt] - Omit entirely for today's self-generating behavior.
|
|
431
|
+
* @param {number} [adopt.epoch] - Externally-agreed epoch number to adopt. Must be
|
|
432
|
+
* provided together with `adopt.key`, never alone.
|
|
433
|
+
* @param {CryptoKey} [adopt.key] - Externally-agreed key to adopt in-process (e.g. from
|
|
434
|
+
* `unwrapKeyForMember`/an envelope decrypt), rather than generating a new one. Must be
|
|
435
|
+
* provided together with `adopt.epoch`, never alone.
|
|
390
436
|
* @returns {Promise<GroupState>}
|
|
391
437
|
*/
|
|
392
|
-
async rotate(newMembers) {
|
|
438
|
+
async rotate(newMembers, { epoch, key } = {}) {
|
|
439
|
+
const hasEpoch = epoch !== undefined
|
|
440
|
+
const hasKey = key !== undefined
|
|
441
|
+
if (hasEpoch !== hasKey) {
|
|
442
|
+
throw new Error('rotate: epoch and key must be provided together (both or neither)')
|
|
443
|
+
}
|
|
444
|
+
if (hasKey && !(typeof CryptoKey !== 'undefined' && key instanceof CryptoKey)) {
|
|
445
|
+
throw new Error('rotate: key must be a CryptoKey (e.g. from unwrapKeyForMember/an envelope decrypt), not exported bytes')
|
|
446
|
+
}
|
|
447
|
+
|
|
393
448
|
const current = this.getCurrentState()
|
|
394
449
|
const members = newMembers || (current ? current.members : [this.#localPodId])
|
|
395
450
|
|
|
396
|
-
const nextEpoch = this.#currentEpoch + 1
|
|
397
|
-
const
|
|
451
|
+
const nextEpoch = hasEpoch ? epoch : this.#currentEpoch + 1
|
|
452
|
+
const nextKey = hasKey ? key : await this.#generateKey()
|
|
398
453
|
const state = new GroupState({
|
|
399
454
|
epoch: nextEpoch,
|
|
400
|
-
key,
|
|
455
|
+
key: nextKey,
|
|
401
456
|
members,
|
|
402
457
|
})
|
|
403
458
|
|
package/src/handshake.mjs
CHANGED
|
@@ -750,6 +750,29 @@ export class HandshakeCoordinator {
|
|
|
750
750
|
/** @type {Map<string, Set<Function>>} */
|
|
751
751
|
#listeners = new Map()
|
|
752
752
|
|
|
753
|
+
/**
|
|
754
|
+
* Tracks, per remote pod, the Promise for this coordinator's one and only
|
|
755
|
+
* negotiation with that peer -- whichever of connectToPeer()'s own offer
|
|
756
|
+
* or acceptConnection()'s handling of an incoming offer actually runs.
|
|
757
|
+
* Both methods consult and populate this map so that "glare" -- two pods
|
|
758
|
+
* each calling connectToPeer() on the other at close to the same time --
|
|
759
|
+
* always settles on exactly one negotiation instead of each side racing
|
|
760
|
+
* its own offerer AND answerer RTCPeerConnection for the same remote pod
|
|
761
|
+
* (four connections total for one pair instead of one each). See #202.
|
|
762
|
+
* @type {Map<string, Promise<{transport: object, sessionInfo: object}>>}
|
|
763
|
+
*/
|
|
764
|
+
#peerConnections = new Map()
|
|
765
|
+
|
|
766
|
+
/**
|
|
767
|
+
* Deferred resolvers for connectToPeer() calls that lost the glare
|
|
768
|
+
* tie-break (see #isDesignatedOfferer) and are waiting for
|
|
769
|
+
* acceptConnection() to finish handling the designated offerer's
|
|
770
|
+
* incoming offer for the same remotePodId, instead of sending a second,
|
|
771
|
+
* competing offer of their own.
|
|
772
|
+
* @type {Map<string, Array<{ resolve: Function, reject: Function }>>}
|
|
773
|
+
*/
|
|
774
|
+
#glareWaiters = new Map()
|
|
775
|
+
|
|
753
776
|
/**
|
|
754
777
|
* @param {object} opts
|
|
755
778
|
* @param {string} opts.localPodId - Local pod identifier
|
|
@@ -796,46 +819,76 @@ export class HandshakeCoordinator {
|
|
|
796
819
|
}
|
|
797
820
|
|
|
798
821
|
const timeout = opts.timeout || DEFAULT_TIMEOUT_MS
|
|
822
|
+
|
|
823
|
+
// Glare handling (#202): reuse whatever negotiation with this
|
|
824
|
+
// remotePodId is already in flight or established, rather than
|
|
825
|
+
// starting a second, competing one.
|
|
826
|
+
const existing = this.#peerConnections.get(remotePodId)
|
|
827
|
+
if (existing) {
|
|
828
|
+
this.#onLog(2, `Reusing existing connection/negotiation with ${remotePodId}`)
|
|
829
|
+
return existing
|
|
830
|
+
}
|
|
831
|
+
|
|
832
|
+
if (!this.#isDesignatedOfferer(remotePodId)) {
|
|
833
|
+
// Both sides discover each other independently and both call
|
|
834
|
+
// connectToPeer() on each other at close to the same time -- classic
|
|
835
|
+
// WebRTC "glare". Resolve it with a deterministic tie-breaker both
|
|
836
|
+
// sides can compute alone, with no further coordination: the pod
|
|
837
|
+
// whose ID sorts lower is always the designated offerer. We are not
|
|
838
|
+
// it, so don't race our own offer -- wait for remotePodId's offer to
|
|
839
|
+
// arrive over signaling and be handled by acceptConnection(), and
|
|
840
|
+
// adopt that session instead.
|
|
841
|
+
this.#onLog(2, `Deferring to ${remotePodId} as designated offerer (glare tie-break)`)
|
|
842
|
+
return this.#waitForPeerConnection(remotePodId, timeout)
|
|
843
|
+
}
|
|
844
|
+
|
|
799
845
|
this.#onLog(2, `Initiating connection to ${remotePodId}`)
|
|
800
846
|
|
|
801
847
|
const endpointOpts = opts.endpoints || {
|
|
802
848
|
webrtc: { config: { iceServers: opts.iceServers || [] } },
|
|
803
849
|
}
|
|
804
850
|
|
|
805
|
-
|
|
806
|
-
|
|
807
|
-
|
|
808
|
-
this.#
|
|
851
|
+
const promise = (async () => {
|
|
852
|
+
let timeoutHandle
|
|
853
|
+
const transport = await Promise.race([
|
|
854
|
+
this.#transportFactory.negotiate(
|
|
855
|
+
this.#localPodId,
|
|
856
|
+
remotePodId,
|
|
857
|
+
this.#signalingClient,
|
|
858
|
+
endpointOpts,
|
|
859
|
+
),
|
|
860
|
+
new Promise((_, reject) => {
|
|
861
|
+
timeoutHandle = setTimeout(() => reject(new Error('Connection timeout')), timeout)
|
|
862
|
+
}),
|
|
863
|
+
])
|
|
864
|
+
clearTimeout(timeoutHandle)
|
|
865
|
+
|
|
866
|
+
// TransportFactory.negotiate() returns a transport that has been
|
|
867
|
+
// created but not yet connected (see its docstring) -- no offer,
|
|
868
|
+
// answer or ICE candidate has crossed the wire yet. Mirror
|
|
869
|
+
// acceptConnection()'s `await transport.handleOffer(offer)` on the
|
|
870
|
+
// answerer side by actually driving the handshake here before this
|
|
871
|
+
// session is adopted as 'connected'.
|
|
872
|
+
if (typeof transport.connect === 'function') {
|
|
873
|
+
await transport.connect()
|
|
874
|
+
}
|
|
875
|
+
|
|
876
|
+
const sessionInfo = {
|
|
877
|
+
localPodId: this.#localPodId,
|
|
809
878
|
remotePodId,
|
|
810
|
-
|
|
811
|
-
|
|
812
|
-
|
|
813
|
-
new Promise((_, reject) => {
|
|
814
|
-
timeoutHandle = setTimeout(() => reject(new Error('Connection timeout')), timeout)
|
|
815
|
-
}),
|
|
816
|
-
])
|
|
817
|
-
clearTimeout(timeoutHandle)
|
|
818
|
-
|
|
819
|
-
// TransportFactory.negotiate() returns a transport that has been
|
|
820
|
-
// created but not yet connected (see its docstring) -- no offer,
|
|
821
|
-
// answer or ICE candidate has crossed the wire yet. Mirror
|
|
822
|
-
// acceptConnection()'s `await transport.handleOffer(offer)` on the
|
|
823
|
-
// answerer side by actually driving the handshake here before this
|
|
824
|
-
// session is adopted as 'connected'.
|
|
825
|
-
if (typeof transport.connect === 'function') {
|
|
826
|
-
await transport.connect()
|
|
827
|
-
}
|
|
879
|
+
transportType: transport.type,
|
|
880
|
+
establishedAt: Date.now(),
|
|
881
|
+
}
|
|
828
882
|
|
|
829
|
-
|
|
830
|
-
|
|
831
|
-
remotePodId,
|
|
832
|
-
|
|
833
|
-
|
|
834
|
-
}
|
|
883
|
+
this.#onLog(2, `Connected to ${remotePodId} via ${transport.type}`)
|
|
884
|
+
const result = { transport, sessionInfo }
|
|
885
|
+
this.#forgetPeerConnectionOnClose(remotePodId, transport)
|
|
886
|
+
this.#fire('connected', { remotePodId, transport, sessionInfo })
|
|
887
|
+
return result
|
|
888
|
+
})()
|
|
835
889
|
|
|
836
|
-
this.#
|
|
837
|
-
|
|
838
|
-
return { transport, sessionInfo }
|
|
890
|
+
this.#settlePeerConnection(remotePodId, promise)
|
|
891
|
+
return promise
|
|
839
892
|
}
|
|
840
893
|
|
|
841
894
|
/**
|
|
@@ -856,28 +909,54 @@ export class HandshakeCoordinator {
|
|
|
856
909
|
throw new Error('SignalingClient is required for acceptConnection')
|
|
857
910
|
}
|
|
858
911
|
|
|
912
|
+
// Glare handling (#202): mirror connectToPeer()'s dedup.
|
|
913
|
+
const existing = this.#peerConnections.get(remotePodId)
|
|
914
|
+
if (existing) {
|
|
915
|
+
if (this.#isDesignatedOfferer(remotePodId)) {
|
|
916
|
+
// We are the designated offerer for this pair and already have our
|
|
917
|
+
// own negotiation with remotePodId in flight or established. This
|
|
918
|
+
// incoming offer is a late/duplicate glare offer from the side
|
|
919
|
+
// that should have deferred to ours -- ignore it instead of
|
|
920
|
+
// starting a second, competing negotiation.
|
|
921
|
+
this.#onLog(1, `Ignoring incoming offer from ${remotePodId}: already the designated offerer (glare tie-break)`)
|
|
922
|
+
return existing
|
|
923
|
+
}
|
|
924
|
+
// Not the designated offerer, and already negotiating/negotiated
|
|
925
|
+
// with remotePodId (a duplicate/retried offer for the same pair,
|
|
926
|
+
// or this accept is already underway) -- reuse it.
|
|
927
|
+
this.#onLog(2, `Reusing existing negotiation with ${remotePodId}`)
|
|
928
|
+
return existing
|
|
929
|
+
}
|
|
930
|
+
|
|
859
931
|
this.#onLog(2, `Accepting connection from ${remotePodId}`)
|
|
860
932
|
|
|
861
|
-
const
|
|
862
|
-
|
|
863
|
-
|
|
864
|
-
|
|
865
|
-
|
|
933
|
+
const promise = (async () => {
|
|
934
|
+
const transport = await this.#transportFactory.create('webrtc', {
|
|
935
|
+
localPodId: this.#localPodId,
|
|
936
|
+
remotePodId,
|
|
937
|
+
signaler: this.#signalingClient,
|
|
938
|
+
})
|
|
866
939
|
|
|
867
|
-
|
|
868
|
-
|
|
869
|
-
|
|
940
|
+
if (typeof transport.handleOffer === 'function') {
|
|
941
|
+
await transport.handleOffer(offer)
|
|
942
|
+
}
|
|
870
943
|
|
|
871
|
-
|
|
872
|
-
|
|
873
|
-
|
|
874
|
-
|
|
875
|
-
|
|
876
|
-
|
|
944
|
+
const sessionInfo = {
|
|
945
|
+
localPodId: this.#localPodId,
|
|
946
|
+
remotePodId,
|
|
947
|
+
transportType: transport.type,
|
|
948
|
+
establishedAt: Date.now(),
|
|
949
|
+
}
|
|
877
950
|
|
|
878
|
-
|
|
879
|
-
|
|
880
|
-
|
|
951
|
+
this.#onLog(2, `Accepted connection from ${remotePodId}`)
|
|
952
|
+
const result = { transport, sessionInfo }
|
|
953
|
+
this.#forgetPeerConnectionOnClose(remotePodId, transport)
|
|
954
|
+
this.#fire('connected', { remotePodId, transport, sessionInfo })
|
|
955
|
+
return result
|
|
956
|
+
})()
|
|
957
|
+
|
|
958
|
+
this.#settlePeerConnection(remotePodId, promise)
|
|
959
|
+
return promise
|
|
881
960
|
}
|
|
882
961
|
|
|
883
962
|
/**
|
|
@@ -1020,6 +1099,108 @@ export class HandshakeCoordinator {
|
|
|
1020
1099
|
|
|
1021
1100
|
// -- Internal -------------------------------------------------------------
|
|
1022
1101
|
|
|
1102
|
+
/**
|
|
1103
|
+
* Deterministic glare tie-break (#202): exactly one side of any pod pair
|
|
1104
|
+
* is the designated offerer, decided purely from both pods' own IDs so
|
|
1105
|
+
* both sides agree without any further coordination -- neither needs to
|
|
1106
|
+
* know what the other is doing, only its ID. The lower podId is always
|
|
1107
|
+
* the designated offerer; the higher podId always defers to the
|
|
1108
|
+
* incoming offer instead of sending its own.
|
|
1109
|
+
* @param {string} remotePodId
|
|
1110
|
+
* @returns {boolean} true when the local pod is the designated offerer.
|
|
1111
|
+
*/
|
|
1112
|
+
#isDesignatedOfferer(remotePodId) {
|
|
1113
|
+
return this.#localPodId < remotePodId
|
|
1114
|
+
}
|
|
1115
|
+
|
|
1116
|
+
/**
|
|
1117
|
+
* Wait for acceptConnection() to settle a negotiation for remotePodId
|
|
1118
|
+
* that this coordinator lost the glare tie-break for, instead of racing
|
|
1119
|
+
* a second offer of its own. Resolves/rejects exactly like the
|
|
1120
|
+
* negotiation itself; rejects on timeout, matching connectToPeer()'s own
|
|
1121
|
+
* "Connection timeout" behavior for the offerer path.
|
|
1122
|
+
* @param {string} remotePodId
|
|
1123
|
+
* @param {number} timeoutMs
|
|
1124
|
+
* @returns {Promise<{transport: object, sessionInfo: object}>}
|
|
1125
|
+
*/
|
|
1126
|
+
#waitForPeerConnection(remotePodId, timeoutMs) {
|
|
1127
|
+
// Re-check: acceptConnection() may have already settled this between
|
|
1128
|
+
// connectToPeer()'s own check and this call.
|
|
1129
|
+
const existing = this.#peerConnections.get(remotePodId)
|
|
1130
|
+
if (existing) return existing
|
|
1131
|
+
|
|
1132
|
+
return new Promise((resolve, reject) => {
|
|
1133
|
+
const entry = {}
|
|
1134
|
+
const timeoutHandle = setTimeout(() => {
|
|
1135
|
+
const list = this.#glareWaiters.get(remotePodId)
|
|
1136
|
+
if (list) {
|
|
1137
|
+
const idx = list.indexOf(entry)
|
|
1138
|
+
if (idx !== -1) list.splice(idx, 1)
|
|
1139
|
+
if (list.length === 0) this.#glareWaiters.delete(remotePodId)
|
|
1140
|
+
}
|
|
1141
|
+
reject(new Error(`Timed out waiting for ${remotePodId}'s offer (lost glare tie-break)`))
|
|
1142
|
+
}, timeoutMs)
|
|
1143
|
+
entry.resolve = (value) => { clearTimeout(timeoutHandle); resolve(value) }
|
|
1144
|
+
entry.reject = (err) => { clearTimeout(timeoutHandle); reject(err) }
|
|
1145
|
+
|
|
1146
|
+
if (!this.#glareWaiters.has(remotePodId)) this.#glareWaiters.set(remotePodId, [])
|
|
1147
|
+
this.#glareWaiters.get(remotePodId).push(entry)
|
|
1148
|
+
})
|
|
1149
|
+
}
|
|
1150
|
+
|
|
1151
|
+
/**
|
|
1152
|
+
* Record `promise` as this coordinator's one negotiation with
|
|
1153
|
+
* remotePodId, and wake any connectToPeer() calls that deferred to it
|
|
1154
|
+
* (see #waitForPeerConnection) once it settles. On rejection, forgets
|
|
1155
|
+
* the entry so a later, genuine reconnection attempt isn't permanently
|
|
1156
|
+
* blocked by a failed one.
|
|
1157
|
+
* @param {string} remotePodId
|
|
1158
|
+
* @param {Promise<{transport: object, sessionInfo: object}>} promise
|
|
1159
|
+
*/
|
|
1160
|
+
#settlePeerConnection(remotePodId, promise) {
|
|
1161
|
+
this.#peerConnections.set(remotePodId, promise)
|
|
1162
|
+
promise.then(
|
|
1163
|
+
(value) => {
|
|
1164
|
+
const waiters = this.#glareWaiters.get(remotePodId)
|
|
1165
|
+
if (!waiters) return
|
|
1166
|
+
this.#glareWaiters.delete(remotePodId)
|
|
1167
|
+
for (const w of waiters) w.resolve(value)
|
|
1168
|
+
},
|
|
1169
|
+
(err) => {
|
|
1170
|
+
if (this.#peerConnections.get(remotePodId) === promise) {
|
|
1171
|
+
this.#peerConnections.delete(remotePodId)
|
|
1172
|
+
}
|
|
1173
|
+
const waiters = this.#glareWaiters.get(remotePodId)
|
|
1174
|
+
if (!waiters) return
|
|
1175
|
+
this.#glareWaiters.delete(remotePodId)
|
|
1176
|
+
for (const w of waiters) w.reject(err)
|
|
1177
|
+
},
|
|
1178
|
+
)
|
|
1179
|
+
}
|
|
1180
|
+
|
|
1181
|
+
/**
|
|
1182
|
+
* Once an established session's transport actually closes, forget it so
|
|
1183
|
+
* a genuine future reconnection to remotePodId isn't permanently blocked
|
|
1184
|
+
* by #peerConnections/#isDesignatedOfferer dedup (#202). No-op when the
|
|
1185
|
+
* transport exposes no onClose (mirrors connectViaToken()'s own handling
|
|
1186
|
+
* of that case).
|
|
1187
|
+
* @param {string} remotePodId
|
|
1188
|
+
* @param {object} transport
|
|
1189
|
+
*/
|
|
1190
|
+
#forgetPeerConnectionOnClose(remotePodId, transport) {
|
|
1191
|
+
if (typeof transport.onClose !== 'function') return
|
|
1192
|
+
transport.onClose(() => {
|
|
1193
|
+
// Only delete if this transport's own entry is still the current
|
|
1194
|
+
// one -- a newer negotiation for the same remotePodId may already
|
|
1195
|
+
// have replaced it by the time this fires.
|
|
1196
|
+
const current = this.#peerConnections.get(remotePodId)
|
|
1197
|
+
if (!current) return
|
|
1198
|
+
current.then((v) => {
|
|
1199
|
+
if (v && v.transport === transport) this.#peerConnections.delete(remotePodId)
|
|
1200
|
+
}, () => {})
|
|
1201
|
+
})
|
|
1202
|
+
}
|
|
1203
|
+
|
|
1023
1204
|
/**
|
|
1024
1205
|
* Fire all listeners for a given event, swallowing listener errors.
|
|
1025
1206
|
* @param {string} event
|