@abraca/dabra 2.89.0 → 2.91.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/package.json +5 -11
- package/src/AbracadabraBaseProvider.ts +0 -963
- package/src/AbracadabraClient.ts +0 -1960
- package/src/AbracadabraProvider.ts +0 -915
- package/src/AbracadabraWS.ts +0 -695
- package/src/BackgroundSyncManager.ts +0 -856
- package/src/BackgroundSyncPersistence.ts +0 -140
- package/src/ChatClient.ts +0 -314
- package/src/CloseEvents.ts +0 -49
- package/src/ContentManager.ts +0 -246
- package/src/CoverReconcile.ts +0 -168
- package/src/CryptoIdentityKeystore.ts +0 -754
- package/src/DeviceRegistrationService.ts +0 -257
- package/src/DocConverters.ts +0 -1859
- package/src/DocKeyManager.ts +0 -163
- package/src/DocTypes.ts +0 -628
- package/src/DocUtils.ts +0 -251
- package/src/DocumentCache.ts +0 -210
- package/src/DocumentManager.ts +0 -410
- package/src/E2EAbracadabraProvider.ts +0 -426
- package/src/E2EOfflineStore.ts +0 -55
- package/src/EncryptedChatClient.ts +0 -173
- package/src/EncryptedY.ts +0 -145
- package/src/EventEmitter.ts +0 -59
- package/src/FileBlobStore.ts +0 -569
- package/src/IdentityDoc.ts +0 -711
- package/src/IncomingMessage.ts +0 -63
- package/src/MessageReceiver.ts +0 -151
- package/src/MessageSender.ts +0 -22
- package/src/MetaManager.ts +0 -194
- package/src/MnemonicKeyDerivation.ts +0 -171
- package/src/NodeConnect.ts +0 -63
- package/src/NodeIdentity.ts +0 -378
- package/src/NotificationsClient.ts +0 -207
- package/src/OfflineStore.ts +0 -294
- package/src/OutgoingMessage.ts +0 -25
- package/src/OutgoingMessages/AuthenticationMessage.ts +0 -23
- package/src/OutgoingMessages/AwarenessMessage.ts +0 -41
- package/src/OutgoingMessages/CloseMessage.ts +0 -17
- package/src/OutgoingMessages/QueryAwarenessMessage.ts +0 -17
- package/src/OutgoingMessages/StatelessMessage.ts +0 -18
- package/src/OutgoingMessages/SubdocMessage.ts +0 -35
- package/src/OutgoingMessages/SyncStepOneMessage.ts +0 -25
- package/src/OutgoingMessages/SyncStepTwoMessage.ts +0 -25
- package/src/OutgoingMessages/UpdateMessage.ts +0 -20
- package/src/QueryClient.ts +0 -209
- package/src/RpcClient.ts +0 -659
- package/src/SchemaTypes.ts +0 -179
- package/src/SearchIndex.ts +0 -250
- package/src/ServerRegistry.ts +0 -220
- package/src/ServerReset.ts +0 -222
- package/src/TokenManager.ts +0 -337
- package/src/TreeManager.ts +0 -894
- package/src/TreeTimestamps.ts +0 -101
- package/src/auth.ts +0 -62
- package/src/awarenessStatesToArray.ts +0 -10
- package/src/index.ts +0 -219
- package/src/messageRecord.ts +0 -121
- package/src/sync/BroadcastChannelSync.ts +0 -235
- package/src/types.ts +0 -790
- package/src/webrtc/AbracadabraWebRTC.ts +0 -683
- package/src/webrtc/DataChannelRouter.ts +0 -179
- package/src/webrtc/DevicePairingChannel.ts +0 -496
- package/src/webrtc/E2EEChannel.ts +0 -195
- package/src/webrtc/FileTransferChannel.ts +0 -367
- package/src/webrtc/ManualSignaling.ts +0 -204
- package/src/webrtc/PeerConnection.ts +0 -133
- package/src/webrtc/SignalingSocket.ts +0 -378
- package/src/webrtc/YjsDataChannel.ts +0 -203
- package/src/webrtc/index.ts +0 -26
- package/src/webrtc/types.ts +0 -177
|
@@ -1,683 +0,0 @@
|
|
|
1
|
-
import type * as Y from "yjs";
|
|
2
|
-
import type { Awareness } from "y-protocols/awareness";
|
|
3
|
-
import EventEmitter from "../EventEmitter.ts";
|
|
4
|
-
import type { AbracadabraProvider } from "../AbracadabraProvider.ts";
|
|
5
|
-
import { SignalingSocket } from "./SignalingSocket.ts";
|
|
6
|
-
import { PeerConnection } from "./PeerConnection.ts";
|
|
7
|
-
import { YjsDataChannel } from "./YjsDataChannel.ts";
|
|
8
|
-
import { FileTransferChannel, FileTransferHandle } from "./FileTransferChannel.ts";
|
|
9
|
-
import { E2EEChannel, type E2EEIdentity } from "./E2EEChannel.ts";
|
|
10
|
-
import { KEY_EXCHANGE_CHANNEL } from "./DataChannelRouter.ts";
|
|
11
|
-
import {
|
|
12
|
-
DEFAULT_ICE_SERVERS,
|
|
13
|
-
CHANNEL_NAMES,
|
|
14
|
-
type AbracadabraWebRTCConfiguration,
|
|
15
|
-
type PeerInfo,
|
|
16
|
-
type PeerState,
|
|
17
|
-
} from "./types.ts";
|
|
18
|
-
|
|
19
|
-
const HAS_RTC = typeof globalThis.RTCPeerConnection !== "undefined";
|
|
20
|
-
|
|
21
|
-
/**
|
|
22
|
-
* Optional WebRTC provider for peer-to-peer Y.js sync, awareness, and file transfer.
|
|
23
|
-
*
|
|
24
|
-
* Uses the server's signaling endpoint (`/ws/:doc_id/signaling`) for connection
|
|
25
|
-
* negotiation, then establishes direct data channels between peers. Designed to
|
|
26
|
-
* work alongside `AbracadabraProvider` — the server remains the persistence layer,
|
|
27
|
-
* while WebRTC provides low-latency P2P sync.
|
|
28
|
-
*
|
|
29
|
-
* Falls back to a no-op when `RTCPeerConnection` is unavailable (e.g. Node.js).
|
|
30
|
-
*/
|
|
31
|
-
export class AbracadabraWebRTC extends EventEmitter {
|
|
32
|
-
private signaling: SignalingSocket | null = null;
|
|
33
|
-
private peerConnections = new Map<string, PeerConnection>();
|
|
34
|
-
private yjsChannels = new Map<string, YjsDataChannel>();
|
|
35
|
-
private fileChannels = new Map<string, FileTransferChannel>();
|
|
36
|
-
private e2eeChannels = new Map<string, E2EEChannel>();
|
|
37
|
-
|
|
38
|
-
private readonly config: {
|
|
39
|
-
docId: string;
|
|
40
|
-
url: string;
|
|
41
|
-
signalingUrl: string | null;
|
|
42
|
-
token: string | (() => string) | (() => Promise<string>);
|
|
43
|
-
document: Y.Doc | null;
|
|
44
|
-
awareness: Awareness | null;
|
|
45
|
-
iceServers: RTCIceServer[];
|
|
46
|
-
displayName: string | null;
|
|
47
|
-
color: string | null;
|
|
48
|
-
enableDocSync: boolean;
|
|
49
|
-
enableAwarenessSync: boolean;
|
|
50
|
-
enableFileTransfer: boolean;
|
|
51
|
-
fileChunkSize: number;
|
|
52
|
-
e2ee: E2EEIdentity | (() => Promise<E2EEIdentity>) | null;
|
|
53
|
-
WebSocketPolyfill: any;
|
|
54
|
-
};
|
|
55
|
-
|
|
56
|
-
/** Cached resolved E2EE identity (lazily resolved from factory on first peer connect). */
|
|
57
|
-
private _resolvedE2ee: E2EEIdentity | null = null;
|
|
58
|
-
private _resolveE2eePromise: Promise<E2EEIdentity> | null = null;
|
|
59
|
-
|
|
60
|
-
public readonly peers = new Map<string, PeerState>();
|
|
61
|
-
public localPeerId: string | null = null;
|
|
62
|
-
public isConnected = false;
|
|
63
|
-
|
|
64
|
-
constructor(configuration: AbracadabraWebRTCConfiguration) {
|
|
65
|
-
super();
|
|
66
|
-
|
|
67
|
-
const doc = configuration.document ?? null;
|
|
68
|
-
const awareness = configuration.awareness ?? null;
|
|
69
|
-
|
|
70
|
-
this.config = {
|
|
71
|
-
docId: configuration.docId,
|
|
72
|
-
url: configuration.url,
|
|
73
|
-
signalingUrl: configuration.signalingUrl ?? null,
|
|
74
|
-
token: configuration.token,
|
|
75
|
-
document: doc,
|
|
76
|
-
awareness,
|
|
77
|
-
iceServers: configuration.iceServers ?? DEFAULT_ICE_SERVERS,
|
|
78
|
-
displayName: configuration.displayName ?? null,
|
|
79
|
-
color: configuration.color ?? null,
|
|
80
|
-
enableDocSync: configuration.enableDocSync ?? !!doc,
|
|
81
|
-
enableAwarenessSync: configuration.enableAwarenessSync ?? !!awareness,
|
|
82
|
-
enableFileTransfer: configuration.enableFileTransfer ?? false,
|
|
83
|
-
fileChunkSize: configuration.fileChunkSize ?? 16384,
|
|
84
|
-
e2ee: configuration.e2ee ?? null,
|
|
85
|
-
WebSocketPolyfill: configuration.WebSocketPolyfill,
|
|
86
|
-
};
|
|
87
|
-
|
|
88
|
-
if (configuration.autoConnect !== false && HAS_RTC) {
|
|
89
|
-
this.connect();
|
|
90
|
-
}
|
|
91
|
-
}
|
|
92
|
-
|
|
93
|
-
/**
|
|
94
|
-
* Create an AbracadabraWebRTC instance from an existing provider,
|
|
95
|
-
* reusing its document, awareness, URL, and token.
|
|
96
|
-
*/
|
|
97
|
-
static fromProvider(
|
|
98
|
-
provider: AbracadabraProvider,
|
|
99
|
-
options?: Partial<AbracadabraWebRTCConfiguration>,
|
|
100
|
-
): AbracadabraWebRTC {
|
|
101
|
-
// Derive the HTTP URL from the provider's WebSocket URL.
|
|
102
|
-
const config = provider.configuration;
|
|
103
|
-
const wsUrl =
|
|
104
|
-
config.websocketProvider?.url ??
|
|
105
|
-
(config as { url?: string }).url ??
|
|
106
|
-
"";
|
|
107
|
-
const httpUrl = wsUrl
|
|
108
|
-
.replace(/^wss:/, "https:")
|
|
109
|
-
.replace(/^ws:/, "http:")
|
|
110
|
-
.replace(/\/ws\/?$/, "");
|
|
111
|
-
|
|
112
|
-
return new AbracadabraWebRTC({
|
|
113
|
-
docId: config.name,
|
|
114
|
-
url: httpUrl,
|
|
115
|
-
token: config.token as string | (() => string) | (() => Promise<string>),
|
|
116
|
-
document: provider.document,
|
|
117
|
-
awareness: provider.awareness,
|
|
118
|
-
...options,
|
|
119
|
-
});
|
|
120
|
-
}
|
|
121
|
-
|
|
122
|
-
// ── Connection Lifecycle ────────────────────────────────────────────────
|
|
123
|
-
|
|
124
|
-
async connect(): Promise<void> {
|
|
125
|
-
if (!HAS_RTC) return;
|
|
126
|
-
if (this.isConnected) return;
|
|
127
|
-
|
|
128
|
-
const signalingUrl = this.buildSignalingUrl();
|
|
129
|
-
|
|
130
|
-
this.signaling = new SignalingSocket({
|
|
131
|
-
url: signalingUrl,
|
|
132
|
-
token: this.config.token,
|
|
133
|
-
autoConnect: false,
|
|
134
|
-
WebSocketPolyfill: this.config.WebSocketPolyfill,
|
|
135
|
-
});
|
|
136
|
-
|
|
137
|
-
this.signaling.on(
|
|
138
|
-
"welcome",
|
|
139
|
-
(data: { peerId: string; peers: PeerInfo[] }) => {
|
|
140
|
-
this.localPeerId = data.peerId;
|
|
141
|
-
this.isConnected = true;
|
|
142
|
-
this.emit("connected");
|
|
143
|
-
|
|
144
|
-
// Send profile if configured.
|
|
145
|
-
if (this.config.displayName && this.config.color) {
|
|
146
|
-
this.signaling!.sendProfile(
|
|
147
|
-
this.config.displayName,
|
|
148
|
-
this.config.color,
|
|
149
|
-
);
|
|
150
|
-
}
|
|
151
|
-
|
|
152
|
-
// Initiate connections to existing peers.
|
|
153
|
-
for (const peer of data.peers) {
|
|
154
|
-
this.addPeer(peer);
|
|
155
|
-
// Deterministic initiator: lower peer_id sends offer.
|
|
156
|
-
if (this.localPeerId! < peer.peer_id) {
|
|
157
|
-
this.initiateConnection(peer.peer_id);
|
|
158
|
-
}
|
|
159
|
-
}
|
|
160
|
-
},
|
|
161
|
-
);
|
|
162
|
-
|
|
163
|
-
this.signaling.on("joined", (peer: PeerInfo) => {
|
|
164
|
-
this.addPeer(peer);
|
|
165
|
-
this.emit("peerJoined", peer);
|
|
166
|
-
|
|
167
|
-
// Deterministic initiator.
|
|
168
|
-
if (this.localPeerId! < peer.peer_id) {
|
|
169
|
-
this.initiateConnection(peer.peer_id);
|
|
170
|
-
}
|
|
171
|
-
});
|
|
172
|
-
|
|
173
|
-
this.signaling.on("left", ({ peerId }: { peerId: string }) => {
|
|
174
|
-
this.removePeer(peerId);
|
|
175
|
-
this.emit("peerLeft", { peerId });
|
|
176
|
-
});
|
|
177
|
-
|
|
178
|
-
this.signaling.on(
|
|
179
|
-
"offer",
|
|
180
|
-
async ({ from, sdp }: { from: string; sdp: string }) => {
|
|
181
|
-
await this.handleOffer(from, sdp);
|
|
182
|
-
},
|
|
183
|
-
);
|
|
184
|
-
|
|
185
|
-
this.signaling.on(
|
|
186
|
-
"answer",
|
|
187
|
-
async ({ from, sdp }: { from: string; sdp: string }) => {
|
|
188
|
-
const pc = this.peerConnections.get(from);
|
|
189
|
-
if (pc) {
|
|
190
|
-
await pc.setRemoteAnswer(sdp);
|
|
191
|
-
}
|
|
192
|
-
},
|
|
193
|
-
);
|
|
194
|
-
|
|
195
|
-
this.signaling.on(
|
|
196
|
-
"ice",
|
|
197
|
-
async ({
|
|
198
|
-
from,
|
|
199
|
-
candidate,
|
|
200
|
-
}: { from: string; candidate: string }) => {
|
|
201
|
-
const pc = this.peerConnections.get(from);
|
|
202
|
-
if (pc) {
|
|
203
|
-
await pc.addIceCandidate(candidate);
|
|
204
|
-
}
|
|
205
|
-
},
|
|
206
|
-
);
|
|
207
|
-
|
|
208
|
-
this.signaling.on(
|
|
209
|
-
"mute",
|
|
210
|
-
({ peerId, muted }: { peerId: string; muted: boolean }) => {
|
|
211
|
-
const peer = this.peers.get(peerId);
|
|
212
|
-
if (peer) {
|
|
213
|
-
peer.muted = muted;
|
|
214
|
-
this.emit("peerMuted", { peerId, muted });
|
|
215
|
-
}
|
|
216
|
-
},
|
|
217
|
-
);
|
|
218
|
-
|
|
219
|
-
this.signaling.on(
|
|
220
|
-
"media-state",
|
|
221
|
-
({
|
|
222
|
-
peerId,
|
|
223
|
-
video,
|
|
224
|
-
screen,
|
|
225
|
-
}: { peerId: string; video: boolean; screen: boolean }) => {
|
|
226
|
-
const peer = this.peers.get(peerId);
|
|
227
|
-
if (peer) {
|
|
228
|
-
peer.video = video;
|
|
229
|
-
peer.screen = screen;
|
|
230
|
-
this.emit("peerMediaState", { peerId, video, screen });
|
|
231
|
-
}
|
|
232
|
-
},
|
|
233
|
-
);
|
|
234
|
-
|
|
235
|
-
this.signaling.on(
|
|
236
|
-
"profile",
|
|
237
|
-
({
|
|
238
|
-
peerId,
|
|
239
|
-
name,
|
|
240
|
-
color,
|
|
241
|
-
}: { peerId: string; name: string; color: string }) => {
|
|
242
|
-
const peer = this.peers.get(peerId);
|
|
243
|
-
if (peer) {
|
|
244
|
-
peer.name = name;
|
|
245
|
-
peer.color = color;
|
|
246
|
-
this.emit("peerProfile", { peerId, name, color });
|
|
247
|
-
}
|
|
248
|
-
},
|
|
249
|
-
);
|
|
250
|
-
|
|
251
|
-
this.signaling.on("disconnected", () => {
|
|
252
|
-
this.isConnected = false;
|
|
253
|
-
this.localPeerId = null;
|
|
254
|
-
// Clean up all peer connections — signaling will auto-reconnect.
|
|
255
|
-
this.removeAllPeers();
|
|
256
|
-
this.emit("disconnected");
|
|
257
|
-
});
|
|
258
|
-
|
|
259
|
-
this.signaling.on(
|
|
260
|
-
"error",
|
|
261
|
-
(err: { code: string; message: string }) => {
|
|
262
|
-
this.emit("signalingError", err);
|
|
263
|
-
},
|
|
264
|
-
);
|
|
265
|
-
|
|
266
|
-
await this.signaling.connect();
|
|
267
|
-
}
|
|
268
|
-
|
|
269
|
-
disconnect(): void {
|
|
270
|
-
if (!HAS_RTC) return;
|
|
271
|
-
|
|
272
|
-
this.removeAllPeers();
|
|
273
|
-
|
|
274
|
-
if (this.signaling) {
|
|
275
|
-
this.signaling.disconnect();
|
|
276
|
-
this.signaling = null;
|
|
277
|
-
}
|
|
278
|
-
|
|
279
|
-
this.isConnected = false;
|
|
280
|
-
this.localPeerId = null;
|
|
281
|
-
}
|
|
282
|
-
|
|
283
|
-
destroy(): void {
|
|
284
|
-
this.disconnect();
|
|
285
|
-
|
|
286
|
-
if (this.signaling) {
|
|
287
|
-
this.signaling.destroy();
|
|
288
|
-
this.signaling = null;
|
|
289
|
-
}
|
|
290
|
-
|
|
291
|
-
this._resolvedE2ee = null;
|
|
292
|
-
this._resolveE2eePromise = null;
|
|
293
|
-
|
|
294
|
-
this.removeAllListeners();
|
|
295
|
-
}
|
|
296
|
-
|
|
297
|
-
// ── Media State ─────────────────────────────────────────────────────────
|
|
298
|
-
|
|
299
|
-
setMuted(muted: boolean): void {
|
|
300
|
-
this.signaling?.sendMute(muted);
|
|
301
|
-
}
|
|
302
|
-
|
|
303
|
-
setMediaState(video: boolean, screen: boolean): void {
|
|
304
|
-
this.signaling?.sendMediaState(video, screen);
|
|
305
|
-
}
|
|
306
|
-
|
|
307
|
-
setProfile(name: string, color: string): void {
|
|
308
|
-
this.signaling?.sendProfile(name, color);
|
|
309
|
-
}
|
|
310
|
-
|
|
311
|
-
// ── File Transfer ───────────────────────────────────────────────────────
|
|
312
|
-
|
|
313
|
-
/**
|
|
314
|
-
* Send a file to a specific peer. Returns a handle for tracking progress.
|
|
315
|
-
*/
|
|
316
|
-
async sendFile(
|
|
317
|
-
peerId: string,
|
|
318
|
-
file: File | Blob,
|
|
319
|
-
filename: string,
|
|
320
|
-
): Promise<FileTransferHandle | null> {
|
|
321
|
-
const fc = this.fileChannels.get(peerId);
|
|
322
|
-
if (!fc) return null;
|
|
323
|
-
return fc.send(file, filename);
|
|
324
|
-
}
|
|
325
|
-
|
|
326
|
-
/**
|
|
327
|
-
* Send a file to all connected peers. Returns an array of handles.
|
|
328
|
-
*/
|
|
329
|
-
async broadcastFile(
|
|
330
|
-
file: File | Blob,
|
|
331
|
-
filename: string,
|
|
332
|
-
): Promise<FileTransferHandle[]> {
|
|
333
|
-
const handles: FileTransferHandle[] = [];
|
|
334
|
-
for (const [peerId, fc] of this.fileChannels) {
|
|
335
|
-
const handle = await fc.send(file, filename);
|
|
336
|
-
handles.push(handle);
|
|
337
|
-
}
|
|
338
|
-
return handles;
|
|
339
|
-
}
|
|
340
|
-
|
|
341
|
-
// ── Custom Messages ─────────────────────────────────────────────────────
|
|
342
|
-
|
|
343
|
-
/**
|
|
344
|
-
* Send a custom string message to a specific peer via a data channel.
|
|
345
|
-
* When E2EE is active, the message is encrypted through the router.
|
|
346
|
-
*/
|
|
347
|
-
sendCustomMessage(peerId: string, payload: string): void {
|
|
348
|
-
const pc = this.peerConnections.get(peerId);
|
|
349
|
-
if (!pc) return;
|
|
350
|
-
|
|
351
|
-
const channelName = "custom";
|
|
352
|
-
const channel = pc.router.getChannel(channelName);
|
|
353
|
-
if (channel && channel.readyState === "open") {
|
|
354
|
-
const data = new TextEncoder().encode(payload);
|
|
355
|
-
pc.router.send(channelName, data).catch(() => {});
|
|
356
|
-
return;
|
|
357
|
-
}
|
|
358
|
-
|
|
359
|
-
// Channel not open yet — queue via the router's channelOpen event.
|
|
360
|
-
// Do NOT create a new channel here. The "custom" channel must be
|
|
361
|
-
// created during initiateConnection to be included in the SDP offer.
|
|
362
|
-
// If it doesn't exist yet, the peer hasn't finished negotiation.
|
|
363
|
-
const onOpen = ({ name }: { name: string }) => {
|
|
364
|
-
if (name === channelName) {
|
|
365
|
-
pc.router.off("channelOpen", onOpen);
|
|
366
|
-
const data = new TextEncoder().encode(payload);
|
|
367
|
-
pc.router.send(channelName, data).catch(() => {});
|
|
368
|
-
}
|
|
369
|
-
};
|
|
370
|
-
pc.router.on("channelOpen", onOpen);
|
|
371
|
-
}
|
|
372
|
-
|
|
373
|
-
/**
|
|
374
|
-
* Send a custom string message to all connected peers.
|
|
375
|
-
*/
|
|
376
|
-
broadcastCustomMessage(payload: string): void {
|
|
377
|
-
for (const peerId of this.peerConnections.keys()) {
|
|
378
|
-
this.sendCustomMessage(peerId, payload);
|
|
379
|
-
}
|
|
380
|
-
}
|
|
381
|
-
|
|
382
|
-
// ── Private: Peer Management ────────────────────────────────────────────
|
|
383
|
-
|
|
384
|
-
private addPeer(info: PeerInfo): void {
|
|
385
|
-
this.peers.set(info.peer_id, {
|
|
386
|
-
...info,
|
|
387
|
-
connectionState: "new",
|
|
388
|
-
});
|
|
389
|
-
}
|
|
390
|
-
|
|
391
|
-
private removePeer(peerId: string): void {
|
|
392
|
-
this.peers.delete(peerId);
|
|
393
|
-
|
|
394
|
-
const e2ee = this.e2eeChannels.get(peerId);
|
|
395
|
-
if (e2ee) {
|
|
396
|
-
e2ee.destroy();
|
|
397
|
-
this.e2eeChannels.delete(peerId);
|
|
398
|
-
}
|
|
399
|
-
|
|
400
|
-
const yjs = this.yjsChannels.get(peerId);
|
|
401
|
-
if (yjs) {
|
|
402
|
-
yjs.destroy();
|
|
403
|
-
this.yjsChannels.delete(peerId);
|
|
404
|
-
}
|
|
405
|
-
|
|
406
|
-
const fc = this.fileChannels.get(peerId);
|
|
407
|
-
if (fc) {
|
|
408
|
-
fc.destroy();
|
|
409
|
-
this.fileChannels.delete(peerId);
|
|
410
|
-
}
|
|
411
|
-
|
|
412
|
-
const pc = this.peerConnections.get(peerId);
|
|
413
|
-
if (pc) {
|
|
414
|
-
pc.destroy();
|
|
415
|
-
this.peerConnections.delete(peerId);
|
|
416
|
-
}
|
|
417
|
-
}
|
|
418
|
-
|
|
419
|
-
private removeAllPeers(): void {
|
|
420
|
-
for (const peerId of [...this.peers.keys()]) {
|
|
421
|
-
this.removePeer(peerId);
|
|
422
|
-
}
|
|
423
|
-
}
|
|
424
|
-
|
|
425
|
-
// ── Private: Connection Negotiation ─────────────────────────────────────
|
|
426
|
-
|
|
427
|
-
private createPeerConnection(peerId: string): PeerConnection {
|
|
428
|
-
const pc = new PeerConnection(peerId, this.config.iceServers);
|
|
429
|
-
|
|
430
|
-
// Forward ICE candidates to signaling.
|
|
431
|
-
pc.on(
|
|
432
|
-
"iceCandidate",
|
|
433
|
-
({ peerId, candidate }: { peerId: string; candidate: string }) => {
|
|
434
|
-
this.signaling?.sendIce(peerId, candidate);
|
|
435
|
-
},
|
|
436
|
-
);
|
|
437
|
-
|
|
438
|
-
// Handle ICE failure with restart.
|
|
439
|
-
pc.on("iceFailed", async ({ peerId }: { peerId: string }) => {
|
|
440
|
-
try {
|
|
441
|
-
const sdp = await pc.createOffer(true);
|
|
442
|
-
this.signaling?.sendOffer(peerId, sdp);
|
|
443
|
-
} catch {
|
|
444
|
-
// If ICE restart fails, remove peer.
|
|
445
|
-
this.removePeer(peerId);
|
|
446
|
-
}
|
|
447
|
-
});
|
|
448
|
-
|
|
449
|
-
// Track connection state.
|
|
450
|
-
pc.on(
|
|
451
|
-
"connectionStateChange",
|
|
452
|
-
({ peerId, state }: { peerId: string; state: RTCPeerConnectionState }) => {
|
|
453
|
-
const peer = this.peers.get(peerId);
|
|
454
|
-
if (peer) {
|
|
455
|
-
peer.connectionState = state;
|
|
456
|
-
}
|
|
457
|
-
|
|
458
|
-
if (state === "disconnected" || state === "closed") {
|
|
459
|
-
// Peer connection dropped. Don't remove yet — ICE may recover.
|
|
460
|
-
// If "failed", the iceFailed handler will attempt restart.
|
|
461
|
-
}
|
|
462
|
-
|
|
463
|
-
this.emit("peerConnectionState", { peerId, state });
|
|
464
|
-
},
|
|
465
|
-
);
|
|
466
|
-
|
|
467
|
-
// Listen for custom messages on the router.
|
|
468
|
-
pc.router.on("channelMessage", ({ name, data }: { name: string; data: any }) => {
|
|
469
|
-
if (name === "custom") {
|
|
470
|
-
const payload = typeof data === "string" ? data : new TextDecoder().decode(data);
|
|
471
|
-
this.emit("customMessage", { peerId, payload });
|
|
472
|
-
}
|
|
473
|
-
});
|
|
474
|
-
|
|
475
|
-
this.peerConnections.set(peerId, pc);
|
|
476
|
-
this.attachDataHandlers(peerId, pc);
|
|
477
|
-
|
|
478
|
-
return pc;
|
|
479
|
-
}
|
|
480
|
-
|
|
481
|
-
/** Resolve the E2EE identity, supporting both pre-resolved objects and lazy factories. */
|
|
482
|
-
private async resolveE2ee(): Promise<E2EEIdentity | null> {
|
|
483
|
-
if (this._resolvedE2ee) return this._resolvedE2ee;
|
|
484
|
-
if (!this.config.e2ee) return null;
|
|
485
|
-
if (typeof this.config.e2ee === "function") {
|
|
486
|
-
if (!this._resolveE2eePromise) {
|
|
487
|
-
this._resolveE2eePromise = this.config.e2ee().then((id) => {
|
|
488
|
-
this._resolvedE2ee = id;
|
|
489
|
-
return id;
|
|
490
|
-
});
|
|
491
|
-
}
|
|
492
|
-
return this._resolveE2eePromise;
|
|
493
|
-
}
|
|
494
|
-
this._resolvedE2ee = this.config.e2ee;
|
|
495
|
-
return this._resolvedE2ee;
|
|
496
|
-
}
|
|
497
|
-
|
|
498
|
-
private attachDataHandlers(peerId: string, pc: PeerConnection): void {
|
|
499
|
-
if (!this.config.e2ee) {
|
|
500
|
-
this.startDataSync(peerId, pc);
|
|
501
|
-
return;
|
|
502
|
-
}
|
|
503
|
-
|
|
504
|
-
// E2EE identity may resolve asynchronously (e.g. lazy passkey-derived key).
|
|
505
|
-
// Register handlers synchronously so no messages are lost during resolution.
|
|
506
|
-
let e2ee: E2EEChannel | null = null;
|
|
507
|
-
const pendingMessages: Uint8Array[] = [];
|
|
508
|
-
let pendingKeyExchangeChannel: RTCDataChannel | null = null;
|
|
509
|
-
|
|
510
|
-
pc.router.on("channelMessage", async ({ name, data }: { name: string; data: any }) => {
|
|
511
|
-
if (name !== KEY_EXCHANGE_CHANNEL) return;
|
|
512
|
-
const buf = data instanceof ArrayBuffer ? new Uint8Array(data) : data;
|
|
513
|
-
if (!e2ee) {
|
|
514
|
-
pendingMessages.push(buf);
|
|
515
|
-
return;
|
|
516
|
-
}
|
|
517
|
-
try {
|
|
518
|
-
await e2ee.handleKeyExchange(buf);
|
|
519
|
-
} catch (err) {
|
|
520
|
-
this.emit("e2eeFailed", { peerId, error: err });
|
|
521
|
-
}
|
|
522
|
-
});
|
|
523
|
-
|
|
524
|
-
pc.router.on("channelOpen", ({ name, channel }: { name: string; channel: RTCDataChannel }) => {
|
|
525
|
-
if (name !== KEY_EXCHANGE_CHANNEL) return;
|
|
526
|
-
if (!e2ee) {
|
|
527
|
-
pendingKeyExchangeChannel = channel;
|
|
528
|
-
return;
|
|
529
|
-
}
|
|
530
|
-
channel.send(e2ee.getKeyExchangeMessage() as unknown as ArrayBuffer);
|
|
531
|
-
});
|
|
532
|
-
|
|
533
|
-
this.resolveE2ee().then(async (identity) => {
|
|
534
|
-
if (!identity) {
|
|
535
|
-
this.startDataSync(peerId, pc);
|
|
536
|
-
return;
|
|
537
|
-
}
|
|
538
|
-
e2ee = new E2EEChannel(identity, this.config.docId);
|
|
539
|
-
this.e2eeChannels.set(peerId, e2ee);
|
|
540
|
-
pc.router.setEncryptor(e2ee);
|
|
541
|
-
|
|
542
|
-
// Drain buffered key-exchange channel open
|
|
543
|
-
if (pendingKeyExchangeChannel) {
|
|
544
|
-
pendingKeyExchangeChannel.send(e2ee.getKeyExchangeMessage() as unknown as ArrayBuffer);
|
|
545
|
-
}
|
|
546
|
-
// Drain buffered messages
|
|
547
|
-
for (const msg of pendingMessages) {
|
|
548
|
-
try {
|
|
549
|
-
await e2ee.handleKeyExchange(msg);
|
|
550
|
-
} catch (err) {
|
|
551
|
-
this.emit("e2eeFailed", { peerId, error: err });
|
|
552
|
-
}
|
|
553
|
-
}
|
|
554
|
-
|
|
555
|
-
e2ee.on("established", () => {
|
|
556
|
-
this.emit("e2eeEstablished", { peerId });
|
|
557
|
-
this.startDataSync(peerId, pc);
|
|
558
|
-
});
|
|
559
|
-
|
|
560
|
-
e2ee.on("error", (err: Error) => {
|
|
561
|
-
this.emit("e2eeFailed", { peerId, error: err });
|
|
562
|
-
});
|
|
563
|
-
}).catch((err) => {
|
|
564
|
-
this.emit("e2eeFailed", { peerId, error: err });
|
|
565
|
-
this.startDataSync(peerId, pc);
|
|
566
|
-
});
|
|
567
|
-
}
|
|
568
|
-
|
|
569
|
-
private startDataSync(peerId: string, pc: PeerConnection): void {
|
|
570
|
-
// Attach Y.js sync.
|
|
571
|
-
if (this.config.document && this.config.enableDocSync) {
|
|
572
|
-
// Don't double-attach if already set up.
|
|
573
|
-
if (this.yjsChannels.has(peerId)) return;
|
|
574
|
-
|
|
575
|
-
const yjs = new YjsDataChannel(
|
|
576
|
-
this.config.document,
|
|
577
|
-
this.config.enableAwarenessSync ? this.config.awareness : null,
|
|
578
|
-
pc.router,
|
|
579
|
-
);
|
|
580
|
-
yjs.attach();
|
|
581
|
-
this.yjsChannels.set(peerId, yjs);
|
|
582
|
-
}
|
|
583
|
-
|
|
584
|
-
// Attach file transfer.
|
|
585
|
-
if (this.config.enableFileTransfer && !this.fileChannels.has(peerId)) {
|
|
586
|
-
const fc = new FileTransferChannel(pc.router, this.config.fileChunkSize);
|
|
587
|
-
|
|
588
|
-
fc.on("receiveStart", (meta: any) => {
|
|
589
|
-
this.emit("fileReceiveStart", { peerId, ...meta });
|
|
590
|
-
});
|
|
591
|
-
fc.on("receiveProgress", (data: any) => {
|
|
592
|
-
this.emit("fileReceiveProgress", { peerId, ...data });
|
|
593
|
-
});
|
|
594
|
-
fc.on("receiveComplete", (data: any) => {
|
|
595
|
-
this.emit("fileReceiveComplete", { peerId, ...data });
|
|
596
|
-
});
|
|
597
|
-
fc.on("receiveError", (data: any) => {
|
|
598
|
-
this.emit("fileReceiveError", { peerId, ...data });
|
|
599
|
-
});
|
|
600
|
-
fc.on("receiveCancelled", (data: any) => {
|
|
601
|
-
this.emit("fileReceiveCancelled", { peerId, ...data });
|
|
602
|
-
});
|
|
603
|
-
|
|
604
|
-
this.fileChannels.set(peerId, fc);
|
|
605
|
-
}
|
|
606
|
-
}
|
|
607
|
-
|
|
608
|
-
private async initiateConnection(peerId: string): Promise<void> {
|
|
609
|
-
const pc = this.createPeerConnection(peerId);
|
|
610
|
-
|
|
611
|
-
// Create key-exchange channel first if E2EE is enabled.
|
|
612
|
-
if (this.config.e2ee) {
|
|
613
|
-
pc.router.createChannel(KEY_EXCHANGE_CHANNEL, { ordered: true });
|
|
614
|
-
}
|
|
615
|
-
|
|
616
|
-
// Create data channels (initiator creates them).
|
|
617
|
-
pc.router.createDefaultChannels({
|
|
618
|
-
enableDocSync: this.config.enableDocSync,
|
|
619
|
-
enableAwareness: this.config.enableAwarenessSync,
|
|
620
|
-
enableFileTransfer: this.config.enableFileTransfer,
|
|
621
|
-
});
|
|
622
|
-
|
|
623
|
-
// Always create the "custom" channel for application messages
|
|
624
|
-
// (e.g. device pairing). Must be in the initial offer so the
|
|
625
|
-
// remote peer receives it via ondatachannel.
|
|
626
|
-
pc.router.createChannel("custom", { ordered: true });
|
|
627
|
-
|
|
628
|
-
try {
|
|
629
|
-
const sdp = await pc.createOffer();
|
|
630
|
-
this.signaling?.sendOffer(peerId, sdp);
|
|
631
|
-
} catch (err) {
|
|
632
|
-
this.emit("error", { type: "offer-failed", peerId, error: err });
|
|
633
|
-
this.removePeer(peerId);
|
|
634
|
-
}
|
|
635
|
-
}
|
|
636
|
-
|
|
637
|
-
private async handleOffer(from: string, sdp: string): Promise<void> {
|
|
638
|
-
// Clean up any existing connection to this peer.
|
|
639
|
-
const existing = this.peerConnections.get(from);
|
|
640
|
-
if (existing) {
|
|
641
|
-
existing.destroy();
|
|
642
|
-
this.yjsChannels.get(from)?.destroy();
|
|
643
|
-
this.yjsChannels.delete(from);
|
|
644
|
-
this.fileChannels.get(from)?.destroy();
|
|
645
|
-
this.fileChannels.delete(from);
|
|
646
|
-
this.peerConnections.delete(from);
|
|
647
|
-
}
|
|
648
|
-
|
|
649
|
-
const pc = this.createPeerConnection(from);
|
|
650
|
-
|
|
651
|
-
try {
|
|
652
|
-
const answerSdp = await pc.setRemoteOffer(sdp);
|
|
653
|
-
this.signaling?.sendAnswer(from, answerSdp);
|
|
654
|
-
} catch (err) {
|
|
655
|
-
this.emit("error", { type: "answer-failed", peerId: from, error: err });
|
|
656
|
-
this.removePeer(from);
|
|
657
|
-
}
|
|
658
|
-
}
|
|
659
|
-
|
|
660
|
-
// ── Private: URL Building ───────────────────────────────────────────────
|
|
661
|
-
|
|
662
|
-
private buildSignalingUrl(): string {
|
|
663
|
-
// Use explicit signalingUrl if provided.
|
|
664
|
-
if (this.config.signalingUrl) {
|
|
665
|
-
let sigBase = this.config.signalingUrl;
|
|
666
|
-
while (sigBase.endsWith("/")) sigBase = sigBase.slice(0, -1);
|
|
667
|
-
sigBase = sigBase.replace(/^https:/, "wss:").replace(/^http:/, "ws:");
|
|
668
|
-
return `${sigBase}/ws/${encodeURIComponent(this.config.docId)}/signaling`;
|
|
669
|
-
}
|
|
670
|
-
|
|
671
|
-
let base = this.config.url;
|
|
672
|
-
|
|
673
|
-
// Remove trailing slashes.
|
|
674
|
-
while (base.endsWith("/")) {
|
|
675
|
-
base = base.slice(0, -1);
|
|
676
|
-
}
|
|
677
|
-
|
|
678
|
-
// Convert http(s) to ws(s).
|
|
679
|
-
base = base.replace(/^https:/, "wss:").replace(/^http:/, "ws:");
|
|
680
|
-
|
|
681
|
-
return `${base}/ws/${encodeURIComponent(this.config.docId)}/signaling`;
|
|
682
|
-
}
|
|
683
|
-
}
|