@statewalker/webrun-streams-signaling 0.1.1
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/LICENSE +21 -0
- package/README.md +113 -0
- package/dist/byte-channel.d.ts +23 -0
- package/dist/byte-channel.d.ts.map +1 -0
- package/dist/byte-queue.d.ts +15 -0
- package/dist/byte-queue.d.ts.map +1 -0
- package/dist/index.d.ts +22 -0
- package/dist/index.d.ts.map +1 -0
- package/dist/index.js +708 -0
- package/dist/peer-connection.d.ts +72 -0
- package/dist/peer-connection.d.ts.map +1 -0
- package/dist/peer-manager.d.ts +30 -0
- package/dist/peer-manager.d.ts.map +1 -0
- package/dist/qr-signaling.d.ts +60 -0
- package/dist/qr-signaling.d.ts.map +1 -0
- package/dist/room-manager.d.ts +32 -0
- package/dist/room-manager.d.ts.map +1 -0
- package/dist/types.d.ts +159 -0
- package/dist/types.d.ts.map +1 -0
- package/package.json +53 -0
- package/src/byte-channel.ts +99 -0
- package/src/byte-queue.ts +68 -0
- package/src/index.ts +30 -0
- package/src/peer-connection.ts +355 -0
- package/src/peer-manager.ts +74 -0
- package/src/qr-signaling.ts +227 -0
- package/src/room-manager.ts +114 -0
- package/src/types.ts +177 -0
|
@@ -0,0 +1,355 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* WebRTC peer connection lifecycle (single connection).
|
|
3
|
+
*
|
|
4
|
+
* Relocated from `@statewalker/vcs-port-webrtc`'s `PeerManager` and neutralised
|
|
5
|
+
* (no Git/VCS coupling). Handles signaling, ICE candidate gathering and data
|
|
6
|
+
* channel creation for one peer, in either "initiator" (creates offer) or
|
|
7
|
+
* "responder" (creates answer) role.
|
|
8
|
+
*
|
|
9
|
+
* Adaptations vs. the original:
|
|
10
|
+
* - `new RTCPeerConnection(...)` is behind an injectable {@link RtcPeerConnectionFactory}
|
|
11
|
+
* so tests run without a real WebRTC stack.
|
|
12
|
+
* - remote ICE candidates are added as plain `RTCIceCandidateInit` (accepted by
|
|
13
|
+
* `addIceCandidate`) instead of constructing a global `RTCIceCandidate`,
|
|
14
|
+
* which does not exist outside a browser.
|
|
15
|
+
* - `open()` yields a webrun-streams {@link ByteChannel} rather than a `MessagePort`.
|
|
16
|
+
*/
|
|
17
|
+
|
|
18
|
+
import type { ByteChannel } from "@statewalker/webrun-streams";
|
|
19
|
+
import { byteChannelFromDataChannel } from "./byte-channel.js";
|
|
20
|
+
import type {
|
|
21
|
+
ConnectionState,
|
|
22
|
+
IceCandidate,
|
|
23
|
+
PeerConnectionEvents,
|
|
24
|
+
PeerRole,
|
|
25
|
+
SessionDescription,
|
|
26
|
+
SignalingMessage,
|
|
27
|
+
WebRtcConnectionOptions,
|
|
28
|
+
} from "./types.js";
|
|
29
|
+
import { DEFAULT_ICE_SERVERS } from "./types.js";
|
|
30
|
+
|
|
31
|
+
const DEFAULT_CONNECTION_TIMEOUT = 30000;
|
|
32
|
+
const DEFAULT_ICE_GATHERING_TIMEOUT = 5000;
|
|
33
|
+
const DEFAULT_CHANNEL_LABEL = "webrun-data";
|
|
34
|
+
|
|
35
|
+
type EventListener<K extends keyof PeerConnectionEvents> = PeerConnectionEvents[K];
|
|
36
|
+
|
|
37
|
+
/**
|
|
38
|
+
* Manages a single WebRTC peer connection lifecycle.
|
|
39
|
+
*/
|
|
40
|
+
export class PeerConnection {
|
|
41
|
+
private readonly role: PeerRole;
|
|
42
|
+
private readonly options: WebRtcConnectionOptions;
|
|
43
|
+
private pc: RTCPeerConnection | null = null;
|
|
44
|
+
private dataChannel: RTCDataChannel | null = null;
|
|
45
|
+
private state: ConnectionState = "new";
|
|
46
|
+
|
|
47
|
+
private readonly listeners: Map<
|
|
48
|
+
keyof PeerConnectionEvents,
|
|
49
|
+
Set<EventListener<keyof PeerConnectionEvents>>
|
|
50
|
+
> = new Map();
|
|
51
|
+
|
|
52
|
+
private pendingCandidates: RTCIceCandidateInit[] = [];
|
|
53
|
+
private remoteDescriptionSet = false;
|
|
54
|
+
|
|
55
|
+
private collectedCandidates: IceCandidate[] = [];
|
|
56
|
+
private iceGatheringComplete = false;
|
|
57
|
+
|
|
58
|
+
constructor(role: PeerRole, options: WebRtcConnectionOptions = {}) {
|
|
59
|
+
this.role = role;
|
|
60
|
+
this.options = options;
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
getState(): ConnectionState {
|
|
64
|
+
return this.state;
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
getRole(): PeerRole {
|
|
68
|
+
return this.role;
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
getDataChannel(): RTCDataChannel | null {
|
|
72
|
+
return this.dataChannel;
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
on<K extends keyof PeerConnectionEvents>(event: K, listener: PeerConnectionEvents[K]): this {
|
|
76
|
+
let listeners = this.listeners.get(event);
|
|
77
|
+
if (!listeners) {
|
|
78
|
+
listeners = new Set();
|
|
79
|
+
this.listeners.set(event, listeners);
|
|
80
|
+
}
|
|
81
|
+
listeners.add(listener as EventListener<keyof PeerConnectionEvents>);
|
|
82
|
+
return this;
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
off<K extends keyof PeerConnectionEvents>(event: K, listener: PeerConnectionEvents[K]): this {
|
|
86
|
+
this.listeners.get(event)?.delete(listener as EventListener<keyof PeerConnectionEvents>);
|
|
87
|
+
return this;
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
private emit<K extends keyof PeerConnectionEvents>(
|
|
91
|
+
event: K,
|
|
92
|
+
...args: Parameters<PeerConnectionEvents[K]>
|
|
93
|
+
): void {
|
|
94
|
+
const listeners = this.listeners.get(event);
|
|
95
|
+
if (listeners) {
|
|
96
|
+
for (const listener of listeners) {
|
|
97
|
+
(listener as (...args: Parameters<PeerConnectionEvents[K]>) => void)(...args);
|
|
98
|
+
}
|
|
99
|
+
}
|
|
100
|
+
}
|
|
101
|
+
|
|
102
|
+
private createRtc(config: RTCConfiguration): RTCPeerConnection {
|
|
103
|
+
const factory = this.options.rtc ?? ((c: RTCConfiguration) => new RTCPeerConnection(c));
|
|
104
|
+
return factory(config);
|
|
105
|
+
}
|
|
106
|
+
|
|
107
|
+
private initConnection(): RTCPeerConnection {
|
|
108
|
+
if (this.pc) return this.pc;
|
|
109
|
+
|
|
110
|
+
this.setState("connecting");
|
|
111
|
+
const iceServers = this.options.iceServers ?? DEFAULT_ICE_SERVERS;
|
|
112
|
+
this.pc = this.createRtc({ iceServers });
|
|
113
|
+
|
|
114
|
+
this.pc.onicecandidate = (event) => {
|
|
115
|
+
if (event.candidate) {
|
|
116
|
+
this.collectedCandidates.push({
|
|
117
|
+
candidate: event.candidate.candidate,
|
|
118
|
+
sdpMid: event.candidate.sdpMid,
|
|
119
|
+
sdpMLineIndex: event.candidate.sdpMLineIndex,
|
|
120
|
+
});
|
|
121
|
+
this.emit("signal", {
|
|
122
|
+
type: "candidate",
|
|
123
|
+
candidate: {
|
|
124
|
+
candidate: event.candidate.candidate,
|
|
125
|
+
sdpMid: event.candidate.sdpMid,
|
|
126
|
+
sdpMLineIndex: event.candidate.sdpMLineIndex,
|
|
127
|
+
},
|
|
128
|
+
});
|
|
129
|
+
}
|
|
130
|
+
};
|
|
131
|
+
|
|
132
|
+
this.pc.onicegatheringstatechange = () => {
|
|
133
|
+
if (this.pc?.iceGatheringState === "complete") {
|
|
134
|
+
this.iceGatheringComplete = true;
|
|
135
|
+
this.emit("signal", { type: "ready" });
|
|
136
|
+
}
|
|
137
|
+
};
|
|
138
|
+
|
|
139
|
+
this.pc.onconnectionstatechange = () => {
|
|
140
|
+
switch (this.pc?.connectionState) {
|
|
141
|
+
case "connected":
|
|
142
|
+
this.setState("connected");
|
|
143
|
+
break;
|
|
144
|
+
case "disconnected":
|
|
145
|
+
this.setState("disconnected");
|
|
146
|
+
break;
|
|
147
|
+
case "failed":
|
|
148
|
+
this.setState("failed");
|
|
149
|
+
this.emit("error", new Error("Connection failed"));
|
|
150
|
+
break;
|
|
151
|
+
case "closed":
|
|
152
|
+
this.setState("closed");
|
|
153
|
+
break;
|
|
154
|
+
}
|
|
155
|
+
};
|
|
156
|
+
|
|
157
|
+
this.pc.ondatachannel = (event) => {
|
|
158
|
+
this.dataChannel = event.channel;
|
|
159
|
+
this.setupDataChannel();
|
|
160
|
+
};
|
|
161
|
+
|
|
162
|
+
return this.pc;
|
|
163
|
+
}
|
|
164
|
+
|
|
165
|
+
private setupDataChannel(): void {
|
|
166
|
+
if (!this.dataChannel) return;
|
|
167
|
+
this.dataChannel.binaryType = "arraybuffer";
|
|
168
|
+
this.dataChannel.onopen = () => this.emit("open");
|
|
169
|
+
this.dataChannel.onclose = () => this.emit("close");
|
|
170
|
+
this.dataChannel.onerror = (event) => {
|
|
171
|
+
const errorEvent = event as RTCErrorEvent;
|
|
172
|
+
this.emit("error", errorEvent.error ?? new Error("DataChannel error"));
|
|
173
|
+
};
|
|
174
|
+
}
|
|
175
|
+
|
|
176
|
+
private setState(newState: ConnectionState): void {
|
|
177
|
+
if (this.state !== newState) {
|
|
178
|
+
this.state = newState;
|
|
179
|
+
this.emit("stateChange", newState);
|
|
180
|
+
}
|
|
181
|
+
}
|
|
182
|
+
|
|
183
|
+
/**
|
|
184
|
+
* Start connection as initiator: create the data channel and offer, emit the
|
|
185
|
+
* offer via the `signal` event.
|
|
186
|
+
*/
|
|
187
|
+
async connect(): Promise<void> {
|
|
188
|
+
if (this.role !== "initiator") {
|
|
189
|
+
throw new Error("connect() should only be called by initiator");
|
|
190
|
+
}
|
|
191
|
+
const pc = this.initConnection();
|
|
192
|
+
|
|
193
|
+
const label = this.options.channelLabel ?? DEFAULT_CHANNEL_LABEL;
|
|
194
|
+
this.dataChannel = pc.createDataChannel(label, {
|
|
195
|
+
ordered: this.options.ordered ?? true,
|
|
196
|
+
maxRetransmits: this.options.maxRetransmits,
|
|
197
|
+
});
|
|
198
|
+
this.setupDataChannel();
|
|
199
|
+
|
|
200
|
+
const offer = await pc.createOffer();
|
|
201
|
+
await pc.setLocalDescription(offer);
|
|
202
|
+
if (offer.sdp) {
|
|
203
|
+
this.emit("signal", { type: "offer", sdp: offer.sdp });
|
|
204
|
+
}
|
|
205
|
+
}
|
|
206
|
+
|
|
207
|
+
/** Handle a signaling message from the remote peer. */
|
|
208
|
+
async handleSignal(message: SignalingMessage): Promise<void> {
|
|
209
|
+
const pc = this.initConnection();
|
|
210
|
+
switch (message.type) {
|
|
211
|
+
case "offer":
|
|
212
|
+
await this.handleOffer(pc, message.sdp);
|
|
213
|
+
break;
|
|
214
|
+
case "answer":
|
|
215
|
+
await this.handleAnswer(pc, message.sdp);
|
|
216
|
+
break;
|
|
217
|
+
case "candidate":
|
|
218
|
+
await this.handleCandidate(pc, message.candidate);
|
|
219
|
+
break;
|
|
220
|
+
case "ready":
|
|
221
|
+
break;
|
|
222
|
+
}
|
|
223
|
+
}
|
|
224
|
+
|
|
225
|
+
private async handleOffer(pc: RTCPeerConnection, sdp: string): Promise<void> {
|
|
226
|
+
if (this.role !== "responder") {
|
|
227
|
+
throw new Error("Received offer but not in responder role");
|
|
228
|
+
}
|
|
229
|
+
await pc.setRemoteDescription({ type: "offer", sdp });
|
|
230
|
+
this.remoteDescriptionSet = true;
|
|
231
|
+
await this.processPendingCandidates(pc);
|
|
232
|
+
|
|
233
|
+
const answer = await pc.createAnswer();
|
|
234
|
+
await pc.setLocalDescription(answer);
|
|
235
|
+
if (answer.sdp) {
|
|
236
|
+
this.emit("signal", { type: "answer", sdp: answer.sdp });
|
|
237
|
+
}
|
|
238
|
+
}
|
|
239
|
+
|
|
240
|
+
private async handleAnswer(pc: RTCPeerConnection, sdp: string): Promise<void> {
|
|
241
|
+
if (this.role !== "initiator") {
|
|
242
|
+
throw new Error("Received answer but not in initiator role");
|
|
243
|
+
}
|
|
244
|
+
await pc.setRemoteDescription({ type: "answer", sdp });
|
|
245
|
+
this.remoteDescriptionSet = true;
|
|
246
|
+
await this.processPendingCandidates(pc);
|
|
247
|
+
}
|
|
248
|
+
|
|
249
|
+
private async handleCandidate(pc: RTCPeerConnection, candidate: IceCandidate): Promise<void> {
|
|
250
|
+
const init: RTCIceCandidateInit = {
|
|
251
|
+
candidate: candidate.candidate,
|
|
252
|
+
sdpMid: candidate.sdpMid,
|
|
253
|
+
sdpMLineIndex: candidate.sdpMLineIndex,
|
|
254
|
+
};
|
|
255
|
+
if (this.remoteDescriptionSet) {
|
|
256
|
+
await pc.addIceCandidate(init);
|
|
257
|
+
} else {
|
|
258
|
+
this.pendingCandidates.push(init);
|
|
259
|
+
}
|
|
260
|
+
}
|
|
261
|
+
|
|
262
|
+
private async processPendingCandidates(pc: RTCPeerConnection): Promise<void> {
|
|
263
|
+
for (const candidate of this.pendingCandidates) {
|
|
264
|
+
await pc.addIceCandidate(candidate);
|
|
265
|
+
}
|
|
266
|
+
this.pendingCandidates = [];
|
|
267
|
+
}
|
|
268
|
+
|
|
269
|
+
/**
|
|
270
|
+
* Wait for ICE gathering to complete (batch/QR signaling). Resolves early on
|
|
271
|
+
* timeout, using whatever candidates were collected.
|
|
272
|
+
*/
|
|
273
|
+
async waitForIceGathering(): Promise<void> {
|
|
274
|
+
if (this.iceGatheringComplete) return;
|
|
275
|
+
const timeout = this.options.iceGatheringTimeout ?? DEFAULT_ICE_GATHERING_TIMEOUT;
|
|
276
|
+
|
|
277
|
+
return new Promise((resolve) => {
|
|
278
|
+
const interval = setInterval(() => {
|
|
279
|
+
if (this.iceGatheringComplete) {
|
|
280
|
+
clearInterval(interval);
|
|
281
|
+
clearTimeout(timer);
|
|
282
|
+
resolve();
|
|
283
|
+
}
|
|
284
|
+
}, 20);
|
|
285
|
+
const timer = setTimeout(() => {
|
|
286
|
+
clearInterval(interval);
|
|
287
|
+
resolve();
|
|
288
|
+
}, timeout);
|
|
289
|
+
});
|
|
290
|
+
}
|
|
291
|
+
|
|
292
|
+
/** Local session description after negotiation. */
|
|
293
|
+
getLocalDescription(): SessionDescription | null {
|
|
294
|
+
if (!this.pc?.localDescription) return null;
|
|
295
|
+
return {
|
|
296
|
+
type: this.pc.localDescription.type as "offer" | "answer",
|
|
297
|
+
sdp: this.pc.localDescription.sdp,
|
|
298
|
+
};
|
|
299
|
+
}
|
|
300
|
+
|
|
301
|
+
/** Collected ICE candidates (batch/QR signaling). */
|
|
302
|
+
getCollectedCandidates(): IceCandidate[] {
|
|
303
|
+
return [...this.collectedCandidates];
|
|
304
|
+
}
|
|
305
|
+
|
|
306
|
+
/**
|
|
307
|
+
* Resolve with a {@link ByteChannel} once the data channel opens. Rejects on
|
|
308
|
+
* error or after {@link WebRtcConnectionOptions.connectionTimeout}.
|
|
309
|
+
*/
|
|
310
|
+
open(): Promise<ByteChannel> {
|
|
311
|
+
const timeout = this.options.connectionTimeout ?? DEFAULT_CONNECTION_TIMEOUT;
|
|
312
|
+
return new Promise<ByteChannel>((resolve, reject) => {
|
|
313
|
+
const existing = this.dataChannel;
|
|
314
|
+
if (existing && existing.readyState === "open") {
|
|
315
|
+
resolve(byteChannelFromDataChannel(existing));
|
|
316
|
+
return;
|
|
317
|
+
}
|
|
318
|
+
const cleanup = () => {
|
|
319
|
+
this.off("open", onOpen);
|
|
320
|
+
this.off("error", onError);
|
|
321
|
+
clearTimeout(timer);
|
|
322
|
+
};
|
|
323
|
+
const onOpen = () => {
|
|
324
|
+
cleanup();
|
|
325
|
+
const ch = this.dataChannel;
|
|
326
|
+
if (ch) resolve(byteChannelFromDataChannel(ch));
|
|
327
|
+
else reject(new Error("No data channel after open"));
|
|
328
|
+
};
|
|
329
|
+
const onError = (error: Error) => {
|
|
330
|
+
cleanup();
|
|
331
|
+
reject(error);
|
|
332
|
+
};
|
|
333
|
+
this.on("open", onOpen);
|
|
334
|
+
this.on("error", onError);
|
|
335
|
+
const timer = setTimeout(() => {
|
|
336
|
+
cleanup();
|
|
337
|
+
reject(new Error(`Connection timeout after ${timeout}ms`));
|
|
338
|
+
}, timeout);
|
|
339
|
+
});
|
|
340
|
+
}
|
|
341
|
+
|
|
342
|
+
/** Close the connection and release resources. */
|
|
343
|
+
close(): void {
|
|
344
|
+
if (this.dataChannel) {
|
|
345
|
+
this.dataChannel.close();
|
|
346
|
+
this.dataChannel = null;
|
|
347
|
+
}
|
|
348
|
+
if (this.pc) {
|
|
349
|
+
this.pc.close();
|
|
350
|
+
this.pc = null;
|
|
351
|
+
}
|
|
352
|
+
this.setState("closed");
|
|
353
|
+
this.listeners.clear();
|
|
354
|
+
}
|
|
355
|
+
}
|
|
@@ -0,0 +1,74 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Peer discovery + connection manager over a {@link SignalingTransport}.
|
|
3
|
+
*
|
|
4
|
+
* Wraps the low-level {@link PeerConnection} (relocated from
|
|
5
|
+
* `@statewalker/vcs-port-webrtc`) with a multi-peer, id-keyed surface: dial a
|
|
6
|
+
* peer with `connect(peerId)` or accept inbound dials via `onConnection`. Each
|
|
7
|
+
* established connection yields a webrun-streams {@link ByteChannel}. The WebRTC
|
|
8
|
+
* offer/answer/ICE routing is the original logic; only the routing-by-peer-id
|
|
9
|
+
* and the ByteChannel result are new.
|
|
10
|
+
*/
|
|
11
|
+
|
|
12
|
+
import type { ByteChannel } from "@statewalker/webrun-streams";
|
|
13
|
+
import { PeerConnection } from "./peer-connection.js";
|
|
14
|
+
import type { SignalingMessage, SignalingTransport, WebRtcConnectionOptions } from "./types.js";
|
|
15
|
+
|
|
16
|
+
export type PeerManagerOptions = WebRtcConnectionOptions;
|
|
17
|
+
|
|
18
|
+
export class PeerManager {
|
|
19
|
+
private readonly signaling: SignalingTransport;
|
|
20
|
+
private readonly options: PeerManagerOptions;
|
|
21
|
+
private readonly connections = new Map<string, PeerConnection>();
|
|
22
|
+
private readonly connectionHandlers = new Set<(peerId: string, ch: ByteChannel) => void>();
|
|
23
|
+
private readonly unsubscribe: () => void;
|
|
24
|
+
|
|
25
|
+
constructor(signaling: SignalingTransport, options: PeerManagerOptions = {}) {
|
|
26
|
+
this.signaling = signaling;
|
|
27
|
+
this.options = options;
|
|
28
|
+
this.unsubscribe = signaling.onMessage((from, msg) => this.onSignal(from, msg));
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
/** Dial `peerId` and resolve with the established channel. */
|
|
32
|
+
async connect(peerId: string): Promise<ByteChannel> {
|
|
33
|
+
const pc = this.makeConnection(peerId, "initiator");
|
|
34
|
+
const channel = pc.open();
|
|
35
|
+
await pc.connect();
|
|
36
|
+
return channel;
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
/** Register a handler for inbound connections. Returns an unsubscribe fn. */
|
|
40
|
+
onConnection(handler: (peerId: string, ch: ByteChannel) => void): () => void {
|
|
41
|
+
this.connectionHandlers.add(handler);
|
|
42
|
+
return () => this.connectionHandlers.delete(handler);
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
/** Tear down all connections and stop listening for signaling. */
|
|
46
|
+
close(): void {
|
|
47
|
+
this.unsubscribe();
|
|
48
|
+
for (const pc of this.connections.values()) pc.close();
|
|
49
|
+
this.connections.clear();
|
|
50
|
+
this.connectionHandlers.clear();
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
private makeConnection(peerId: string, role: "initiator" | "responder"): PeerConnection {
|
|
54
|
+
const pc = new PeerConnection(role, this.options);
|
|
55
|
+
pc.on("signal", (msg) => this.signaling.send(peerId, msg));
|
|
56
|
+
pc.on("close", () => this.connections.delete(peerId));
|
|
57
|
+
this.connections.set(peerId, pc);
|
|
58
|
+
return pc;
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
private onSignal(from: string, msg: SignalingMessage): void {
|
|
62
|
+
let pc = this.connections.get(from);
|
|
63
|
+
if (!pc) {
|
|
64
|
+
// Only an inbound offer starts a new responder connection; stray
|
|
65
|
+
// candidates/answers for an unknown peer are ignored.
|
|
66
|
+
if (msg.type !== "offer") return;
|
|
67
|
+
pc = this.makeConnection(from, "responder");
|
|
68
|
+
void pc.open().then((channel) => {
|
|
69
|
+
for (const handler of this.connectionHandlers) handler(from, channel);
|
|
70
|
+
});
|
|
71
|
+
}
|
|
72
|
+
void pc.handleSignal(msg);
|
|
73
|
+
}
|
|
74
|
+
}
|
|
@@ -0,0 +1,227 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* QR code signaling for serverless WebRTC connection.
|
|
3
|
+
*
|
|
4
|
+
* Relocated from `@statewalker/vcs-port-webrtc`'s `signaling.ts` (neutralised).
|
|
5
|
+
* Compresses WebRTC signaling data (SDP + ICE candidates) into a compact,
|
|
6
|
+
* base64 form suitable for QR codes, enabling out-of-band manual pairing where
|
|
7
|
+
* peers exchange QR strings instead of using a live signaling server.
|
|
8
|
+
*
|
|
9
|
+
* The compress/expand/encode/decode functions are pure and unchanged; the
|
|
10
|
+
* {@link QrSignaling} class is adapted to the target API and yields
|
|
11
|
+
* webrun-streams {@link ByteChannel}s.
|
|
12
|
+
*/
|
|
13
|
+
|
|
14
|
+
import type { ByteChannel } from "@statewalker/webrun-streams";
|
|
15
|
+
import { PeerConnection } from "./peer-connection.js";
|
|
16
|
+
import type {
|
|
17
|
+
CompressedSignal,
|
|
18
|
+
IceCandidate,
|
|
19
|
+
PeerRole,
|
|
20
|
+
SessionDescription,
|
|
21
|
+
WebRtcConnectionOptions,
|
|
22
|
+
} from "./types.js";
|
|
23
|
+
|
|
24
|
+
/** Current protocol version */
|
|
25
|
+
const PROTOCOL_VERSION = 1;
|
|
26
|
+
|
|
27
|
+
/** Generate a short random session ID. */
|
|
28
|
+
export function generateSessionId(): string {
|
|
29
|
+
const bytes = new Uint8Array(6);
|
|
30
|
+
crypto.getRandomValues(bytes);
|
|
31
|
+
return btoa(String.fromCharCode(...bytes))
|
|
32
|
+
.replace(/\+/g, "-")
|
|
33
|
+
.replace(/\//g, "_")
|
|
34
|
+
.replace(/=/g, "");
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
/** Compress SDP by keeping only the essential lines. */
|
|
38
|
+
function compressSdp(sdp: string): string {
|
|
39
|
+
const lines = sdp.split("\r\n");
|
|
40
|
+
const essential: string[] = [];
|
|
41
|
+
for (const line of lines) {
|
|
42
|
+
if (
|
|
43
|
+
line.startsWith("v=") ||
|
|
44
|
+
line.startsWith("o=") ||
|
|
45
|
+
line.startsWith("s=") ||
|
|
46
|
+
line.startsWith("t=") ||
|
|
47
|
+
line.startsWith("a=group:") ||
|
|
48
|
+
line.startsWith("a=ice-ufrag:") ||
|
|
49
|
+
line.startsWith("a=ice-pwd:") ||
|
|
50
|
+
line.startsWith("a=fingerprint:") ||
|
|
51
|
+
line.startsWith("a=setup:") ||
|
|
52
|
+
line.startsWith("m=") ||
|
|
53
|
+
line.startsWith("c=") ||
|
|
54
|
+
line.startsWith("a=mid:") ||
|
|
55
|
+
line.startsWith("a=sctp-port:") ||
|
|
56
|
+
line.startsWith("a=max-message-size:")
|
|
57
|
+
) {
|
|
58
|
+
essential.push(line);
|
|
59
|
+
}
|
|
60
|
+
}
|
|
61
|
+
return essential.join("\n");
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
/** Expand compressed SDP back to a valid (CRLF) form. */
|
|
65
|
+
function expandSdp(compressed: string): string {
|
|
66
|
+
const lines = compressed.split("\n");
|
|
67
|
+
return `${lines.join("\r\n")}\r\n`;
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
/** Compress an ICE candidate to its essential parts. */
|
|
71
|
+
function compressCandidate(candidate: IceCandidate): string {
|
|
72
|
+
const { candidate: c, sdpMid, sdpMLineIndex } = candidate;
|
|
73
|
+
const match = c.match(/candidate:(\S+)\s+(\d+)\s+(\S+)\s+(\d+)\s+(\S+)\s+(\d+)\s+typ\s+(\S+)/);
|
|
74
|
+
if (!match) {
|
|
75
|
+
return `R:${sdpMid ?? ""}:${sdpMLineIndex ?? 0}:${c}`;
|
|
76
|
+
}
|
|
77
|
+
const [, foundation, component, protocol, priority, ip, port, type] = match;
|
|
78
|
+
return `${foundation}|${component}|${protocol}|${priority}|${ip}|${port}|${type}|${sdpMid ?? ""}|${sdpMLineIndex ?? 0}`;
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
/** Expand a compressed ICE candidate. */
|
|
82
|
+
function expandCandidate(compressed: string): IceCandidate {
|
|
83
|
+
if (compressed.startsWith("R:")) {
|
|
84
|
+
const [, sdpMid, sdpMLineIndexStr, ...rest] = compressed.split(":");
|
|
85
|
+
return {
|
|
86
|
+
candidate: rest.join(":"),
|
|
87
|
+
sdpMid: sdpMid || null,
|
|
88
|
+
sdpMLineIndex: Number.parseInt(sdpMLineIndexStr, 10) || null,
|
|
89
|
+
};
|
|
90
|
+
}
|
|
91
|
+
const parts = compressed.split("|");
|
|
92
|
+
if (parts.length < 9) {
|
|
93
|
+
throw new Error(`Invalid compressed candidate: ${compressed}`);
|
|
94
|
+
}
|
|
95
|
+
const [foundation, component, protocol, priority, ip, port, type, sdpMid, sdpMLineIndexStr] =
|
|
96
|
+
parts;
|
|
97
|
+
const candidate = `candidate:${foundation} ${component} ${protocol} ${priority} ${ip} ${port} typ ${type}`;
|
|
98
|
+
return {
|
|
99
|
+
candidate,
|
|
100
|
+
sdpMid: sdpMid || null,
|
|
101
|
+
sdpMLineIndex: sdpMLineIndexStr ? Number.parseInt(sdpMLineIndexStr, 10) : null,
|
|
102
|
+
};
|
|
103
|
+
}
|
|
104
|
+
|
|
105
|
+
/** Create a compressed signal for QR code exchange. */
|
|
106
|
+
export function createCompressedSignal(
|
|
107
|
+
sessionId: string,
|
|
108
|
+
role: PeerRole,
|
|
109
|
+
description: SessionDescription,
|
|
110
|
+
candidates: IceCandidate[],
|
|
111
|
+
): CompressedSignal {
|
|
112
|
+
return {
|
|
113
|
+
v: PROTOCOL_VERSION,
|
|
114
|
+
id: sessionId,
|
|
115
|
+
role,
|
|
116
|
+
sdp: compressSdp(description.sdp),
|
|
117
|
+
ice: candidates.map(compressCandidate),
|
|
118
|
+
};
|
|
119
|
+
}
|
|
120
|
+
|
|
121
|
+
/** Parse a compressed signal. */
|
|
122
|
+
export function parseCompressedSignal(signal: CompressedSignal): {
|
|
123
|
+
sessionId: string;
|
|
124
|
+
role: PeerRole;
|
|
125
|
+
description: SessionDescription;
|
|
126
|
+
candidates: IceCandidate[];
|
|
127
|
+
} {
|
|
128
|
+
if (signal.v !== PROTOCOL_VERSION) {
|
|
129
|
+
throw new Error(`Unsupported protocol version: ${signal.v}`);
|
|
130
|
+
}
|
|
131
|
+
const type = signal.role === "initiator" ? "offer" : "answer";
|
|
132
|
+
return {
|
|
133
|
+
sessionId: signal.id,
|
|
134
|
+
role: signal.role,
|
|
135
|
+
description: { type, sdp: expandSdp(signal.sdp) },
|
|
136
|
+
candidates: signal.ice.map(expandCandidate),
|
|
137
|
+
};
|
|
138
|
+
}
|
|
139
|
+
|
|
140
|
+
/** Encode a compressed signal to a URL-safe base64 string for a QR code. */
|
|
141
|
+
export function encodeSignal(signal: CompressedSignal): string {
|
|
142
|
+
const json = JSON.stringify(signal);
|
|
143
|
+
return btoa(json).replace(/\+/g, "-").replace(/\//g, "_").replace(/=/g, "");
|
|
144
|
+
}
|
|
145
|
+
|
|
146
|
+
/** Decode a signal string from a QR code. */
|
|
147
|
+
export function decodeSignal(encoded: string): CompressedSignal {
|
|
148
|
+
let base64 = encoded.replace(/-/g, "+").replace(/_/g, "/");
|
|
149
|
+
while (base64.length % 4) base64 += "=";
|
|
150
|
+
return JSON.parse(atob(base64));
|
|
151
|
+
}
|
|
152
|
+
|
|
153
|
+
/** Options for {@link QrSignaling}. */
|
|
154
|
+
export interface QrSignalingOptions {
|
|
155
|
+
sessionId?: string;
|
|
156
|
+
connection?: WebRtcConnectionOptions;
|
|
157
|
+
}
|
|
158
|
+
|
|
159
|
+
/**
|
|
160
|
+
* Serverless WebRTC pairing over QR codes.
|
|
161
|
+
*
|
|
162
|
+
* Flow:
|
|
163
|
+
* 1. Initiator `offer()` → `{ qr, accept }`; displays `qr`.
|
|
164
|
+
* 2. Responder `answer(offerQr)` → `{ qr, channel }`; displays its `qr`.
|
|
165
|
+
* 3. Initiator `accept(answerQr)` → `channel`. Both ends now hold a working
|
|
166
|
+
* {@link ByteChannel}.
|
|
167
|
+
*/
|
|
168
|
+
export class QrSignaling {
|
|
169
|
+
private readonly sessionId: string;
|
|
170
|
+
private readonly connection: WebRtcConnectionOptions;
|
|
171
|
+
|
|
172
|
+
constructor(options: QrSignalingOptions = {}) {
|
|
173
|
+
this.sessionId = options.sessionId ?? generateSessionId();
|
|
174
|
+
this.connection = options.connection ?? {};
|
|
175
|
+
}
|
|
176
|
+
|
|
177
|
+
getSessionId(): string {
|
|
178
|
+
return this.sessionId;
|
|
179
|
+
}
|
|
180
|
+
|
|
181
|
+
/** Create an offer QR; `accept(answerQr)` finishes the handshake. */
|
|
182
|
+
async offer(): Promise<{ qr: string; accept(answerQr: string): Promise<ByteChannel> }> {
|
|
183
|
+
const pc = new PeerConnection("initiator", this.connection);
|
|
184
|
+
const channel = pc.open();
|
|
185
|
+
await pc.connect();
|
|
186
|
+
await pc.waitForIceGathering();
|
|
187
|
+
|
|
188
|
+
const description = pc.getLocalDescription();
|
|
189
|
+
if (!description) throw new Error("No local description after offer");
|
|
190
|
+
const qr = encodeSignal(
|
|
191
|
+
createCompressedSignal(this.sessionId, "initiator", description, pc.getCollectedCandidates()),
|
|
192
|
+
);
|
|
193
|
+
|
|
194
|
+
return {
|
|
195
|
+
qr,
|
|
196
|
+
accept: async (answerQr: string): Promise<ByteChannel> => {
|
|
197
|
+
const parsed = parseCompressedSignal(decodeSignal(answerQr));
|
|
198
|
+
await pc.handleSignal({ type: "answer", sdp: parsed.description.sdp });
|
|
199
|
+
for (const candidate of parsed.candidates) {
|
|
200
|
+
await pc.handleSignal({ type: "candidate", candidate });
|
|
201
|
+
}
|
|
202
|
+
return channel;
|
|
203
|
+
},
|
|
204
|
+
};
|
|
205
|
+
}
|
|
206
|
+
|
|
207
|
+
/** Consume an offer QR and produce an answer QR + the established channel. */
|
|
208
|
+
async answer(offerQr: string): Promise<{ qr: string; channel: ByteChannel }> {
|
|
209
|
+
const parsed = parseCompressedSignal(decodeSignal(offerQr));
|
|
210
|
+
const pc = new PeerConnection("responder", this.connection);
|
|
211
|
+
const channel = pc.open();
|
|
212
|
+
|
|
213
|
+
await pc.handleSignal({ type: "offer", sdp: parsed.description.sdp });
|
|
214
|
+
for (const candidate of parsed.candidates) {
|
|
215
|
+
await pc.handleSignal({ type: "candidate", candidate });
|
|
216
|
+
}
|
|
217
|
+
await pc.waitForIceGathering();
|
|
218
|
+
|
|
219
|
+
const description = pc.getLocalDescription();
|
|
220
|
+
if (!description) throw new Error("No local description after answer");
|
|
221
|
+
const qr = encodeSignal(
|
|
222
|
+
createCompressedSignal(parsed.sessionId, "responder", description, pc.getCollectedCandidates()),
|
|
223
|
+
);
|
|
224
|
+
|
|
225
|
+
return { qr, channel: await channel };
|
|
226
|
+
}
|
|
227
|
+
}
|