@abraca/dabra 2.102.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.
Files changed (151) hide show
  1. package/dist/abracadabra-provider.cjs +6673 -6543
  2. package/dist/abracadabra-provider.cjs.map +1 -1
  3. package/dist/esm/AbracadabraBaseProvider.js +558 -0
  4. package/dist/esm/AbracadabraBaseProvider.js.map +1 -0
  5. package/dist/esm/AbracadabraClient.js +1424 -0
  6. package/dist/esm/AbracadabraClient.js.map +1 -0
  7. package/dist/esm/AbracadabraProvider.js +547 -0
  8. package/dist/esm/AbracadabraProvider.js.map +1 -0
  9. package/dist/esm/AbracadabraWS.js +398 -0
  10. package/dist/esm/AbracadabraWS.js.map +1 -0
  11. package/dist/esm/BackgroundSyncManager.js +571 -0
  12. package/dist/esm/BackgroundSyncManager.js.map +1 -0
  13. package/dist/esm/BackgroundSyncPersistence.js +62 -0
  14. package/dist/esm/BackgroundSyncPersistence.js.map +1 -0
  15. package/dist/esm/ChatClient.js +176 -0
  16. package/dist/esm/ChatClient.js.map +1 -0
  17. package/dist/esm/CloseEvents.js +45 -0
  18. package/dist/esm/CloseEvents.js.map +1 -0
  19. package/dist/esm/ContentManager.js +153 -0
  20. package/dist/esm/ContentManager.js.map +1 -0
  21. package/dist/esm/CoverReconcile.js +124 -0
  22. package/dist/esm/CoverReconcile.js.map +1 -0
  23. package/dist/esm/CryptoIdentityKeystore.js +580 -0
  24. package/dist/esm/CryptoIdentityKeystore.js.map +1 -0
  25. package/dist/esm/DeviceRegistrationService.js +158 -0
  26. package/dist/esm/DeviceRegistrationService.js.map +1 -0
  27. package/dist/esm/DocConverters.js +1300 -0
  28. package/dist/esm/DocConverters.js.map +1 -0
  29. package/dist/esm/DocKeyManager.js +145 -0
  30. package/dist/esm/DocKeyManager.js.map +1 -0
  31. package/dist/esm/DocTypes.js +792 -0
  32. package/dist/esm/DocTypes.js.map +1 -0
  33. package/dist/esm/DocUtils.js +180 -0
  34. package/dist/esm/DocUtils.js.map +1 -0
  35. package/dist/esm/DocumentCache.js +131 -0
  36. package/dist/esm/DocumentCache.js.map +1 -0
  37. package/dist/esm/DocumentManager.js +240 -0
  38. package/dist/esm/DocumentManager.js.map +1 -0
  39. package/dist/esm/E2EAbracadabraProvider.js +273 -0
  40. package/dist/esm/E2EAbracadabraProvider.js.map +1 -0
  41. package/dist/esm/E2EOfflineStore.js +53 -0
  42. package/dist/esm/E2EOfflineStore.js.map +1 -0
  43. package/dist/esm/EncryptedChatClient.js +156 -0
  44. package/dist/esm/EncryptedChatClient.js.map +1 -0
  45. package/dist/esm/EncryptedY.js +115 -0
  46. package/dist/esm/EncryptedY.js.map +1 -0
  47. package/dist/esm/EventEmitter.js +40 -0
  48. package/dist/esm/EventEmitter.js.map +1 -0
  49. package/dist/esm/FileBlobStore.js +410 -0
  50. package/dist/esm/FileBlobStore.js.map +1 -0
  51. package/dist/esm/IdentityDoc.js +413 -0
  52. package/dist/esm/IdentityDoc.js.map +1 -0
  53. package/dist/esm/IncomingMessage.js +39 -0
  54. package/dist/esm/IncomingMessage.js.map +1 -0
  55. package/dist/esm/LifecycleGate.js +124 -0
  56. package/dist/esm/LifecycleGate.js.map +1 -0
  57. package/dist/esm/MessageReceiver.js +86 -0
  58. package/dist/esm/MessageReceiver.js.map +1 -0
  59. package/dist/esm/MessageSender.js +19 -0
  60. package/dist/esm/MessageSender.js.map +1 -0
  61. package/dist/esm/MetaManager.js +112 -0
  62. package/dist/esm/MetaManager.js.map +1 -0
  63. package/dist/esm/MnemonicKeyDerivation.js +137 -0
  64. package/dist/esm/MnemonicKeyDerivation.js.map +1 -0
  65. package/dist/esm/NodeConnect.js +63 -0
  66. package/dist/esm/NodeConnect.js.map +1 -0
  67. package/dist/esm/NodeIdentity.js +212 -0
  68. package/dist/esm/NodeIdentity.js.map +1 -0
  69. package/dist/esm/NotificationsClient.js +136 -0
  70. package/dist/esm/NotificationsClient.js.map +1 -0
  71. package/dist/esm/OfflineStore.js +291 -0
  72. package/dist/esm/OfflineStore.js.map +1 -0
  73. package/dist/esm/OutgoingMessage.js +18 -0
  74. package/dist/esm/OutgoingMessage.js.map +1 -0
  75. package/dist/esm/OutgoingMessages/AuthenticationMessage.js +24 -0
  76. package/dist/esm/OutgoingMessages/AuthenticationMessage.js.map +1 -0
  77. package/dist/esm/OutgoingMessages/AwarenessMessage.js +28 -0
  78. package/dist/esm/OutgoingMessages/AwarenessMessage.js.map +1 -0
  79. package/dist/esm/OutgoingMessages/CloseMessage.js +21 -0
  80. package/dist/esm/OutgoingMessages/CloseMessage.js.map +1 -0
  81. package/dist/esm/OutgoingMessages/QueryAwarenessMessage.js +21 -0
  82. package/dist/esm/OutgoingMessages/QueryAwarenessMessage.js.map +1 -0
  83. package/dist/esm/OutgoingMessages/StatelessMessage.js +22 -0
  84. package/dist/esm/OutgoingMessages/StatelessMessage.js.map +1 -0
  85. package/dist/esm/OutgoingMessages/SubdocMessage.js +34 -0
  86. package/dist/esm/OutgoingMessages/SubdocMessage.js.map +1 -0
  87. package/dist/esm/OutgoingMessages/SyncStepOneMessage.js +24 -0
  88. package/dist/esm/OutgoingMessages/SyncStepOneMessage.js.map +1 -0
  89. package/dist/esm/OutgoingMessages/UpdateMessage.js +23 -0
  90. package/dist/esm/OutgoingMessages/UpdateMessage.js.map +1 -0
  91. package/dist/esm/PerfCounters.js +336 -0
  92. package/dist/esm/PerfCounters.js.map +1 -0
  93. package/dist/esm/QueryClient.js +117 -0
  94. package/dist/esm/QueryClient.js.map +1 -0
  95. package/dist/esm/RpcClient.js +456 -0
  96. package/dist/esm/RpcClient.js.map +1 -0
  97. package/dist/esm/SchemaTypes.js +38 -0
  98. package/dist/esm/SchemaTypes.js.map +1 -0
  99. package/dist/esm/SearchIndex.js +167 -0
  100. package/dist/esm/SearchIndex.js.map +1 -0
  101. package/dist/esm/ServerRegistry.js +139 -0
  102. package/dist/esm/ServerRegistry.js.map +1 -0
  103. package/dist/esm/ServerReset.js +170 -0
  104. package/dist/esm/ServerReset.js.map +1 -0
  105. package/dist/esm/TokenManager.js +236 -0
  106. package/dist/esm/TokenManager.js.map +1 -0
  107. package/dist/esm/TreeManager.js +655 -0
  108. package/dist/esm/TreeManager.js.map +1 -0
  109. package/dist/esm/TreeTimestamps.js +61 -0
  110. package/dist/esm/TreeTimestamps.js.map +1 -0
  111. package/dist/esm/auth.js +43 -0
  112. package/dist/esm/auth.js.map +1 -0
  113. package/dist/esm/awarenessStatesToArray.js +13 -0
  114. package/dist/esm/awarenessStatesToArray.js.map +1 -0
  115. package/dist/esm/docIds.js +53 -0
  116. package/dist/esm/docIds.js.map +1 -0
  117. package/dist/esm/encryptedContent.js +21 -0
  118. package/dist/esm/encryptedContent.js.map +1 -0
  119. package/dist/esm/index.js +61 -0
  120. package/dist/esm/messageRecord.js +64 -0
  121. package/dist/esm/messageRecord.js.map +1 -0
  122. package/dist/esm/sync/BroadcastChannelSync.js +160 -0
  123. package/dist/esm/sync/BroadcastChannelSync.js.map +1 -0
  124. package/dist/esm/types.js +54 -0
  125. package/dist/esm/types.js.map +1 -0
  126. package/dist/esm/webrtc/AbracadabraWebRTC.js +483 -0
  127. package/dist/esm/webrtc/AbracadabraWebRTC.js.map +1 -0
  128. package/dist/esm/webrtc/DataChannelRouter.js +124 -0
  129. package/dist/esm/webrtc/DataChannelRouter.js.map +1 -0
  130. package/dist/esm/webrtc/DevicePairingChannel.js +335 -0
  131. package/dist/esm/webrtc/DevicePairingChannel.js.map +1 -0
  132. package/dist/esm/webrtc/E2EEChannel.js +137 -0
  133. package/dist/esm/webrtc/E2EEChannel.js.map +1 -0
  134. package/dist/esm/webrtc/FileTransferChannel.js +250 -0
  135. package/dist/esm/webrtc/FileTransferChannel.js.map +1 -0
  136. package/dist/esm/webrtc/ManualSignaling.js +161 -0
  137. package/dist/esm/webrtc/ManualSignaling.js.map +1 -0
  138. package/dist/esm/webrtc/PeerConnection.js +96 -0
  139. package/dist/esm/webrtc/PeerConnection.js.map +1 -0
  140. package/dist/esm/webrtc/SignalingSocket.js +274 -0
  141. package/dist/esm/webrtc/SignalingSocket.js.map +1 -0
  142. package/dist/esm/webrtc/YjsDataChannel.js +135 -0
  143. package/dist/esm/webrtc/YjsDataChannel.js.map +1 -0
  144. package/dist/esm/webrtc/types.js +29 -0
  145. package/dist/esm/webrtc/types.js.map +1 -0
  146. package/dist/esm/x25519Convert.js +69 -0
  147. package/dist/esm/x25519Convert.js.map +1 -0
  148. package/dist/index.d.ts +26 -11
  149. package/package.json +6 -4
  150. package/dist/abracadabra-provider.esm.js +0 -14860
  151. package/dist/abracadabra-provider.esm.js.map +0 -1
@@ -0,0 +1,240 @@
1
+ import { Kind, SERVER_ROOT_ID } from "./types.js";
2
+ import { AbracadabraProvider } from "./AbracadabraProvider.js";
3
+ import { AbracadabraClient } from "./AbracadabraClient.js";
4
+ import { waitForSync } from "./DocUtils.js";
5
+ import { TypedDocTypeMismatchError, projectTreeEntry } from "./SchemaTypes.js";
6
+ import { TreeManager } from "./TreeManager.js";
7
+ import { ContentManager } from "./ContentManager.js";
8
+ import { MetaManager } from "./MetaManager.js";
9
+ import * as Y from "yjs";
10
+
11
+ //#region packages/provider/src/DocumentManager.ts
12
+ /**
13
+ * DocumentManager — high-level ORM entry point for Abracadabra CRDT documents.
14
+ *
15
+ * Consolidates the shared connection lifecycle, authentication, space discovery,
16
+ * provider caching, and Y.Map access patterns that were previously duplicated
17
+ * across `mcp/src/server.ts` and `cli/src/connection.ts`.
18
+ *
19
+ * Usage:
20
+ * ```ts
21
+ * const dm = new DocumentManager({
22
+ * url: 'https://my-server.example.com',
23
+ * name: 'My Agent',
24
+ * })
25
+ * // Authenticate before connecting (consumer handles crypto):
26
+ * await dm.client.loginWithKey(publicKey, signFn)
27
+ * await dm.connect()
28
+ *
29
+ * // Use the ORM:
30
+ * const docs = dm.tree.childrenOf(null) // root-level docs
31
+ * const content = await dm.content.read(docId) // markdown + children
32
+ * dm.meta.update(docId, { color: '#ff0000' }) // update metadata
33
+ * ```
34
+ */
35
+ var DocumentManager = class {
36
+ constructor(config) {
37
+ this._serverInfo = null;
38
+ this._rootDocId = null;
39
+ this._spaces = [];
40
+ this._rootDoc = null;
41
+ this._rootProvider = null;
42
+ this.childCache = /* @__PURE__ */ new Map();
43
+ this._config = config;
44
+ this.client = config.client ?? new AbracadabraClient({
45
+ url: config.url,
46
+ persistAuth: false,
47
+ fetch: config.fetch
48
+ });
49
+ this.tree = new TreeManager(this);
50
+ this.content = new ContentManager(this);
51
+ this.meta = new MetaManager(this);
52
+ }
53
+ /**
54
+ * Bind a schema registry to a typed accessor surface. The returned
55
+ * client offers `.get(type, id)` with the registry's meta types
56
+ * inferred at the call site, removing the need to pass `schema`
57
+ * to every lookup. The provider remains schema-free at runtime —
58
+ * `schema` is only used to drive type inference (see
59
+ * `SchemaRegistryLike` for the structural witness).
60
+ *
61
+ * @example
62
+ * const docs = dm.docs(kanbanSchema);
63
+ * const board = docs.get("kanban", id);
64
+ * if (board) console.log(board.meta.kanbanColumnWidth); // typed
65
+ */
66
+ docs(_schema) {
67
+ const tree = this.tree;
68
+ const meta = this.meta;
69
+ const expectType = (expected, id) => {
70
+ const actual = tree.get(id)?.type;
71
+ if (actual !== expected) throw new TypedDocTypeMismatchError(id, expected, actual);
72
+ };
73
+ return {
74
+ get: (expectedType, id) => projectTreeEntry(tree.get(id), expectedType),
75
+ getEntry: (id) => tree.get(id),
76
+ narrow: (expectedType, entry) => projectTreeEntry(entry ?? null, expectedType),
77
+ update: (expectedType, id, patch) => {
78
+ expectType(expectedType, id);
79
+ meta.update(id, patch);
80
+ },
81
+ set: (expectedType, id, value) => {
82
+ expectType(expectedType, id);
83
+ meta.set(id, value);
84
+ },
85
+ clear: (expectedType, id, keys) => {
86
+ expectType(expectedType, id);
87
+ meta.clear(id, keys);
88
+ }
89
+ };
90
+ }
91
+ get displayName() {
92
+ return this._config.name || "DocumentManager";
93
+ }
94
+ get displayColor() {
95
+ return this._config.color || "hsl(45, 90%, 55%)";
96
+ }
97
+ get serverInfo() {
98
+ return this._serverInfo;
99
+ }
100
+ get rootDocId() {
101
+ return this._rootDocId;
102
+ }
103
+ /**
104
+ * Whether the TreeManager in-memory index is enabled.
105
+ * On by default — see {@link DocumentManagerConfig.treeIndex}.
106
+ */
107
+ get treeIndexEnabled() {
108
+ return this._config.treeIndex ?? true;
109
+ }
110
+ get rootDocument() {
111
+ return this._rootDoc;
112
+ }
113
+ get rootProvider() {
114
+ return this._rootProvider;
115
+ }
116
+ /**
117
+ * Spaces visible to the caller — direct children of the server root with
118
+ * `kind === "space"`. Populated by {@link connect}.
119
+ */
120
+ get spaces() {
121
+ return this._spaces;
122
+ }
123
+ get isConnected() {
124
+ return this._rootProvider?.isConnected ?? false;
125
+ }
126
+ /** Get the root doc-tree Y.Map. */
127
+ getTreeMap() {
128
+ return this._rootDoc?.getMap("doc-tree") ?? null;
129
+ }
130
+ /** Get the root doc-trash Y.Map. */
131
+ getTrashMap() {
132
+ return this._rootDoc?.getMap("doc-trash") ?? null;
133
+ }
134
+ /** Get the root space-plugins Y.Map. */
135
+ getPluginsMap() {
136
+ return this._rootDoc?.getMap("space-plugins") ?? null;
137
+ }
138
+ /**
139
+ * Connect to the server: discover the entry-point document, sync the root
140
+ * Y.Doc, and set awareness.
141
+ *
142
+ * **Authentication must be done before calling connect().**
143
+ * Call `dm.client.loginWithKey(publicKey, signFn)` or `dm.client.login()`
144
+ * to authenticate first.
145
+ *
146
+ * When `rootDocId` is set in the config, server discovery is skipped and
147
+ * the manager connects directly to that document.
148
+ */
149
+ async connect() {
150
+ this._serverInfo = await this.client.serverInfo();
151
+ let initialDocId = this._config.rootDocId ?? null;
152
+ if (!initialDocId) {
153
+ const roots = await this.client.listChildren();
154
+ this._spaces = roots.filter((d) => d.kind === Kind.Space);
155
+ const first = this._spaces[0] ?? roots[0];
156
+ if (first) {
157
+ initialDocId = first.id;
158
+ this.log(`Entry document: ${first.label ?? first.id} (${first.id})`);
159
+ }
160
+ }
161
+ if (!initialDocId) throw new Error(`No entry point found: server has no top-level documents under ${SERVER_ROOT_ID}. Create a Space first.`);
162
+ this._rootDocId = initialDocId;
163
+ await this._connectToRoot(initialDocId);
164
+ this.log("Connected and synced");
165
+ }
166
+ /** Switch active space to a different root document. */
167
+ async switchSpace(docId) {
168
+ for (const [, cached] of this.childCache) cached.provider.destroy();
169
+ this.childCache.clear();
170
+ if (this._rootProvider) {
171
+ this._rootProvider.destroy();
172
+ this._rootProvider = null;
173
+ }
174
+ this._rootDoc = null;
175
+ await this._connectToRoot(docId);
176
+ this._rootDocId = docId;
177
+ this.log(`Switched to space ${docId}`);
178
+ }
179
+ /** Create, sync, and set awareness on a root provider for the given docId. */
180
+ async _connectToRoot(docId) {
181
+ const doc = new Y.Doc({ guid: docId });
182
+ const wsp = this._config.websocketProvider;
183
+ const provider = new AbracadabraProvider({
184
+ name: docId,
185
+ document: doc,
186
+ client: this.client,
187
+ disableOfflineStore: this._config.disableOfflineStore ?? true,
188
+ subdocLoading: "lazy",
189
+ ...wsp ? { websocketProvider: wsp } : {}
190
+ });
191
+ if (wsp) provider.attach();
192
+ await waitForSync(provider);
193
+ provider.awareness?.setLocalStateField("user", {
194
+ name: this.displayName,
195
+ color: this.displayColor
196
+ });
197
+ provider.awareness?.setLocalStateField("status", null);
198
+ this._rootDoc = doc;
199
+ this._rootProvider = provider;
200
+ }
201
+ /** Graceful shutdown. */
202
+ async destroy() {
203
+ for (const [, cached] of this.childCache) cached.provider.destroy();
204
+ this.childCache.clear();
205
+ if (this._rootProvider) {
206
+ this._rootProvider.awareness?.setLocalStateField("status", null);
207
+ this._rootProvider.destroy();
208
+ this._rootProvider = null;
209
+ }
210
+ this._rootDoc = null;
211
+ this.log("Disconnected");
212
+ }
213
+ /** Get or create a child provider for a document (synced). */
214
+ async getChildProvider(docId) {
215
+ const cached = this.childCache.get(docId);
216
+ if (cached) {
217
+ cached.lastAccessed = Date.now();
218
+ return cached.provider;
219
+ }
220
+ if (!this._rootProvider) throw new Error("Not connected. Call connect() first.");
221
+ const childProvider = await this._rootProvider.loadChild(docId);
222
+ await waitForSync(childProvider);
223
+ childProvider.awareness?.setLocalStateField("user", {
224
+ name: this.displayName,
225
+ color: this.displayColor
226
+ });
227
+ this.childCache.set(docId, {
228
+ provider: childProvider,
229
+ lastAccessed: Date.now()
230
+ });
231
+ return childProvider;
232
+ }
233
+ log(msg) {
234
+ if (!this._config.quiet) console.error(`[abracadabra] ${msg}`);
235
+ }
236
+ };
237
+
238
+ //#endregion
239
+ export { DocumentManager };
240
+ //# sourceMappingURL=DocumentManager.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"DocumentManager.js","names":[],"sources":["../../src/DocumentManager.ts"],"sourcesContent":["/**\n * DocumentManager — high-level ORM entry point for Abracadabra CRDT documents.\n *\n * Consolidates the shared connection lifecycle, authentication, space discovery,\n * provider caching, and Y.Map access patterns that were previously duplicated\n * across `mcp/src/server.ts` and `cli/src/connection.ts`.\n *\n * Usage:\n * ```ts\n * const dm = new DocumentManager({\n * url: 'https://my-server.example.com',\n * name: 'My Agent',\n * })\n * // Authenticate before connecting (consumer handles crypto):\n * await dm.client.loginWithKey(publicKey, signFn)\n * await dm.connect()\n *\n * // Use the ORM:\n * const docs = dm.tree.childrenOf(null) // root-level docs\n * const content = await dm.content.read(docId) // markdown + children\n * dm.meta.update(docId, { color: '#ff0000' }) // update metadata\n * ```\n */\nimport * as Y from \"yjs\";\nimport { AbracadabraProvider } from \"./AbracadabraProvider.ts\";\nimport { AbracadabraClient } from \"./AbracadabraClient.ts\";\nimport type { AbracadabraWS } from \"./AbracadabraWS.ts\";\nimport type { ServerInfo, DocumentMeta } from \"./types.ts\";\nimport { Kind, SERVER_ROOT_ID } from \"./types.ts\";\nimport { TreeManager } from \"./TreeManager.ts\";\nimport { ContentManager } from \"./ContentManager.ts\";\nimport { MetaManager } from \"./MetaManager.ts\";\nimport { waitForSync } from \"./DocUtils.ts\";\nimport type { TreeEntry, PageMeta } from \"./DocTypes.ts\";\nimport {\n\tprojectTreeEntry,\n\tTypedDocTypeMismatchError,\n\ttype SchemaRegistryLike,\n\ttype TypedDocsClient,\n} from \"./SchemaTypes.ts\";\n\nexport interface DocumentManagerConfig {\n\t/** Server base URL (http or https). */\n\turl: string;\n\t/** Display name for awareness (cursor labels, presence). */\n\tname?: string;\n\t/** Cursor / awareness color. */\n\tcolor?: string;\n\t/** Invite code for first-time registration. */\n\tinviteCode?: string;\n\t/** Suppress stderr logging. */\n\tquiet?: boolean;\n\t/** Disable IndexedDB offline persistence. */\n\tdisableOfflineStore?: boolean;\n\t/** Custom fetch for Node.js environments. */\n\tfetch?: typeof globalThis.fetch;\n\t/**\n\t * Pre-configured AbracadabraClient instance.\n\t * When provided, the `url` and `fetch` fields are ignored — the client's\n\t * configuration is used instead. This is useful when the consumer has\n\t * already authenticated or configured the client externally.\n\t */\n\tclient?: AbracadabraClient;\n\t/**\n\t * Shared WebSocket connection. Required in Node.js environments — pass an\n\t * AbracadabraWS constructed with WebSocketPolyfill set to the `ws` package.\n\t * When omitted, each provider creates its own connection from client.wsUrl.\n\t * The caller owns this instance and must destroy it after dm.destroy().\n\t */\n\twebsocketProvider?: AbracadabraWS;\n\t/**\n\t * Known root document ID. When provided, connect() skips server discovery\n\t * and connects directly to this document. Useful in tests or CLIs where\n\t * the entry-point docId is already known.\n\t */\n\trootDocId?: string;\n\t/**\n\t * TreeManager's in-memory parent→children index. When `true` (the\n\t * default), tree WALKS resolve against a lazily-rebuilt adjacency index\n\t * (O(k) per lookup, O(result) traversal), kept fresh by an `observeDeep`\n\t * dirty bit and rebuilt at most once per mutation batch; `childrenOfPage()`\n\t * becomes usable with stable (order,id) sibling ordering. Set `false` to\n\t * force the legacy whole-map scan (O(n) per call, O(n²) recursive) — only\n\t * needed to reproduce the exact historical order-only sibling ordering.\n\t * Benchmarked at ~700× on deep walks. Index affects WALK reads only;\n\t * `readEntries`/`get` keep raw parentId either way. Lazy: no index or\n\t * observer is bound until the first walk read.\n\t */\n\ttreeIndex?: boolean;\n}\n\ninterface CachedProvider {\n\tprovider: AbracadabraProvider;\n\tlastAccessed: number;\n}\n\nexport class DocumentManager {\n\treadonly client: AbracadabraClient;\n\n\t/** Tree CRUD operations. */\n\treadonly tree: TreeManager;\n\t/** Document content read/write. */\n\treadonly content: ContentManager;\n\t/** Document metadata read/write. */\n\treadonly meta: MetaManager;\n\n\tprivate _config: DocumentManagerConfig;\n\tprivate _serverInfo: ServerInfo | null = null;\n\tprivate _rootDocId: string | null = null;\n\tprivate _spaces: DocumentMeta[] = [];\n\tprivate _rootDoc: Y.Doc | null = null;\n\tprivate _rootProvider: AbracadabraProvider | null = null;\n\tprivate childCache = new Map<string, CachedProvider>();\n\n\tconstructor(config: DocumentManagerConfig) {\n\t\tthis._config = config;\n\t\tthis.client =\n\t\t\tconfig.client ??\n\t\t\tnew AbracadabraClient({\n\t\t\t\turl: config.url,\n\t\t\t\tpersistAuth: false,\n\t\t\t\tfetch: config.fetch,\n\t\t\t});\n\n\t\tthis.tree = new TreeManager(this);\n\t\tthis.content = new ContentManager(this);\n\t\tthis.meta = new MetaManager(this);\n\t}\n\n\t/**\n\t * Bind a schema registry to a typed accessor surface. The returned\n\t * client offers `.get(type, id)` with the registry's meta types\n\t * inferred at the call site, removing the need to pass `schema`\n\t * to every lookup. The provider remains schema-free at runtime —\n\t * `schema` is only used to drive type inference (see\n\t * `SchemaRegistryLike` for the structural witness).\n\t *\n\t * @example\n\t * const docs = dm.docs(kanbanSchema);\n\t * const board = docs.get(\"kanban\", id);\n\t * if (board) console.log(board.meta.kanbanColumnWidth); // typed\n\t */\n\tdocs<TMap extends Record<string, unknown>>(\n\t\t_schema: SchemaRegistryLike<TMap>,\n\t): TypedDocsClient<TMap> {\n\t\tconst tree = this.tree;\n\t\tconst meta = this.meta;\n\t\tconst expectType = <N extends keyof TMap & string>(\n\t\t\texpected: N,\n\t\t\tid: string,\n\t\t): void => {\n\t\t\tconst entry = tree.get(id);\n\t\t\tconst actual = entry?.type;\n\t\t\tif (actual !== expected) {\n\t\t\t\tthrow new TypedDocTypeMismatchError(id, expected, actual);\n\t\t\t}\n\t\t};\n\t\treturn {\n\t\t\tget: <N extends keyof TMap & string>(expectedType: N, id: string) =>\n\t\t\t\tprojectTreeEntry<TMap, N>(tree.get(id), expectedType),\n\t\t\tgetEntry: (id: string) => tree.get(id),\n\t\t\tnarrow: <N extends keyof TMap & string>(\n\t\t\t\texpectedType: N,\n\t\t\t\tentry: TreeEntry | null | undefined,\n\t\t\t) => projectTreeEntry<TMap, N>(entry ?? null, expectedType),\n\t\t\tupdate: <N extends keyof TMap & string>(\n\t\t\t\texpectedType: N,\n\t\t\t\tid: string,\n\t\t\t\tpatch: Partial<TMap[N]>,\n\t\t\t) => {\n\t\t\t\texpectType(expectedType, id);\n\t\t\t\tmeta.update(id, patch as Partial<PageMeta>);\n\t\t\t},\n\t\t\tset: <N extends keyof TMap & string>(\n\t\t\t\texpectedType: N,\n\t\t\t\tid: string,\n\t\t\t\tvalue: TMap[N],\n\t\t\t) => {\n\t\t\t\texpectType(expectedType, id);\n\t\t\t\tmeta.set(id, value as unknown as PageMeta);\n\t\t\t},\n\t\t\tclear: <N extends keyof TMap & string>(\n\t\t\t\texpectedType: N,\n\t\t\t\tid: string,\n\t\t\t\tkeys: ReadonlyArray<keyof TMap[N] & string>,\n\t\t\t) => {\n\t\t\t\texpectType(expectedType, id);\n\t\t\t\tmeta.clear(id, keys as ReadonlyArray<string> as string[]);\n\t\t\t},\n\t\t};\n\t}\n\n\t// ── Accessors ─────────────────────────────────────────────────────────────\n\n\tget displayName(): string {\n\t\treturn this._config.name || \"DocumentManager\";\n\t}\n\n\tget displayColor(): string {\n\t\treturn this._config.color || \"hsl(45, 90%, 55%)\";\n\t}\n\n\tget serverInfo(): ServerInfo | null {\n\t\treturn this._serverInfo;\n\t}\n\n\tget rootDocId(): string | null {\n\t\treturn this._rootDocId;\n\t}\n\n\t/**\n\t * Whether the TreeManager in-memory index is enabled.\n\t * On by default — see {@link DocumentManagerConfig.treeIndex}.\n\t */\n\tget treeIndexEnabled(): boolean {\n\t\treturn this._config.treeIndex ?? true;\n\t}\n\n\tget rootDocument(): Y.Doc | null {\n\t\treturn this._rootDoc;\n\t}\n\n\tget rootProvider(): AbracadabraProvider | null {\n\t\treturn this._rootProvider;\n\t}\n\n\t/**\n\t * Spaces visible to the caller — direct children of the server root with\n\t * `kind === \"space\"`. Populated by {@link connect}.\n\t */\n\tget spaces(): DocumentMeta[] {\n\t\treturn this._spaces;\n\t}\n\n\tget isConnected(): boolean {\n\t\treturn this._rootProvider?.isConnected ?? false;\n\t}\n\n\t// ── Y.Map access ──────────────────────────────────────────────────────────\n\n\t/** Get the root doc-tree Y.Map. */\n\tgetTreeMap(): Y.Map<any> | null {\n\t\treturn this._rootDoc?.getMap(\"doc-tree\") ?? null;\n\t}\n\n\t/** Get the root doc-trash Y.Map. */\n\tgetTrashMap(): Y.Map<any> | null {\n\t\treturn this._rootDoc?.getMap(\"doc-trash\") ?? null;\n\t}\n\n\t/** Get the root space-plugins Y.Map. */\n\tgetPluginsMap(): Y.Map<any> | null {\n\t\treturn this._rootDoc?.getMap(\"space-plugins\") ?? null;\n\t}\n\n\t// ── Lifecycle ─────────────────────────────────────────────────────────────\n\n\t/**\n\t * Connect to the server: discover the entry-point document, sync the root\n\t * Y.Doc, and set awareness.\n\t *\n\t * **Authentication must be done before calling connect().**\n\t * Call `dm.client.loginWithKey(publicKey, signFn)` or `dm.client.login()`\n\t * to authenticate first.\n\t *\n\t * When `rootDocId` is set in the config, server discovery is skipped and\n\t * the manager connects directly to that document.\n\t */\n\tasync connect(): Promise<void> {\n\t\t// Step 1: Discover server info (used for awareness colour, name, etc.).\n\t\tthis._serverInfo = await this.client.serverInfo();\n\n\t\t// Step 2: Pick an entry-point doc.\n\t\t//\n\t\t// In the new model the dashboard's notion of \"open the hub\" maps to\n\t\t// \"open the first Space\". A Space is a top-level doc with\n\t\t// `kind === \"space\"`. If the caller pinned a `rootDocId`, honour it\n\t\t// directly — useful in tests/CLIs where the entry doc is known.\n\t\tlet initialDocId: string | null = this._config.rootDocId ?? null;\n\n\t\tif (!initialDocId) {\n\t\t\tconst roots = await this.client.listChildren();\n\t\t\tthis._spaces = roots.filter((d) => d.kind === Kind.Space);\n\t\t\tconst first = this._spaces[0] ?? roots[0];\n\t\t\tif (first) {\n\t\t\t\tinitialDocId = first.id;\n\t\t\t\tthis.log(`Entry document: ${first.label ?? first.id} (${first.id})`);\n\t\t\t}\n\t\t}\n\n\t\tif (!initialDocId) {\n\t\t\tthrow new Error(\n\t\t\t\t`No entry point found: server has no top-level documents under ${SERVER_ROOT_ID}. Create a Space first.`,\n\t\t\t);\n\t\t}\n\n\t\tthis._rootDocId = initialDocId;\n\n\t\t// Step 3: Connect provider and sync\n\t\tawait this._connectToRoot(initialDocId);\n\t\tthis.log(\"Connected and synced\");\n\t}\n\n\t/** Switch active space to a different root document. */\n\tasync switchSpace(docId: string): Promise<void> {\n\t\t// Destroy existing child providers\n\t\tfor (const [, cached] of this.childCache) {\n\t\t\tcached.provider.destroy();\n\t\t}\n\t\tthis.childCache.clear();\n\n\t\t// Destroy current root provider (not the wsp — caller owns it)\n\t\tif (this._rootProvider) {\n\t\t\tthis._rootProvider.destroy();\n\t\t\tthis._rootProvider = null;\n\t\t}\n\t\tthis._rootDoc = null;\n\n\t\tawait this._connectToRoot(docId);\n\t\tthis._rootDocId = docId;\n\t\tthis.log(`Switched to space ${docId}`);\n\t}\n\n\t/** Create, sync, and set awareness on a root provider for the given docId. */\n\tprivate async _connectToRoot(docId: string): Promise<void> {\n\t\tconst doc = new Y.Doc({ guid: docId });\n\t\tconst wsp = this._config.websocketProvider;\n\t\tconst provider = new AbracadabraProvider({\n\t\t\tname: docId,\n\t\t\tdocument: doc,\n\t\t\tclient: this.client,\n\t\t\tdisableOfflineStore: this._config.disableOfflineStore ?? true,\n\t\t\tsubdocLoading: \"lazy\",\n\t\t\t...(wsp ? { websocketProvider: wsp } : {}),\n\t\t});\n\n\t\t// When a shared websocketProvider is supplied, manageSocket=false so\n\t\t// the base constructor does NOT call attach(). We must do it ourselves.\n\t\tif (wsp) provider.attach();\n\n\t\tawait waitForSync(provider);\n\n\t\tprovider.awareness?.setLocalStateField(\"user\", {\n\t\t\tname: this.displayName,\n\t\t\tcolor: this.displayColor,\n\t\t});\n\t\tprovider.awareness?.setLocalStateField(\"status\", null);\n\n\t\tthis._rootDoc = doc;\n\t\tthis._rootProvider = provider;\n\t}\n\n\t/** Graceful shutdown. */\n\tasync destroy(): Promise<void> {\n\t\tfor (const [, cached] of this.childCache) {\n\t\t\tcached.provider.destroy();\n\t\t}\n\t\tthis.childCache.clear();\n\n\t\tif (this._rootProvider) {\n\t\t\tthis._rootProvider.awareness?.setLocalStateField(\n\t\t\t\t\"status\",\n\t\t\t\tnull,\n\t\t\t);\n\t\t\tthis._rootProvider.destroy();\n\t\t\tthis._rootProvider = null;\n\t\t}\n\t\tthis._rootDoc = null;\n\n\t\tthis.log(\"Disconnected\");\n\t}\n\n\t// ── Provider cache ────────────────────────────────────────────────────────\n\n\t/** Get or create a child provider for a document (synced). */\n\tasync getChildProvider(docId: string): Promise<AbracadabraProvider> {\n\t\tconst cached = this.childCache.get(docId);\n\t\tif (cached) {\n\t\t\tcached.lastAccessed = Date.now();\n\t\t\treturn cached.provider;\n\t\t}\n\n\t\tif (!this._rootProvider) {\n\t\t\tthrow new Error(\"Not connected. Call connect() first.\");\n\t\t}\n\n\t\tconst childProvider = await this._rootProvider.loadChild(docId);\n\t\tawait waitForSync(childProvider);\n\n\t\tchildProvider.awareness?.setLocalStateField(\"user\", {\n\t\t\tname: this.displayName,\n\t\t\tcolor: this.displayColor,\n\t\t});\n\n\t\tthis.childCache.set(docId, {\n\t\t\tprovider: childProvider,\n\t\t\tlastAccessed: Date.now(),\n\t\t});\n\n\t\treturn childProvider;\n\t}\n\n\t// ── Internal ──────────────────────────────────────────────────────────────\n\n\tprivate log(msg: string): void {\n\t\tif (!this._config.qui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C1B,UAAU;GACV,cAAc,KAAK,KAAK;GACxB,CAAC;AAEF,SAAO;;CAKR,AAAQ,IAAI,KAAmB;AAC9B,MAAI,CAAC,KAAK,QAAQ,MACjB,SAAQ,MAAM,iBAAiB,MAAM"}
@@ -0,0 +1,273 @@
1
+ import { UpdateMessage } from "./OutgoingMessages/UpdateMessage.js";
2
+ import { AbracadabraProvider } from "./AbracadabraProvider.js";
3
+ import { decryptField, encryptField } from "./EncryptedY.js";
4
+ import { E2EOfflineStore } from "./E2EOfflineStore.js";
5
+ import * as Y from "yjs";
6
+
7
+ //#region packages/provider/src/E2EAbracadabraProvider.ts
8
+ /**
9
+ * E2EAbracadabraProvider
10
+ *
11
+ * Extends AbracadabraProvider with full E2E encryption support.
12
+ *
13
+ * Differences from standard provider:
14
+ * - startSync() sends a stateless e2e_sync_request instead of SYNC_STEP1
15
+ * - On receiving e2e_ready, fetches all blobs via REST, decrypts, applies to Y.Doc
16
+ * - Local updates are AES-GCM encrypted before sending over WebSocket
17
+ * - Incoming e2e_update stateless messages are decrypted and applied
18
+ *
19
+ * Phase 2 offline support:
20
+ * - After the doc key is obtained, an E2EOfflineStore is created for this doc.
21
+ * - The stored encrypted snapshot is applied before fetching server updates.
22
+ * - The last-seen sequence number (e2e_seq) is persisted so only delta updates
23
+ * are fetched on subsequent connects.
24
+ * - After sync, a fresh encrypted snapshot is saved.
25
+ *
26
+ * Client-side compaction:
27
+ * - After `compactionThreshold` encrypted updates have been applied in this
28
+ * session (local + remote), and the doc has been quiescent for
29
+ * `compactionQuiescenceMs`, the provider merges the whole Y.Doc, encrypts it,
30
+ * and sends `snapshot:compact` — the server atomically replaces the per-doc
31
+ * update log with that single compacted blob. The server acknowledges by
32
+ * broadcasting `snapshot:compacted`, which emits the `"compacted"` event.
33
+ * - Requires Owner or above (server silently drops non-Owner requests).
34
+ * - Callers that want a final compaction before teardown should
35
+ * `await provider.compactNow()` before `destroy()`. `destroy()` does not
36
+ * compact (it'd race with the socket teardown) — any pending debounce is
37
+ * cancelled.
38
+ *
39
+ * Key availability limitation: if the user's WebAuthn key is not in
40
+ * DocKeyManager's in-memory cache and there is no network, E2E docs show
41
+ * empty — the key fetch requires either a cached in-memory key or network.
42
+ */
43
+ function fromBase64(b64) {
44
+ return Uint8Array.from(atob(b64), (c) => c.charCodeAt(0));
45
+ }
46
+ function toBase64(bytes) {
47
+ let bin = "";
48
+ for (let i = 0; i < bytes.length; i += 32768) bin += String.fromCharCode(...bytes.subarray(i, i + 32768));
49
+ return btoa(bin);
50
+ }
51
+ var E2EAbracadabraProvider = class E2EAbracadabraProvider extends AbracadabraProvider {
52
+ constructor(configuration) {
53
+ super({
54
+ ...configuration,
55
+ disableOfflineStore: true
56
+ });
57
+ this.docKey = null;
58
+ this.lastSeq = -1;
59
+ this.e2eStore = null;
60
+ this.updatesSinceCompaction = 0;
61
+ this.compactionInFlight = false;
62
+ this.compactionInFlightTimeout = null;
63
+ this.compactionDebounceTimer = null;
64
+ this.destroyed = false;
65
+ this._pendingPreAuthUpdates = [];
66
+ this.docKeyManager = configuration.docKeyManager;
67
+ this.keystore = configuration.keystore;
68
+ this.e2eClient = configuration.client;
69
+ this.compactionEnabled = configuration.compactionEnabled !== false;
70
+ this.compactionThreshold = Math.max(1, configuration.compactionThreshold ?? 50);
71
+ this.compactionQuiescenceMs = Math.max(0, configuration.compactionQuiescenceMs ?? 2e3);
72
+ this.e2eServerOrigin = E2EAbracadabraProvider.deriveServerOrigin(configuration, configuration.client);
73
+ }
74
+ /** Fetch the doc key from the server (requires WebAuthn if not cached). */
75
+ async ensureDocKey() {
76
+ if (this.docKey) return this.docKey;
77
+ this.docKey = await this.docKeyManager.getDocKey(this.configuration.name, this.e2eClient, this.keystore);
78
+ if (this.docKey && !this.e2eStore) this.e2eStore = new E2EOfflineStore(this.configuration.name, this.e2eServerOrigin, this.docKey);
79
+ return this.docKey;
80
+ }
81
+ /** Handle stateless messages including e2e_ready and e2e_update. */
82
+ receiveStateless(payload) {
83
+ if (payload.startsWith("snapshot:compacted ")) {
84
+ this._handleCompactedBroadcast(payload.slice(19));
85
+ return;
86
+ }
87
+ let parsed;
88
+ try {
89
+ parsed = JSON.parse(payload);
90
+ } catch {
91
+ super.receiveStateless(payload);
92
+ return;
93
+ }
94
+ const msg = parsed;
95
+ if (msg.type === "e2e_ready") {
96
+ this._fetchAndApplyAllBlobs().catch((e) => {
97
+ console.error("[E2EAbracadabraProvider] failed to fetch e2e blobs:", e);
98
+ });
99
+ return;
100
+ }
101
+ if (msg.type === "e2e_update" && msg.data !== void 0 && msg.seq !== void 0) {
102
+ if (msg.seq <= this.lastSeq) return;
103
+ this._decryptAndApply(fromBase64(msg.data), msg.seq).catch((e) => {
104
+ console.error("[E2EAbracadabraProvider] failed to apply e2e_update:", e);
105
+ });
106
+ return;
107
+ }
108
+ super.receiveStateless(payload);
109
+ }
110
+ async _fetchAndApplyAllBlobs() {
111
+ if (!await this.ensureDocKey()) {
112
+ console.warn("[E2EAbracadabraProvider] no doc key available, cannot decrypt blobs");
113
+ this.synced = true;
114
+ return;
115
+ }
116
+ if (this.e2eStore) {
117
+ const storedSeqStr = await this.e2eStore.getMeta("e2e_seq").catch(() => null);
118
+ if (storedSeqStr !== null) this.lastSeq = parseInt(storedSeqStr, 10);
119
+ const snapshot = await this.e2eStore.getDocSnapshot().catch(() => null);
120
+ if (snapshot) Y.applyUpdate(this.document, snapshot, this.e2eStore);
121
+ }
122
+ const updates = await this.e2eClient.getE2EUpdatesSince(this.configuration.name, this.lastSeq);
123
+ for (const { seq, data } of updates) await this._decryptAndApply(data, seq);
124
+ this.synced = true;
125
+ if (this.e2eStore) {
126
+ const snapshot = Y.encodeStateAsUpdate(this.document);
127
+ await this.e2eStore.saveDocSnapshot(snapshot).catch(() => null);
128
+ await this.e2eStore.setMeta("e2e_seq", String(this.lastSeq)).catch(() => null);
129
+ }
130
+ }
131
+ async _decryptAndApply(encryptedData, seq) {
132
+ const key = await this.ensureDocKey();
133
+ if (!key) return;
134
+ try {
135
+ const plaintext = await decryptField(encryptedData, key);
136
+ Y.applyUpdate(this.document, plaintext, this);
137
+ this.lastSeq = Math.max(this.lastSeq, seq);
138
+ this._noteUpdateApplied();
139
+ } catch (e) {
140
+ console.error("[E2EAbracadabraProvider] decryption failed for seq", seq, e);
141
+ }
142
+ }
143
+ /** Encrypt local updates before sending over WebSocket. */
144
+ documentUpdateHandler(update, origin) {
145
+ if (origin === this) return;
146
+ if (!this.isAuthenticated) {
147
+ this._pendingPreAuthUpdates.push(update);
148
+ return;
149
+ }
150
+ this._encryptAndSend(update).catch((e) => {
151
+ console.error("[E2EAbracadabraProvider] failed to encrypt update:", e);
152
+ });
153
+ }
154
+ /**
155
+ * Flush updates buffered while unauthenticated once the server confirms the
156
+ * doc is subscribed, then resume normal live sends.
157
+ */
158
+ authenticatedHandler(scope) {
159
+ super.authenticatedHandler(scope);
160
+ if (this._pendingPreAuthUpdates.length === 0) return;
161
+ const pending = this._pendingPreAuthUpdates;
162
+ this._pendingPreAuthUpdates = [];
163
+ for (const update of pending) this._encryptAndSend(update).catch((e) => {
164
+ console.error("[E2EAbracadabraProvider] failed to flush pre-auth update:", e);
165
+ });
166
+ }
167
+ async _encryptAndSend(update) {
168
+ const key = await this.ensureDocKey();
169
+ if (!key) {
170
+ console.warn("[E2EAbracadabraProvider] no doc key, dropping update");
171
+ return;
172
+ }
173
+ const encrypted = await encryptField(update, key);
174
+ this.send(UpdateMessage, {
175
+ update: encrypted,
176
+ documentName: this.configuration.name
177
+ });
178
+ this._noteUpdateApplied();
179
+ }
180
+ /**
181
+ * Force an immediate compaction attempt, bypassing the threshold and
182
+ * quiescence debounce. Resolves once the `snapshot:compact` frame has been
183
+ * sent (or rejected locally for missing prerequisites — destroyed, no
184
+ * doc key, or already in-flight). The server acknowledges via a
185
+ * `snapshot:compacted` broadcast, which emits the `"compacted"` event.
186
+ */
187
+ async compactNow() {
188
+ if (this.compactionDebounceTimer) {
189
+ clearTimeout(this.compactionDebounceTimer);
190
+ this.compactionDebounceTimer = null;
191
+ }
192
+ await this._performCompaction();
193
+ }
194
+ _noteUpdateApplied() {
195
+ if (!this.compactionEnabled || this.destroyed) return;
196
+ this.updatesSinceCompaction += 1;
197
+ if (this.updatesSinceCompaction < this.compactionThreshold) return;
198
+ if (this.compactionDebounceTimer) clearTimeout(this.compactionDebounceTimer);
199
+ this.compactionDebounceTimer = setTimeout(() => {
200
+ this.compactionDebounceTimer = null;
201
+ this._performCompaction().catch((e) => {
202
+ console.error("[E2EAbracadabraProvider] compaction failed:", e);
203
+ });
204
+ }, this.compactionQuiescenceMs);
205
+ }
206
+ async _performCompaction() {
207
+ if (this.destroyed) return;
208
+ if (this.compactionInFlight) return;
209
+ if (this.updatesSinceCompaction === 0) return;
210
+ if (!this.synced) return;
211
+ const key = await this.ensureDocKey();
212
+ if (!key) return;
213
+ if (this.destroyed) return;
214
+ this.compactionInFlight = true;
215
+ try {
216
+ const stateVector = Y.encodeStateVector(this.document);
217
+ const encrypted = await encryptField(Y.encodeStateAsUpdate(this.document), key);
218
+ if (this.destroyed) {
219
+ this.compactionInFlight = false;
220
+ return;
221
+ }
222
+ const payload = `snapshot:compact ${JSON.stringify({
223
+ state_vector: toBase64(stateVector),
224
+ compacted: toBase64(encrypted)
225
+ })}`;
226
+ this.sendStateless(payload);
227
+ this.compactionInFlightTimeout = setTimeout(() => {
228
+ this.compactionInFlight = false;
229
+ this.compactionInFlightTimeout = null;
230
+ }, 3e4);
231
+ } catch (e) {
232
+ this.compactionInFlight = false;
233
+ throw e;
234
+ }
235
+ }
236
+ _handleCompactedBroadcast(jsonStr) {
237
+ let parsed = {};
238
+ try {
239
+ parsed = JSON.parse(jsonStr);
240
+ } catch {}
241
+ if (parsed.doc_id && parsed.doc_id !== this.configuration.name) return;
242
+ if (this.compactionInFlightTimeout) {
243
+ clearTimeout(this.compactionInFlightTimeout);
244
+ this.compactionInFlightTimeout = null;
245
+ }
246
+ this.compactionInFlight = false;
247
+ this.updatesSinceCompaction = 0;
248
+ const event = {
249
+ docId: parsed.doc_id ?? this.configuration.name,
250
+ by: parsed.by
251
+ };
252
+ this.emit("compacted", event);
253
+ }
254
+ destroy() {
255
+ if (this.destroyed) return;
256
+ this.destroyed = true;
257
+ if (this.compactionDebounceTimer) {
258
+ clearTimeout(this.compactionDebounceTimer);
259
+ this.compactionDebounceTimer = null;
260
+ }
261
+ if (this.compactionInFlightTimeout) {
262
+ clearTimeout(this.compactionInFlightTimeout);
263
+ this.compactionInFlightTimeout = null;
264
+ }
265
+ this.e2eStore?.destroy();
266
+ this.e2eStore = null;
267
+ super.destroy();
268
+ }
269
+ };
270
+
271
+ //#endregion
272
+ export { E2EAbracadabraProvider };
273
+ //# sourceMappingURL=E2EAbracadabraProvider.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"E2EAbracadabraProvider.js","names":[],"sources":["../../src/E2EAbracadabraProvider.ts"],"sourcesContent":["/**\n * E2EAbracadabraProvider\n *\n * Extends AbracadabraProvider with full E2E encryption support.\n *\n * Differences from standard provider:\n * - startSync() sends a stateless e2e_sync_request instead of SYNC_STEP1\n * - On receiving e2e_ready, fetches all blobs via REST, decrypts, applies to Y.Doc\n * - Local updates are AES-GCM encrypted before sending over WebSocket\n * - Incoming e2e_update stateless messages are decrypted and applied\n *\n * Phase 2 offline support:\n * - After the doc key is obtained, an E2EOfflineStore is created for this doc.\n * - The stored encrypted snapshot is applied before fetching server updates.\n * - The last-seen sequence number (e2e_seq) is persisted so only delta updates\n * are fetched on subsequent connects.\n * - After sync, a fresh encrypted snapshot is saved.\n *\n * Client-side compaction:\n * - After `compactionThreshold` encrypted updates have been applied in this\n * session (local + remote), and the doc has been quiescent for\n * `compactionQuiescenceMs`, the provider merges the whole Y.Doc, encrypts it,\n * and sends `snapshot:compact` — the server atomically replaces the per-doc\n * update log with that single compacted blob. The server acknowledges by\n * broadcasting `snapshot:compacted`, which emits the `\"compacted\"` event.\n * - Requires Owner or above (server silently drops non-Owner requests).\n * - Callers that want a final compaction before teardown should\n * `await provider.compactNow()` before `destroy()`. `destroy()` does not\n * compact (it'd race with the socket teardown) — any pending debounce is\n * cancelled.\n *\n * Key availability limitation: if the user's WebAuthn key is not in\n * DocKeyManager's in-memory cache and there is no network, E2E docs show\n * empty — the key fetch requires either a cached in-memory key or network.\n */\n\nimport * as Y from \"yjs\";\nimport { AbracadabraProvider } from \"./AbracadabraProvider.ts\";\nimport type { AbracadabraProviderConfiguration } from \"./AbracadabraProvider.ts\";\nimport type { DocKeyManager } from \"./DocKeyManager.ts\";\nimport type { CryptoIdentityKeystore } from \"./CryptoIdentityKeystore.ts\";\nimport type { AbracadabraClient } from \"./AbracadabraClient.ts\";\nimport { UpdateMessage } from \"./OutgoingMessages/UpdateMessage.ts\";\nimport { encryptField, decryptField } from \"./EncryptedY.ts\";\nimport { E2EOfflineStore } from \"./E2EOfflineStore.ts\";\nimport type { onCompactedParameters } from \"./types.ts\";\n\nfunction fromBase64(b64: string): Uint8Array {\n\treturn Uint8Array.from(atob(b64), (c) => c.charCodeAt(0));\n}\n\nfunction toBase64(bytes: Uint8Array): string {\n\tlet bin = \"\";\n\tfor (let i = 0; i < bytes.length; i += 0x8000) {\n\t\tbin += String.fromCharCode(...bytes.subarray(i, i + 0x8000));\n\t}\n\treturn btoa(bin);\n}\n\nexport interface E2EAbracadabraProviderConfiguration extends AbracadabraProviderConfiguration {\n\tdocKeyManager: DocKeyManager;\n\tkeystore: CryptoIdentityKeystore;\n\tclient: AbracadabraClient;\n\t/**\n\t * Enable client-side compaction: after `compactionThreshold` E2E updates,\n\t * the provider merges the whole doc, re-encrypts it, and asks the server to\n\t * atomically replace its update log via the `snapshot:compact` stateless\n\t * protocol. Requires the user to have a role that `can_manage` the doc\n\t * (Owner or above); otherwise the server silently rejects.\n\t *\n\t * Default: true.\n\t */\n\tcompactionEnabled?: boolean;\n\t/**\n\t * Number of E2E updates applied in this session before compaction fires.\n\t * Default: 50. Ignored when `compactionEnabled === false`.\n\t */\n\tcompactionThreshold?: number;\n\t/**\n\t * Quiescence delay: once the threshold is crossed, wait this many ms with\n\t * no further updates before firing compaction. Debounces active editing\n\t * and reduces the chance of racing an in-flight remote update that hasn't\n\t * reached us yet (the server does not currently validate state-vector\n\t * coverage, so a compaction fired mid-flight could drop an update).\n\t *\n\t * Default: 2000 ms.\n\t */\n\tcompactionQuiescenceMs?: number;\n}\n\nexport class E2EAbracadabraProvider extends AbracadabraProvider {\n\tprivate readonly docKeyManager: DocKeyManager;\n\tprivate readonly keystore: CryptoIdentityKeystore;\n\tprivate readonly e2eClient: AbracadabraClient;\n\tprivate docKey: CryptoKey | null = null;\n\tprivate lastSeq = -1;\n\n\t/** E2E-encrypted offline store; created after the doc key is available. */\n\tprivate e2eStore: E2EOfflineStore | null = null;\n\tprivate readonly e2eServerOrigin: string | undefined;\n\n\t// ── Client-side compaction ────────────────────────────────────────────────\n\tprivate readonly compactionEnabled: boolean;\n\tprivate readonly compactionThreshold: number;\n\tprivate readonly compactionQuiescenceMs: number;\n\tprivate updatesSinceCompaction = 0;\n\tprivate compactionInFlight = false;\n\t/** Cleared on `snapshot:compacted` or on 30s timeout. */\n\tprivate compactionInFlightTimeout: ReturnType<typeof setTimeout> | null = null;\n\t/** Quiescence debounce: reset on every update, fires the actual compaction. */\n\tprivate compactionDebounceTimer: ReturnType<typeof setTimeout> | null = null;\n\tprivate destroyed = false;\n\t/**\n\t * Plaintext local updates produced while this doc is not yet authenticated\n\t * on the connection. Unlike the plaintext provider, E2E does not convey\n\t * local state via SyncStep2 (it ships discrete encrypted update frames keyed\n\t * by server-assigned seq), so a pre-auth update that loses the AUTH race and\n\t * gets \"not subscribed\"-rejected would be lost. We queue them here and flush\n\t * (encrypt + send) once `authenticatedHandler` confirms the doc is\n\t * subscribed. Survives reconnects (only cleared on flush or destroy).\n\t */\n\tprivate _pendingPreAuthUpdates: Uint8Array[] = [];\n\n\tconstructor(configuration: E2EAbracadabraProviderConfiguration) {\n\t\t// Disable the parent's offline store — E2E uses its own encrypted store.\n\t\tsuper({ ...configuration, disableOfflineStore: true });\n\t\tthis.docKeyManager = configuration.docKeyManager;\n\t\tthis.keystore = configuration.keystore;\n\t\tthis.e2eClient = configuration.client;\n\n\t\tthis.compactionEnabled = configuration.compactionEnabled !== false;\n\t\tthis.compactionThreshold = Math.max(1, configuration.compactionThreshold ?? 50);\n\t\tthis.compactionQuiescenceMs = Math.max(0, configuration.compactionQuiescenceMs ?? 2000);\n\n\t\t// Derive server origin for E2EOfflineStore namespacing\n\t\tthis.e2eServerOrigin = E2EAbracadabraProvider.deriveServerOrigin(\n\t\t\tconfiguration,\n\t\t\tconfiguration.client,\n\t\t);\n\t}\n\n\t/** Fetch the doc key from the server (requires WebAuthn if not cached). */\n\tprivate async ensureDocKey(): Promise<CryptoKey | null> {\n\t\tif (this.docKey) return this.docKey;\n\t\tthis.docKey = await this.docKeyManager.getDocKey(\n\t\t\tthis.configuration.name,\n\t\t\tthis.e2eClient,\n\t\t\tthis.keystore,\n\t\t);\n\n\t\t// Create the encrypted offline store now that we have the key\n\t\tif (this.docKey && !this.e2eStore) {\n\t\t\tthis.e2eStore = new E2EOfflineStore(\n\t\t\t\tthis.configuration.name,\n\t\t\t\tthis.e2eServerOrigin,\n\t\t\t\tthis.docKey,\n\t\t\t);\n\t\t}\n\n\t\treturn this.docKey;\n\t}\n\n\t/** Handle stateless messages including e2e_ready and e2e_update. */\n\toverride receiveStateless(payload: string): void {\n\t\t// `snapshot:compacted {\"doc_id\":\"...\",\"by\":\"...\"}` is a space-separated\n\t\t// stateless frame — not valid JSON as a whole — so handle it before the\n\t\t// JSON.parse fallthrough.\n\t\tif (payload.startsWith(\"snapshot:compacted \")) {\n\t\t\tthis._handleCompactedBroadcast(payload.slice(\"snapshot:compacted \".length));\n\t\t\treturn;\n\t\t}\n\n\t\tlet parsed: unknown;\n\t\ttry {\n\t\t\tparsed = JSON.parse(payload);\n\t\t} catch {\n\t\t\tsuper.receiveStateless(payload);\n\t\t\treturn;\n\t\t}\n\n\t\tconst msg = parsed as { type?: string; seq?: number; data?: string; doc_id?: string };\n\n\t\tif (msg.type === \"e2e_ready\") {\n\t\t\t// Fetch all blobs and hydrate doc\n\t\t\tthis._fetchAndApplyAllBlobs().catch((e) => {\n\t\t\t\tconsole.error(\"[E2EAbracadabraProvider] failed to fetch e2e blobs:\", e);\n\t\t\t});\n\t\t\treturn;\n\t\t}\n\n\t\tif (msg.type === \"e2e_update\" && msg.data !== undefined && msg.seq !== undefined) {\n\t\t\tif (msg.seq <= this.lastSeq) return; // Already applied\n\t\t\tthis._decryptAndApply(fromBase64(msg.data), msg.seq).catch((e) => {\n\t\t\t\tconsole.error(\"[E2EAbracadabraProvider] failed to apply e2e_update:\", e);\n\t\t\t});\n\t\t\treturn;\n\t\t}\n\n\t\tsuper.receiveStateless(payload);\n\t}\n\n\tprivate async _fetchAndApplyAllBlobs(): Promise<void> {\n\t\tconst key = await this.ensureDocKey();\n\t\tif (!key) {\n\t\t\tconsole.warn(\"[E2EAbracadabraProvider] no doc key available, cannot decrypt blobs\");\n\t\t\tthis.synced = true;\n\t\t\treturn;\n\t\t}\n\n\t\t// Phase 2: load stored snapshot + lastSeq before fetching from server\n\t\tif (this.e2eStore) {\n\t\t\tconst storedSeqStr = await this.e2eStore.getMeta(\"e2e_seq\").catch(() => null);\n\t\t\tif (storedSeqStr !== null) {\n\t\t\t\tthis.lastSeq = parseInt(storedSeqStr, 10);\n\t\t\t}\n\n\t\t\tconst snapshot = await this.e2eStore.getDocSnapshot().catch(() => null);\n\t\t\tif (snapshot) {\n\t\t\t\tY.applyUpdate(this.document, snapshot, this.e2eStore);\n\t\t\t}\n\t\t}\n\n\t\t// Only fetch updates newer than lastSeq\n\t\tconst updates = await this.e2eClient.getE2EUpdatesSince(\n\t\t\tthis.configuration.name,\n\t\t\tthis.lastSeq,\n\t\t);\n\t\tfor (const { seq, data } of updates) {\n\t\t\tawait this._decryptAndApply(data, seq);\n\t\t}\n\n\t\tthis.synced = true;\n\n\t\t// Phase 2: persist updated snapshot and lastSeq\n\t\tif (this.e2eStore) {\n\t\t\tconst snapshot = Y.encodeStateAsUpdate(this.document);\n\t\t\tawait this.e2eStore.saveDocSnapshot(snapshot).catch(() => null);\n\t\t\tawait this.e2eStore.setMeta(\"e2e_seq\", String(this.lastSeq)).catch(() => null);\n\t\t}\n\t}\n\n\tprivate async _decryptAndApply(encryptedData: Uint8Array, seq: number): Promise<void> {\n\t\tconst key = await this.ensureDocKey();\n\t\tif (!key) return;\n\t\ttry {\n\t\t\tconst plaintext = await decryptField(encryptedData, key);\n\t\t\tY.applyUpdate(this.document, plaintext, this);\n\t\t\tthis.lastSeq = Math.max(this.lastSeq, seq);\n\t\t\tthis._noteUpdateApplied();\n\t\t} catch (e) {\n\t\t\tconsole.error(\"[E2EAbracadabraProvider] decryption failed for seq\", seq, e);\n\t\t}\n\t}\n\n\t/** Encrypt local updates before sending over WebSocket. */\n\toverride documentUpdateHandler(update: Uint8Array, origin: unknown): void {\n\t\tif (origin === this) return;\n\n\t\t// AUTH-ordering guard (see _pendingPreAuthUpdates): until the doc is\n\t\t// authenticated on the connection, an encrypted update would race ahead\n\t\t// of the AUTH frame on the shared multiplexed socket and be rejected with\n\t\t// \"not subscribed\". Queue it and flush on authenticatedHandler instead of\n\t\t// racing (and losing) it.\n\t\tif (!this.isAuthenticated) {\n\t\t\tthis._pendingPreAuthUpdates.push(update);\n\t\t\treturn;\n\t\t}\n\n\t\t// Don't call super (which would send plaintext); encrypt first\n\t\tthis._encryptAndSend(update).catch((e) => {\n\t\t\tconsole.error(\"[E2EAbracadabraProvider] failed to encrypt update:\", e);\n\t\t});\n\t}\n\n\t/**\n\t * Flush updates buffered while unauthenticated once the server confirms the\n\t * doc is subscribed, then resume normal live sends.\n\t */\n\toverride authenticatedHandler(scope: string): void {\n\t\tsuper.authenticatedHandler(scope);\n\t\tif (this._pendingPreAuthUpdates.length === 0) return;\n\t\tconst pending = this._pendingPreAuthUpdates;\n\t\tthis._pendingPreAuthUpdates = [];\n\t\tfor (const update of pending) {\n\t\t\tthis._encryptAndSend(update).catch((e) => {\n\t\t\t\tconsole.error(\"[E2EAbracadabraProvider] failed to flush pre-auth update:\", e);\n\t\t\t});\n\t\t}\n\t}\n\n\tprivate async _encryptAndSend(update: Uint8Array): Promise<void> {\n\t\tconst key = await this.ensureDocKey();\n\t\tif (!key) {\n\t\t\tconsole.warn(\"[E2EAbracadabraProvider] no doc key, dropping update\");\n\t\t\treturn;\n\t\t}\n\t\tconst encrypted = await encryptField(update, key);\n\t\tthis.send(UpdateMessage, {\n\t\t\tupdate: encrypted,\n\t\t\tdocumentName: this.configuration.name,\n\t\t});\n\t\tthis._noteUpdateApplied();\n\t}\n\n\t// ── Compaction ────────────────────────────────────────────────────────────\n\n\t/**\n\t * Force an immediate compaction attempt, bypassing the threshold and\n\t * quiescence debounce. Resolves once the `snapshot:compact` frame has been\n\t * sent (or rejected locally for missing prerequisites — destroyed, no\n\t * doc key, or already in-flight). The server acknowledges via a\n\t * `snapshot:compacted` broadcast, which emits the `\"compacted\"` event.\n\t */\n\tasync compactNow(): Promise<void> {\n\t\tif (this.compactionDebounceTimer) {\n\t\t\tclearTimeout(this.compactionDebounceTimer);\n\t\t\tthis.compactionDebounceTimer = null;\n\t\t}\n\t\tawait this._performCompaction();\n\t}\n\n\tprivate _noteUpdateApplied(): void {\n\t\tif (!this.compactionEnabled || this.destroyed) return;\n\t\tthis.updatesSinceCompaction += 1;\n\t\tif (this.updatesSinceCompaction < this.compactionThreshold) return;\n\n\t\t// Debounce: reset on every update so compaction only fires after a\n\t\t// quiescent window. This avoids racing concurrent remote updates that\n\t\t// are still propagating through the server.\n\t\tif (this.compactionDebounceTimer) clearTimeout(this.compactionDebounceTimer);\n\t\tthis.compactionDebounceTimer = setTimeout(() => {\n\t\t\tthis.compactionDebounceTimer = null;\n\t\t\tthis._performCompaction().catch((e) => {\n\t\t\t\tconsole.error(\"[E2EAbracadabraProvider] compaction failed:\", e);\n\t\t\t});\n\t\t}, this.compactionQuiescenceMs);\n\t}\n\n\tprivate async _performCompaction(): Promise<void> {\n\t\tif (this.destroyed) return;\n\t\t// Single-flight: server handles concurrent compactions, but we don't\n\t\t// want to pile up outbound frames.\n\t\tif (this.compactionInFlight) return;\n\t\t// Nothing to compact — skip unless explicitly forced after threshold.\n\t\tif (this.updatesSinceCompaction === 0) return;\n\n\t\t// Compaction replaces the entire server-side update log with our state.\n\t\t// Only run after the initial sync — otherwise we'd overwrite the log\n\t\t// with a partial state.\n\t\tif (!this.synced) return;\n\n\t\tconst key = await this.ensureDocKey();\n\t\tif (!key) return;\n\t\tif (this.destroyed) return; // key fetch may be async\n\n\t\tthis.compactionInFlight = true;\n\t\ttry {\n\t\t\tconst stateVector = Y.encodeStateVector(this.document);\n\t\t\tconst fullState = Y.encodeStateAsUpdate(this.document);\n\t\t\tconst encrypted = await encryptField(fullState, key);\n\t\t\tif (this.destroyed) {\n\t\t\t\tthis.compactionInFlight = false;\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\tconst payload = `snapshot:compact ${JSON.stringify({\n\t\t\t\tstate_vector: toBase64(stateVector),\n\t\t\t\tcompacted: toBase64(encrypted),\n\t\t\t})}`;\n\t\t\tthis.sendStateless(payload);\n\n\t\t\t// Release in-flight on server broadcast; if nothing arrives in 30s\n\t\t\t// (e.g. permissions rejected, connection dropped) release anyway.\n\t\t\tthis.compactionInFlightTimeout = setTimeout(() => {\n\t\t\t\tthis.compactionInFlight = false;\n\t\t\t\tthis.compactionInFlightTimeout = null;\n\t\t\t}, 30_000);\n\t\t} catch (e) {\n\t\t\tthis.compactionInFlight = false;\n\t\t\tthrow e;\n\t\t}\n\t}\n\n\tprivate _handleCompactedBroadcast(jsonStr: string): void {\n\t\tlet parsed: { doc_id?: string; by?: string } = {};\n\t\ttry {\n\t\t\tparsed = JSON.parse(jsonStr);\n\t\t} catch {\n\t\t\t/* malformed — still clear in-flight below */\n\t\t}\n\n\t\t// Only act on broadcasts for our own doc (server scopes this already,\n\t\t// but be defensive).\n\t\tif (parsed.doc_id && parsed.doc_id !== this.configuration.name) return;\n\n\t\tif (this.compactionInFlightTimeout) {\n\t\t\tclearTimeout(this.compactionInFlightTimeout);\n\t\t\tthis.compactionInFlightTimeout = null;\n\t\t}\n\t\tthis.compactionInFlight = false;\n\t\tthis.updatesSinceCompaction = 0;\n\n\t\tconst event: onCompactedParameters = {\n\t\t\tdocId: parsed.doc_id ?? this.configuration.name,\n\t\t\tby: parsed.by,\n\t\t};\n\t\tthis.emit(\"compacted\", event);\n\t}\n\n\toverride destroy(): void {\n\t\tif (this.destroyed) return;\n\t\tthis.destroyed = true;\n\n\t\tif (this.compactionDebounceTimer) {\n\t\t\tclearTimeout(this.compactionDebounceTimer);\n\t\t\tthis.compactionDebounceTimer = null;\n\t\t}\n\t\tif (this.compactionInFlightTimeout) {\n\t\t\tclearTimeout(this.compactionInFlightTimeout);\n\t\t\tthis.compactionInFlightTimeout = null;\n\t\t}\n\t\tthis.e2eStore?.destroy();\n\t\tthis.e2eStore = null;\n\t\tsuper.destroy();\n\t}\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA+CA,SAAS,WAAW,KAAyB;AAC5C,QAAO,WAAW,KAAK,KAAK,IAAI,GAAG,MAAM,EAAE,WAAW,EAAE,CAAC;;AAG1D,SAAS,SAAS,OAA2B;CAC5C,IAAI,MAAM;AACV,MAAK,IAAI,IAAI,GAAG,IAAI,MAAM,QAAQ,KAAK,MACtC,QAAO,OAAO,aAAa,GAAG,MAAM,SAAS,GAAG,IAAI,MAAO,CAAC;AAE7D,QAAO,KAAK,IAAI;;AAkCjB,IAAa,yBAAb,MAAa,+BAA+B,oBAAoB;CAiC/D,YAAY,eAAoD;AAE/D,QAAM;GAAE,GAAG;GAAe,qBAAqB;GAAM,CAAC;gBA/BpB;iBACjB;kBAGyB;gCAOV;4BACJ;mCAE6C;iCAEF;mBACpD;gCAU2B,EAAE;AAKhD,OAAK,gBAAgB,cAAc;AACnC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AAE,kBAAkB,KAAK,SAAS;GAEtD,MAAM,YAAY,MAAM,aADN,EAAE,oBAAoB,KAAK,SAAS,EACN,IAAI;AACpD,OAAI,KAAK,WAAW;AACnB,SAAK,qBAAqB;AAC1B;;GAGD,MAAM,UAAU,oBAAoB,KAAK,UAAU;IAClD,cAAc,SAAS,YAAY;IACnC,WAAW,SAAS,UAAU;IAC9B,CAAC;AACF,QAAK,cAAc,QAAQ;AAI3B,QAAK,4BAA4B,iBAAiB;AACjD,SAAK,qBAAqB;AAC1B,SAAK,4BAA4B;MAC/B,IAAO;WACF,GAAG;AACX,QAAK,qBAAqB;AAC1B,SAAM;;;CAIR,AAAQ,0BAA0B,SAAuB;EACxD,IAAI,SAA2C,EAAE;AACjD,MAAI;AACH,YAAS,KAAK,MAAM,QAAQ;UACrB;AAMR,MAAI,OAAO,UAAU,OAAO,WAAW,KAAK,cAAc,KAAM;AAEhE,MAAI,KAAK,2BAA2B;AACnC,gBAAa,KAAK,0BAA0B;AAC5C,QAAK,4BAA4B;;AAElC,OAAK,qBAAqB;AAC1B,OAAK,yBAAyB;EAE9B,MAAM,QAA+B;GACpC,OAAO,OAAO,UAAU,KAAK,cAAc;GAC3C,IAAI,OAAO;GACX;AACD,OAAK,KAAK,aAAa,MAAM;;CAG9B,AAAS,UAAgB;AACxB,MAAI,KAAK,UAAW;AACpB,OAAK,YAAY;AAEjB,MAAI,KAAK,yBAAyB;AACjC,gBAAa,KAAK,wBAAwB;AAC1C,QAAK,0BAA0B;;AAEhC,MAAI,KAAK,2BAA2B;AACnC,gBAAa,KAAK,0BAA0B;AAC5C,QAAK,4BAA4B;;AAElC,OAAK,UAAU,SAAS;AACxB,OAAK,WAAW;AAChB,QAAM,SAAS"}
@@ -0,0 +1,53 @@
1
+ import { OfflineStore } from "./OfflineStore.js";
2
+ import { decryptField, encryptField } from "./EncryptedY.js";
3
+
4
+ //#region packages/provider/src/E2EOfflineStore.ts
5
+ /**
6
+ * E2EOfflineStore
7
+ *
8
+ * Extends OfflineStore with transparent AES-GCM encryption of the document
9
+ * snapshot, ensuring that even if the device is compromised, the local
10
+ * IndexedDB data cannot be read without the doc key.
11
+ *
12
+ * Only the snapshot is encrypted (not the meta store entries, which contain
13
+ * non-sensitive data like sequence numbers).
14
+ *
15
+ * Key availability limitation: if the user's WebAuthn key is not in
16
+ * DocKeyManager's in-memory cache and there is no network, E2E docs show
17
+ * empty — this is expected Phase 2 behavior.
18
+ */
19
+ var E2EOfflineStore = class extends OfflineStore {
20
+ /**
21
+ * @param docId The document UUID.
22
+ * @param serverOrigin Hostname of the server (namespaces the IDB key).
23
+ * @param docKey AES-GCM CryptoKey used to encrypt/decrypt the snapshot.
24
+ */
25
+ constructor(docId, serverOrigin, docKey) {
26
+ super(docId, serverOrigin);
27
+ this.docKey = docKey;
28
+ }
29
+ /**
30
+ * Encrypt the snapshot before storing it.
31
+ */
32
+ async saveDocSnapshot(snapshot) {
33
+ const encrypted = await encryptField(snapshot, this.docKey);
34
+ await super.saveDocSnapshot(encrypted);
35
+ }
36
+ /**
37
+ * Decrypt the snapshot after loading it.
38
+ * Returns null if decryption fails (e.g. key mismatch or corrupt data).
39
+ */
40
+ async getDocSnapshot() {
41
+ const encrypted = await super.getDocSnapshot();
42
+ if (!encrypted) return null;
43
+ try {
44
+ return await decryptField(encrypted, this.docKey);
45
+ } catch {
46
+ return null;
47
+ }
48
+ }
49
+ };
50
+
51
+ //#endregion
52
+ export { E2EOfflineStore };
53
+ //# sourceMappingURL=E2EOfflineStore.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"E2EOfflineStore.js","names":[],"sources":["../../src/E2EOfflineStore.ts"],"sourcesContent":["/**\n * E2EOfflineStore\n *\n * Extends OfflineStore with transparent AES-GCM encryption of the document\n * snapshot, ensuring that even if the device is compromised, the local\n * IndexedDB data cannot be read without the doc key.\n *\n * Only the snapshot is encrypted (not the meta store entries, which contain\n * non-sensitive data like sequence numbers).\n *\n * Key availability limitation: if the user's WebAuthn key is not in\n * DocKeyManager's in-memory cache and there is no network, E2E docs show\n * empty — this is expected Phase 2 behavior.\n */\n\nimport { OfflineStore } from \"./OfflineStore.ts\";\nimport { encryptField, decryptField } from \"./EncryptedY.ts\";\n\nexport class E2EOfflineStore extends OfflineStore {\n\tprivate readonly docKey: CryptoKey;\n\n\t/**\n\t * @param docId The document UUID.\n\t * @param serverOrigin Hostname of the server (namespaces the IDB key).\n\t * @param docKey AES-GCM CryptoKey used to encrypt/decrypt the snapshot.\n\t */\n\tconstructor(docId: string, serverOrigin: string | undefined, docKey: CryptoKey) {\n\t\tsuper(docId, serverOrigin);\n\t\tthis.docKey = docKey;\n\t}\n\n\t/**\n\t * Encrypt the snapshot before storing it.\n\t */\n\toverride async saveDocSnapshot(snapshot: Uint8Array): Promise<void> {\n\t\tconst encrypted = await encryptField(snapshot, this.docKey);\n\t\tawait super.saveDocSnapshot(encrypted);\n\t}\n\n\t/**\n\t * Decrypt the snapshot after loading it.\n\t * Returns null if decryption fails (e.g. key mismatch or corrupt data).\n\t */\n\toverride async getDocSnapshot(): Promise<Uint8Array | null> {\n\t\tconst encrypted = await super.getDocSnapshot();\n\t\tif (!encrypted) return null;\n\t\ttry {\n\t\t\treturn await decryptField(encrypted, this.docKey);\n\t\t} catch {\n\t\t\t// Key mismatch or tampered data — return null so the provider falls\n\t\t\t// back to fetching from the server.\n\t\t\treturn null;\n\t\t}\n\t}\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;AAkBA,IAAa,kBAAb,cAAqC,aAAa;;;;;;CAQjD,YAAY,OAAe,cAAkC,QAAmB;AAC/E,QAAM,OAAO,aAAa;AAC1B,OAAK,SAAS;;;;;CAMf,MAAe,gBAAgB,UAAqC;EACnE,MAAM,YAAY,MAAM,aAAa,UAAU,KAAK,OAAO;AAC3D,QAAM,MAAM,gBAAgB,UAAU;;;;;;CAOvC,MAAe,iBAA6C;EAC3D,MAAM,YAAY,MAAM,MAAM,gBAAgB;AAC9C,MAAI,CAAC,UAAW,QAAO;AACvB,MAAI;AACH,UAAO,MAAM,aAAa,WAAW,KAAK,OAAO;UAC1C;AAGP,UAAO"}