@abraca/dabra 2.90.0 → 2.92.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,426 +0,0 @@
|
|
|
1
|
-
/**
|
|
2
|
-
* E2EAbracadabraProvider
|
|
3
|
-
*
|
|
4
|
-
* Extends AbracadabraProvider with full E2E encryption support.
|
|
5
|
-
*
|
|
6
|
-
* Differences from standard provider:
|
|
7
|
-
* - startSync() sends a stateless e2e_sync_request instead of SYNC_STEP1
|
|
8
|
-
* - On receiving e2e_ready, fetches all blobs via REST, decrypts, applies to Y.Doc
|
|
9
|
-
* - Local updates are AES-GCM encrypted before sending over WebSocket
|
|
10
|
-
* - Incoming e2e_update stateless messages are decrypted and applied
|
|
11
|
-
*
|
|
12
|
-
* Phase 2 offline support:
|
|
13
|
-
* - After the doc key is obtained, an E2EOfflineStore is created for this doc.
|
|
14
|
-
* - The stored encrypted snapshot is applied before fetching server updates.
|
|
15
|
-
* - The last-seen sequence number (e2e_seq) is persisted so only delta updates
|
|
16
|
-
* are fetched on subsequent connects.
|
|
17
|
-
* - After sync, a fresh encrypted snapshot is saved.
|
|
18
|
-
*
|
|
19
|
-
* Client-side compaction:
|
|
20
|
-
* - After `compactionThreshold` encrypted updates have been applied in this
|
|
21
|
-
* session (local + remote), and the doc has been quiescent for
|
|
22
|
-
* `compactionQuiescenceMs`, the provider merges the whole Y.Doc, encrypts it,
|
|
23
|
-
* and sends `snapshot:compact` — the server atomically replaces the per-doc
|
|
24
|
-
* update log with that single compacted blob. The server acknowledges by
|
|
25
|
-
* broadcasting `snapshot:compacted`, which emits the `"compacted"` event.
|
|
26
|
-
* - Requires Owner or above (server silently drops non-Owner requests).
|
|
27
|
-
* - Callers that want a final compaction before teardown should
|
|
28
|
-
* `await provider.compactNow()` before `destroy()`. `destroy()` does not
|
|
29
|
-
* compact (it'd race with the socket teardown) — any pending debounce is
|
|
30
|
-
* cancelled.
|
|
31
|
-
*
|
|
32
|
-
* Key availability limitation: if the user's WebAuthn key is not in
|
|
33
|
-
* DocKeyManager's in-memory cache and there is no network, E2E docs show
|
|
34
|
-
* empty — the key fetch requires either a cached in-memory key or network.
|
|
35
|
-
*/
|
|
36
|
-
|
|
37
|
-
import * as Y from "yjs";
|
|
38
|
-
import { AbracadabraProvider } from "./AbracadabraProvider.ts";
|
|
39
|
-
import type { AbracadabraProviderConfiguration } from "./AbracadabraProvider.ts";
|
|
40
|
-
import type { DocKeyManager } from "./DocKeyManager.ts";
|
|
41
|
-
import type { CryptoIdentityKeystore } from "./CryptoIdentityKeystore.ts";
|
|
42
|
-
import type { AbracadabraClient } from "./AbracadabraClient.ts";
|
|
43
|
-
import { UpdateMessage } from "./OutgoingMessages/UpdateMessage.ts";
|
|
44
|
-
import { encryptField, decryptField } from "./EncryptedY.ts";
|
|
45
|
-
import { E2EOfflineStore } from "./E2EOfflineStore.ts";
|
|
46
|
-
import type { onCompactedParameters } from "./types.ts";
|
|
47
|
-
|
|
48
|
-
function fromBase64(b64: string): Uint8Array {
|
|
49
|
-
return Uint8Array.from(atob(b64), (c) => c.charCodeAt(0));
|
|
50
|
-
}
|
|
51
|
-
|
|
52
|
-
function toBase64(bytes: Uint8Array): string {
|
|
53
|
-
let bin = "";
|
|
54
|
-
for (let i = 0; i < bytes.length; i += 0x8000) {
|
|
55
|
-
bin += String.fromCharCode(...bytes.subarray(i, i + 0x8000));
|
|
56
|
-
}
|
|
57
|
-
return btoa(bin);
|
|
58
|
-
}
|
|
59
|
-
|
|
60
|
-
export interface E2EAbracadabraProviderConfiguration extends AbracadabraProviderConfiguration {
|
|
61
|
-
docKeyManager: DocKeyManager;
|
|
62
|
-
keystore: CryptoIdentityKeystore;
|
|
63
|
-
client: AbracadabraClient;
|
|
64
|
-
/**
|
|
65
|
-
* Enable client-side compaction: after `compactionThreshold` E2E updates,
|
|
66
|
-
* the provider merges the whole doc, re-encrypts it, and asks the server to
|
|
67
|
-
* atomically replace its update log via the `snapshot:compact` stateless
|
|
68
|
-
* protocol. Requires the user to have a role that `can_manage` the doc
|
|
69
|
-
* (Owner or above); otherwise the server silently rejects.
|
|
70
|
-
*
|
|
71
|
-
* Default: true.
|
|
72
|
-
*/
|
|
73
|
-
compactionEnabled?: boolean;
|
|
74
|
-
/**
|
|
75
|
-
* Number of E2E updates applied in this session before compaction fires.
|
|
76
|
-
* Default: 50. Ignored when `compactionEnabled === false`.
|
|
77
|
-
*/
|
|
78
|
-
compactionThreshold?: number;
|
|
79
|
-
/**
|
|
80
|
-
* Quiescence delay: once the threshold is crossed, wait this many ms with
|
|
81
|
-
* no further updates before firing compaction. Debounces active editing
|
|
82
|
-
* and reduces the chance of racing an in-flight remote update that hasn't
|
|
83
|
-
* reached us yet (the server does not currently validate state-vector
|
|
84
|
-
* coverage, so a compaction fired mid-flight could drop an update).
|
|
85
|
-
*
|
|
86
|
-
* Default: 2000 ms.
|
|
87
|
-
*/
|
|
88
|
-
compactionQuiescenceMs?: number;
|
|
89
|
-
}
|
|
90
|
-
|
|
91
|
-
export class E2EAbracadabraProvider extends AbracadabraProvider {
|
|
92
|
-
private readonly docKeyManager: DocKeyManager;
|
|
93
|
-
private readonly keystore: CryptoIdentityKeystore;
|
|
94
|
-
private readonly e2eClient: AbracadabraClient;
|
|
95
|
-
private docKey: CryptoKey | null = null;
|
|
96
|
-
private lastSeq = -1;
|
|
97
|
-
|
|
98
|
-
/** E2E-encrypted offline store; created after the doc key is available. */
|
|
99
|
-
private e2eStore: E2EOfflineStore | null = null;
|
|
100
|
-
private readonly e2eServerOrigin: string | undefined;
|
|
101
|
-
|
|
102
|
-
// ── Client-side compaction ────────────────────────────────────────────────
|
|
103
|
-
private readonly compactionEnabled: boolean;
|
|
104
|
-
private readonly compactionThreshold: number;
|
|
105
|
-
private readonly compactionQuiescenceMs: number;
|
|
106
|
-
private updatesSinceCompaction = 0;
|
|
107
|
-
private compactionInFlight = false;
|
|
108
|
-
/** Cleared on `snapshot:compacted` or on 30s timeout. */
|
|
109
|
-
private compactionInFlightTimeout: ReturnType<typeof setTimeout> | null = null;
|
|
110
|
-
/** Quiescence debounce: reset on every update, fires the actual compaction. */
|
|
111
|
-
private compactionDebounceTimer: ReturnType<typeof setTimeout> | null = null;
|
|
112
|
-
private destroyed = false;
|
|
113
|
-
/**
|
|
114
|
-
* Plaintext local updates produced while this doc is not yet authenticated
|
|
115
|
-
* on the connection. Unlike the plaintext provider, E2E does not convey
|
|
116
|
-
* local state via SyncStep2 (it ships discrete encrypted update frames keyed
|
|
117
|
-
* by server-assigned seq), so a pre-auth update that loses the AUTH race and
|
|
118
|
-
* gets "not subscribed"-rejected would be lost. We queue them here and flush
|
|
119
|
-
* (encrypt + send) once `authenticatedHandler` confirms the doc is
|
|
120
|
-
* subscribed. Survives reconnects (only cleared on flush or destroy).
|
|
121
|
-
*/
|
|
122
|
-
private _pendingPreAuthUpdates: Uint8Array[] = [];
|
|
123
|
-
|
|
124
|
-
constructor(configuration: E2EAbracadabraProviderConfiguration) {
|
|
125
|
-
// Disable the parent's offline store — E2E uses its own encrypted store.
|
|
126
|
-
super({ ...configuration, disableOfflineStore: true });
|
|
127
|
-
this.docKeyManager = configuration.docKeyManager;
|
|
128
|
-
this.keystore = configuration.keystore;
|
|
129
|
-
this.e2eClient = configuration.client;
|
|
130
|
-
|
|
131
|
-
this.compactionEnabled = configuration.compactionEnabled !== false;
|
|
132
|
-
this.compactionThreshold = Math.max(1, configuration.compactionThreshold ?? 50);
|
|
133
|
-
this.compactionQuiescenceMs = Math.max(0, configuration.compactionQuiescenceMs ?? 2000);
|
|
134
|
-
|
|
135
|
-
// Derive server origin for E2EOfflineStore namespacing
|
|
136
|
-
this.e2eServerOrigin = E2EAbracadabraProvider.deriveServerOrigin(
|
|
137
|
-
configuration,
|
|
138
|
-
configuration.client,
|
|
139
|
-
);
|
|
140
|
-
}
|
|
141
|
-
|
|
142
|
-
/** Fetch the doc key from the server (requires WebAuthn if not cached). */
|
|
143
|
-
private async ensureDocKey(): Promise<CryptoKey | null> {
|
|
144
|
-
if (this.docKey) return this.docKey;
|
|
145
|
-
this.docKey = await this.docKeyManager.getDocKey(
|
|
146
|
-
this.configuration.name,
|
|
147
|
-
this.e2eClient,
|
|
148
|
-
this.keystore,
|
|
149
|
-
);
|
|
150
|
-
|
|
151
|
-
// Create the encrypted offline store now that we have the key
|
|
152
|
-
if (this.docKey && !this.e2eStore) {
|
|
153
|
-
this.e2eStore = new E2EOfflineStore(
|
|
154
|
-
this.configuration.name,
|
|
155
|
-
this.e2eServerOrigin,
|
|
156
|
-
this.docKey,
|
|
157
|
-
);
|
|
158
|
-
}
|
|
159
|
-
|
|
160
|
-
return this.docKey;
|
|
161
|
-
}
|
|
162
|
-
|
|
163
|
-
/** Handle stateless messages including e2e_ready and e2e_update. */
|
|
164
|
-
override receiveStateless(payload: string): void {
|
|
165
|
-
// `snapshot:compacted {"doc_id":"...","by":"..."}` is a space-separated
|
|
166
|
-
// stateless frame — not valid JSON as a whole — so handle it before the
|
|
167
|
-
// JSON.parse fallthrough.
|
|
168
|
-
if (payload.startsWith("snapshot:compacted ")) {
|
|
169
|
-
this._handleCompactedBroadcast(payload.slice("snapshot:compacted ".length));
|
|
170
|
-
return;
|
|
171
|
-
}
|
|
172
|
-
|
|
173
|
-
let parsed: unknown;
|
|
174
|
-
try {
|
|
175
|
-
parsed = JSON.parse(payload);
|
|
176
|
-
} catch {
|
|
177
|
-
super.receiveStateless(payload);
|
|
178
|
-
return;
|
|
179
|
-
}
|
|
180
|
-
|
|
181
|
-
const msg = parsed as { type?: string; seq?: number; data?: string; doc_id?: string };
|
|
182
|
-
|
|
183
|
-
if (msg.type === "e2e_ready") {
|
|
184
|
-
// Fetch all blobs and hydrate doc
|
|
185
|
-
this._fetchAndApplyAllBlobs().catch((e) => {
|
|
186
|
-
console.error("[E2EAbracadabraProvider] failed to fetch e2e blobs:", e);
|
|
187
|
-
});
|
|
188
|
-
return;
|
|
189
|
-
}
|
|
190
|
-
|
|
191
|
-
if (msg.type === "e2e_update" && msg.data !== undefined && msg.seq !== undefined) {
|
|
192
|
-
if (msg.seq <= this.lastSeq) return; // Already applied
|
|
193
|
-
this._decryptAndApply(fromBase64(msg.data), msg.seq).catch((e) => {
|
|
194
|
-
console.error("[E2EAbracadabraProvider] failed to apply e2e_update:", e);
|
|
195
|
-
});
|
|
196
|
-
return;
|
|
197
|
-
}
|
|
198
|
-
|
|
199
|
-
super.receiveStateless(payload);
|
|
200
|
-
}
|
|
201
|
-
|
|
202
|
-
private async _fetchAndApplyAllBlobs(): Promise<void> {
|
|
203
|
-
const key = await this.ensureDocKey();
|
|
204
|
-
if (!key) {
|
|
205
|
-
console.warn("[E2EAbracadabraProvider] no doc key available, cannot decrypt blobs");
|
|
206
|
-
this.synced = true;
|
|
207
|
-
return;
|
|
208
|
-
}
|
|
209
|
-
|
|
210
|
-
// Phase 2: load stored snapshot + lastSeq before fetching from server
|
|
211
|
-
if (this.e2eStore) {
|
|
212
|
-
const storedSeqStr = await this.e2eStore.getMeta("e2e_seq").catch(() => null);
|
|
213
|
-
if (storedSeqStr !== null) {
|
|
214
|
-
this.lastSeq = parseInt(storedSeqStr, 10);
|
|
215
|
-
}
|
|
216
|
-
|
|
217
|
-
const snapshot = await this.e2eStore.getDocSnapshot().catch(() => null);
|
|
218
|
-
if (snapshot) {
|
|
219
|
-
Y.applyUpdate(this.document, snapshot, this.e2eStore);
|
|
220
|
-
}
|
|
221
|
-
}
|
|
222
|
-
|
|
223
|
-
// Only fetch updates newer than lastSeq
|
|
224
|
-
const updates = await this.e2eClient.getE2EUpdatesSince(
|
|
225
|
-
this.configuration.name,
|
|
226
|
-
this.lastSeq,
|
|
227
|
-
);
|
|
228
|
-
for (const { seq, data } of updates) {
|
|
229
|
-
await this._decryptAndApply(data, seq);
|
|
230
|
-
}
|
|
231
|
-
|
|
232
|
-
this.synced = true;
|
|
233
|
-
|
|
234
|
-
// Phase 2: persist updated snapshot and lastSeq
|
|
235
|
-
if (this.e2eStore) {
|
|
236
|
-
const snapshot = Y.encodeStateAsUpdate(this.document);
|
|
237
|
-
await this.e2eStore.saveDocSnapshot(snapshot).catch(() => null);
|
|
238
|
-
await this.e2eStore.setMeta("e2e_seq", String(this.lastSeq)).catch(() => null);
|
|
239
|
-
}
|
|
240
|
-
}
|
|
241
|
-
|
|
242
|
-
private async _decryptAndApply(encryptedData: Uint8Array, seq: number): Promise<void> {
|
|
243
|
-
const key = await this.ensureDocKey();
|
|
244
|
-
if (!key) return;
|
|
245
|
-
try {
|
|
246
|
-
const plaintext = await decryptField(encryptedData, key);
|
|
247
|
-
Y.applyUpdate(this.document, plaintext, this);
|
|
248
|
-
this.lastSeq = Math.max(this.lastSeq, seq);
|
|
249
|
-
this._noteUpdateApplied();
|
|
250
|
-
} catch (e) {
|
|
251
|
-
console.error("[E2EAbracadabraProvider] decryption failed for seq", seq, e);
|
|
252
|
-
}
|
|
253
|
-
}
|
|
254
|
-
|
|
255
|
-
/** Encrypt local updates before sending over WebSocket. */
|
|
256
|
-
override documentUpdateHandler(update: Uint8Array, origin: unknown): void {
|
|
257
|
-
if (origin === this) return;
|
|
258
|
-
|
|
259
|
-
// AUTH-ordering guard (see _pendingPreAuthUpdates): until the doc is
|
|
260
|
-
// authenticated on the connection, an encrypted update would race ahead
|
|
261
|
-
// of the AUTH frame on the shared multiplexed socket and be rejected with
|
|
262
|
-
// "not subscribed". Queue it and flush on authenticatedHandler instead of
|
|
263
|
-
// racing (and losing) it.
|
|
264
|
-
if (!this.isAuthenticated) {
|
|
265
|
-
this._pendingPreAuthUpdates.push(update);
|
|
266
|
-
return;
|
|
267
|
-
}
|
|
268
|
-
|
|
269
|
-
// Don't call super (which would send plaintext); encrypt first
|
|
270
|
-
this._encryptAndSend(update).catch((e) => {
|
|
271
|
-
console.error("[E2EAbracadabraProvider] failed to encrypt update:", e);
|
|
272
|
-
});
|
|
273
|
-
}
|
|
274
|
-
|
|
275
|
-
/**
|
|
276
|
-
* Flush updates buffered while unauthenticated once the server confirms the
|
|
277
|
-
* doc is subscribed, then resume normal live sends.
|
|
278
|
-
*/
|
|
279
|
-
override authenticatedHandler(scope: string): void {
|
|
280
|
-
super.authenticatedHandler(scope);
|
|
281
|
-
if (this._pendingPreAuthUpdates.length === 0) return;
|
|
282
|
-
const pending = this._pendingPreAuthUpdates;
|
|
283
|
-
this._pendingPreAuthUpdates = [];
|
|
284
|
-
for (const update of pending) {
|
|
285
|
-
this._encryptAndSend(update).catch((e) => {
|
|
286
|
-
console.error("[E2EAbracadabraProvider] failed to flush pre-auth update:", e);
|
|
287
|
-
});
|
|
288
|
-
}
|
|
289
|
-
}
|
|
290
|
-
|
|
291
|
-
private async _encryptAndSend(update: Uint8Array): Promise<void> {
|
|
292
|
-
const key = await this.ensureDocKey();
|
|
293
|
-
if (!key) {
|
|
294
|
-
console.warn("[E2EAbracadabraProvider] no doc key, dropping update");
|
|
295
|
-
return;
|
|
296
|
-
}
|
|
297
|
-
const encrypted = await encryptField(update, key);
|
|
298
|
-
this.send(UpdateMessage, {
|
|
299
|
-
update: encrypted,
|
|
300
|
-
documentName: this.configuration.name,
|
|
301
|
-
});
|
|
302
|
-
this._noteUpdateApplied();
|
|
303
|
-
}
|
|
304
|
-
|
|
305
|
-
// ── Compaction ────────────────────────────────────────────────────────────
|
|
306
|
-
|
|
307
|
-
/**
|
|
308
|
-
* Force an immediate compaction attempt, bypassing the threshold and
|
|
309
|
-
* quiescence debounce. Resolves once the `snapshot:compact` frame has been
|
|
310
|
-
* sent (or rejected locally for missing prerequisites — destroyed, no
|
|
311
|
-
* doc key, or already in-flight). The server acknowledges via a
|
|
312
|
-
* `snapshot:compacted` broadcast, which emits the `"compacted"` event.
|
|
313
|
-
*/
|
|
314
|
-
async compactNow(): Promise<void> {
|
|
315
|
-
if (this.compactionDebounceTimer) {
|
|
316
|
-
clearTimeout(this.compactionDebounceTimer);
|
|
317
|
-
this.compactionDebounceTimer = null;
|
|
318
|
-
}
|
|
319
|
-
await this._performCompaction();
|
|
320
|
-
}
|
|
321
|
-
|
|
322
|
-
private _noteUpdateApplied(): void {
|
|
323
|
-
if (!this.compactionEnabled || this.destroyed) return;
|
|
324
|
-
this.updatesSinceCompaction += 1;
|
|
325
|
-
if (this.updatesSinceCompaction < this.compactionThreshold) return;
|
|
326
|
-
|
|
327
|
-
// Debounce: reset on every update so compaction only fires after a
|
|
328
|
-
// quiescent window. This avoids racing concurrent remote updates that
|
|
329
|
-
// are still propagating through the server.
|
|
330
|
-
if (this.compactionDebounceTimer) clearTimeout(this.compactionDebounceTimer);
|
|
331
|
-
this.compactionDebounceTimer = setTimeout(() => {
|
|
332
|
-
this.compactionDebounceTimer = null;
|
|
333
|
-
this._performCompaction().catch((e) => {
|
|
334
|
-
console.error("[E2EAbracadabraProvider] compaction failed:", e);
|
|
335
|
-
});
|
|
336
|
-
}, this.compactionQuiescenceMs);
|
|
337
|
-
}
|
|
338
|
-
|
|
339
|
-
private async _performCompaction(): Promise<void> {
|
|
340
|
-
if (this.destroyed) return;
|
|
341
|
-
// Single-flight: server handles concurrent compactions, but we don't
|
|
342
|
-
// want to pile up outbound frames.
|
|
343
|
-
if (this.compactionInFlight) return;
|
|
344
|
-
// Nothing to compact — skip unless explicitly forced after threshold.
|
|
345
|
-
if (this.updatesSinceCompaction === 0) return;
|
|
346
|
-
|
|
347
|
-
// Compaction replaces the entire server-side update log with our state.
|
|
348
|
-
// Only run after the initial sync — otherwise we'd overwrite the log
|
|
349
|
-
// with a partial state.
|
|
350
|
-
if (!this.synced) return;
|
|
351
|
-
|
|
352
|
-
const key = await this.ensureDocKey();
|
|
353
|
-
if (!key) return;
|
|
354
|
-
if (this.destroyed) return; // key fetch may be async
|
|
355
|
-
|
|
356
|
-
this.compactionInFlight = true;
|
|
357
|
-
try {
|
|
358
|
-
const stateVector = Y.encodeStateVector(this.document);
|
|
359
|
-
const fullState = Y.encodeStateAsUpdate(this.document);
|
|
360
|
-
const encrypted = await encryptField(fullState, key);
|
|
361
|
-
if (this.destroyed) {
|
|
362
|
-
this.compactionInFlight = false;
|
|
363
|
-
return;
|
|
364
|
-
}
|
|
365
|
-
|
|
366
|
-
const payload = `snapshot:compact ${JSON.stringify({
|
|
367
|
-
state_vector: toBase64(stateVector),
|
|
368
|
-
compacted: toBase64(encrypted),
|
|
369
|
-
})}`;
|
|
370
|
-
this.sendStateless(payload);
|
|
371
|
-
|
|
372
|
-
// Release in-flight on server broadcast; if nothing arrives in 30s
|
|
373
|
-
// (e.g. permissions rejected, connection dropped) release anyway.
|
|
374
|
-
this.compactionInFlightTimeout = setTimeout(() => {
|
|
375
|
-
this.compactionInFlight = false;
|
|
376
|
-
this.compactionInFlightTimeout = null;
|
|
377
|
-
}, 30_000);
|
|
378
|
-
} catch (e) {
|
|
379
|
-
this.compactionInFlight = false;
|
|
380
|
-
throw e;
|
|
381
|
-
}
|
|
382
|
-
}
|
|
383
|
-
|
|
384
|
-
private _handleCompactedBroadcast(jsonStr: string): void {
|
|
385
|
-
let parsed: { doc_id?: string; by?: string } = {};
|
|
386
|
-
try {
|
|
387
|
-
parsed = JSON.parse(jsonStr);
|
|
388
|
-
} catch {
|
|
389
|
-
/* malformed — still clear in-flight below */
|
|
390
|
-
}
|
|
391
|
-
|
|
392
|
-
// Only act on broadcasts for our own doc (server scopes this already,
|
|
393
|
-
// but be defensive).
|
|
394
|
-
if (parsed.doc_id && parsed.doc_id !== this.configuration.name) return;
|
|
395
|
-
|
|
396
|
-
if (this.compactionInFlightTimeout) {
|
|
397
|
-
clearTimeout(this.compactionInFlightTimeout);
|
|
398
|
-
this.compactionInFlightTimeout = null;
|
|
399
|
-
}
|
|
400
|
-
this.compactionInFlight = false;
|
|
401
|
-
this.updatesSinceCompaction = 0;
|
|
402
|
-
|
|
403
|
-
const event: onCompactedParameters = {
|
|
404
|
-
docId: parsed.doc_id ?? this.configuration.name,
|
|
405
|
-
by: parsed.by,
|
|
406
|
-
};
|
|
407
|
-
this.emit("compacted", event);
|
|
408
|
-
}
|
|
409
|
-
|
|
410
|
-
override destroy(): void {
|
|
411
|
-
if (this.destroyed) return;
|
|
412
|
-
this.destroyed = true;
|
|
413
|
-
|
|
414
|
-
if (this.compactionDebounceTimer) {
|
|
415
|
-
clearTimeout(this.compactionDebounceTimer);
|
|
416
|
-
this.compactionDebounceTimer = null;
|
|
417
|
-
}
|
|
418
|
-
if (this.compactionInFlightTimeout) {
|
|
419
|
-
clearTimeout(this.compactionInFlightTimeout);
|
|
420
|
-
this.compactionInFlightTimeout = null;
|
|
421
|
-
}
|
|
422
|
-
this.e2eStore?.destroy();
|
|
423
|
-
this.e2eStore = null;
|
|
424
|
-
super.destroy();
|
|
425
|
-
}
|
|
426
|
-
}
|
package/src/E2EOfflineStore.ts
DELETED
|
@@ -1,55 +0,0 @@
|
|
|
1
|
-
/**
|
|
2
|
-
* E2EOfflineStore
|
|
3
|
-
*
|
|
4
|
-
* Extends OfflineStore with transparent AES-GCM encryption of the document
|
|
5
|
-
* snapshot, ensuring that even if the device is compromised, the local
|
|
6
|
-
* IndexedDB data cannot be read without the doc key.
|
|
7
|
-
*
|
|
8
|
-
* Only the snapshot is encrypted (not the meta store entries, which contain
|
|
9
|
-
* non-sensitive data like sequence numbers).
|
|
10
|
-
*
|
|
11
|
-
* Key availability limitation: if the user's WebAuthn key is not in
|
|
12
|
-
* DocKeyManager's in-memory cache and there is no network, E2E docs show
|
|
13
|
-
* empty — this is expected Phase 2 behavior.
|
|
14
|
-
*/
|
|
15
|
-
|
|
16
|
-
import { OfflineStore } from "./OfflineStore.ts";
|
|
17
|
-
import { encryptField, decryptField } from "./EncryptedY.ts";
|
|
18
|
-
|
|
19
|
-
export class E2EOfflineStore extends OfflineStore {
|
|
20
|
-
private readonly docKey: CryptoKey;
|
|
21
|
-
|
|
22
|
-
/**
|
|
23
|
-
* @param docId The document UUID.
|
|
24
|
-
* @param serverOrigin Hostname of the server (namespaces the IDB key).
|
|
25
|
-
* @param docKey AES-GCM CryptoKey used to encrypt/decrypt the snapshot.
|
|
26
|
-
*/
|
|
27
|
-
constructor(docId: string, serverOrigin: string | undefined, docKey: CryptoKey) {
|
|
28
|
-
super(docId, serverOrigin);
|
|
29
|
-
this.docKey = docKey;
|
|
30
|
-
}
|
|
31
|
-
|
|
32
|
-
/**
|
|
33
|
-
* Encrypt the snapshot before storing it.
|
|
34
|
-
*/
|
|
35
|
-
override async saveDocSnapshot(snapshot: Uint8Array): Promise<void> {
|
|
36
|
-
const encrypted = await encryptField(snapshot, this.docKey);
|
|
37
|
-
await super.saveDocSnapshot(encrypted);
|
|
38
|
-
}
|
|
39
|
-
|
|
40
|
-
/**
|
|
41
|
-
* Decrypt the snapshot after loading it.
|
|
42
|
-
* Returns null if decryption fails (e.g. key mismatch or corrupt data).
|
|
43
|
-
*/
|
|
44
|
-
override async getDocSnapshot(): Promise<Uint8Array | null> {
|
|
45
|
-
const encrypted = await super.getDocSnapshot();
|
|
46
|
-
if (!encrypted) return null;
|
|
47
|
-
try {
|
|
48
|
-
return await decryptField(encrypted, this.docKey);
|
|
49
|
-
} catch {
|
|
50
|
-
// Key mismatch or tampered data — return null so the provider falls
|
|
51
|
-
// back to fetching from the server.
|
|
52
|
-
return null;
|
|
53
|
-
}
|
|
54
|
-
}
|
|
55
|
-
}
|
|
@@ -1,173 +0,0 @@
|
|
|
1
|
-
/**
|
|
2
|
-
* EncryptedChatClient — `ChatClient` wrapper that transparently encrypts
|
|
3
|
-
* message content for channels in `e2e` mode and decrypts entries read
|
|
4
|
-
* back from the period doc's `messages` Y.Array.
|
|
5
|
-
*
|
|
6
|
-
* Threat model
|
|
7
|
-
* - Server cannot read message bodies (the `content` field is opaque
|
|
8
|
-
* ciphertext bytes, base64-encoded into the wire string).
|
|
9
|
-
* - Server CAN see `sender_id`, `channel_doc_id`, `period_id`, `ts`,
|
|
10
|
-
* `mentions[]` (kept cleartext for fan-out), `message_id`,
|
|
11
|
-
* and the `server_sig` it stamps. That envelope is the only thing
|
|
12
|
-
* the server inspects to do its job.
|
|
13
|
-
*
|
|
14
|
-
* Wire format
|
|
15
|
-
* `content` for an e2e message is the literal string
|
|
16
|
-
* `"e2e:1:<base64>"`
|
|
17
|
-
* where the decoded blob is `[nonce(12) || AES-GCM-ciphertext]` and
|
|
18
|
-
* the AES-256-GCM key is the channel's existing DocKey (the same one
|
|
19
|
-
* used for `EncryptedY` doc-level encryption — same threat boundary,
|
|
20
|
-
* no extra key derivation, identical envelope distribution).
|
|
21
|
-
*
|
|
22
|
-
* The `e2e:1:` sentinel is a strict prefix to disambiguate from
|
|
23
|
-
* cleartext content that happens to start with "{". Never unwrap a
|
|
24
|
-
* message whose content doesn't start with the sentinel — passing
|
|
25
|
-
* ciphertext from a server you don't trust through `decrypt` would
|
|
26
|
-
* open the door to malformed-input oracles.
|
|
27
|
-
*/
|
|
28
|
-
|
|
29
|
-
import { encryptField, decryptField } from "./EncryptedY.ts";
|
|
30
|
-
import { DocKeyManager } from "./DocKeyManager.ts";
|
|
31
|
-
import type { AbracadabraClient } from "./AbracadabraClient.ts";
|
|
32
|
-
import type { CryptoIdentityKeystore } from "./CryptoIdentityKeystore.ts";
|
|
33
|
-
import type {
|
|
34
|
-
ChatClient,
|
|
35
|
-
SendMessageInput,
|
|
36
|
-
SendMessageResult,
|
|
37
|
-
EditMessageInput,
|
|
38
|
-
} from "./ChatClient.ts";
|
|
39
|
-
|
|
40
|
-
const SENTINEL = "e2e:1:";
|
|
41
|
-
|
|
42
|
-
function toBase64(bytes: Uint8Array): string {
|
|
43
|
-
let s = "";
|
|
44
|
-
for (let i = 0; i < bytes.length; i++) s += String.fromCharCode(bytes[i]!);
|
|
45
|
-
return btoa(s);
|
|
46
|
-
}
|
|
47
|
-
|
|
48
|
-
function fromBase64(b64: string): Uint8Array {
|
|
49
|
-
const bin = atob(b64);
|
|
50
|
-
const out = new Uint8Array(bin.length);
|
|
51
|
-
for (let i = 0; i < bin.length; i++) out[i] = bin.charCodeAt(i);
|
|
52
|
-
return out;
|
|
53
|
-
}
|
|
54
|
-
|
|
55
|
-
/**
|
|
56
|
-
* Returns true if `content` is wrapped by this module (i.e. an `e2e:1:`
|
|
57
|
-
* envelope). Cleartext content always returns false.
|
|
58
|
-
*/
|
|
59
|
-
export function isEncryptedContent(content: string): boolean {
|
|
60
|
-
return typeof content === "string" && content.startsWith(SENTINEL);
|
|
61
|
-
}
|
|
62
|
-
|
|
63
|
-
/**
|
|
64
|
-
* Decrypt an `e2e:1:` envelope back to cleartext using the channel's
|
|
65
|
-
* DocKey. Returns null if the envelope is malformed (don't surface
|
|
66
|
-
* partial decryption — show the user a placeholder instead).
|
|
67
|
-
*/
|
|
68
|
-
export async function decryptChatContent(content: string, docKey: CryptoKey): Promise<string | null> {
|
|
69
|
-
if (!isEncryptedContent(content)) return content; // already cleartext
|
|
70
|
-
try {
|
|
71
|
-
const blob = fromBase64(content.slice(SENTINEL.length));
|
|
72
|
-
const plain = await decryptField(blob, docKey);
|
|
73
|
-
return new TextDecoder().decode(plain);
|
|
74
|
-
} catch {
|
|
75
|
-
return null;
|
|
76
|
-
}
|
|
77
|
-
}
|
|
78
|
-
|
|
79
|
-
/**
|
|
80
|
-
* Encrypt cleartext into an `e2e:1:` envelope ready to send as the
|
|
81
|
-
* stateless `messages:send` `content` field.
|
|
82
|
-
*/
|
|
83
|
-
export async function encryptChatContent(content: string, docKey: CryptoKey): Promise<string> {
|
|
84
|
-
const blob = await encryptField(new TextEncoder().encode(content), docKey);
|
|
85
|
-
return SENTINEL + toBase64(blob);
|
|
86
|
-
}
|
|
87
|
-
|
|
88
|
-
/**
|
|
89
|
-
* Per-channel encryption-mode + DocKey resolver. Caches the encryption
|
|
90
|
-
* mode lookup for `cacheTtlMs`; the DocKey itself is cached inside
|
|
91
|
-
* `DocKeyManager`. Returns `null` for non-E2E channels.
|
|
92
|
-
*/
|
|
93
|
-
export class ChannelKeyResolver {
|
|
94
|
-
private modeCache = new Map<string, { mode: "none" | "cse" | "e2e"; fetchedAt: number }>();
|
|
95
|
-
private static readonly DEFAULT_TTL_MS = 5 * 60 * 1000;
|
|
96
|
-
|
|
97
|
-
constructor(
|
|
98
|
-
private readonly client: AbracadabraClient,
|
|
99
|
-
private readonly docKeys: DocKeyManager,
|
|
100
|
-
private readonly keystore: CryptoIdentityKeystore,
|
|
101
|
-
private readonly options: { cacheTtlMs?: number } = {},
|
|
102
|
-
) {}
|
|
103
|
-
|
|
104
|
-
async modeFor(channelDocId: string): Promise<"none" | "cse" | "e2e"> {
|
|
105
|
-
const cached = this.modeCache.get(channelDocId);
|
|
106
|
-
const ttl = this.options.cacheTtlMs ?? ChannelKeyResolver.DEFAULT_TTL_MS;
|
|
107
|
-
if (cached && Date.now() - cached.fetchedAt < ttl) return cached.mode;
|
|
108
|
-
const info = await this.client.getDocEncryption(channelDocId);
|
|
109
|
-
const mode = info.effective_mode;
|
|
110
|
-
this.modeCache.set(channelDocId, { mode, fetchedAt: Date.now() });
|
|
111
|
-
return mode;
|
|
112
|
-
}
|
|
113
|
-
|
|
114
|
-
/**
|
|
115
|
-
* Returns the DocKey for an E2E channel, or null for cleartext channels
|
|
116
|
-
* (no envelope to fetch). Throws if the channel is E2E but no envelope
|
|
117
|
-
* exists for the current user — the caller should let the send fail
|
|
118
|
-
* loudly rather than fall back to cleartext, which would silently
|
|
119
|
-
* downgrade the threat model.
|
|
120
|
-
*/
|
|
121
|
-
async docKeyFor(channelDocId: string): Promise<CryptoKey | null> {
|
|
122
|
-
const mode = await this.modeFor(channelDocId);
|
|
123
|
-
if (mode !== "e2e") return null;
|
|
124
|
-
const key = await this.docKeys.getDocKey(channelDocId, this.client, this.keystore);
|
|
125
|
-
if (!key) {
|
|
126
|
-
throw new Error(
|
|
127
|
-
`EncryptedChatClient: no key envelope for channel ${channelDocId} — user is not provisioned for this E2E channel.`,
|
|
128
|
-
);
|
|
129
|
-
}
|
|
130
|
-
return key;
|
|
131
|
-
}
|
|
132
|
-
|
|
133
|
-
/** Drop the cached encryption mode for `channelDocId` (or all). */
|
|
134
|
-
clearCache(channelDocId?: string): void {
|
|
135
|
-
if (channelDocId) this.modeCache.delete(channelDocId);
|
|
136
|
-
else this.modeCache.clear();
|
|
137
|
-
}
|
|
138
|
-
}
|
|
139
|
-
|
|
140
|
-
/**
|
|
141
|
-
* Drop-in wrapper around an existing ChatClient that intercepts the
|
|
142
|
-
* write side (`send` / `edit`) and encrypts content for E2E channels.
|
|
143
|
-
* Reading is handled separately — the consumer pumps the period's Y.Array
|
|
144
|
-
* directly and calls `decryptChatContent` per record.
|
|
145
|
-
*
|
|
146
|
-
* Channels in `none` or `cse` mode are passed through untouched.
|
|
147
|
-
*/
|
|
148
|
-
export class EncryptedChatClient {
|
|
149
|
-
constructor(
|
|
150
|
-
private readonly inner: ChatClient,
|
|
151
|
-
private readonly resolver: ChannelKeyResolver,
|
|
152
|
-
) {}
|
|
153
|
-
|
|
154
|
-
async send(input: SendMessageInput): Promise<SendMessageResult> {
|
|
155
|
-
const docKey = await this.resolver.docKeyFor(input.channel_doc_id);
|
|
156
|
-
if (!docKey) return this.inner.send(input);
|
|
157
|
-
const ciphertext = await encryptChatContent(input.content, docKey);
|
|
158
|
-
return this.inner.send({ ...input, content: ciphertext });
|
|
159
|
-
}
|
|
160
|
-
|
|
161
|
-
async edit(input: EditMessageInput): Promise<void> {
|
|
162
|
-
const docKey = await this.resolver.docKeyFor(input.channel_doc_id);
|
|
163
|
-
if (!docKey) return this.inner.edit(input);
|
|
164
|
-
const ciphertext = await encryptChatContent(input.content, docKey);
|
|
165
|
-
return this.inner.edit({ ...input, content: ciphertext });
|
|
166
|
-
}
|
|
167
|
-
|
|
168
|
-
// Pass-through methods that don't carry encryptable content.
|
|
169
|
-
delete(...args: Parameters<ChatClient["delete"]>) { return this.inner.delete(...args); }
|
|
170
|
-
markRead(...args: Parameters<ChatClient["markRead"]>) { return this.inner.markRead(...args); }
|
|
171
|
-
typing(...args: Parameters<ChatClient["typing"]>) { return this.inner.typing(...args); }
|
|
172
|
-
destroy() { this.inner.destroy(); }
|
|
173
|
-
}
|