@abraca/dabra 2.101.0 → 2.103.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/dist/abracadabra-provider.cjs +6673 -6543
- package/dist/abracadabra-provider.cjs.map +1 -1
- package/dist/esm/AbracadabraBaseProvider.js +558 -0
- package/dist/esm/AbracadabraBaseProvider.js.map +1 -0
- package/dist/esm/AbracadabraClient.js +1424 -0
- package/dist/esm/AbracadabraClient.js.map +1 -0
- package/dist/esm/AbracadabraProvider.js +547 -0
- package/dist/esm/AbracadabraProvider.js.map +1 -0
- package/dist/esm/AbracadabraWS.js +398 -0
- package/dist/esm/AbracadabraWS.js.map +1 -0
- package/dist/esm/BackgroundSyncManager.js +571 -0
- package/dist/esm/BackgroundSyncManager.js.map +1 -0
- package/dist/esm/BackgroundSyncPersistence.js +62 -0
- package/dist/esm/BackgroundSyncPersistence.js.map +1 -0
- package/dist/esm/ChatClient.js +176 -0
- package/dist/esm/ChatClient.js.map +1 -0
- package/dist/esm/CloseEvents.js +45 -0
- package/dist/esm/CloseEvents.js.map +1 -0
- package/dist/esm/ContentManager.js +153 -0
- package/dist/esm/ContentManager.js.map +1 -0
- package/dist/esm/CoverReconcile.js +124 -0
- package/dist/esm/CoverReconcile.js.map +1 -0
- package/dist/esm/CryptoIdentityKeystore.js +580 -0
- package/dist/esm/CryptoIdentityKeystore.js.map +1 -0
- package/dist/esm/DeviceRegistrationService.js +158 -0
- package/dist/esm/DeviceRegistrationService.js.map +1 -0
- package/dist/esm/DocConverters.js +1300 -0
- package/dist/esm/DocConverters.js.map +1 -0
- package/dist/esm/DocKeyManager.js +145 -0
- package/dist/esm/DocKeyManager.js.map +1 -0
- package/dist/esm/DocTypes.js +792 -0
- package/dist/esm/DocTypes.js.map +1 -0
- package/dist/esm/DocUtils.js +180 -0
- package/dist/esm/DocUtils.js.map +1 -0
- package/dist/esm/DocumentCache.js +131 -0
- package/dist/esm/DocumentCache.js.map +1 -0
- package/dist/esm/DocumentManager.js +240 -0
- package/dist/esm/DocumentManager.js.map +1 -0
- package/dist/esm/E2EAbracadabraProvider.js +273 -0
- package/dist/esm/E2EAbracadabraProvider.js.map +1 -0
- package/dist/esm/E2EOfflineStore.js +53 -0
- package/dist/esm/E2EOfflineStore.js.map +1 -0
- package/dist/esm/EncryptedChatClient.js +156 -0
- package/dist/esm/EncryptedChatClient.js.map +1 -0
- package/dist/esm/EncryptedY.js +115 -0
- package/dist/esm/EncryptedY.js.map +1 -0
- package/dist/esm/EventEmitter.js +40 -0
- package/dist/esm/EventEmitter.js.map +1 -0
- package/dist/esm/FileBlobStore.js +410 -0
- package/dist/esm/FileBlobStore.js.map +1 -0
- package/dist/esm/IdentityDoc.js +413 -0
- package/dist/esm/IdentityDoc.js.map +1 -0
- package/dist/esm/IncomingMessage.js +39 -0
- package/dist/esm/IncomingMessage.js.map +1 -0
- package/dist/esm/LifecycleGate.js +124 -0
- package/dist/esm/LifecycleGate.js.map +1 -0
- package/dist/esm/MessageReceiver.js +86 -0
- package/dist/esm/MessageReceiver.js.map +1 -0
- package/dist/esm/MessageSender.js +19 -0
- package/dist/esm/MessageSender.js.map +1 -0
- package/dist/esm/MetaManager.js +112 -0
- package/dist/esm/MetaManager.js.map +1 -0
- package/dist/esm/MnemonicKeyDerivation.js +137 -0
- package/dist/esm/MnemonicKeyDerivation.js.map +1 -0
- package/dist/esm/NodeConnect.js +63 -0
- package/dist/esm/NodeConnect.js.map +1 -0
- package/dist/esm/NodeIdentity.js +212 -0
- package/dist/esm/NodeIdentity.js.map +1 -0
- package/dist/esm/NotificationsClient.js +136 -0
- package/dist/esm/NotificationsClient.js.map +1 -0
- package/dist/esm/OfflineStore.js +291 -0
- package/dist/esm/OfflineStore.js.map +1 -0
- package/dist/esm/OutgoingMessage.js +18 -0
- package/dist/esm/OutgoingMessage.js.map +1 -0
- package/dist/esm/OutgoingMessages/AuthenticationMessage.js +24 -0
- package/dist/esm/OutgoingMessages/AuthenticationMessage.js.map +1 -0
- package/dist/esm/OutgoingMessages/AwarenessMessage.js +28 -0
- package/dist/esm/OutgoingMessages/AwarenessMessage.js.map +1 -0
- package/dist/esm/OutgoingMessages/CloseMessage.js +21 -0
- package/dist/esm/OutgoingMessages/CloseMessage.js.map +1 -0
- package/dist/esm/OutgoingMessages/QueryAwarenessMessage.js +21 -0
- package/dist/esm/OutgoingMessages/QueryAwarenessMessage.js.map +1 -0
- package/dist/esm/OutgoingMessages/StatelessMessage.js +22 -0
- package/dist/esm/OutgoingMessages/StatelessMessage.js.map +1 -0
- package/dist/esm/OutgoingMessages/SubdocMessage.js +34 -0
- package/dist/esm/OutgoingMessages/SubdocMessage.js.map +1 -0
- package/dist/esm/OutgoingMessages/SyncStepOneMessage.js +24 -0
- package/dist/esm/OutgoingMessages/SyncStepOneMessage.js.map +1 -0
- package/dist/esm/OutgoingMessages/UpdateMessage.js +23 -0
- package/dist/esm/OutgoingMessages/UpdateMessage.js.map +1 -0
- package/dist/esm/PerfCounters.js +336 -0
- package/dist/esm/PerfCounters.js.map +1 -0
- package/dist/esm/QueryClient.js +117 -0
- package/dist/esm/QueryClient.js.map +1 -0
- package/dist/esm/RpcClient.js +456 -0
- package/dist/esm/RpcClient.js.map +1 -0
- package/dist/esm/SchemaTypes.js +38 -0
- package/dist/esm/SchemaTypes.js.map +1 -0
- package/dist/esm/SearchIndex.js +167 -0
- package/dist/esm/SearchIndex.js.map +1 -0
- package/dist/esm/ServerRegistry.js +139 -0
- package/dist/esm/ServerRegistry.js.map +1 -0
- package/dist/esm/ServerReset.js +170 -0
- package/dist/esm/ServerReset.js.map +1 -0
- package/dist/esm/TokenManager.js +236 -0
- package/dist/esm/TokenManager.js.map +1 -0
- package/dist/esm/TreeManager.js +655 -0
- package/dist/esm/TreeManager.js.map +1 -0
- package/dist/esm/TreeTimestamps.js +61 -0
- package/dist/esm/TreeTimestamps.js.map +1 -0
- package/dist/esm/auth.js +43 -0
- package/dist/esm/auth.js.map +1 -0
- package/dist/esm/awarenessStatesToArray.js +13 -0
- package/dist/esm/awarenessStatesToArray.js.map +1 -0
- package/dist/esm/docIds.js +53 -0
- package/dist/esm/docIds.js.map +1 -0
- package/dist/esm/encryptedContent.js +21 -0
- package/dist/esm/encryptedContent.js.map +1 -0
- package/dist/esm/index.js +61 -0
- package/dist/esm/messageRecord.js +64 -0
- package/dist/esm/messageRecord.js.map +1 -0
- package/dist/esm/sync/BroadcastChannelSync.js +160 -0
- package/dist/esm/sync/BroadcastChannelSync.js.map +1 -0
- package/dist/esm/types.js +54 -0
- package/dist/esm/types.js.map +1 -0
- package/dist/esm/webrtc/AbracadabraWebRTC.js +483 -0
- package/dist/esm/webrtc/AbracadabraWebRTC.js.map +1 -0
- package/dist/esm/webrtc/DataChannelRouter.js +124 -0
- package/dist/esm/webrtc/DataChannelRouter.js.map +1 -0
- package/dist/esm/webrtc/DevicePairingChannel.js +335 -0
- package/dist/esm/webrtc/DevicePairingChannel.js.map +1 -0
- package/dist/esm/webrtc/E2EEChannel.js +137 -0
- package/dist/esm/webrtc/E2EEChannel.js.map +1 -0
- package/dist/esm/webrtc/FileTransferChannel.js +250 -0
- package/dist/esm/webrtc/FileTransferChannel.js.map +1 -0
- package/dist/esm/webrtc/ManualSignaling.js +161 -0
- package/dist/esm/webrtc/ManualSignaling.js.map +1 -0
- package/dist/esm/webrtc/PeerConnection.js +96 -0
- package/dist/esm/webrtc/PeerConnection.js.map +1 -0
- package/dist/esm/webrtc/SignalingSocket.js +274 -0
- package/dist/esm/webrtc/SignalingSocket.js.map +1 -0
- package/dist/esm/webrtc/YjsDataChannel.js +135 -0
- package/dist/esm/webrtc/YjsDataChannel.js.map +1 -0
- package/dist/esm/webrtc/types.js +29 -0
- package/dist/esm/webrtc/types.js.map +1 -0
- package/dist/esm/x25519Convert.js +69 -0
- package/dist/esm/x25519Convert.js.map +1 -0
- package/dist/index.d.ts +26 -11
- package/package.json +6 -4
- package/dist/abracadabra-provider.esm.js +0 -14860
- package/dist/abracadabra-provider.esm.js.map +0 -1
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"DataChannelRouter.js","names":[],"sources":["../../../src/webrtc/DataChannelRouter.ts"],"sourcesContent":["import EventEmitter from \"../EventEmitter.ts\";\nimport type { E2EEChannel } from \"./E2EEChannel.ts\";\nimport { CHANNEL_NAMES } from \"./types.ts\";\n\n/** Name of the data channel used for E2EE key exchange. */\nexport const KEY_EXCHANGE_CHANNEL = \"key-exchange\";\n\nexport class DataChannelRouter extends EventEmitter {\n\tprivate channels = new Map<string, RTCDataChannel>();\n\tprivate encryptor: E2EEChannel | null = null;\n\t/** Channels excluded from encryption (key-exchange itself, awareness). */\n\tprivate plaintextChannels = new Set<string>([KEY_EXCHANGE_CHANNEL]);\n\n\tconstructor(private connection: RTCPeerConnection) {\n\t\tsuper();\n\n\t\t// Accept incoming data channels from the remote peer.\n\t\tthis.connection.ondatachannel = (event) => {\n\t\t\tthis.registerChannel(event.channel);\n\t\t};\n\t}\n\n\t/** Attach an E2EE encryptor. All channels (except key-exchange) will be encrypted. */\n\tsetEncryptor(encryptor: E2EEChannel): void {\n\t\tthis.encryptor = encryptor;\n\t}\n\n\t/** Create a named data channel (initiator side). */\n\tcreateChannel(\n\t\tname: string,\n\t\toptions?: RTCDataChannelInit,\n\t): RTCDataChannel {\n\t\tconst channel = this.connection.createDataChannel(name, options);\n\t\tthis.registerChannel(channel);\n\t\treturn channel;\n\t}\n\n\t/** Create the standard set of channels for Abracadabra WebRTC. */\n\tcreateDefaultChannels(opts: {\n\t\tenableDocSync: boolean;\n\t\tenableAwareness: boolean;\n\t\tenableFileTransfer: boolean;\n\t}): void {\n\t\tif (opts.enableDocSync) {\n\t\t\tthis.createChannel(CHANNEL_NAMES.YJS_SYNC, {\n\t\t\t\tordered: true,\n\t\t\t});\n\t\t}\n\n\t\tif (opts.enableAwareness) {\n\t\t\tthis.createChannel(CHANNEL_NAMES.AWARENESS, {\n\t\t\t\tordered: false,\n\t\t\t\tmaxRetransmits: 0,\n\t\t\t});\n\t\t}\n\n\t\tif (opts.enableFileTransfer) {\n\t\t\tthis.createChannel(CHANNEL_NAMES.FILE_TRANSFER, {\n\t\t\t\tordered: true,\n\t\t\t});\n\t\t}\n\t}\n\n\t/**\n\t * Create namespaced channels for a child/subdocument.\n\t * Channel names are prefixed with `{childId}:` to avoid collisions.\n\t */\n\tcreateSubdocChannels(childId: string, opts: {\n\t\tenableDocSync: boolean;\n\t\tenableAwareness: boolean;\n\t}): void {\n\t\tif (opts.enableDocSync) {\n\t\t\tthis.createChannel(`${childId}:${CHANNEL_NAMES.YJS_SYNC}`, {\n\t\t\t\tordered: true,\n\t\t\t});\n\t\t}\n\t\tif (opts.enableAwareness) {\n\t\t\tthis.createChannel(`${childId}:${CHANNEL_NAMES.AWARENESS}`, {\n\t\t\t\tordered: false,\n\t\t\t\tmaxRetransmits: 0,\n\t\t\t});\n\t\t}\n\t}\n\n\tgetChannel(name: string): RTCDataChannel | null {\n\t\treturn this.channels.get(name) ?? null;\n\t}\n\n\tisOpen(name: string): boolean {\n\t\treturn this.channels.get(name)?.readyState === \"open\";\n\t}\n\n\t/**\n\t * Send data on a named channel, encrypting if E2EE is active.\n\t * Falls back to plaintext if no encryptor is set or for exempt channels.\n\t */\n\tasync send(name: string, data: Uint8Array): Promise<boolean> {\n\t\tconst channel = this.channels.get(name);\n\t\tif (!channel || channel.readyState !== \"open\") return false;\n\n\t\tif (this.encryptor?.isEstablished && !this.plaintextChannels.has(name)) {\n\t\t\tconst encrypted = await this.encryptor.encrypt(data);\n\t\t\tchannel.send(encrypted as unknown as ArrayBuffer);\n\t\t} else {\n\t\t\tchannel.send(data as unknown as ArrayBuffer);\n\t\t}\n\t\treturn true;\n\t}\n\n\tprivate registerChannel(channel: RTCDataChannel): void {\n\t\tchannel.binaryType = \"arraybuffer\";\n\t\tthis.channels.set(channel.label, channel);\n\n\t\tchannel.onopen = () => {\n\t\t\tthis.emit(\"channelOpen\", { name: channel.label, channel });\n\t\t};\n\n\t\tchannel.onclose = () => {\n\t\t\tthis.emit(\"channelClose\", { name: channel.label });\n\t\t\tthis.channels.delete(channel.label);\n\t\t};\n\n\t\tchannel.onmessage = async (event) => {\n\t\t\tconst name = channel.label;\n\t\t\tlet data = event.data;\n\n\t\t\t// Decrypt incoming data if E2EE is active (skip plaintext channels).\n\t\t\tif (\n\t\t\t\tthis.encryptor?.isEstablished &&\n\t\t\t\t!this.plaintextChannels.has(name) &&\n\t\t\t\t(data instanceof ArrayBuffer || data instanceof Uint8Array)\n\t\t\t) {\n\t\t\t\ttry {\n\t\t\t\t\tconst buf =\n\t\t\t\t\t\tdata instanceof ArrayBuffer ? new Uint8Array(data) : data;\n\t\t\t\t\tdata = await this.encryptor.decrypt(buf);\n\t\t\t\t} catch (err) {\n\t\t\t\t\tthis.emit(\"channelError\", {\n\t\t\t\t\t\tname,\n\t\t\t\t\t\terror: err,\n\t\t\t\t\t});\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tthis.emit(\"channelMessage\", { name, data });\n\t\t};\n\n\t\tchannel.onerror = (event) => {\n\t\t\tthis.emit(\"channelError\", {\n\t\t\t\tname: channel.label,\n\t\t\t\terror: event,\n\t\t\t});\n\t\t};\n\n\t\t// If the channel is already open (can happen with ondatachannel),\n\t\t// emit immediately.\n\t\tif (channel.readyState === \"open\") {\n\t\t\tthis.emit(\"channelOpen\", { name: channel.label, channel });\n\t\t}\n\t}\n\n\tclose(): void {\n\t\tfor (const channel of this.channels.values()) {\n\t\t\ttry {\n\t\t\t\tchannel.close();\n\t\t\t} catch {\n\t\t\t\t// Ignore\n\t\t\t}\n\t\t}\n\t\tthis.channels.clear();\n\t}\n\n\tdestroy(): void {\n\t\tthis.close();\n\t\tthis.connection.ondatachannel = null;\n\t\tthis.removeAllListeners();\n\t}\n}\n"],"mappings":";;;;;AAKA,MAAa,uBAAuB;AAEpC,IAAa,oBAAb,cAAuC,aAAa;CAMnD,YAAY,AAAQ,YAA+B;AAClD,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RTC } from "./AbracadabraWebRTC.js";
|
|
4
|
+
import { sha256 } from "@noble/hashes/sha2.js";
|
|
5
|
+
|
|
6
|
+
//#region packages/provider/src/webrtc/DevicePairingChannel.ts
|
|
7
|
+
/**
|
|
8
|
+
* DevicePairingChannel
|
|
9
|
+
*
|
|
10
|
+
* Enables cross-device identity pairing over an E2EE WebRTC data channel.
|
|
11
|
+
* Device A (approver) creates a pairing session with a short code. Device B
|
|
12
|
+
* (requester) joins with the code. After E2EE is established, Device B sends
|
|
13
|
+
* its public key and Device A registers it via `addKey()`.
|
|
14
|
+
*
|
|
15
|
+
* Reuses the existing WebRTC stack: SignalingSocket, PeerConnection,
|
|
16
|
+
* DataChannelRouter, and E2EEChannel (X25519 ECDH + AES-256-GCM).
|
|
17
|
+
*/
|
|
18
|
+
/** Ambiguity-free charset (no 0/O/1/I). */
|
|
19
|
+
const CODE_CHARSET = "ABCDEFGHJKLMNPQRSTUVWXYZ23456789";
|
|
20
|
+
const CODE_LENGTH = 6;
|
|
21
|
+
const PAIRING_TIMEOUT_MS = 300 * 1e3;
|
|
22
|
+
const SIGNALING_CONNECT_TIMEOUT_MS = 5e3;
|
|
23
|
+
function generatePairingCode() {
|
|
24
|
+
const bytes = crypto.getRandomValues(new Uint8Array(CODE_LENGTH));
|
|
25
|
+
return Array.from(bytes).map((b) => CODE_CHARSET[b % 32]).join("");
|
|
26
|
+
}
|
|
27
|
+
function codeToRoomId(code) {
|
|
28
|
+
const hash = sha256(new TextEncoder().encode(code.toUpperCase()));
|
|
29
|
+
return `__pairing_${Array.from(hash.slice(0, 8)).map((b) => b.toString(16).padStart(2, "0")).join("")}`;
|
|
30
|
+
}
|
|
31
|
+
var DevicePairingChannel = class DevicePairingChannel extends EventEmitter {
|
|
32
|
+
constructor(role, pairingCode, config) {
|
|
33
|
+
super();
|
|
34
|
+
this.config = config;
|
|
35
|
+
this.webrtc = null;
|
|
36
|
+
this.timeoutHandle = null;
|
|
37
|
+
this._destroyed = false;
|
|
38
|
+
this._pendingRequest = null;
|
|
39
|
+
this._connectedPeerId = null;
|
|
40
|
+
this._usingFallback = false;
|
|
41
|
+
this.role = role;
|
|
42
|
+
this.pairingCode = pairingCode;
|
|
43
|
+
}
|
|
44
|
+
/**
|
|
45
|
+
* Create an approver session (Device A). Returns the channel and a
|
|
46
|
+
* 6-character pairing code to share with Device B.
|
|
47
|
+
*/
|
|
48
|
+
static createApprover(config) {
|
|
49
|
+
const code = generatePairingCode();
|
|
50
|
+
const channel = new DevicePairingChannel("approver", code, config);
|
|
51
|
+
channel.start();
|
|
52
|
+
return {
|
|
53
|
+
channel,
|
|
54
|
+
pairingCode: code
|
|
55
|
+
};
|
|
56
|
+
}
|
|
57
|
+
/**
|
|
58
|
+
* Create a requester session (Device B). Joins with a pairing code
|
|
59
|
+
* obtained from Device A.
|
|
60
|
+
*/
|
|
61
|
+
static createRequester(config, pairingCode) {
|
|
62
|
+
const channel = new DevicePairingChannel("requester", pairingCode.toUpperCase().replace(/[^A-Z2-9]/g, ""), config);
|
|
63
|
+
channel.start();
|
|
64
|
+
return channel;
|
|
65
|
+
}
|
|
66
|
+
/**
|
|
67
|
+
* Approve the pending pairing request. Calls `client.addKey()` to
|
|
68
|
+
* register Device B's public key, then notifies Device B.
|
|
69
|
+
*
|
|
70
|
+
* @param client Authenticated REST client.
|
|
71
|
+
* @param masterPublicKey Approver's account-level Ed25519 public key (base64url).
|
|
72
|
+
* Sent to Device B so it can adopt the master's identity doc.
|
|
73
|
+
*/
|
|
74
|
+
async approve(client, masterPublicKey) {
|
|
75
|
+
if (this.role !== "approver") return {
|
|
76
|
+
success: false,
|
|
77
|
+
error: "Only the approver can approve"
|
|
78
|
+
};
|
|
79
|
+
if (!this._pendingRequest) return {
|
|
80
|
+
success: false,
|
|
81
|
+
error: "No pending pairing request"
|
|
82
|
+
};
|
|
83
|
+
if (!this._connectedPeerId) return {
|
|
84
|
+
success: false,
|
|
85
|
+
error: "Peer not connected"
|
|
86
|
+
};
|
|
87
|
+
const req = this._pendingRequest;
|
|
88
|
+
try {
|
|
89
|
+
await client.addKey({
|
|
90
|
+
publicKey: req.publicKey,
|
|
91
|
+
deviceName: req.deviceName,
|
|
92
|
+
x25519Key: req.x25519Key
|
|
93
|
+
});
|
|
94
|
+
this.sendMessage({
|
|
95
|
+
type: "pair-approved",
|
|
96
|
+
masterPublicKey
|
|
97
|
+
});
|
|
98
|
+
this._pendingRequest = null;
|
|
99
|
+
this.emit("pairingComplete", { success: true });
|
|
100
|
+
return { success: true };
|
|
101
|
+
} catch (err) {
|
|
102
|
+
const error = err?.message ?? "Failed to register device key";
|
|
103
|
+
this.sendMessage({
|
|
104
|
+
type: "pair-rejected",
|
|
105
|
+
reason: error
|
|
106
|
+
});
|
|
107
|
+
this._pendingRequest = null;
|
|
108
|
+
const result = {
|
|
109
|
+
success: false,
|
|
110
|
+
error
|
|
111
|
+
};
|
|
112
|
+
this.emit("pairingComplete", result);
|
|
113
|
+
return result;
|
|
114
|
+
}
|
|
115
|
+
}
|
|
116
|
+
/**
|
|
117
|
+
* Approve via server-side device invite. Creates a single-use invite code
|
|
118
|
+
* and sends it to Device B over the E2EE channel. Device B redeems it
|
|
119
|
+
* independently via HTTP — Device A can go offline after this.
|
|
120
|
+
*
|
|
121
|
+
* @param client Authenticated REST client.
|
|
122
|
+
* @param masterPublicKey Approver's account-level Ed25519 public key (base64url).
|
|
123
|
+
* Sent to Device B so it can adopt the master's identity doc.
|
|
124
|
+
*/
|
|
125
|
+
async approveWithInvite(client, masterPublicKey) {
|
|
126
|
+
if (this.role !== "approver") return {
|
|
127
|
+
success: false,
|
|
128
|
+
error: "Only the approver can approve"
|
|
129
|
+
};
|
|
130
|
+
if (!this._pendingRequest) return {
|
|
131
|
+
success: false,
|
|
132
|
+
error: "No pending pairing request"
|
|
133
|
+
};
|
|
134
|
+
if (!this._connectedPeerId) return {
|
|
135
|
+
success: false,
|
|
136
|
+
error: "Peer not connected"
|
|
137
|
+
};
|
|
138
|
+
try {
|
|
139
|
+
const { code } = await client.createDeviceInvite();
|
|
140
|
+
this.sendMessage({
|
|
141
|
+
type: "pair-invite-code",
|
|
142
|
+
code,
|
|
143
|
+
masterPublicKey
|
|
144
|
+
});
|
|
145
|
+
this._pendingRequest = null;
|
|
146
|
+
this.emit("pairingComplete", { success: true });
|
|
147
|
+
return { success: true };
|
|
148
|
+
} catch (err) {
|
|
149
|
+
const error = err?.message ?? "Failed to create device invite";
|
|
150
|
+
this.sendMessage({
|
|
151
|
+
type: "pair-rejected",
|
|
152
|
+
reason: error
|
|
153
|
+
});
|
|
154
|
+
this._pendingRequest = null;
|
|
155
|
+
const result = {
|
|
156
|
+
success: false,
|
|
157
|
+
error
|
|
158
|
+
};
|
|
159
|
+
this.emit("pairingComplete", result);
|
|
160
|
+
return result;
|
|
161
|
+
}
|
|
162
|
+
}
|
|
163
|
+
/**
|
|
164
|
+
* Reject the pending pairing request.
|
|
165
|
+
*/
|
|
166
|
+
reject(reason = "Rejected by user") {
|
|
167
|
+
if (this.role !== "approver" || !this._pendingRequest) return;
|
|
168
|
+
this.sendMessage({
|
|
169
|
+
type: "pair-rejected",
|
|
170
|
+
reason
|
|
171
|
+
});
|
|
172
|
+
this._pendingRequest = null;
|
|
173
|
+
this.emit("pairingComplete", {
|
|
174
|
+
success: false,
|
|
175
|
+
error: reason
|
|
176
|
+
});
|
|
177
|
+
}
|
|
178
|
+
/**
|
|
179
|
+
* Send a pairing request to Device A. Call this after the "connected"
|
|
180
|
+
* event fires.
|
|
181
|
+
*/
|
|
182
|
+
requestPairing(request) {
|
|
183
|
+
if (this.role !== "requester") return;
|
|
184
|
+
this.sendMessage({
|
|
185
|
+
type: "pair-request",
|
|
186
|
+
publicKey: request.publicKey,
|
|
187
|
+
x25519Key: request.x25519Key,
|
|
188
|
+
deviceName: request.deviceName
|
|
189
|
+
});
|
|
190
|
+
}
|
|
191
|
+
get isDestroyed() {
|
|
192
|
+
return this._destroyed;
|
|
193
|
+
}
|
|
194
|
+
destroy() {
|
|
195
|
+
if (this._destroyed) return;
|
|
196
|
+
this._destroyed = true;
|
|
197
|
+
if (this.timeoutHandle) {
|
|
198
|
+
clearTimeout(this.timeoutHandle);
|
|
199
|
+
this.timeoutHandle = null;
|
|
200
|
+
}
|
|
201
|
+
if (this.webrtc) {
|
|
202
|
+
this.webrtc.destroy();
|
|
203
|
+
this.webrtc = null;
|
|
204
|
+
}
|
|
205
|
+
this.removeAllListeners();
|
|
206
|
+
}
|
|
207
|
+
async resolveToken(serverUrl) {
|
|
208
|
+
if (this.config.token && serverUrl === this.config.serverUrl) return this.config.token;
|
|
209
|
+
let base = serverUrl ?? this.config.serverUrl;
|
|
210
|
+
while (base.endsWith("/")) base = base.slice(0, -1);
|
|
211
|
+
const resp = await fetch(`${base}/auth/pairing-token`, { method: "POST" });
|
|
212
|
+
if (!resp.ok) throw new Error(`Failed to fetch pairing token: ${resp.status} ${resp.statusText}`);
|
|
213
|
+
const { token } = await resp.json();
|
|
214
|
+
return token;
|
|
215
|
+
}
|
|
216
|
+
start() {
|
|
217
|
+
this.connectToServer(this.config.serverUrl);
|
|
218
|
+
this.timeoutHandle = setTimeout(() => {
|
|
219
|
+
if (!this._destroyed) {
|
|
220
|
+
this.emit("error", /* @__PURE__ */ new Error("Pairing timed out"));
|
|
221
|
+
this.destroy();
|
|
222
|
+
}
|
|
223
|
+
}, PAIRING_TIMEOUT_MS);
|
|
224
|
+
}
|
|
225
|
+
connectToServer(serverUrl, signalingUrl) {
|
|
226
|
+
const roomId = codeToRoomId(this.pairingCode);
|
|
227
|
+
const tokenPromise = this.resolveToken(serverUrl);
|
|
228
|
+
const tokenFactory = async () => {
|
|
229
|
+
const t = await tokenPromise;
|
|
230
|
+
if (typeof t === "function") return await t();
|
|
231
|
+
return t;
|
|
232
|
+
};
|
|
233
|
+
if (!this.config.iceServers) new AbracadabraClient({ url: serverUrl }).getIceServers().then((servers) => {
|
|
234
|
+
if (servers.length > 0) this._resolvedIceServers = servers;
|
|
235
|
+
});
|
|
236
|
+
this.webrtc = new AbracadabraWebRTC({
|
|
237
|
+
docId: roomId,
|
|
238
|
+
url: serverUrl,
|
|
239
|
+
signalingUrl: signalingUrl ?? void 0,
|
|
240
|
+
token: tokenFactory,
|
|
241
|
+
iceServers: this.config.iceServers ?? this._resolvedIceServers,
|
|
242
|
+
e2ee: this.config.e2ee,
|
|
243
|
+
enableDocSync: false,
|
|
244
|
+
enableAwarenessSync: false,
|
|
245
|
+
enableFileTransfer: false,
|
|
246
|
+
autoConnect: false,
|
|
247
|
+
WebSocketPolyfill: this.config.WebSocketPolyfill
|
|
248
|
+
});
|
|
249
|
+
let connected = false;
|
|
250
|
+
this.webrtc.on("connected", () => {
|
|
251
|
+
connected = true;
|
|
252
|
+
});
|
|
253
|
+
this.webrtc.on("e2eeEstablished", ({ peerId }) => {
|
|
254
|
+
this._connectedPeerId = peerId;
|
|
255
|
+
this.emit("connected");
|
|
256
|
+
});
|
|
257
|
+
this.webrtc.on("customMessage", ({ peerId, payload }) => {
|
|
258
|
+
this.handleMessage(peerId, payload);
|
|
259
|
+
});
|
|
260
|
+
this.webrtc.on("e2eeFailed", ({ peerId, error }) => {
|
|
261
|
+
if (!this._destroyed) this.emit("error", /* @__PURE__ */ new Error(`E2EE failed: ${error?.message ?? error}`));
|
|
262
|
+
});
|
|
263
|
+
this.webrtc.on("error", (err) => {
|
|
264
|
+
if (!this._destroyed) this.emit("error", /* @__PURE__ */ new Error(`WebRTC: ${err?.type ?? err?.message ?? "unknown"}`));
|
|
265
|
+
});
|
|
266
|
+
this.webrtc.on("peerLeft", () => {
|
|
267
|
+
if (!this._destroyed) this.emit("error", /* @__PURE__ */ new Error("Peer disconnected"));
|
|
268
|
+
});
|
|
269
|
+
this.webrtc.on("signalingError", (err) => {
|
|
270
|
+
this.emit("error", /* @__PURE__ */ new Error(`Signaling: ${err.message}`));
|
|
271
|
+
});
|
|
272
|
+
if (this.config.fallbackSignalingUrl && !signalingUrl) {
|
|
273
|
+
const fallbackTimer = setTimeout(() => {
|
|
274
|
+
if (this._destroyed || connected) return;
|
|
275
|
+
if (this.webrtc) {
|
|
276
|
+
this.webrtc.destroy();
|
|
277
|
+
this.webrtc = null;
|
|
278
|
+
}
|
|
279
|
+
this._usingFallback = true;
|
|
280
|
+
this.emit("fallback", { url: this.config.fallbackSignalingUrl });
|
|
281
|
+
this.connectToServer(this.config.fallbackSignalingUrl);
|
|
282
|
+
}, SIGNALING_CONNECT_TIMEOUT_MS);
|
|
283
|
+
this.webrtc.on("connected", () => clearTimeout(fallbackTimer));
|
|
284
|
+
}
|
|
285
|
+
this.webrtc.connect();
|
|
286
|
+
}
|
|
287
|
+
/** Whether the connection fell back to the fallback signaling server. */
|
|
288
|
+
get usingFallback() {
|
|
289
|
+
return this._usingFallback;
|
|
290
|
+
}
|
|
291
|
+
sendMessage(msg) {
|
|
292
|
+
if (!this.webrtc || !this._connectedPeerId) return;
|
|
293
|
+
this.webrtc.sendCustomMessage(this._connectedPeerId, JSON.stringify(msg));
|
|
294
|
+
}
|
|
295
|
+
handleMessage(peerId, payload) {
|
|
296
|
+
let msg;
|
|
297
|
+
try {
|
|
298
|
+
msg = JSON.parse(payload);
|
|
299
|
+
} catch {
|
|
300
|
+
return;
|
|
301
|
+
}
|
|
302
|
+
switch (msg.type) {
|
|
303
|
+
case "pair-request":
|
|
304
|
+
if (this.role !== "approver") return;
|
|
305
|
+
this._pendingRequest = {
|
|
306
|
+
publicKey: msg.publicKey,
|
|
307
|
+
x25519Key: msg.x25519Key,
|
|
308
|
+
deviceName: msg.deviceName
|
|
309
|
+
};
|
|
310
|
+
this.emit("pairingRequest", this._pendingRequest);
|
|
311
|
+
break;
|
|
312
|
+
case "pair-approved":
|
|
313
|
+
if (this.role !== "requester") return;
|
|
314
|
+
this.emit("approved", { masterPublicKey: msg.masterPublicKey });
|
|
315
|
+
this.emit("pairingComplete", { success: true });
|
|
316
|
+
break;
|
|
317
|
+
case "pair-rejected":
|
|
318
|
+
if (this.role !== "requester") return;
|
|
319
|
+
this.emit("rejected", msg.reason);
|
|
320
|
+
this.emit("pairingComplete", {
|
|
321
|
+
success: false,
|
|
322
|
+
error: msg.reason
|
|
323
|
+
});
|
|
324
|
+
break;
|
|
325
|
+
case "pair-invite-code":
|
|
326
|
+
if (this.role !== "requester") return;
|
|
327
|
+
this.emit("inviteCode", msg.code, msg.masterPublicKey);
|
|
328
|
+
break;
|
|
329
|
+
}
|
|
330
|
+
}
|
|
331
|
+
};
|
|
332
|
+
|
|
333
|
+
//#endregion
|
|
334
|
+
export { DevicePairingChannel };
|
|
335
|
+
//# sourceMappingURL=DevicePairingChannel.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"DevicePairingChannel.js","names":[],"sources":["../../../src/webrtc/DevicePairingChannel.ts"],"sourcesContent":["/**\n * DevicePairingChannel\n *\n * Enables cross-device identity pairing over an E2EE WebRTC data channel.\n * Device A (approver) creates a pairing session with a short code. Device B\n * (requester) joins with the code. After E2EE is established, Device B sends\n * its public key and Device A registers it via `addKey()`.\n *\n * Reuses the existing WebRTC stack: SignalingSocket, PeerConnection,\n * DataChannelRouter, and E2EEChannel (X25519 ECDH + AES-256-GCM).\n */\n\nimport { sha256 } from \"@noble/hashes/sha2.js\";\nimport EventEmitter from \"../EventEmitter.ts\";\nimport { AbracadabraClient } from \"../AbracadabraClient.ts\";\nimport { AbracadabraWebRTC } from \"./AbracadabraWebRTC.ts\";\nimport type { E2EEIdentity } from \"./E2EEChannel.ts\";\n\n// ── Constants ───────────────────────────────────────────────────────────────\n\n/** Ambiguity-free charset (no 0/O/1/I). */\nconst CODE_CHARSET = \"ABCDEFGHJKLMNPQRSTUVWXYZ23456789\";\nconst CODE_LENGTH = 6;\nconst PAIRING_TIMEOUT_MS = 5 * 60 * 1000; // 5 minutes\nconst SIGNALING_CONNECT_TIMEOUT_MS = 5_000; // 5 seconds before trying fallback\nconst PAIRING_CHANNEL = \"device-pairing\";\n\n// ── Types ───────────────────────────────────────────────────────────────────\n\nexport interface DevicePairingConfig {\n\t/** Server base URL (http/https). */\n\tserverUrl: string;\n\t/**\n\t * JWT token or async token factory for signaling auth.\n\t * When omitted, a short-lived anonymous pairing token is fetched automatically\n\t * from `POST /auth/pairing-token`.\n\t */\n\ttoken?: string | (() => string) | (() => Promise<string>);\n\t/** E2EE identity (Ed25519 public key + X25519 private key). */\n\te2ee: E2EEIdentity;\n\t/** ICE servers. Defaults to Google STUN. */\n\ticeServers?: RTCIceServer[];\n\t/**\n\t * Fallback signaling server URL. If the primary server is unreachable,\n\t * signaling will retry through this server. The actual pairing data is\n\t * E2EE-encrypted, so the relay server cannot read it.\n\t */\n\tfallbackSignalingUrl?: string;\n\t/** WebSocket polyfill (for Node.js). */\n\tWebSocketPolyfill?: any;\n}\n\nexport interface PairingRequest {\n\t/** Device B's Ed25519 public key (base64url). */\n\tpublicKey: string;\n\t/** Device B's X25519 public key (base64url). */\n\tx25519Key: string;\n\t/** Human-readable device label. */\n\tdeviceName: string;\n}\n\nexport interface PairingResult {\n\tsuccess: boolean;\n\terror?: string;\n}\n\ntype PairingRole = \"approver\" | \"requester\";\n\n// ── Internal wire messages ──────────────────────────────────────────────────\n\ninterface PairRequestMsg {\n\ttype: \"pair-request\";\n\tpublicKey: string;\n\tx25519Key: string;\n\tdeviceName: string;\n}\n\ninterface PairApprovedMsg {\n\ttype: \"pair-approved\";\n\t/** Approver's account-level Ed25519 public key (base64url). */\n\tmasterPublicKey?: string;\n}\n\ninterface PairInviteCodeMsg {\n\ttype: \"pair-invite-code\";\n\tcode: string;\n\t/** Approver's account-level Ed25519 public key (base64url). */\n\tmasterPublicKey?: string;\n}\n\ninterface PairRejectedMsg {\n\ttype: \"pair-rejected\";\n\treason: string;\n}\n\ntype PairingMsg = PairRequestMsg | PairApprovedMsg | PairRejectedMsg | PairInviteCodeMsg;\n\n// ── Helpers ─────────────────────────────────────────────────────────────────\n\nfunction generatePairingCode(): string {\n\tconst bytes = crypto.getRandomValues(new Uint8Array(CODE_LENGTH));\n\treturn Array.from(bytes)\n\t\t.map((b) => CODE_CHARSET[b % CODE_CHARSET.length])\n\t\t.join(\"\");\n}\n\nfunction codeToRoomId(code: string): string {\n\tconst hash = sha256(new TextEncoder().encode(code.toUpperCase()));\n\t// Take first 16 hex chars for the room ID.\n\tconst hex = Array.from(hash.slice(0, 8))\n\t\t.map((b) => b.toString(16).padStart(2, \"0\"))\n\t\t.join(\"\");\n\treturn `__pairing_${hex}`;\n}\n\n// ── DevicePairingChannel ────────────────────────────────────────────────────\n\nexport class DevicePairingChannel extends EventEmitter {\n\tprivate webrtc: AbracadabraWebRTC | null = null;\n\tprivate timeoutHandle: ReturnType<typeof setTimeout> | null = null;\n\tprivate _destroyed = false;\n\tprivate _pendingRequest: PairingRequest | null = null;\n\tprivate _connectedPeerId: string | null = null;\n\tprivate _usingFallback = false;\n\tprivate _resolvedIceServers: RTCIceServer[] | undefined;\n\n\treadonly role: PairingRole;\n\treadonly pairingCode: string;\n\n\tprivate constructor(\n\t\trole: PairingRole,\n\t\tpairingCode: string,\n\t\tprivate readonly config: DevicePairingConfig,\n\t) {\n\t\tsuper();\n\t\tthis.role = role;\n\t\tthis.pairingCode = pairingCode;\n\t}\n\n\t// ── Factory Methods ───────────────────────────────────────────────────\n\n\t/**\n\t * Create an approver session (Device A). Returns the channel and a\n\t * 6-character pairing code to share with Device B.\n\t */\n\tstatic createApprover(config: DevicePairingConfig): {\n\t\tchannel: DevicePairingChannel;\n\t\tpairingCode: string;\n\t} {\n\t\tconst code = generatePairingCode();\n\t\tconst channel = new DevicePairingChannel(\"approver\", code, config);\n\t\tchannel.start();\n\t\treturn { channel, pairingCode: code };\n\t}\n\n\t/**\n\t * Create a requester session (Device B). Joins with a pairing code\n\t * obtained from Device A.\n\t */\n\tstatic createRequester(\n\t\tconfig: DevicePairingConfig,\n\t\tpairingCode: string,\n\t): DevicePairingChannel {\n\t\tconst channel = new DevicePairingChannel(\n\t\t\t\"requester\",\n\t\t\tpairingCode.toUpperCase().replace(/[^A-Z2-9]/g, \"\"),\n\t\t\tconfig,\n\t\t);\n\t\tchannel.start();\n\t\treturn channel;\n\t}\n\n\t// ── Approver API ──────────────────────────────────────────────────────\n\n\t/**\n\t * Approve the pending pairing request. Calls `client.addKey()` to\n\t * register Device B's public key, then notifies Device B.\n\t *\n\t * @param client Authenticated REST client.\n\t * @param masterPublicKey Approver's account-level Ed25519 public key (base64url).\n\t * Sent to Device B so it can adopt the master's identity doc.\n\t */\n\tasync approve(client: AbracadabraClient, masterPublicKey?: string): Promise<PairingResult> {\n\t\tif (this.role !== \"approver\") {\n\t\t\treturn { success: false, error: \"Only the approver can approve\" };\n\t\t}\n\t\tif (!this._pendingRequest) {\n\t\t\treturn { success: false, error: \"No pending pairing request\" };\n\t\t}\n\t\tif (!this._connectedPeerId) {\n\t\t\treturn { success: false, error: \"Peer not connected\" };\n\t\t}\n\n\t\tconst req = this._pendingRequest;\n\n\t\ttry {\n\t\t\tawait client.addKey({\n\t\t\t\tpublicKey: req.publicKey,\n\t\t\t\tdeviceName: req.deviceName,\n\t\t\t\tx25519Key: req.x25519Key,\n\t\t\t});\n\n\t\t\tthis.sendMessage({ type: \"pair-approved\", masterPublicKey });\n\t\t\tthis._pendingRequest = null;\n\t\t\tthis.emit(\"pairingComplete\", { success: true } as PairingResult);\n\t\t\treturn { success: true };\n\t\t} catch (err: any) {\n\t\t\tconst error = err?.message ?? \"Failed to register device key\";\n\t\t\tthis.sendMessage({ type: \"pair-rejected\", reason: error });\n\t\t\tthis._pendingRequest = null;\n\t\t\tconst result: PairingResult = { success: false, error };\n\t\t\tthis.emit(\"pairingComplete\", result);\n\t\t\treturn result;\n\t\t}\n\t}\n\n\t/**\n\t * Approve via server-side device invite. Creates a single-use invite code\n\t * and sends it to Device B over the E2EE channel. Device B redeems it\n\t * independently via HTTP — Device A can go offline after this.\n\t *\n\t * @param client Authenticated REST client.\n\t * @param masterPublicKey Approver's account-level Ed25519 public key (base64url).\n\t * Sent to Device B so it can adopt the master's identity doc.\n\t */\n\tasync approveWithInvite(client: AbracadabraClient, masterPublicKey?: string): Promise<PairingResult> {\n\t\tif (this.role !== \"approver\") {\n\t\t\treturn { success: false, error: \"Only the approver can approve\" };\n\t\t}\n\t\tif (!this._pendingRequest) {\n\t\t\treturn { success: false, error: \"No pending pairing request\" };\n\t\t}\n\t\tif (!this._connectedPeerId) {\n\t\t\treturn { success: false, error: \"Peer not connected\" };\n\t\t}\n\n\t\ttry {\n\t\t\tconst { code } = await client.createDeviceInvite();\n\t\t\tthis.sendMessage({ type: \"pair-invite-code\", code, masterPublicKey });\n\t\t\tthis._pendingRequest = null;\n\t\t\tthis.emit(\"pairingComplete\", { success: true } as PairingResult);\n\t\t\treturn { success: true };\n\t\t} catch (err: any) {\n\t\t\tconst error = err?.message ?? \"Failed to create device invite\";\n\t\t\tthis.sendMessage({ type: \"pair-rejected\", reason: error });\n\t\t\tthis._pendingRequest = null;\n\t\t\tconst result: PairingResult = { success: false, error };\n\t\t\tthis.emit(\"pairingComplete\", result);\n\t\t\treturn result;\n\t\t}\n\t}\n\n\t/**\n\t * Reject the pending pairing request.\n\t */\n\treject(reason = \"Rejected by user\"): void {\n\t\tif (this.role !== \"approver\" || !this._pendingRequest) return;\n\t\tthis.sendMessage({ type: \"pair-rejected\", reason });\n\t\tthis._pendingRequest = null;\n\t\tthis.emit(\"pairingComplete\", {\n\t\t\tsuccess: false,\n\t\t\terror: reason,\n\t\t} as PairingResult);\n\t}\n\n\t// ── Requester API ─────────────────────────────────────────────────────\n\n\t/**\n\t * Send a pairing request to Device A. Call this after the \"connected\"\n\t * event fires.\n\t */\n\trequestPairing(request: PairingRequest): void {\n\t\tif (this.role !== \"requester\") return;\n\t\tthis.sendMessage({\n\t\t\ttype: \"pair-request\",\n\t\t\tpublicKey: request.publicKey,\n\t\t\tx25519Key: request.x25519Key,\n\t\t\tdeviceName: request.deviceName,\n\t\t});\n\t}\n\n\t// ── Lifecycle ─────────────────────────────────────────────────────────\n\n\tget isDestroyed(): boolean {\n\t\treturn this._destroyed;\n\t}\n\n\tdestroy(): void {\n\t\tif (this._destroyed) return;\n\t\tthis._destroyed = true;\n\n\t\tif (this.timeoutHandle) {\n\t\t\tclearTimeout(this.timeoutHandle);\n\t\t\tthis.timeoutHandle = null;\n\t\t}\n\n\t\tif (this.webrtc) {\n\t\t\tthis.webrtc.destroy();\n\t\t\tthis.webrtc = null;\n\t\t}\n\n\t\tthis.removeAllListeners();\n\t}\n\n\t// ── Private ─────────────────────────────────────────────────────────\n\n\tprivate async resolveToken(\n\t\tserverUrl?: string,\n\t): Promise<string | (() => string) | (() => Promise<string>)> {\n\t\t// Use provided token if connecting to the primary server.\n\t\tif (this.config.token && serverUrl === this.config.serverUrl) {\n\t\t\treturn this.config.token;\n\t\t}\n\n\t\t// Fetch a short-lived anonymous pairing token from the target server.\n\t\tlet base = serverUrl ?? this.config.serverUrl;\n\t\twhile (base.endsWith(\"/\")) base = base.slice(0, -1);\n\t\tconst resp = await fetch(`${base}/auth/pairing-token`, {\n\t\t\tmethod: \"POST\",\n\t\t});\n\t\tif (!resp.ok) {\n\t\t\tthrow new Error(\n\t\t\t\t`Failed to fetch pairing token: ${resp.status} ${resp.statusText}`,\n\t\t\t);\n\t\t}\n\t\tconst { token } = (await resp.json()) as { token: string };\n\t\treturn token;\n\t}\n\n\tprivate start(): void {\n\t\tthis.connectToServer(this.config.serverUrl);\n\n\t\t// Auto-destroy after timeout.\n\t\tthis.timeoutHandle = setTimeout(() => {\n\t\t\tif (!this._destroyed) {\n\t\t\t\tthis.emit(\"error\", new Error(\"Pairing timed out\"));\n\t\t\t\tthis.destroy();\n\t\t\t}\n\t\t}, PAIRING_TIMEOUT_MS);\n\t}\n\n\tprivate connectToServer(serverUrl: string, signalingUrl?: string): void {\n\t\tconst roomId = codeToRoomId(this.pairingCode);\n\n\t\t// Resolve token (possibly async) — uses a factory so SignalingSocket can await it.\n\t\tconst tokenPromise = this.resolveToken(serverUrl);\n\t\tconst tokenFactory = async (): Promise<string> => {\n\t\t\tconst t = await tokenPromise;\n\t\t\tif (typeof t === \"function\") return await t();\n\t\t\treturn t;\n\t\t};\n\n\t\t// Fetch ICE servers from the target server if none configured.\n\t\tif (!this.config.iceServers) {\n\t\t\tconst client = new AbracadabraClient({ url: serverUrl });\n\t\t\tclient.getIceServers().then((servers) => {\n\t\t\t\tif (servers.length > 0) this._resolvedIceServers = servers;\n\t\t\t});\n\t\t}\n\n\t\tthis.webrtc = new AbracadabraWebRTC({\n\t\t\tdocId: roomId,\n\t\t\turl: serverUrl,\n\t\t\tsignalingUrl: signalingUrl ?? undefined,\n\t\t\ttoken: tokenFactory,\n\t\t\ticeServers: this.config.iceServers ?? this._resolvedIceServers,\n\t\t\te2ee: this.config.e2ee,\n\t\t\tenableDocSync: false,\n\t\t\tenableAwarenessSync: false,\n\t\t\tenableFileTransfer: false,\n\t\t\tautoConnect: false,\n\t\t\tWebSocketPolyfill: this.config.WebSocketPolyfill,\n\t\t});\n\n\t\tlet connected = false;\n\n\t\tthis.webrtc.on(\"connected\", () => {\n\t\t\tconnected = true;\n\t\t});\n\n\t\tthis.webrtc.on(\"e2eeEstablished\", ({ peerId }: { peerId: string }) => {\n\t\t\tthis._connectedPeerId = peerId;\n\t\t\tthis.emit(\"connected\");\n\t\t});\n\n\t\tthis.webrtc.on(\n\t\t\t\"customMessage\",\n\t\t\t({ peerId, payload }: { peerId: string; payload: string }) => {\n\t\t\t\tthis.handleMessage(peerId, payload);\n\t\t\t},\n\t\t);\n\n\t\tthis.webrtc.on(\"e2eeFailed\", ({ peerId, error }: { peerId: string; error: any }) => {\n\t\t\tif (!this._destroyed) {\n\t\t\t\tthis.emit(\"error\", new Error(`E2EE failed: ${error?.message ?? error}`));\n\t\t\t}\n\t\t});\n\n\t\tthis.webrtc.on(\"error\", (err: any) => {\n\t\t\tif (!this._destroyed) {\n\t\t\t\tthis.emit(\"error\", new Error(`WebRTC: ${err?.type ?? err?.message ?? \"unknown\"}`));\n\t\t\t}\n\t\t});\n\n\t\tthis.webrtc.on(\"peerLeft\", () => {\n\t\t\tif (!this._destroyed) {\n\t\t\t\tthis.emit(\"error\", new Error(\"Peer disconnected\"));\n\t\t\t}\n\t\t});\n\n\t\tthis.webrtc.on(\n\t\t\t\"signalingError\",\n\t\t\t(err: { code: string; message: string }) => {\n\t\t\t\tthis.emit(\"error\", new Error(`Signaling: ${err.message}`));\n\t\t\t},\n\t\t);\n\n\t\t// If a fallback signaling server is configured, try it after a timeout.\n\t\tif (this.config.fallbackSignalingUrl && !signalingUrl) {\n\t\t\tconst fallbackTimer = setTimeout(() => {\n\t\t\t\tif (this._destroyed || connected) return;\n\t\t\t\t// Primary server didn't connect in time — try fallback.\n\t\t\t\tif (this.webrtc) {\n\t\t\t\t\tthis.webrtc.destroy();\n\t\t\t\t\tthis.webrtc = null;\n\t\t\t\t}\n\t\t\t\tthis._usingFallback = true;\n\t\t\t\tthis.emit(\"fallback\", { url: this.config.fallbackSignalingUrl });\n\t\t\t\tthis.connectToServer(\n\t\t\t\t\tthis.config.fallbackSignalingUrl!,\n\t\t\t\t);\n\t\t\t}, SIGNALING_CONNECT_TIMEOUT_MS);\n\n\t\t\t// Clear fallback timer if primary succeeds.\n\t\t\tthis.webrtc.on(\"connected\", () => clearTimeout(fallbackTimer));\n\t\t}\n\n\t\tthis.webrtc.connect();\n\t}\n\n\t/** Whether the connection fell back to the fallback signaling server. */\n\tget usingFallback(): boolean {\n\t\treturn this._usingFallback;\n\t}\n\n\tprivate sendMessage(msg: PairingMsg): void {\n\t\tif (!this.webrtc || !this._connectedPeerId) return;\n\t\t// Send via the custom message path — the E2EE layer on the data channel\n\t\t// encrypts all non-key-exchange traffic via the DataChannelRouter.\n\t\tthis.webrtc.sendCustomMessage(\n\t\t\tthis._connectedPeerId,\n\t\t\tJSON.stringify(msg),\n\t\t);\n\t}\n\n\tprivate handleMessage(peerId: string, payload: string): void {\n\t\tlet msg: PairingMsg;\n\t\ttry {\n\t\t\tmsg = JSON.parse(payload);\n\t\t} catch {\n\t\t\treturn;\n\t\t}\n\n\t\tswitch (msg.type) {\n\t\t\tcase \"pair-request\":\n\t\t\t\tif (this.role !== \"approver\") return;\n\t\t\t\tthis._pendingRequest = {\n\t\t\t\t\tpublicKey: msg.publicKey,\n\t\t\t\t\tx25519Key: msg.x25519Key,\n\t\t\t\t\tdeviceName: msg.deviceName,\n\t\t\t\t};\n\t\t\t\tthis.emit(\"pairingRequest\", this._pendingRequest);\n\t\t\t\tbreak;\n\n\t\t\tcase \"pair-approved\":\n\t\t\t\tif (this.role !== \"requester\") return;\n\t\t\t\tthis.emit(\"approved\", { masterPublicKey: msg.masterPublicKey });\n\t\t\t\tthis.emit(\"pairingComplete\", { success: true } as PairingResult);\n\t\t\t\tbreak;\n\n\t\t\tcase \"pair-rejected\":\n\t\t\t\tif (this.role !== \"requester\") return;\n\t\t\t\tthis.emit(\"rejected\", msg.reason);\n\t\t\t\tthis.emit(\"pairingComplete\", {\n\t\t\t\t\tsuccess: false,\n\t\t\t\t\terror: msg.reason,\n\t\t\t\t} as PairingResult);\n\t\t\t\tbreak;\n\n\t\t\tcase \"pair-invite-code\":\n\t\t\t\tif (this.role !== \"requester\") return;\n\t\t\t\tthis.emit(\"inviteCode\", msg.code, msg.masterPublicKey);\n\t\t\t\tbreak;\n\t\t}\n\t}\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;AAqBA,MAAM,eAAe;AACrB,MAAM,cAAc;AACpB,MAAM,qBAAqB,MAAS;AACpC,MAAM,+BAA+B;AA2ErC,SAAS,sBAA8B;CACtC,MAAM,QAAQ,OAAO,gBAAgB,IAAI,WAAW,YAAY,CAAC;AACjE,QAAO,MAAM,KAAK,MAAM,CACtB,KAAK,MAAM,aAAa,IAAI,IAAqB,CACjD,KAAK,GAAG;;AAGX,SAAS,aAAa,MAAsB;CAC3C,MAAM,OAAO,OAAO,IAAI,aAAa,CAAC,OAAO,KAAK,aAAa,CAAC,CAAC;AAKjE,QAAO,aAHK,MAAM,KAAK,KA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AAK,gBACJ,KAAK,OAAO,qBACZ;MACC,6BAA6B;AAGhC,QAAK,OAAO,GAAG,mBAAmB,aAAa,cAAc,CAAC;;AAG/D,OAAK,OAAO,SAAS;;;CAItB,IAAI,gBAAyB;AAC5B,SAAO,KAAK;;CAGb,AAAQ,YAAY,KAAuB;AAC1C,MAAI,CAAC,KAAK,UAAU,CAAC,KAAK,iBAAkB;AAG5C,OAAK,OAAO,kBACX,KAAK,kBACL,KAAK,UAAU,IAAI,CACnB;;CAGF,AAAQ,cAAc,QAAgB,SAAuB;EAC5D,IAAI;AACJ,MAAI;AACH,SAAM,KAAK,MAAM,QAAQ;UAClB;AACP;;AAGD,UAAQ,IAAI,MAAZ;GACC,KAAK;AACJ,QAAI,KAAK,SAAS,WAAY;AAC9B,SAAK,kBAAkB;KACtB,WAAW,IAAI;KACf,WAAW,IAAI;KACf,YAAY,IAAI;KAChB;AACD,SAAK,KAAK,kBAAkB,KAAK,gBAAgB;AACjD;GAED,KAAK;AACJ,QAAI,KAAK,SAAS,YAAa;AAC/B,SAAK,KAAK,YAAY,EAAE,iBAAiB,IAAI,iBAAiB,CAAC;AAC/D,SAAK,KAAK,mBAAmB,EAAE,SAAS,MAAM,CAAkB;AAChE;GAED,KAAK;AACJ,QAAI,KAAK,SAAS,YAAa;AAC/B,SAAK,KAAK,YAAY,IAAI,OAAO;AACjC,SAAK,KAAK,mBAAmB;KAC5B,SAAS;KACT,OAAO,IAAI;KACX,CAAkB;AACnB;GAED,KAAK;AACJ,QAAI,KAAK,SAAS,YAAa;AAC/B,SAAK,KAAK,cAAc,IAAI,MAAM,IAAI,gBAAgB;AACtD"}
|
|
@@ -0,0 +1,137 @@
|
|
|
1
|
+
import EventEmitter from "../EventEmitter.js";
|
|
2
|
+
import { sha256 } from "@noble/hashes/sha2.js";
|
|
3
|
+
import { hkdf } from "@noble/hashes/hkdf.js";
|
|
4
|
+
import { ed25519, x25519 } from "@noble/curves/ed25519.js";
|
|
5
|
+
|
|
6
|
+
//#region packages/provider/src/webrtc/E2EEChannel.ts
|
|
7
|
+
/**
|
|
8
|
+
* E2EEChannel
|
|
9
|
+
*
|
|
10
|
+
* Per-peer end-to-end encryption for WebRTC data channels using
|
|
11
|
+
* X25519 ECDH key agreement + HKDF-SHA256 + AES-256-GCM.
|
|
12
|
+
*
|
|
13
|
+
* Leverages the same cryptographic primitives as `DocKeyManager` and
|
|
14
|
+
* `CryptoIdentityKeystore` but applied to data channel messages rather
|
|
15
|
+
* than stored document keys.
|
|
16
|
+
*
|
|
17
|
+
* Key agreement flow:
|
|
18
|
+
* 1. Both peers exchange Ed25519 public keys via the `key-exchange` data channel
|
|
19
|
+
* 2. Convert Ed25519 → X25519 (Montgomery form)
|
|
20
|
+
* 3. Run X25519 ECDH to derive a shared secret
|
|
21
|
+
* 4. HKDF-SHA256(sharedSecret, salt, info) → 32-byte AES-256-GCM session key
|
|
22
|
+
* 5. All subsequent data channel messages are encrypted with this key
|
|
23
|
+
*
|
|
24
|
+
* Message wire format: [12-byte nonce || AES-256-GCM ciphertext]
|
|
25
|
+
*
|
|
26
|
+
* Dependencies: @noble/curves (already in the project for CryptoIdentityKeystore)
|
|
27
|
+
*/
|
|
28
|
+
const HKDF_INFO = new TextEncoder().encode("abracadabra-webrtc-e2ee-v1");
|
|
29
|
+
const NONCE_BYTES = 12;
|
|
30
|
+
var E2EEChannel = class extends EventEmitter {
|
|
31
|
+
constructor(identity, docId) {
|
|
32
|
+
super();
|
|
33
|
+
this.identity = identity;
|
|
34
|
+
this.docId = docId;
|
|
35
|
+
this.sessionKey = null;
|
|
36
|
+
this.remotePublicKey = null;
|
|
37
|
+
this._isEstablished = false;
|
|
38
|
+
}
|
|
39
|
+
get isEstablished() {
|
|
40
|
+
return this._isEstablished;
|
|
41
|
+
}
|
|
42
|
+
/**
|
|
43
|
+
* Process a key-exchange message from the remote peer.
|
|
44
|
+
* Called when the `key-exchange` data channel receives a message.
|
|
45
|
+
*
|
|
46
|
+
* The message is the remote peer's raw 32-byte Ed25519 public key.
|
|
47
|
+
* After receiving it, ECDH is computed and the session key derived.
|
|
48
|
+
*/
|
|
49
|
+
async handleKeyExchange(remoteEdPubKey) {
|
|
50
|
+
if (remoteEdPubKey.length !== 32) {
|
|
51
|
+
this.emit("error", /* @__PURE__ */ new Error("Invalid remote public key length"));
|
|
52
|
+
return;
|
|
53
|
+
}
|
|
54
|
+
this.remotePublicKey = remoteEdPubKey;
|
|
55
|
+
const remoteX25519Pub = ed25519.utils.toMontgomery(remoteEdPubKey);
|
|
56
|
+
const sharedSecret = x25519.getSharedSecret(this.identity.x25519PrivateKey, remoteX25519Pub);
|
|
57
|
+
const localPub = this.identity.publicKey;
|
|
58
|
+
const remotePub = remoteEdPubKey;
|
|
59
|
+
const [first, second] = this.sortKeys(localPub, remotePub);
|
|
60
|
+
const saltParts = [
|
|
61
|
+
new TextEncoder().encode(this.docId),
|
|
62
|
+
first,
|
|
63
|
+
second
|
|
64
|
+
];
|
|
65
|
+
const salt = new Uint8Array(saltParts.reduce((acc, p) => acc + p.length, 0));
|
|
66
|
+
let offset = 0;
|
|
67
|
+
for (const part of saltParts) {
|
|
68
|
+
salt.set(part, offset);
|
|
69
|
+
offset += part.length;
|
|
70
|
+
}
|
|
71
|
+
const keyBytes = hkdf(sha256, sharedSecret, salt, HKDF_INFO, 32);
|
|
72
|
+
this.sessionKey = await crypto.subtle.importKey("raw", keyBytes, { name: "AES-GCM" }, false, ["encrypt", "decrypt"]);
|
|
73
|
+
this._isEstablished = true;
|
|
74
|
+
this.emit("established", { remotePublicKey: remoteEdPubKey });
|
|
75
|
+
}
|
|
76
|
+
/**
|
|
77
|
+
* Returns the local Ed25519 public key to send to the remote peer
|
|
78
|
+
* via the `key-exchange` data channel.
|
|
79
|
+
*/
|
|
80
|
+
getKeyExchangeMessage() {
|
|
81
|
+
return this.identity.publicKey;
|
|
82
|
+
}
|
|
83
|
+
/**
|
|
84
|
+
* Encrypt a message for sending over a data channel.
|
|
85
|
+
* Returns `[12-byte nonce || AES-256-GCM ciphertext]`.
|
|
86
|
+
*
|
|
87
|
+
* @throws if the session key has not been established yet.
|
|
88
|
+
*/
|
|
89
|
+
async encrypt(plaintext) {
|
|
90
|
+
if (!this.sessionKey) throw new Error("E2EE session key not established");
|
|
91
|
+
const nonce = crypto.getRandomValues(new Uint8Array(NONCE_BYTES));
|
|
92
|
+
const ciphertext = new Uint8Array(await crypto.subtle.encrypt({
|
|
93
|
+
name: "AES-GCM",
|
|
94
|
+
iv: nonce
|
|
95
|
+
}, this.sessionKey, plaintext));
|
|
96
|
+
const result = new Uint8Array(NONCE_BYTES + ciphertext.length);
|
|
97
|
+
result.set(nonce, 0);
|
|
98
|
+
result.set(ciphertext, NONCE_BYTES);
|
|
99
|
+
return result;
|
|
100
|
+
}
|
|
101
|
+
/**
|
|
102
|
+
* Decrypt a message received from a data channel.
|
|
103
|
+
* Expects `[12-byte nonce || AES-256-GCM ciphertext]`.
|
|
104
|
+
*
|
|
105
|
+
* @throws if the session key has not been established or decryption fails.
|
|
106
|
+
*/
|
|
107
|
+
async decrypt(data) {
|
|
108
|
+
if (!this.sessionKey) throw new Error("E2EE session key not established");
|
|
109
|
+
if (data.length < NONCE_BYTES + 16) throw new Error("E2EE ciphertext too short");
|
|
110
|
+
const nonce = data.slice(0, NONCE_BYTES);
|
|
111
|
+
const ciphertext = data.slice(NONCE_BYTES);
|
|
112
|
+
const plaintext = await crypto.subtle.decrypt({
|
|
113
|
+
name: "AES-GCM",
|
|
114
|
+
iv: nonce
|
|
115
|
+
}, this.sessionKey, ciphertext);
|
|
116
|
+
return new Uint8Array(plaintext);
|
|
117
|
+
}
|
|
118
|
+
/** Destroy the session key and wipe sensitive material. */
|
|
119
|
+
destroy() {
|
|
120
|
+
this.sessionKey = null;
|
|
121
|
+
this.remotePublicKey = null;
|
|
122
|
+
this._isEstablished = false;
|
|
123
|
+
this.removeAllListeners();
|
|
124
|
+
}
|
|
125
|
+
/** Sort two keys lexicographically so both peers produce the same order. */
|
|
126
|
+
sortKeys(a, b) {
|
|
127
|
+
for (let i = 0; i < Math.min(a.length, b.length); i++) {
|
|
128
|
+
if (a[i] < b[i]) return [a, b];
|
|
129
|
+
if (a[i] > b[i]) return [b, a];
|
|
130
|
+
}
|
|
131
|
+
return a.length <= b.length ? [a, b] : [b, a];
|
|
132
|
+
}
|
|
133
|
+
};
|
|
134
|
+
|
|
135
|
+
//#endregion
|
|
136
|
+
export { E2EEChannel };
|
|
137
|
+
//# sourceMappingURL=E2EEChannel.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"E2EEChannel.js","names":["nobleEd25519"],"sources":["../../../src/webrtc/E2EEChannel.ts"],"sourcesContent":["/**\n * E2EEChannel\n *\n * Per-peer end-to-end encryption for WebRTC data channels using\n * X25519 ECDH key agreement + HKDF-SHA256 + AES-256-GCM.\n *\n * Leverages the same cryptographic primitives as `DocKeyManager` and\n * `CryptoIdentityKeystore` but applied to data channel messages rather\n * than stored document keys.\n *\n * Key agreement flow:\n * 1. Both peers exchange Ed25519 public keys via the `key-exchange` data channel\n * 2. Convert Ed25519 → X25519 (Montgomery form)\n * 3. Run X25519 ECDH to derive a shared secret\n * 4. HKDF-SHA256(sharedSecret, salt, info) → 32-byte AES-256-GCM session key\n * 5. All subsequent data channel messages are encrypted with this key\n *\n * Message wire format: [12-byte nonce || AES-256-GCM ciphertext]\n *\n * Dependencies: @noble/curves (already in the project for CryptoIdentityKeystore)\n */\n\nimport { x25519, ed25519 as nobleEd25519 } from \"@noble/curves/ed25519.js\";\nimport { hkdf } from \"@noble/hashes/hkdf.js\";\nimport { sha256 } from \"@noble/hashes/sha2.js\";\nimport EventEmitter from \"../EventEmitter.ts\";\n\nconst HKDF_INFO = new TextEncoder().encode(\"abracadabra-webrtc-e2ee-v1\");\nconst NONCE_BYTES = 12;\n\nexport interface E2EEIdentity {\n\t/** Raw 32-byte Ed25519 public key. */\n\tpublicKey: Uint8Array;\n\t/** Raw 32-byte X25519 private key. Caller must wipe after E2EEChannel.destroy(). */\n\tx25519PrivateKey: Uint8Array;\n}\n\nexport class E2EEChannel extends EventEmitter {\n\tprivate sessionKey: CryptoKey | null = null;\n\tprivate remotePublicKey: Uint8Array | null = null;\n\tprivate _isEstablished = false;\n\n\tconstructor(\n\t\tprivate readonly identity: E2EEIdentity,\n\t\tprivate readonly docId: string,\n\t) {\n\t\tsuper();\n\t}\n\n\tget isEstablished(): boolean {\n\t\treturn this._isEstablished;\n\t}\n\n\t/**\n\t * Process a key-exchange message from the remote peer.\n\t * Called when the `key-exchange` data channel receives a message.\n\t *\n\t * The message is the remote peer's raw 32-byte Ed25519 public key.\n\t * After receiving it, ECDH is computed and the session key derived.\n\t */\n\tasync handleKeyExchange(remoteEdPubKey: Uint8Array): Promise<void> {\n\t\tif (remoteEdPubKey.length !== 32) {\n\t\t\tthis.emit(\"error\", new Error(\"Invalid remote public key length\"));\n\t\t\treturn;\n\t\t}\n\n\t\tthis.remotePublicKey = remoteEdPubKey;\n\n\t\t// Convert remote Ed25519 public key to X25519 (Montgomery form).\n\t\tconst remoteX25519Pub = nobleEd25519.utils.toMontgomery(remoteEdPubKey);\n\n\t\t// X25519 ECDH: compute shared secret.\n\t\tconst sharedSecret = x25519.getSharedSecret(\n\t\t\tthis.identity.x25519PrivateKey,\n\t\t\tremoteX25519Pub,\n\t\t);\n\n\t\t// Deterministic salt: docId + sorted public keys (ensures both peers derive the same key).\n\t\tconst localPub = this.identity.publicKey;\n\t\tconst remotePub = remoteEdPubKey;\n\t\tconst [first, second] = this.sortKeys(localPub, remotePub);\n\t\tconst saltParts = [\n\t\t\tnew TextEncoder().encode(this.docId),\n\t\t\tfirst,\n\t\t\tsecond,\n\t\t];\n\t\tconst salt = new Uint8Array(\n\t\t\tsaltParts.reduce((acc, p) => acc + p.length, 0),\n\t\t);\n\t\tlet offset = 0;\n\t\tfor (const part of saltParts) {\n\t\t\tsalt.set(part, offset);\n\t\t\toffset += part.length;\n\t\t}\n\n\t\t// HKDF-SHA256 → 32-byte AES key.\n\t\tconst keyBytes = hkdf(sha256, sharedSecret, salt, HKDF_INFO, 32);\n\n\t\tthis.sessionKey = await crypto.subtle.importKey(\n\t\t\t\"raw\",\n\t\t\tkeyBytes as BufferSource,\n\t\t\t{ name: \"AES-GCM\" },\n\t\t\tfalse,\n\t\t\t[\"encrypt\", \"decrypt\"],\n\t\t);\n\n\t\tthis._isEstablished = true;\n\t\tthis.emit(\"established\", { remotePublicKey: remoteEdPubKey });\n\t}\n\n\t/**\n\t * Returns the local Ed25519 public key to send to the remote peer\n\t * via the `key-exchange` data channel.\n\t */\n\tgetKeyExchangeMessage(): Uint8Array {\n\t\treturn this.identity.publicKey;\n\t}\n\n\t/**\n\t * Encrypt a message for sending over a data channel.\n\t * Returns `[12-byte nonce || AES-256-GCM ciphertext]`.\n\t *\n\t * @throws if the session key has not been established yet.\n\t */\n\tasync encrypt(plaintext: Uint8Array): Promise<Uint8Array> {\n\t\tif (!this.sessionKey) {\n\t\t\tthrow new Error(\"E2EE session key not established\");\n\t\t}\n\n\t\tconst nonce = crypto.getRandomValues(new Uint8Array(NONCE_BYTES));\n\t\tconst ciphertext = new Uint8Array(\n\t\t\tawait crypto.subtle.encrypt(\n\t\t\t\t{ name: \"AES-GCM\", iv: nonce as BufferSource },\n\t\t\t\tthis.sessionKey,\n\t\t\t\tplaintext as BufferSource,\n\t\t\t),\n\t\t);\n\n\t\t// Wire format: [nonce(12) || ciphertext].\n\t\tconst result = new Uint8Array(NONCE_BYTES + ciphertext.length);\n\t\tresult.set(nonce, 0);\n\t\tresult.set(ciphertext, NONCE_BYTES);\n\t\treturn result;\n\t}\n\n\t/**\n\t * Decrypt a message received from a data channel.\n\t * Expects `[12-byte nonce || AES-256-GCM ciphertext]`.\n\t *\n\t * @throws if the session key has not been established or decryption fails.\n\t */\n\tasync decrypt(data: Uint8Array): Promise<Uint8Array> {\n\t\tif (!this.sessionKey) {\n\t\t\tthrow new Error(\"E2EE session key not established\");\n\t\t}\n\n\t\tif (data.length < NONCE_BYTES + 16) {\n\t\t\t// Minimum: nonce + AES-GCM tag (16 bytes).\n\t\t\tthrow new Error(\"E2EE ciphertext too short\");\n\t\t}\n\n\t\tconst nonce = data.slice(0, NONCE_BYTES);\n\t\tconst ciphertext = data.slice(NONCE_BYTES);\n\n\t\tconst plaintext = await crypto.subtle.decrypt(\n\t\t\t{ name: \"AES-GCM\", iv: nonce },\n\t\t\tthis.sessionKey,\n\t\t\tciphertext,\n\t\t);\n\n\t\treturn new Uint8Array(plaintext);\n\t}\n\n\t/** Destroy the session key and wipe sensitive material. */\n\tdestroy(): void {\n\t\tthis.sessionKey = null;\n\t\tthis.remotePublicKey = null;\n\t\tthis._isEstablished = false;\n\t\tthis.removeAllListeners();\n\t}\n\n\t// ── Private ──────────────────────────────────────────────────────────────\n\n\t/** Sort two keys lexicographically so both peers produce the same order. */\n\tprivate sortKeys(\n\t\ta: Uint8Array,\n\t\tb: Uint8Array,\n\t): [Uint8Array, Uint8Array] {\n\t\tfor (let i = 0; i < Math.min(a.length, b.length); i++) {\n\t\t\tif (a[i] < b[i]) return [a, b];\n\t\t\tif (a[i] > b[i]) return [b, a];\n\t\t}\n\t\treturn a.length <= b.length ? [a, b] : [b, a];\n\t}\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;AA2BA,MAAM,YAAY,IAAI,aAAa,CAAC,OAAO,6BAA6B;AACxE,MAAM,cAAc;AASpB,IAAa,cAAb,cAAiC,aAAa;CAK7C,YACC,AAAiB,UACjB,AAAiB,OAChB;AACD,SAAO;EAHU;EACA;oBANqB;yBACM;wBACpB;;CASzB,IAAI,gBAAyB;AAC5B,SAAO,KAAK;;;;;;;;;CAUb,MAAM,kBAAkB,gBAA2C;AAClE,MAAI,eAAe,WAAW,IAAI;AACjC,QAAK,KAAK,yBAAS,IAAI,MAAM,mCAAmC,CAAC;AACjE;;AAGD,OAAK,kBAAkB;EAGvB,MAAM,kBAAkBA,QAAa,MAAM,aAAa,eAAe;EA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