@abraca/dabra 1.0.21 → 1.0.23

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.
@@ -0,0 +1,533 @@
1
+ import * as Y from "yjs";
2
+ import { sha256 } from "@noble/hashes/sha256";
3
+ import EventEmitter from "./EventEmitter.ts";
4
+ import { AbracadabraProvider } from "./AbracadabraProvider.ts";
5
+ import type { AbracadabraProviderConfiguration } from "./AbracadabraProvider.ts";
6
+ import { AbracadabraWS } from "./AbracadabraWS.ts";
7
+ import { AbracadabraWebRTC } from "./webrtc/AbracadabraWebRTC.ts";
8
+ import type { CryptoIdentity } from "./types.ts";
9
+ import type { E2EEIdentity } from "./webrtc/E2EEChannel.ts";
10
+
11
+ // ── Identity Doc ID Derivation ─────────────────────────────────────────────
12
+
13
+ /**
14
+ * Derives a deterministic UUID from an Ed25519 account-level public key.
15
+ *
16
+ * The result is a valid UUID v5-style string that any device sharing the
17
+ * same identity can independently compute. The `abracadabra:identity:`
18
+ * prefix prevents collisions with randomly generated doc UUIDs.
19
+ *
20
+ * @param publicKeyB64 Base64url-encoded Ed25519 public key (32 bytes).
21
+ */
22
+ export function deriveIdentityDocId(publicKeyB64: string): string {
23
+ const hash = sha256(
24
+ new TextEncoder().encode(`abracadabra:identity:${publicKeyB64}`),
25
+ );
26
+ const bytes = new Uint8Array(hash.buffer, hash.byteOffset, 16);
27
+ // Set UUID version 5 + variant 1 bits.
28
+ bytes[6] = (bytes[6] & 0x0f) | 0x50;
29
+ bytes[8] = (bytes[8] & 0x3f) | 0x80;
30
+ const hex = Array.from(bytes, (b) => b.toString(16).padStart(2, "0")).join(
31
+ "",
32
+ );
33
+ return `${hex.slice(0, 8)}-${hex.slice(8, 12)}-${hex.slice(12, 16)}-${hex.slice(16, 20)}-${hex.slice(20, 32)}`;
34
+ }
35
+
36
+ // ── Types ──────────────────────────────────────────────────────────────────
37
+
38
+ export interface IdentityProfile {
39
+ username?: string;
40
+ displayName?: string;
41
+ colorName?: string;
42
+ neutralColorName?: string;
43
+ locale?: string;
44
+ avatarUrl?: string;
45
+ }
46
+
47
+ export interface IdentityServerEntry {
48
+ label: string;
49
+ hubDocId?: string;
50
+ entryDocId?: string;
51
+ defaultRole?: string;
52
+ spacesEnabled?: boolean;
53
+ addedAt: number;
54
+ }
55
+
56
+ export interface IdentitySpaceEntry {
57
+ id: string;
58
+ name: string;
59
+ type: "local" | "remote";
60
+ serverUrl: string | null;
61
+ docId: string;
62
+ remoteSpaceId?: string;
63
+ visibility: "public" | "private" | "invite";
64
+ isHub: boolean;
65
+ order: number;
66
+ lastSyncedAt?: number;
67
+ createdAt: number;
68
+ }
69
+
70
+ export interface IdentityDocConfiguration {
71
+ /** Base64url-encoded Ed25519 account public key. */
72
+ publicKey: string;
73
+
74
+ /**
75
+ * Trusted server URL for identity doc sync.
76
+ * Only this server (plus the local server) will receive the identity doc.
77
+ */
78
+ syncServerUrl?: string;
79
+
80
+ /** Local Tauri server URL for on-device persistence. */
81
+ localServerUrl?: string;
82
+
83
+ /**
84
+ * JWT token or async factory for authenticating with sync servers.
85
+ * When using multiple servers, provide a factory that returns the correct
86
+ * token for each.
87
+ */
88
+ token?: string | (() => string) | (() => Promise<string>);
89
+
90
+ /** Per-server token factories keyed by base URL. */
91
+ tokens?: Record<string, string | (() => string) | (() => Promise<string>)>;
92
+
93
+ /**
94
+ * Crypto identity for Ed25519 challenge-response auth.
95
+ * When provided, used instead of JWT tokens for authenticating with servers.
96
+ */
97
+ cryptoIdentity?: CryptoIdentity | (() => Promise<CryptoIdentity>);
98
+
99
+ /**
100
+ * Signs a base64url challenge and returns a base64url signature.
101
+ * Required when cryptoIdentity is set.
102
+ */
103
+ signChallenge?: (challenge: string) => Promise<string>;
104
+
105
+ /**
106
+ * WebRTC configuration for P2P identity sync.
107
+ * When provided, enables E2EE peer-to-peer sync using signaling from
108
+ * any connected server.
109
+ */
110
+ webrtc?: {
111
+ /** Server URL to use for signaling (any connected server works). */
112
+ signalingServerUrl: string;
113
+ /** Token for the signaling server. */
114
+ token: string | (() => string) | (() => Promise<string>);
115
+ /** E2EE identity for the data channel. */
116
+ e2ee?: E2EEIdentity;
117
+ /** ICE servers. */
118
+ iceServers?: RTCIceServer[];
119
+ };
120
+
121
+ /** Disable IndexedDB offline store. */
122
+ disableOfflineStore?: boolean;
123
+
124
+ /** Auto-connect on construction. Default: true. */
125
+ autoConnect?: boolean;
126
+
127
+ /** Additional provider config passed through to each AbracadabraProvider. */
128
+ providerDefaults?: Partial<AbracadabraProviderConfiguration>;
129
+ }
130
+
131
+ // ── IdentityDocProvider ────────────────────────────────────────────────────
132
+
133
+ /**
134
+ * Manages a Y.Doc dedicated to user identity that syncs across trusted
135
+ * targets only: a designated sync server, a local Tauri server, and/or
136
+ * WebRTC P2P.
137
+ *
138
+ * The Y.Doc contains cross-device settings (profile, servers, spaces,
139
+ * plugins, preferences). Each sync target gets its own
140
+ * AbracadabraProvider sharing the same Y.Doc, with `serverAgnostic: true`
141
+ * so they all use one IndexedDB store.
142
+ */
143
+ export class IdentityDocProvider extends EventEmitter {
144
+ public readonly docId: string;
145
+ public readonly document: Y.Doc;
146
+
147
+ private providers = new Map<string, AbracadabraProvider>();
148
+ private websockets = new Map<string, AbracadabraWS>();
149
+ private webrtc: AbracadabraWebRTC | null = null;
150
+ private config: IdentityDocConfiguration;
151
+ private _destroyed = false;
152
+
153
+ constructor(configuration: IdentityDocConfiguration) {
154
+ super();
155
+ this.config = configuration;
156
+ this.docId = deriveIdentityDocId(configuration.publicKey);
157
+ this.document = new Y.Doc({ guid: this.docId });
158
+
159
+ if (configuration.autoConnect !== false) {
160
+ this.connect();
161
+ }
162
+ }
163
+
164
+ // ── Connection Management ────────────────────────────────────────────────
165
+
166
+ connect(): void {
167
+ if (this._destroyed) return;
168
+
169
+ const targets: Array<{ url: string; key: string }> = [];
170
+
171
+ if (this.config.localServerUrl) {
172
+ targets.push({ url: this.config.localServerUrl, key: "local" });
173
+ }
174
+ if (this.config.syncServerUrl) {
175
+ targets.push({ url: this.config.syncServerUrl, key: "sync" });
176
+ }
177
+
178
+ for (const { url, key } of targets) {
179
+ if (this.providers.has(key)) continue;
180
+ this.connectToServer(key, url);
181
+ }
182
+
183
+ if (this.config.webrtc && !this.webrtc) {
184
+ this._connectWebRTC();
185
+ }
186
+ }
187
+
188
+ connectToServer(key: string, serverUrl: string): void {
189
+ if (this._destroyed) return;
190
+
191
+ // Tear down existing connection for this key (idempotent reconnect)
192
+ const existingProvider = this.providers.get(key);
193
+ if (existingProvider) {
194
+ existingProvider.destroy();
195
+ this.providers.delete(key);
196
+ }
197
+ const existingWs = this.websockets.get(key);
198
+ if (existingWs) {
199
+ existingWs.destroy();
200
+ this.websockets.delete(key);
201
+ }
202
+
203
+ const token =
204
+ this.config.tokens?.[serverUrl] ?? this.config.token ?? "";
205
+
206
+ const wsUrl = serverUrl
207
+ .replace(/^http/, "ws")
208
+ .replace(/\/$/, "")
209
+ .concat("/ws");
210
+
211
+ const ws = new AbracadabraWS({ url: wsUrl, WebSocketPolyfill: undefined as any });
212
+ this.websockets.set(key, ws);
213
+
214
+ const providerConfig: AbracadabraProviderConfiguration = {
215
+ name: this.docId,
216
+ document: this.document,
217
+ websocketProvider: ws,
218
+ serverAgnostic: true,
219
+ disableOfflineStore: key !== "local" && key !== "sync"
220
+ ? true
221
+ : this.config.disableOfflineStore ?? false,
222
+ ...this.config.providerDefaults,
223
+ };
224
+
225
+ // Use crypto identity auth if available, otherwise JWT token
226
+ if (this.config.cryptoIdentity && this.config.signChallenge) {
227
+ providerConfig.cryptoIdentity = this.config.cryptoIdentity;
228
+ providerConfig.signChallenge = this.config.signChallenge;
229
+ } else {
230
+ providerConfig.token = token;
231
+ }
232
+
233
+ const provider = new AbracadabraProvider(providerConfig);
234
+
235
+ provider.on("synced", () => this.emit("synced", { server: key }));
236
+ provider.on("status", (data: any) =>
237
+ this.emit("status", { server: key, ...data }),
238
+ );
239
+
240
+ this.providers.set(key, provider);
241
+ }
242
+
243
+ private _connectWebRTC(): void {
244
+ const rtcConfig = this.config.webrtc;
245
+ if (!rtcConfig) return;
246
+
247
+ this.webrtc = new AbracadabraWebRTC({
248
+ docId: this.docId,
249
+ url: rtcConfig.signalingServerUrl,
250
+ token: rtcConfig.token,
251
+ document: this.document,
252
+ enableDocSync: true,
253
+ enableAwarenessSync: false,
254
+ enableFileTransfer: false,
255
+ e2ee: rtcConfig.e2ee,
256
+ iceServers: rtcConfig.iceServers,
257
+ });
258
+ }
259
+
260
+ // ── Y.Doc Schema Accessors ───────────────────────────────────────────────
261
+
262
+ get profileMap(): Y.Map<string> {
263
+ return this.document.getMap("profile");
264
+ }
265
+
266
+ get serversMap(): Y.Map<Y.Map<any>> {
267
+ return this.document.getMap("servers");
268
+ }
269
+
270
+ get spacesArray(): Y.Array<Y.Map<any>> {
271
+ return this.document.getArray("spaces");
272
+ }
273
+
274
+ get pluginsMap(): Y.Map<any> {
275
+ return this.document.getMap("plugins");
276
+ }
277
+
278
+ get preferencesMap(): Y.Map<any> {
279
+ return this.document.getMap("preferences");
280
+ }
281
+
282
+ // ── Profile ──────────────────────────────────────────────────────────────
283
+
284
+ getProfile(): IdentityProfile {
285
+ const m = this.profileMap;
286
+ return {
287
+ username: m.get("username"),
288
+ displayName: m.get("displayName"),
289
+ colorName: m.get("colorName"),
290
+ neutralColorName: m.get("neutralColorName"),
291
+ locale: m.get("locale"),
292
+ avatarUrl: m.get("avatarUrl"),
293
+ };
294
+ }
295
+
296
+ setProfile(profile: Partial<IdentityProfile>): void {
297
+ const m = this.profileMap;
298
+ this.document.transact(() => {
299
+ for (const [key, value] of Object.entries(profile)) {
300
+ if (value !== undefined) {
301
+ m.set(key, value);
302
+ }
303
+ }
304
+ });
305
+ }
306
+
307
+ // ── Servers ──────────────────────────────────────────────────────────────
308
+
309
+ getServer(url: string): IdentityServerEntry | undefined {
310
+ const entry = this.serversMap.get(url);
311
+ if (!entry) return undefined;
312
+ return {
313
+ label: entry.get("label") ?? url,
314
+ hubDocId: entry.get("hubDocId"),
315
+ entryDocId: entry.get("entryDocId"),
316
+ defaultRole: entry.get("defaultRole"),
317
+ spacesEnabled: entry.get("spacesEnabled"),
318
+ addedAt: entry.get("addedAt") ?? 0,
319
+ };
320
+ }
321
+
322
+ setServer(url: string, entry: IdentityServerEntry): void {
323
+ const m = this.serversMap;
324
+ this.document.transact(() => {
325
+ let yEntry = m.get(url);
326
+ if (!yEntry) {
327
+ yEntry = new Y.Map();
328
+ m.set(url, yEntry);
329
+ }
330
+ for (const [key, value] of Object.entries(entry)) {
331
+ if (value !== undefined) {
332
+ yEntry.set(key, value);
333
+ }
334
+ }
335
+ });
336
+ }
337
+
338
+ removeServer(url: string): void {
339
+ this.serversMap.delete(url);
340
+ }
341
+
342
+ getServers(): Map<string, IdentityServerEntry> {
343
+ const result = new Map<string, IdentityServerEntry>();
344
+ this.serversMap.forEach((entry, url) => {
345
+ result.set(url, {
346
+ label: entry.get("label") ?? url,
347
+ hubDocId: entry.get("hubDocId"),
348
+ entryDocId: entry.get("entryDocId"),
349
+ defaultRole: entry.get("defaultRole"),
350
+ spacesEnabled: entry.get("spacesEnabled"),
351
+ addedAt: entry.get("addedAt") ?? 0,
352
+ });
353
+ });
354
+ return result;
355
+ }
356
+
357
+ // ── Spaces ───────────────────────────────────────────────────────────────
358
+
359
+ getSpaces(): IdentitySpaceEntry[] {
360
+ const result: IdentitySpaceEntry[] = [];
361
+ this.spacesArray.forEach((yMap) => {
362
+ result.push({
363
+ id: yMap.get("id"),
364
+ name: yMap.get("name"),
365
+ type: yMap.get("type") ?? "remote",
366
+ serverUrl: yMap.get("serverUrl") ?? null,
367
+ docId: yMap.get("docId"),
368
+ remoteSpaceId: yMap.get("remoteSpaceId"),
369
+ visibility: yMap.get("visibility") ?? "private",
370
+ isHub: yMap.get("isHub") ?? false,
371
+ order: yMap.get("order") ?? 0,
372
+ lastSyncedAt: yMap.get("lastSyncedAt"),
373
+ createdAt: yMap.get("createdAt") ?? 0,
374
+ });
375
+ });
376
+ return result;
377
+ }
378
+
379
+ addSpace(space: IdentitySpaceEntry): void {
380
+ const yMap = new Y.Map();
381
+ this.document.transact(() => {
382
+ for (const [key, value] of Object.entries(space)) {
383
+ if (value !== undefined) {
384
+ yMap.set(key, value);
385
+ }
386
+ }
387
+ this.spacesArray.push([yMap]);
388
+ });
389
+ }
390
+
391
+ removeSpace(spaceId: string): void {
392
+ const arr = this.spacesArray;
393
+ for (let i = 0; i < arr.length; i++) {
394
+ if (arr.get(i).get("id") === spaceId) {
395
+ arr.delete(i, 1);
396
+ return;
397
+ }
398
+ }
399
+ }
400
+
401
+ updateSpace(spaceId: string, updates: Partial<IdentitySpaceEntry>): void {
402
+ const arr = this.spacesArray;
403
+ for (let i = 0; i < arr.length; i++) {
404
+ const yMap = arr.get(i);
405
+ if (yMap.get("id") === spaceId) {
406
+ this.document.transact(() => {
407
+ for (const [key, value] of Object.entries(updates)) {
408
+ if (value !== undefined) {
409
+ yMap.set(key, value);
410
+ }
411
+ }
412
+ });
413
+ return;
414
+ }
415
+ }
416
+ }
417
+
418
+ // ── Plugins ──────────────────────────────────────────────────────────────
419
+
420
+ getExternalPlugins(): Y.Array<Y.Map<any>> {
421
+ let arr = this.pluginsMap.get("external") as Y.Array<Y.Map<any>> | undefined;
422
+ if (!arr) {
423
+ arr = new Y.Array();
424
+ this.pluginsMap.set("external", arr);
425
+ }
426
+ return arr;
427
+ }
428
+
429
+ getDisabledBuiltins(): Y.Array<string> {
430
+ let arr = this.pluginsMap.get("disabledBuiltins") as Y.Array<string> | undefined;
431
+ if (!arr) {
432
+ arr = new Y.Array();
433
+ this.pluginsMap.set("disabledBuiltins", arr);
434
+ }
435
+ return arr;
436
+ }
437
+
438
+ // ── Preferences ──────────────────────────────────────────────────────────
439
+
440
+ getPreference<T = any>(key: string): T | undefined {
441
+ return this.preferencesMap.get(key);
442
+ }
443
+
444
+ setPreference(key: string, value: any): void {
445
+ this.preferencesMap.set(key, value);
446
+ }
447
+
448
+ // ── Observation ──────────────────────────────────────────────────────────
449
+
450
+ /**
451
+ * Observe deep changes on a specific top-level map.
452
+ * Returns an unsubscribe function.
453
+ */
454
+ observe(
455
+ mapName: "profile" | "servers" | "plugins" | "preferences",
456
+ callback: (events: Y.YEvent<any>[], transaction: Y.Transaction) => void,
457
+ ): () => void {
458
+ const map = this.document.getMap(mapName);
459
+ map.observeDeep(callback);
460
+ return () => map.unobserveDeep(callback);
461
+ }
462
+
463
+ /**
464
+ * Observe changes to the spaces array.
465
+ * Returns an unsubscribe function.
466
+ */
467
+ observeSpaces(
468
+ callback: (event: Y.YArrayEvent<Y.Map<any>>, transaction: Y.Transaction) => void,
469
+ ): () => void {
470
+ const arr = this.spacesArray;
471
+ arr.observe(callback);
472
+ return () => arr.unobserve(callback);
473
+ }
474
+
475
+ // ── Migration ────────────────────────────────────────────────────────────
476
+
477
+ /**
478
+ * Returns true if the identity doc has no profile data yet (first use).
479
+ * Call this to decide whether to run migration from localStorage.
480
+ */
481
+ isEmpty(): boolean {
482
+ return this.profileMap.size === 0 && this.serversMap.size === 0;
483
+ }
484
+
485
+ // ── Lifecycle ────────────────────────────────────────────────────────────
486
+
487
+ /**
488
+ * Update the sync server URL at runtime (e.g. when user changes their
489
+ * designated sync server in settings).
490
+ */
491
+ setSyncServer(url: string | null): void {
492
+ // Tear down existing sync provider if any.
493
+ const existing = this.providers.get("sync");
494
+ if (existing) {
495
+ existing.destroy();
496
+ this.providers.delete("sync");
497
+ }
498
+ const existingWs = this.websockets.get("sync");
499
+ if (existingWs) {
500
+ existingWs.destroy();
501
+ this.websockets.delete("sync");
502
+ }
503
+
504
+ if (url) {
505
+ this.config = { ...this.config, syncServerUrl: url };
506
+ this.connectToServer("sync", url);
507
+ }
508
+ }
509
+
510
+ getProvider(key: string): AbracadabraProvider | undefined {
511
+ return this.providers.get(key);
512
+ }
513
+
514
+ destroy(): void {
515
+ if (this._destroyed) return;
516
+ this._destroyed = true;
517
+
518
+ for (const [, provider] of this.providers) {
519
+ provider.destroy();
520
+ }
521
+ for (const [, ws] of this.websockets) {
522
+ ws.destroy();
523
+ }
524
+ if (this.webrtc) {
525
+ (this.webrtc as any).disconnect?.();
526
+ }
527
+
528
+ this.providers.clear();
529
+ this.websockets.clear();
530
+ this.webrtc = null;
531
+ this.document.destroy();
532
+ }
533
+ }
package/src/index.ts CHANGED
@@ -25,3 +25,10 @@ export { BackgroundSyncPersistence } from "./BackgroundSyncPersistence.ts";
25
25
  export type { DocSyncState } from "./BackgroundSyncPersistence.ts";
26
26
  export * from "./webrtc/index.ts";
27
27
  export { BroadcastChannelSync } from "./sync/BroadcastChannelSync.ts";
28
+ export { IdentityDocProvider, deriveIdentityDocId } from "./IdentityDoc.ts";
29
+ export type {
30
+ IdentityDocConfiguration,
31
+ IdentityProfile,
32
+ IdentityServerEntry,
33
+ IdentitySpaceEntry,
34
+ } from "./IdentityDoc.ts";