@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,179 +0,0 @@
|
|
|
1
|
-
import EventEmitter from "../EventEmitter.ts";
|
|
2
|
-
import type { E2EEChannel } from "./E2EEChannel.ts";
|
|
3
|
-
import { CHANNEL_NAMES } from "./types.ts";
|
|
4
|
-
|
|
5
|
-
/** Name of the data channel used for E2EE key exchange. */
|
|
6
|
-
export const KEY_EXCHANGE_CHANNEL = "key-exchange";
|
|
7
|
-
|
|
8
|
-
export class DataChannelRouter extends EventEmitter {
|
|
9
|
-
private channels = new Map<string, RTCDataChannel>();
|
|
10
|
-
private encryptor: E2EEChannel | null = null;
|
|
11
|
-
/** Channels excluded from encryption (key-exchange itself, awareness). */
|
|
12
|
-
private plaintextChannels = new Set<string>([KEY_EXCHANGE_CHANNEL]);
|
|
13
|
-
|
|
14
|
-
constructor(private connection: RTCPeerConnection) {
|
|
15
|
-
super();
|
|
16
|
-
|
|
17
|
-
// Accept incoming data channels from the remote peer.
|
|
18
|
-
this.connection.ondatachannel = (event) => {
|
|
19
|
-
this.registerChannel(event.channel);
|
|
20
|
-
};
|
|
21
|
-
}
|
|
22
|
-
|
|
23
|
-
/** Attach an E2EE encryptor. All channels (except key-exchange) will be encrypted. */
|
|
24
|
-
setEncryptor(encryptor: E2EEChannel): void {
|
|
25
|
-
this.encryptor = encryptor;
|
|
26
|
-
}
|
|
27
|
-
|
|
28
|
-
/** Create a named data channel (initiator side). */
|
|
29
|
-
createChannel(
|
|
30
|
-
name: string,
|
|
31
|
-
options?: RTCDataChannelInit,
|
|
32
|
-
): RTCDataChannel {
|
|
33
|
-
const channel = this.connection.createDataChannel(name, options);
|
|
34
|
-
this.registerChannel(channel);
|
|
35
|
-
return channel;
|
|
36
|
-
}
|
|
37
|
-
|
|
38
|
-
/** Create the standard set of channels for Abracadabra WebRTC. */
|
|
39
|
-
createDefaultChannels(opts: {
|
|
40
|
-
enableDocSync: boolean;
|
|
41
|
-
enableAwareness: boolean;
|
|
42
|
-
enableFileTransfer: boolean;
|
|
43
|
-
}): void {
|
|
44
|
-
if (opts.enableDocSync) {
|
|
45
|
-
this.createChannel(CHANNEL_NAMES.YJS_SYNC, {
|
|
46
|
-
ordered: true,
|
|
47
|
-
});
|
|
48
|
-
}
|
|
49
|
-
|
|
50
|
-
if (opts.enableAwareness) {
|
|
51
|
-
this.createChannel(CHANNEL_NAMES.AWARENESS, {
|
|
52
|
-
ordered: false,
|
|
53
|
-
maxRetransmits: 0,
|
|
54
|
-
});
|
|
55
|
-
}
|
|
56
|
-
|
|
57
|
-
if (opts.enableFileTransfer) {
|
|
58
|
-
this.createChannel(CHANNEL_NAMES.FILE_TRANSFER, {
|
|
59
|
-
ordered: true,
|
|
60
|
-
});
|
|
61
|
-
}
|
|
62
|
-
}
|
|
63
|
-
|
|
64
|
-
/**
|
|
65
|
-
* Create namespaced channels for a child/subdocument.
|
|
66
|
-
* Channel names are prefixed with `{childId}:` to avoid collisions.
|
|
67
|
-
*/
|
|
68
|
-
createSubdocChannels(childId: string, opts: {
|
|
69
|
-
enableDocSync: boolean;
|
|
70
|
-
enableAwareness: boolean;
|
|
71
|
-
}): void {
|
|
72
|
-
if (opts.enableDocSync) {
|
|
73
|
-
this.createChannel(`${childId}:${CHANNEL_NAMES.YJS_SYNC}`, {
|
|
74
|
-
ordered: true,
|
|
75
|
-
});
|
|
76
|
-
}
|
|
77
|
-
if (opts.enableAwareness) {
|
|
78
|
-
this.createChannel(`${childId}:${CHANNEL_NAMES.AWARENESS}`, {
|
|
79
|
-
ordered: false,
|
|
80
|
-
maxRetransmits: 0,
|
|
81
|
-
});
|
|
82
|
-
}
|
|
83
|
-
}
|
|
84
|
-
|
|
85
|
-
getChannel(name: string): RTCDataChannel | null {
|
|
86
|
-
return this.channels.get(name) ?? null;
|
|
87
|
-
}
|
|
88
|
-
|
|
89
|
-
isOpen(name: string): boolean {
|
|
90
|
-
return this.channels.get(name)?.readyState === "open";
|
|
91
|
-
}
|
|
92
|
-
|
|
93
|
-
/**
|
|
94
|
-
* Send data on a named channel, encrypting if E2EE is active.
|
|
95
|
-
* Falls back to plaintext if no encryptor is set or for exempt channels.
|
|
96
|
-
*/
|
|
97
|
-
async send(name: string, data: Uint8Array): Promise<boolean> {
|
|
98
|
-
const channel = this.channels.get(name);
|
|
99
|
-
if (!channel || channel.readyState !== "open") return false;
|
|
100
|
-
|
|
101
|
-
if (this.encryptor?.isEstablished && !this.plaintextChannels.has(name)) {
|
|
102
|
-
const encrypted = await this.encryptor.encrypt(data);
|
|
103
|
-
channel.send(encrypted as unknown as ArrayBuffer);
|
|
104
|
-
} else {
|
|
105
|
-
channel.send(data as unknown as ArrayBuffer);
|
|
106
|
-
}
|
|
107
|
-
return true;
|
|
108
|
-
}
|
|
109
|
-
|
|
110
|
-
private registerChannel(channel: RTCDataChannel): void {
|
|
111
|
-
channel.binaryType = "arraybuffer";
|
|
112
|
-
this.channels.set(channel.label, channel);
|
|
113
|
-
|
|
114
|
-
channel.onopen = () => {
|
|
115
|
-
this.emit("channelOpen", { name: channel.label, channel });
|
|
116
|
-
};
|
|
117
|
-
|
|
118
|
-
channel.onclose = () => {
|
|
119
|
-
this.emit("channelClose", { name: channel.label });
|
|
120
|
-
this.channels.delete(channel.label);
|
|
121
|
-
};
|
|
122
|
-
|
|
123
|
-
channel.onmessage = async (event) => {
|
|
124
|
-
const name = channel.label;
|
|
125
|
-
let data = event.data;
|
|
126
|
-
|
|
127
|
-
// Decrypt incoming data if E2EE is active (skip plaintext channels).
|
|
128
|
-
if (
|
|
129
|
-
this.encryptor?.isEstablished &&
|
|
130
|
-
!this.plaintextChannels.has(name) &&
|
|
131
|
-
(data instanceof ArrayBuffer || data instanceof Uint8Array)
|
|
132
|
-
) {
|
|
133
|
-
try {
|
|
134
|
-
const buf =
|
|
135
|
-
data instanceof ArrayBuffer ? new Uint8Array(data) : data;
|
|
136
|
-
data = await this.encryptor.decrypt(buf);
|
|
137
|
-
} catch (err) {
|
|
138
|
-
this.emit("channelError", {
|
|
139
|
-
name,
|
|
140
|
-
error: err,
|
|
141
|
-
});
|
|
142
|
-
return;
|
|
143
|
-
}
|
|
144
|
-
}
|
|
145
|
-
|
|
146
|
-
this.emit("channelMessage", { name, data });
|
|
147
|
-
};
|
|
148
|
-
|
|
149
|
-
channel.onerror = (event) => {
|
|
150
|
-
this.emit("channelError", {
|
|
151
|
-
name: channel.label,
|
|
152
|
-
error: event,
|
|
153
|
-
});
|
|
154
|
-
};
|
|
155
|
-
|
|
156
|
-
// If the channel is already open (can happen with ondatachannel),
|
|
157
|
-
// emit immediately.
|
|
158
|
-
if (channel.readyState === "open") {
|
|
159
|
-
this.emit("channelOpen", { name: channel.label, channel });
|
|
160
|
-
}
|
|
161
|
-
}
|
|
162
|
-
|
|
163
|
-
close(): void {
|
|
164
|
-
for (const channel of this.channels.values()) {
|
|
165
|
-
try {
|
|
166
|
-
channel.close();
|
|
167
|
-
} catch {
|
|
168
|
-
// Ignore
|
|
169
|
-
}
|
|
170
|
-
}
|
|
171
|
-
this.channels.clear();
|
|
172
|
-
}
|
|
173
|
-
|
|
174
|
-
destroy(): void {
|
|
175
|
-
this.close();
|
|
176
|
-
this.connection.ondatachannel = null;
|
|
177
|
-
this.removeAllListeners();
|
|
178
|
-
}
|
|
179
|
-
}
|
|
@@ -1,496 +0,0 @@
|
|
|
1
|
-
/**
|
|
2
|
-
* DevicePairingChannel
|
|
3
|
-
*
|
|
4
|
-
* Enables cross-device identity pairing over an E2EE WebRTC data channel.
|
|
5
|
-
* Device A (approver) creates a pairing session with a short code. Device B
|
|
6
|
-
* (requester) joins with the code. After E2EE is established, Device B sends
|
|
7
|
-
* its public key and Device A registers it via `addKey()`.
|
|
8
|
-
*
|
|
9
|
-
* Reuses the existing WebRTC stack: SignalingSocket, PeerConnection,
|
|
10
|
-
* DataChannelRouter, and E2EEChannel (X25519 ECDH + AES-256-GCM).
|
|
11
|
-
*/
|
|
12
|
-
|
|
13
|
-
import { sha256 } from "@noble/hashes/sha2.js";
|
|
14
|
-
import EventEmitter from "../EventEmitter.ts";
|
|
15
|
-
import { AbracadabraClient } from "../AbracadabraClient.ts";
|
|
16
|
-
import { AbracadabraWebRTC } from "./AbracadabraWebRTC.ts";
|
|
17
|
-
import type { E2EEIdentity } from "./E2EEChannel.ts";
|
|
18
|
-
|
|
19
|
-
// ── Constants ───────────────────────────────────────────────────────────────
|
|
20
|
-
|
|
21
|
-
/** Ambiguity-free charset (no 0/O/1/I). */
|
|
22
|
-
const CODE_CHARSET = "ABCDEFGHJKLMNPQRSTUVWXYZ23456789";
|
|
23
|
-
const CODE_LENGTH = 6;
|
|
24
|
-
const PAIRING_TIMEOUT_MS = 5 * 60 * 1000; // 5 minutes
|
|
25
|
-
const SIGNALING_CONNECT_TIMEOUT_MS = 5_000; // 5 seconds before trying fallback
|
|
26
|
-
const PAIRING_CHANNEL = "device-pairing";
|
|
27
|
-
|
|
28
|
-
// ── Types ───────────────────────────────────────────────────────────────────
|
|
29
|
-
|
|
30
|
-
export interface DevicePairingConfig {
|
|
31
|
-
/** Server base URL (http/https). */
|
|
32
|
-
serverUrl: string;
|
|
33
|
-
/**
|
|
34
|
-
* JWT token or async token factory for signaling auth.
|
|
35
|
-
* When omitted, a short-lived anonymous pairing token is fetched automatically
|
|
36
|
-
* from `POST /auth/pairing-token`.
|
|
37
|
-
*/
|
|
38
|
-
token?: string | (() => string) | (() => Promise<string>);
|
|
39
|
-
/** E2EE identity (Ed25519 public key + X25519 private key). */
|
|
40
|
-
e2ee: E2EEIdentity;
|
|
41
|
-
/** ICE servers. Defaults to Google STUN. */
|
|
42
|
-
iceServers?: RTCIceServer[];
|
|
43
|
-
/**
|
|
44
|
-
* Fallback signaling server URL. If the primary server is unreachable,
|
|
45
|
-
* signaling will retry through this server. The actual pairing data is
|
|
46
|
-
* E2EE-encrypted, so the relay server cannot read it.
|
|
47
|
-
*/
|
|
48
|
-
fallbackSignalingUrl?: string;
|
|
49
|
-
/** WebSocket polyfill (for Node.js). */
|
|
50
|
-
WebSocketPolyfill?: any;
|
|
51
|
-
}
|
|
52
|
-
|
|
53
|
-
export interface PairingRequest {
|
|
54
|
-
/** Device B's Ed25519 public key (base64url). */
|
|
55
|
-
publicKey: string;
|
|
56
|
-
/** Device B's X25519 public key (base64url). */
|
|
57
|
-
x25519Key: string;
|
|
58
|
-
/** Human-readable device label. */
|
|
59
|
-
deviceName: string;
|
|
60
|
-
}
|
|
61
|
-
|
|
62
|
-
export interface PairingResult {
|
|
63
|
-
success: boolean;
|
|
64
|
-
error?: string;
|
|
65
|
-
}
|
|
66
|
-
|
|
67
|
-
type PairingRole = "approver" | "requester";
|
|
68
|
-
|
|
69
|
-
// ── Internal wire messages ──────────────────────────────────────────────────
|
|
70
|
-
|
|
71
|
-
interface PairRequestMsg {
|
|
72
|
-
type: "pair-request";
|
|
73
|
-
publicKey: string;
|
|
74
|
-
x25519Key: string;
|
|
75
|
-
deviceName: string;
|
|
76
|
-
}
|
|
77
|
-
|
|
78
|
-
interface PairApprovedMsg {
|
|
79
|
-
type: "pair-approved";
|
|
80
|
-
/** Approver's account-level Ed25519 public key (base64url). */
|
|
81
|
-
masterPublicKey?: string;
|
|
82
|
-
}
|
|
83
|
-
|
|
84
|
-
interface PairInviteCodeMsg {
|
|
85
|
-
type: "pair-invite-code";
|
|
86
|
-
code: string;
|
|
87
|
-
/** Approver's account-level Ed25519 public key (base64url). */
|
|
88
|
-
masterPublicKey?: string;
|
|
89
|
-
}
|
|
90
|
-
|
|
91
|
-
interface PairRejectedMsg {
|
|
92
|
-
type: "pair-rejected";
|
|
93
|
-
reason: string;
|
|
94
|
-
}
|
|
95
|
-
|
|
96
|
-
type PairingMsg = PairRequestMsg | PairApprovedMsg | PairRejectedMsg | PairInviteCodeMsg;
|
|
97
|
-
|
|
98
|
-
// ── Helpers ─────────────────────────────────────────────────────────────────
|
|
99
|
-
|
|
100
|
-
function generatePairingCode(): string {
|
|
101
|
-
const bytes = crypto.getRandomValues(new Uint8Array(CODE_LENGTH));
|
|
102
|
-
return Array.from(bytes)
|
|
103
|
-
.map((b) => CODE_CHARSET[b % CODE_CHARSET.length])
|
|
104
|
-
.join("");
|
|
105
|
-
}
|
|
106
|
-
|
|
107
|
-
function codeToRoomId(code: string): string {
|
|
108
|
-
const hash = sha256(new TextEncoder().encode(code.toUpperCase()));
|
|
109
|
-
// Take first 16 hex chars for the room ID.
|
|
110
|
-
const hex = Array.from(hash.slice(0, 8))
|
|
111
|
-
.map((b) => b.toString(16).padStart(2, "0"))
|
|
112
|
-
.join("");
|
|
113
|
-
return `__pairing_${hex}`;
|
|
114
|
-
}
|
|
115
|
-
|
|
116
|
-
// ── DevicePairingChannel ────────────────────────────────────────────────────
|
|
117
|
-
|
|
118
|
-
export class DevicePairingChannel extends EventEmitter {
|
|
119
|
-
private webrtc: AbracadabraWebRTC | null = null;
|
|
120
|
-
private timeoutHandle: ReturnType<typeof setTimeout> | null = null;
|
|
121
|
-
private _destroyed = false;
|
|
122
|
-
private _pendingRequest: PairingRequest | null = null;
|
|
123
|
-
private _connectedPeerId: string | null = null;
|
|
124
|
-
private _usingFallback = false;
|
|
125
|
-
private _resolvedIceServers: RTCIceServer[] | undefined;
|
|
126
|
-
|
|
127
|
-
readonly role: PairingRole;
|
|
128
|
-
readonly pairingCode: string;
|
|
129
|
-
|
|
130
|
-
private constructor(
|
|
131
|
-
role: PairingRole,
|
|
132
|
-
pairingCode: string,
|
|
133
|
-
private readonly config: DevicePairingConfig,
|
|
134
|
-
) {
|
|
135
|
-
super();
|
|
136
|
-
this.role = role;
|
|
137
|
-
this.pairingCode = pairingCode;
|
|
138
|
-
}
|
|
139
|
-
|
|
140
|
-
// ── Factory Methods ───────────────────────────────────────────────────
|
|
141
|
-
|
|
142
|
-
/**
|
|
143
|
-
* Create an approver session (Device A). Returns the channel and a
|
|
144
|
-
* 6-character pairing code to share with Device B.
|
|
145
|
-
*/
|
|
146
|
-
static createApprover(config: DevicePairingConfig): {
|
|
147
|
-
channel: DevicePairingChannel;
|
|
148
|
-
pairingCode: string;
|
|
149
|
-
} {
|
|
150
|
-
const code = generatePairingCode();
|
|
151
|
-
const channel = new DevicePairingChannel("approver", code, config);
|
|
152
|
-
channel.start();
|
|
153
|
-
return { channel, pairingCode: code };
|
|
154
|
-
}
|
|
155
|
-
|
|
156
|
-
/**
|
|
157
|
-
* Create a requester session (Device B). Joins with a pairing code
|
|
158
|
-
* obtained from Device A.
|
|
159
|
-
*/
|
|
160
|
-
static createRequester(
|
|
161
|
-
config: DevicePairingConfig,
|
|
162
|
-
pairingCode: string,
|
|
163
|
-
): DevicePairingChannel {
|
|
164
|
-
const channel = new DevicePairingChannel(
|
|
165
|
-
"requester",
|
|
166
|
-
pairingCode.toUpperCase().replace(/[^A-Z2-9]/g, ""),
|
|
167
|
-
config,
|
|
168
|
-
);
|
|
169
|
-
channel.start();
|
|
170
|
-
return channel;
|
|
171
|
-
}
|
|
172
|
-
|
|
173
|
-
// ── Approver API ──────────────────────────────────────────────────────
|
|
174
|
-
|
|
175
|
-
/**
|
|
176
|
-
* Approve the pending pairing request. Calls `client.addKey()` to
|
|
177
|
-
* register Device B's public key, then notifies Device B.
|
|
178
|
-
*
|
|
179
|
-
* @param client Authenticated REST client.
|
|
180
|
-
* @param masterPublicKey Approver's account-level Ed25519 public key (base64url).
|
|
181
|
-
* Sent to Device B so it can adopt the master's identity doc.
|
|
182
|
-
*/
|
|
183
|
-
async approve(client: AbracadabraClient, masterPublicKey?: string): Promise<PairingResult> {
|
|
184
|
-
if (this.role !== "approver") {
|
|
185
|
-
return { success: false, error: "Only the approver can approve" };
|
|
186
|
-
}
|
|
187
|
-
if (!this._pendingRequest) {
|
|
188
|
-
return { success: false, error: "No pending pairing request" };
|
|
189
|
-
}
|
|
190
|
-
if (!this._connectedPeerId) {
|
|
191
|
-
return { success: false, error: "Peer not connected" };
|
|
192
|
-
}
|
|
193
|
-
|
|
194
|
-
const req = this._pendingRequest;
|
|
195
|
-
|
|
196
|
-
try {
|
|
197
|
-
await client.addKey({
|
|
198
|
-
publicKey: req.publicKey,
|
|
199
|
-
deviceName: req.deviceName,
|
|
200
|
-
x25519Key: req.x25519Key,
|
|
201
|
-
});
|
|
202
|
-
|
|
203
|
-
this.sendMessage({ type: "pair-approved", masterPublicKey });
|
|
204
|
-
this._pendingRequest = null;
|
|
205
|
-
this.emit("pairingComplete", { success: true } as PairingResult);
|
|
206
|
-
return { success: true };
|
|
207
|
-
} catch (err: any) {
|
|
208
|
-
const error = err?.message ?? "Failed to register device key";
|
|
209
|
-
this.sendMessage({ type: "pair-rejected", reason: error });
|
|
210
|
-
this._pendingRequest = null;
|
|
211
|
-
const result: PairingResult = { success: false, error };
|
|
212
|
-
this.emit("pairingComplete", result);
|
|
213
|
-
return result;
|
|
214
|
-
}
|
|
215
|
-
}
|
|
216
|
-
|
|
217
|
-
/**
|
|
218
|
-
* Approve via server-side device invite. Creates a single-use invite code
|
|
219
|
-
* and sends it to Device B over the E2EE channel. Device B redeems it
|
|
220
|
-
* independently via HTTP — Device A can go offline after this.
|
|
221
|
-
*
|
|
222
|
-
* @param client Authenticated REST client.
|
|
223
|
-
* @param masterPublicKey Approver's account-level Ed25519 public key (base64url).
|
|
224
|
-
* Sent to Device B so it can adopt the master's identity doc.
|
|
225
|
-
*/
|
|
226
|
-
async approveWithInvite(client: AbracadabraClient, masterPublicKey?: string): Promise<PairingResult> {
|
|
227
|
-
if (this.role !== "approver") {
|
|
228
|
-
return { success: false, error: "Only the approver can approve" };
|
|
229
|
-
}
|
|
230
|
-
if (!this._pendingRequest) {
|
|
231
|
-
return { success: false, error: "No pending pairing request" };
|
|
232
|
-
}
|
|
233
|
-
if (!this._connectedPeerId) {
|
|
234
|
-
return { success: false, error: "Peer not connected" };
|
|
235
|
-
}
|
|
236
|
-
|
|
237
|
-
try {
|
|
238
|
-
const { code } = await client.createDeviceInvite();
|
|
239
|
-
this.sendMessage({ type: "pair-invite-code", code, masterPublicKey });
|
|
240
|
-
this._pendingRequest = null;
|
|
241
|
-
this.emit("pairingComplete", { success: true } as PairingResult);
|
|
242
|
-
return { success: true };
|
|
243
|
-
} catch (err: any) {
|
|
244
|
-
const error = err?.message ?? "Failed to create device invite";
|
|
245
|
-
this.sendMessage({ type: "pair-rejected", reason: error });
|
|
246
|
-
this._pendingRequest = null;
|
|
247
|
-
const result: PairingResult = { success: false, error };
|
|
248
|
-
this.emit("pairingComplete", result);
|
|
249
|
-
return result;
|
|
250
|
-
}
|
|
251
|
-
}
|
|
252
|
-
|
|
253
|
-
/**
|
|
254
|
-
* Reject the pending pairing request.
|
|
255
|
-
*/
|
|
256
|
-
reject(reason = "Rejected by user"): void {
|
|
257
|
-
if (this.role !== "approver" || !this._pendingRequest) return;
|
|
258
|
-
this.sendMessage({ type: "pair-rejected", reason });
|
|
259
|
-
this._pendingRequest = null;
|
|
260
|
-
this.emit("pairingComplete", {
|
|
261
|
-
success: false,
|
|
262
|
-
error: reason,
|
|
263
|
-
} as PairingResult);
|
|
264
|
-
}
|
|
265
|
-
|
|
266
|
-
// ── Requester API ─────────────────────────────────────────────────────
|
|
267
|
-
|
|
268
|
-
/**
|
|
269
|
-
* Send a pairing request to Device A. Call this after the "connected"
|
|
270
|
-
* event fires.
|
|
271
|
-
*/
|
|
272
|
-
requestPairing(request: PairingRequest): void {
|
|
273
|
-
if (this.role !== "requester") return;
|
|
274
|
-
this.sendMessage({
|
|
275
|
-
type: "pair-request",
|
|
276
|
-
publicKey: request.publicKey,
|
|
277
|
-
x25519Key: request.x25519Key,
|
|
278
|
-
deviceName: request.deviceName,
|
|
279
|
-
});
|
|
280
|
-
}
|
|
281
|
-
|
|
282
|
-
// ── Lifecycle ─────────────────────────────────────────────────────────
|
|
283
|
-
|
|
284
|
-
get isDestroyed(): boolean {
|
|
285
|
-
return this._destroyed;
|
|
286
|
-
}
|
|
287
|
-
|
|
288
|
-
destroy(): void {
|
|
289
|
-
if (this._destroyed) return;
|
|
290
|
-
this._destroyed = true;
|
|
291
|
-
|
|
292
|
-
if (this.timeoutHandle) {
|
|
293
|
-
clearTimeout(this.timeoutHandle);
|
|
294
|
-
this.timeoutHandle = null;
|
|
295
|
-
}
|
|
296
|
-
|
|
297
|
-
if (this.webrtc) {
|
|
298
|
-
this.webrtc.destroy();
|
|
299
|
-
this.webrtc = null;
|
|
300
|
-
}
|
|
301
|
-
|
|
302
|
-
this.removeAllListeners();
|
|
303
|
-
}
|
|
304
|
-
|
|
305
|
-
// ── Private ─────────────────────────────────────────────────────────
|
|
306
|
-
|
|
307
|
-
private async resolveToken(
|
|
308
|
-
serverUrl?: string,
|
|
309
|
-
): Promise<string | (() => string) | (() => Promise<string>)> {
|
|
310
|
-
// Use provided token if connecting to the primary server.
|
|
311
|
-
if (this.config.token && serverUrl === this.config.serverUrl) {
|
|
312
|
-
return this.config.token;
|
|
313
|
-
}
|
|
314
|
-
|
|
315
|
-
// Fetch a short-lived anonymous pairing token from the target server.
|
|
316
|
-
let base = serverUrl ?? this.config.serverUrl;
|
|
317
|
-
while (base.endsWith("/")) base = base.slice(0, -1);
|
|
318
|
-
const resp = await fetch(`${base}/auth/pairing-token`, {
|
|
319
|
-
method: "POST",
|
|
320
|
-
});
|
|
321
|
-
if (!resp.ok) {
|
|
322
|
-
throw new Error(
|
|
323
|
-
`Failed to fetch pairing token: ${resp.status} ${resp.statusText}`,
|
|
324
|
-
);
|
|
325
|
-
}
|
|
326
|
-
const { token } = (await resp.json()) as { token: string };
|
|
327
|
-
return token;
|
|
328
|
-
}
|
|
329
|
-
|
|
330
|
-
private start(): void {
|
|
331
|
-
this.connectToServer(this.config.serverUrl);
|
|
332
|
-
|
|
333
|
-
// Auto-destroy after timeout.
|
|
334
|
-
this.timeoutHandle = setTimeout(() => {
|
|
335
|
-
if (!this._destroyed) {
|
|
336
|
-
this.emit("error", new Error("Pairing timed out"));
|
|
337
|
-
this.destroy();
|
|
338
|
-
}
|
|
339
|
-
}, PAIRING_TIMEOUT_MS);
|
|
340
|
-
}
|
|
341
|
-
|
|
342
|
-
private connectToServer(serverUrl: string, signalingUrl?: string): void {
|
|
343
|
-
const roomId = codeToRoomId(this.pairingCode);
|
|
344
|
-
|
|
345
|
-
// Resolve token (possibly async) — uses a factory so SignalingSocket can await it.
|
|
346
|
-
const tokenPromise = this.resolveToken(serverUrl);
|
|
347
|
-
const tokenFactory = async (): Promise<string> => {
|
|
348
|
-
const t = await tokenPromise;
|
|
349
|
-
if (typeof t === "function") return await t();
|
|
350
|
-
return t;
|
|
351
|
-
};
|
|
352
|
-
|
|
353
|
-
// Fetch ICE servers from the target server if none configured.
|
|
354
|
-
if (!this.config.iceServers) {
|
|
355
|
-
const client = new AbracadabraClient({ url: serverUrl });
|
|
356
|
-
client.getIceServers().then((servers) => {
|
|
357
|
-
if (servers.length > 0) this._resolvedIceServers = servers;
|
|
358
|
-
});
|
|
359
|
-
}
|
|
360
|
-
|
|
361
|
-
this.webrtc = new AbracadabraWebRTC({
|
|
362
|
-
docId: roomId,
|
|
363
|
-
url: serverUrl,
|
|
364
|
-
signalingUrl: signalingUrl ?? undefined,
|
|
365
|
-
token: tokenFactory,
|
|
366
|
-
iceServers: this.config.iceServers ?? this._resolvedIceServers,
|
|
367
|
-
e2ee: this.config.e2ee,
|
|
368
|
-
enableDocSync: false,
|
|
369
|
-
enableAwarenessSync: false,
|
|
370
|
-
enableFileTransfer: false,
|
|
371
|
-
autoConnect: false,
|
|
372
|
-
WebSocketPolyfill: this.config.WebSocketPolyfill,
|
|
373
|
-
});
|
|
374
|
-
|
|
375
|
-
let connected = false;
|
|
376
|
-
|
|
377
|
-
this.webrtc.on("connected", () => {
|
|
378
|
-
connected = true;
|
|
379
|
-
});
|
|
380
|
-
|
|
381
|
-
this.webrtc.on("e2eeEstablished", ({ peerId }: { peerId: string }) => {
|
|
382
|
-
this._connectedPeerId = peerId;
|
|
383
|
-
this.emit("connected");
|
|
384
|
-
});
|
|
385
|
-
|
|
386
|
-
this.webrtc.on(
|
|
387
|
-
"customMessage",
|
|
388
|
-
({ peerId, payload }: { peerId: string; payload: string }) => {
|
|
389
|
-
this.handleMessage(peerId, payload);
|
|
390
|
-
},
|
|
391
|
-
);
|
|
392
|
-
|
|
393
|
-
this.webrtc.on("e2eeFailed", ({ peerId, error }: { peerId: string; error: any }) => {
|
|
394
|
-
if (!this._destroyed) {
|
|
395
|
-
this.emit("error", new Error(`E2EE failed: ${error?.message ?? error}`));
|
|
396
|
-
}
|
|
397
|
-
});
|
|
398
|
-
|
|
399
|
-
this.webrtc.on("error", (err: any) => {
|
|
400
|
-
if (!this._destroyed) {
|
|
401
|
-
this.emit("error", new Error(`WebRTC: ${err?.type ?? err?.message ?? "unknown"}`));
|
|
402
|
-
}
|
|
403
|
-
});
|
|
404
|
-
|
|
405
|
-
this.webrtc.on("peerLeft", () => {
|
|
406
|
-
if (!this._destroyed) {
|
|
407
|
-
this.emit("error", new Error("Peer disconnected"));
|
|
408
|
-
}
|
|
409
|
-
});
|
|
410
|
-
|
|
411
|
-
this.webrtc.on(
|
|
412
|
-
"signalingError",
|
|
413
|
-
(err: { code: string; message: string }) => {
|
|
414
|
-
this.emit("error", new Error(`Signaling: ${err.message}`));
|
|
415
|
-
},
|
|
416
|
-
);
|
|
417
|
-
|
|
418
|
-
// If a fallback signaling server is configured, try it after a timeout.
|
|
419
|
-
if (this.config.fallbackSignalingUrl && !signalingUrl) {
|
|
420
|
-
const fallbackTimer = setTimeout(() => {
|
|
421
|
-
if (this._destroyed || connected) return;
|
|
422
|
-
// Primary server didn't connect in time — try fallback.
|
|
423
|
-
if (this.webrtc) {
|
|
424
|
-
this.webrtc.destroy();
|
|
425
|
-
this.webrtc = null;
|
|
426
|
-
}
|
|
427
|
-
this._usingFallback = true;
|
|
428
|
-
this.emit("fallback", { url: this.config.fallbackSignalingUrl });
|
|
429
|
-
this.connectToServer(
|
|
430
|
-
this.config.fallbackSignalingUrl!,
|
|
431
|
-
);
|
|
432
|
-
}, SIGNALING_CONNECT_TIMEOUT_MS);
|
|
433
|
-
|
|
434
|
-
// Clear fallback timer if primary succeeds.
|
|
435
|
-
this.webrtc.on("connected", () => clearTimeout(fallbackTimer));
|
|
436
|
-
}
|
|
437
|
-
|
|
438
|
-
this.webrtc.connect();
|
|
439
|
-
}
|
|
440
|
-
|
|
441
|
-
/** Whether the connection fell back to the fallback signaling server. */
|
|
442
|
-
get usingFallback(): boolean {
|
|
443
|
-
return this._usingFallback;
|
|
444
|
-
}
|
|
445
|
-
|
|
446
|
-
private sendMessage(msg: PairingMsg): void {
|
|
447
|
-
if (!this.webrtc || !this._connectedPeerId) return;
|
|
448
|
-
// Send via the custom message path — the E2EE layer on the data channel
|
|
449
|
-
// encrypts all non-key-exchange traffic via the DataChannelRouter.
|
|
450
|
-
this.webrtc.sendCustomMessage(
|
|
451
|
-
this._connectedPeerId,
|
|
452
|
-
JSON.stringify(msg),
|
|
453
|
-
);
|
|
454
|
-
}
|
|
455
|
-
|
|
456
|
-
private handleMessage(peerId: string, payload: string): void {
|
|
457
|
-
let msg: PairingMsg;
|
|
458
|
-
try {
|
|
459
|
-
msg = JSON.parse(payload);
|
|
460
|
-
} catch {
|
|
461
|
-
return;
|
|
462
|
-
}
|
|
463
|
-
|
|
464
|
-
switch (msg.type) {
|
|
465
|
-
case "pair-request":
|
|
466
|
-
if (this.role !== "approver") return;
|
|
467
|
-
this._pendingRequest = {
|
|
468
|
-
publicKey: msg.publicKey,
|
|
469
|
-
x25519Key: msg.x25519Key,
|
|
470
|
-
deviceName: msg.deviceName,
|
|
471
|
-
};
|
|
472
|
-
this.emit("pairingRequest", this._pendingRequest);
|
|
473
|
-
break;
|
|
474
|
-
|
|
475
|
-
case "pair-approved":
|
|
476
|
-
if (this.role !== "requester") return;
|
|
477
|
-
this.emit("approved", { masterPublicKey: msg.masterPublicKey });
|
|
478
|
-
this.emit("pairingComplete", { success: true } as PairingResult);
|
|
479
|
-
break;
|
|
480
|
-
|
|
481
|
-
case "pair-rejected":
|
|
482
|
-
if (this.role !== "requester") return;
|
|
483
|
-
this.emit("rejected", msg.reason);
|
|
484
|
-
this.emit("pairingComplete", {
|
|
485
|
-
success: false,
|
|
486
|
-
error: msg.reason,
|
|
487
|
-
} as PairingResult);
|
|
488
|
-
break;
|
|
489
|
-
|
|
490
|
-
case "pair-invite-code":
|
|
491
|
-
if (this.role !== "requester") return;
|
|
492
|
-
this.emit("inviteCode", msg.code, msg.masterPublicKey);
|
|
493
|
-
break;
|
|
494
|
-
}
|
|
495
|
-
}
|
|
496
|
-
}
|