@abraca/dabra 2.82.0 → 2.83.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.d.ts CHANGED
@@ -234,6 +234,120 @@ declare class DocumentCache {
234
234
  destroy(): void;
235
235
  }
236
236
  //#endregion
237
+ //#region packages/provider/src/ServerReset.d.ts
238
+ /**
239
+ * Detect that a server's database has been REPLACED, and drop this browser's
240
+ * caches for it before anything re-pushes them.
241
+ *
242
+ * ## The bug
243
+ *
244
+ * Deleting a backend's database does not give you a clean server. Every browser
245
+ * that was connected still holds that space's CRDT state in IndexedDB, and on
246
+ * reconnect it re-pushes the old tree into the fresh one. A seeder then adds its
247
+ * own on top and you get every page twice — `/about` AND `/about-1`. Repeat the
248
+ * cycle and it MULTIPLIES: `-2`, `-3`, `-4`.
249
+ *
250
+ * This is inherent to a CRDT and cannot be fixed downstream. A deleted database
251
+ * is not a tombstone; it is a peer that lost its memory, and the client is the
252
+ * one holding the newer state. No idempotency guard can see it — by the time one
253
+ * runs, the re-pushed tree looks exactly like real content.
254
+ *
255
+ * It is not a development-only annoyance. The expensive case is a production
256
+ * restore from backup, where the peers re-pushing stale trees are visitors who
257
+ * will never read a release note.
258
+ *
259
+ * ## Why the server can be believed
260
+ *
261
+ * The server mints a `server_id` and persists it beside its database. It
262
+ * survives restarts and changes when, and only when, that database is replaced.
263
+ * So it states outright what a CRDT cannot work out for itself: *the peer you
264
+ * are syncing with is not the one you have been talking to.*
265
+ *
266
+ * ## What gets dropped
267
+ *
268
+ * Everything this SDK scopes to a server, which is more than the document
269
+ * caches:
270
+ *
271
+ * | store | written by |
272
+ * |---|---|
273
+ * | `abracadabra:<host>/<docId>` | {@link OfflineStore} |
274
+ * | `abracadabra:meta-cache:<host>` | `DocumentCache` |
275
+ * | `abracadabra:files:<host>` | `FileBlobStore` |
276
+ * | `abracadabra:bgsync:<host>` | `BackgroundSyncPersistence` |
277
+ * | `abracadabra:search:<host>` | `SearchIndex` |
278
+ *
279
+ * One ANCHORED rule covers all five shapes, so nothing here has to stay in step
280
+ * with how each store builds its key. Anchored rather than a substring test on
281
+ * purpose — see {@link isServerScopedStore}, where the naive version would have
282
+ * cleared a different server's caches.
283
+ *
284
+ * `abracadabra:identity` is deliberately NOT dropped. It is this browser's
285
+ * keypair across every server it talks to; clearing it would sign the user out
286
+ * of all of them because one of them was reinstalled.
287
+ */
288
+ interface ServerResetOutcome {
289
+ /** The id previously seen for this host, if any. */
290
+ previousServerId: string | null;
291
+ /** The id the server reports now. */
292
+ serverId: string;
293
+ /** Databases deleted because they belonged to the replaced server. */
294
+ cleared: string[];
295
+ /**
296
+ * Databases whose deletion was BLOCKED by an open connection.
297
+ *
298
+ * This is a failure, not a warning to swallow: the stale state is still in
299
+ * the tab and will be re-pushed. It happens when a provider opened the store
300
+ * before this ran, which means the guard was called too late. Callers should
301
+ * surface it rather than assume a clean result.
302
+ */
303
+ blocked: string[];
304
+ }
305
+ /**
306
+ * Does this database belong to the given server?
307
+ *
308
+ * The match is ANCHORED, and it has to be. A plain `name.includes(host)` looks
309
+ * right and is wrong in a way that destroys data: `other.example.com:3011`
310
+ * contains `example.com:3011`, so clearing one server's caches would delete a
311
+ * DIFFERENT server's — the exact "too broad" failure this guard exists to avoid.
312
+ * A unit test covers that pair.
313
+ *
314
+ * Three anchored shapes are needed, because the stores are NOT consistently
315
+ * scoped and pretending otherwise silently misses some:
316
+ *
317
+ * - `<host>/…` — {@link OfflineStore}, keyed `<host>/<docId>`
318
+ * - `…:<host>` — a namespaced store handed a bare host
319
+ * - `…://<host>` — a namespaced store handed a full URL. Real, not hypothetical:
320
+ * `@abraca/nuxt` passes `serverUrl` to `FileBlobStore`, so the database is
321
+ * named `abracadabra:files:http://example.com:3011`. Measured in a live
322
+ * browser; a rule written only for the first two shapes left it behind, which
323
+ * is a whole file cache surviving a wipe.
324
+ */
325
+ declare function isServerScopedStore(name: string, host: string): boolean;
326
+ /**
327
+ * Compare the server's identity against the one this browser last saw, and drop
328
+ * every cache belonging to it if the database has been replaced.
329
+ *
330
+ * **Call this before opening any provider.** Once a provider holds an IndexedDB
331
+ * handle, `deleteDatabase` blocks instead of deleting and the stale tree is
332
+ * already queued for re-push — the deletion completes later, having achieved
333
+ * nothing. Any store in that position comes back in `blocked`.
334
+ *
335
+ * Conservative by design:
336
+ *
337
+ * - the FIRST time a host is seen, the id is recorded and nothing is deleted —
338
+ * a new visitor must not have caches cleared for having no history;
339
+ * - a browser with no `indexedDB`/`localStorage` is a no-op;
340
+ * - it never throws. Failing to tidy a cache must not stop an app from starting.
341
+ *
342
+ * @param host The server's `host` (`example.com:3011`) — the same value
343
+ * providers scope their stores by. Not the full origin: the
344
+ * scheme is not part of a server's cache identity here.
345
+ * @param serverId `server_id` from `GET /info`.
346
+ */
347
+ declare function dropCachesIfServerReplaced(host: string, serverId: string): Promise<ServerResetOutcome | null>;
348
+ /** Forget what we know about a host, so the next check treats it as new. */
349
+ declare function forgetServerIdentity(host: string): void;
350
+ //#endregion
237
351
  //#region packages/provider/src/AbracadabraClient.d.ts
238
352
  /**
239
353
  * Reason classifications surfaced to `onAuthFailed`. Consumers can decide
@@ -1111,6 +1225,25 @@ declare class AbracadabraClient {
1111
1225
  * No auth required.
1112
1226
  */
1113
1227
  serverInfo(): Promise<ServerInfo>;
1228
+ /**
1229
+ * Drop this browser's caches for this server if its database has been
1230
+ * REPLACED since the last visit, and report what happened.
1231
+ *
1232
+ * **Call it before opening any provider**, and await it. A deleted database
1233
+ * is not a tombstone — it is a peer that lost its memory — so a tab that
1234
+ * reconnects with stale IndexedDB re-pushes the old tree into the fresh one
1235
+ * and a seeder adds its own on top: every page twice, then three times. Once
1236
+ * a provider holds a store open, `deleteDatabase` blocks instead of deleting
1237
+ * and the damage is already queued; those stores come back in `blocked`,
1238
+ * which is a signal that this ran too late rather than something to ignore.
1239
+ *
1240
+ * Returns `null` when there is nothing to do — no `server_id`, no browser
1241
+ * storage, a first visit, or the same database as last time. It never
1242
+ * throws: an app must not fail to start because a cache could not be tidied.
1243
+ *
1244
+ * @see dropCachesIfServerReplaced for what is dropped and what is kept.
1245
+ */
1246
+ ensureFreshServer(): Promise<ServerResetOutcome | null>;
1114
1247
  /**
1115
1248
  * Fetch ICE server configuration for WebRTC peer connections.
1116
1249
  * Falls back to default Google STUN server if the endpoint is unavailable.
@@ -2056,6 +2189,16 @@ interface HealthStatus {
2056
2189
  interface ServerInfo {
2057
2190
  /** Human-readable server name set by the operator. */
2058
2191
  name?: string;
2192
+ /**
2193
+ * Identity of this server's DATABASE, persisted beside it.
2194
+ *
2195
+ * Stable across restarts and upgrades; it changes only when the database is
2196
+ * replaced — a wipe, or a restore from backup. That makes it the one signal a
2197
+ * client can use to know its cached CRDT state belongs to a peer that no
2198
+ * longer exists, which a CRDT cannot work out for itself. See
2199
+ * {@link dropCachesIfServerReplaced}.
2200
+ */
2201
+ server_id?: string;
2059
2202
  /** Server version string. */
2060
2203
  version?: string;
2061
2204
  /** Hocuspocus wire protocol version (currently 2). */
@@ -6126,4 +6269,4 @@ declare function collectMediaFileBlocks(root: Y.XmlFragment | Y.XmlElement): Med
6126
6269
  */
6127
6270
  declare function reconcileDocCover(treeMap: Y.Map<unknown>, docId: string, fragment: Y.XmlFragment | Y.XmlElement): void;
6128
6271
  //#endregion
6129
- export { AbracadabraBaseProvider, AbracadabraBaseProviderConfiguration, AbracadabraClient, AbracadabraClientConfig, AbracadabraOutgoingMessageArguments, AbracadabraProvider, AbracadabraProviderConfiguration, AbracadabraWS, AbracadabraWSConfiguration, AbracadabraWebRTC, type AbracadabraWebRTCConfiguration, AbracadabraWebSocketConn, AdminConfigField, AdminConfigOriginKind, AuditLogEntry, AuditQueryOpts, AuditVerifyResult, AuthFailureContext, AuthFailureReason, AuthMessageType, AuthorizedScope, AwarenessError, BackgroundSyncManager, type BackgroundSyncManagerOptions, BackgroundSyncPersistence, BroadcastChannelSync, CHANNEL_NAMES, ChannelKeyResolver, type ChatChannel, ChatClient, type ChatClientTransport, type MarkReadInput as ChatMarkReadInput, type ChatMessage, type ChatReadCursor, type ChatReadReceipt, type ChatTypingEvent, type ChildrenPage, CloseEvent, CompleteAbracadabraBaseProviderConfiguration, CompleteAbracadabraWSConfiguration, CompleteHocuspocusProviderConfiguration, CompleteHocuspocusProviderWebsocketConfiguration, type ConnectPolicyResult, ConnectionTimeout, Constructable, ConstructableOutgoingMessage, ContentManager, type CreateNotificationInput, CryptoIdentity, CryptoIdentityKeystore, DEFAULT_FILE_CHUNK_SIZE, DEFAULT_ICE_SERVERS, DataChannelRouter, type DeleteMessageInput, DevicePairingChannel, type DevicePairingConfig, DeviceRegistrationService, type DeviceServerStatus, type DeviceSessionRecord, type DeviceSessionStorage, type DeviceTier, DocBacklink, type DocEncryptionInfo, DocKeyManager, DocSearchHit, type DocSyncState, type DocSyncStatus, type DocumentBlock, DocumentCache, type DocumentCacheOptions, type DocumentContent, DocumentManager, type DocumentManagerConfig, DocumentMeta, type DocumentMetaInfo, type DocumentMetaWire, E2EAbracadabraProvider, E2EEChannel, type E2EEIdentity, E2EOfflineStore, type EditMessageInput, EffectivePermissionEntry, EffectivePermissionsResponse, EffectiveRole, EncryptedChatClient, EncryptedYMap, EncryptedYText, EnvSnapshotExtension, EnvSnapshotItem, EnvSnapshotResponse, type FetchInboxInput, type FetchNotificationsInput, FileBlobStore, FileTransferChannel, FileTransferHandle, type FileTransferMeta, type FileTransferStatus, type FoldedMessage, Forbidden, GEO_TYPE_META_SCHEMAS, type GetChatHistoryInput, HealthStatus, HocusPocusWebSocket, HocuspocusProvider, HocuspocusProviderConfiguration, HocuspocusProviderWebsocket, HocuspocusProviderWebsocketConfiguration, HocuspocusWebSocket, type IdentityDeviceEntry, type IdentityDocConfiguration, IdentityDocProvider, type IdentityProfile, type IdentityServerEntry, type IdentitySpaceEntry, type InboxEntry, type MarkReadInput$1 as InboxMarkReadInput, InviteRow, KEY_EXCHANGE_CHANNEL, type KeyAuthClient, Kind, type LoadKeyFileOptions, LocalStorageDeviceSessionStorage, type LoginOrRegisterOptions, ManualSignaling, type ManualSignalingBlob, type MediaFileBlock, type MessageRecord, MessageTooBig, MessageType, MetaFieldType, MetaManager, MetaValidationError, type NodeKeypair, type NotificationReadUpdate, type NotificationRecord, NotificationsClient, OfflineStore, OutgoingMessageArguments, OutgoingMessageInterface, PAGE_TYPES, PageMeta, PageTypeInfo, PageTypeMetaField, type PairingRequest, type PairingResult, PeerConnection, type PeerInfo, type PeerState, PendingSubdoc, PermissionEntry, type PolicyAuthClient, PublicKeyInfo, QUERY_PREFIX, QueryClient, QueryError, type QueryFrame, type QueryKind, type QuerySpec, type QuerySubscriptionHandle, type QuerySubscriptionHandlers, type QueryTransport, RPC_PREFIX, ReadyzStatus, ResetConnection, type RpcCallHandle, type RpcCallOptions, RpcClient, RpcError, type RpcErrorCode, type RpcErrorPayload, type RpcFrame, type RpcHandler, type RpcHandlerContext, type RpcKind, type RpcTarget, type RpcTransport, SERVER_ROOT_ID, type SchemaDocTypeName, type SchemaMetaOf, type SchemaRegistryLike, type SchemaValidatorLike, SearchIndex, SearchResult, type SendChatMessageInput, type SendMessageInput, type SendMessageResult, ServerInfo, type ServerProfile, type ServerRegistry, type SignalingIncoming, type SignalingOutgoing, SignalingSocket, SnapshotCreateResult, SnapshotData, SnapshotFileEntry, SnapshotForkResult, SnapshotMeta, SnapshotRestoreResult, StatesArray, StreamTokenInfo, SubdocMessage, SubdocRegisteredEvent, TYPE_ALIASES, ThumbnailOptions, TokenManager, type TokenManagerOptions, TreeEntry, TreeManager, TreeNode, TreeSearchResult, TypedDocTypeMismatchError, type TypedDocsClient, type TypedTreeEntry, Unauthorized, UploadInfo, UploadMeta, UploadQueueEntry, UploadQueueStatus, UserMetaField, UserProfile, WebSocketStatus, WriteRejectionKind, WsReadyStates, YjsDataChannel, addServer, attachUpdatedAtObserver, awarenessStatesToArray, wordlist as bip39Wordlist, buildBlockquoteElement, buildBlocksFromMarkdown, buildBulletListElement, buildCodeBlockElement, buildHeadingElement, buildHorizontalRuleElement, buildOrderedListElement, buildParagraphElement, buildTaskListElement, collectMediaFileBlocks, decryptChatContent, decryptField, defaultKeyFileFor, deriveDmDocId, deriveIdentityDocId, deriveSeedWrappingKey, deterministicKeypair, encryptChatContent, encryptField, filenameToLabel, foldRecords, generateMnemonic, isEncryptedContent, isPlaceholderLabel, loadOrCreateKeyFile, loadServerRegistry, loginOrRegisterWithKey, loginOrRegisterWithPolicy, makeChallengeSigner, makeEncryptedYMap, makeEncryptedYText, makeEntryMap, migrateLegacyDefault, mnemonicToEd25519Seed, mnemonicToKeyPair, normalizeRootId, onAuthenticatedParameters, onAuthenticationFailedParameters, onAwarenessChangeParameters, onAwarenessUpdateParameters, onCloseParameters, onCompactedParameters, onDisconnectParameters, onMessageParameters, onOpenParameters, onOutgoingMessageParameters, onReconnectedParameters, onServerErrorParameters, onStatelessParameters, onStatusParameters, onSubdocLoadedParameters, onSubdocRegisteredParameters, onSyncedParameters, onUnsyncedChangesParameters, onWriteRejectedParameters, openSyncedProvider, parseFrontmatter, patchEntry, pickEntrySpace, populateYDocFromMarkdown, readAuthMessage, readBlocksFromFragment, readEntries, reconcileDocCover, recordFromYAny, removeServer, resolvePageType, resolveServer, saveServerRegistry, serverRegistryPath, setDefault, signChallengeWithSeed, toPlain, unwrapSeed, validateMnemonic, waitForSync, withTimeout, wrapSeed, writeAuthenticated, writeAuthentication, writePermissionDenied, writeTokenSyncRequest, yjsToMarkdown };
6272
+ export { AbracadabraBaseProvider, AbracadabraBaseProviderConfiguration, AbracadabraClient, AbracadabraClientConfig, AbracadabraOutgoingMessageArguments, AbracadabraProvider, AbracadabraProviderConfiguration, AbracadabraWS, AbracadabraWSConfiguration, AbracadabraWebRTC, type AbracadabraWebRTCConfiguration, AbracadabraWebSocketConn, AdminConfigField, AdminConfigOriginKind, AuditLogEntry, AuditQueryOpts, AuditVerifyResult, AuthFailureContext, AuthFailureReason, AuthMessageType, AuthorizedScope, AwarenessError, BackgroundSyncManager, type BackgroundSyncManagerOptions, BackgroundSyncPersistence, BroadcastChannelSync, CHANNEL_NAMES, ChannelKeyResolver, type ChatChannel, ChatClient, type ChatClientTransport, type MarkReadInput as ChatMarkReadInput, type ChatMessage, type ChatReadCursor, type ChatReadReceipt, type ChatTypingEvent, type ChildrenPage, CloseEvent, CompleteAbracadabraBaseProviderConfiguration, CompleteAbracadabraWSConfiguration, CompleteHocuspocusProviderConfiguration, CompleteHocuspocusProviderWebsocketConfiguration, type ConnectPolicyResult, ConnectionTimeout, Constructable, ConstructableOutgoingMessage, ContentManager, type CreateNotificationInput, CryptoIdentity, CryptoIdentityKeystore, DEFAULT_FILE_CHUNK_SIZE, DEFAULT_ICE_SERVERS, DataChannelRouter, type DeleteMessageInput, DevicePairingChannel, type DevicePairingConfig, DeviceRegistrationService, type DeviceServerStatus, type DeviceSessionRecord, type DeviceSessionStorage, type DeviceTier, DocBacklink, type DocEncryptionInfo, DocKeyManager, DocSearchHit, type DocSyncState, type DocSyncStatus, type DocumentBlock, DocumentCache, type DocumentCacheOptions, type DocumentContent, DocumentManager, type DocumentManagerConfig, DocumentMeta, type DocumentMetaInfo, type DocumentMetaWire, E2EAbracadabraProvider, E2EEChannel, type E2EEIdentity, E2EOfflineStore, type EditMessageInput, EffectivePermissionEntry, EffectivePermissionsResponse, EffectiveRole, EncryptedChatClient, EncryptedYMap, EncryptedYText, EnvSnapshotExtension, EnvSnapshotItem, EnvSnapshotResponse, type FetchInboxInput, type FetchNotificationsInput, FileBlobStore, FileTransferChannel, FileTransferHandle, type FileTransferMeta, type FileTransferStatus, type FoldedMessage, Forbidden, GEO_TYPE_META_SCHEMAS, type GetChatHistoryInput, HealthStatus, HocusPocusWebSocket, HocuspocusProvider, HocuspocusProviderConfiguration, HocuspocusProviderWebsocket, HocuspocusProviderWebsocketConfiguration, HocuspocusWebSocket, type IdentityDeviceEntry, type IdentityDocConfiguration, IdentityDocProvider, type IdentityProfile, type IdentityServerEntry, type IdentitySpaceEntry, type InboxEntry, type MarkReadInput$1 as InboxMarkReadInput, InviteRow, KEY_EXCHANGE_CHANNEL, type KeyAuthClient, Kind, type LoadKeyFileOptions, LocalStorageDeviceSessionStorage, type LoginOrRegisterOptions, ManualSignaling, type ManualSignalingBlob, type MediaFileBlock, type MessageRecord, MessageTooBig, MessageType, MetaFieldType, MetaManager, MetaValidationError, type NodeKeypair, type NotificationReadUpdate, type NotificationRecord, NotificationsClient, OfflineStore, OutgoingMessageArguments, OutgoingMessageInterface, PAGE_TYPES, PageMeta, PageTypeInfo, PageTypeMetaField, type PairingRequest, type PairingResult, PeerConnection, type PeerInfo, type PeerState, PendingSubdoc, PermissionEntry, type PolicyAuthClient, PublicKeyInfo, QUERY_PREFIX, QueryClient, QueryError, type QueryFrame, type QueryKind, type QuerySpec, type QuerySubscriptionHandle, type QuerySubscriptionHandlers, type QueryTransport, RPC_PREFIX, ReadyzStatus, ResetConnection, type RpcCallHandle, type RpcCallOptions, RpcClient, RpcError, type RpcErrorCode, type RpcErrorPayload, type RpcFrame, type RpcHandler, type RpcHandlerContext, type RpcKind, type RpcTarget, type RpcTransport, SERVER_ROOT_ID, type SchemaDocTypeName, type SchemaMetaOf, type SchemaRegistryLike, type SchemaValidatorLike, SearchIndex, SearchResult, type SendChatMessageInput, type SendMessageInput, type SendMessageResult, ServerInfo, type ServerProfile, type ServerRegistry, ServerResetOutcome, type SignalingIncoming, type SignalingOutgoing, SignalingSocket, SnapshotCreateResult, SnapshotData, SnapshotFileEntry, SnapshotForkResult, SnapshotMeta, SnapshotRestoreResult, StatesArray, StreamTokenInfo, SubdocMessage, SubdocRegisteredEvent, TYPE_ALIASES, ThumbnailOptions, TokenManager, type TokenManagerOptions, TreeEntry, TreeManager, TreeNode, TreeSearchResult, TypedDocTypeMismatchError, type TypedDocsClient, type TypedTreeEntry, Unauthorized, UploadInfo, UploadMeta, UploadQueueEntry, UploadQueueStatus, UserMetaField, UserProfile, WebSocketStatus, WriteRejectionKind, WsReadyStates, YjsDataChannel, addServer, attachUpdatedAtObserver, awarenessStatesToArray, wordlist as bip39Wordlist, buildBlockquoteElement, buildBlocksFromMarkdown, buildBulletListElement, buildCodeBlockElement, buildHeadingElement, buildHorizontalRuleElement, buildOrderedListElement, buildParagraphElement, buildTaskListElement, collectMediaFileBlocks, decryptChatContent, decryptField, defaultKeyFileFor, deriveDmDocId, deriveIdentityDocId, deriveSeedWrappingKey, deterministicKeypair, dropCachesIfServerReplaced, encryptChatContent, encryptField, filenameToLabel, foldRecords, forgetServerIdentity, generateMnemonic, isEncryptedContent, isPlaceholderLabel, isServerScopedStore, loadOrCreateKeyFile, loadServerRegistry, loginOrRegisterWithKey, loginOrRegisterWithPolicy, makeChallengeSigner, makeEncryptedYMap, makeEncryptedYText, makeEntryMap, migrateLegacyDefault, mnemonicToEd25519Seed, mnemonicToKeyPair, normalizeRootId, onAuthenticatedParameters, onAuthenticationFailedParameters, onAwarenessChangeParameters, onAwarenessUpdateParameters, onCloseParameters, onCompactedParameters, onDisconnectParameters, onMessageParameters, onOpenParameters, onOutgoingMessageParameters, onReconnectedParameters, onServerErrorParameters, onStatelessParameters, onStatusParameters, onSubdocLoadedParameters, onSubdocRegisteredParameters, onSyncedParameters, onUnsyncedChangesParameters, onWriteRejectedParameters, openSyncedProvider, parseFrontmatter, patchEntry, pickEntrySpace, populateYDocFromMarkdown, readAuthMessage, readBlocksFromFragment, readEntries, reconcileDocCover, recordFromYAny, removeServer, resolvePageType, resolveServer, saveServerRegistry, serverRegistryPath, setDefault, signChallengeWithSeed, toPlain, unwrapSeed, validateMnemonic, waitForSync, withTimeout, wrapSeed, writeAuthenticated, writeAuthentication, writePermissionDenied, writeTokenSyncRequest, yjsToMarkdown };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@abraca/dabra",
3
- "version": "2.82.0",
3
+ "version": "2.83.0",
4
4
  "description": "abracadabra provider",
5
5
  "keywords": [
6
6
  "abracadabra",
@@ -41,7 +41,7 @@
41
41
  "yjs": "^13.6.8"
42
42
  },
43
43
  "devDependencies": {
44
- "@abraca/schema": "2.82.0"
44
+ "@abraca/schema": "2.83.0"
45
45
  },
46
46
  "scripts": {
47
47
  "test": "node --no-warnings --conditions=source --experimental-transform-types --test 'tests/*.test.ts'"
@@ -28,6 +28,8 @@ import type {
28
28
  import { Kind, SERVER_ROOT_ID } from "./types.ts";
29
29
  import type { DocEncryptionInfo } from "./types.ts";
30
30
  import type { DocumentCache } from "./DocumentCache.ts";
31
+ import type { ServerResetOutcome } from "./ServerReset.ts";
32
+ import { dropCachesIfServerReplaced } from "./ServerReset.ts";
31
33
  import { deriveDmDocId } from "./IdentityDoc.ts";
32
34
 
33
35
  function fromBase64(b64: string): Uint8Array {
@@ -1792,6 +1794,38 @@ export class AbracadabraClient {
1792
1794
  return this.request<ServerInfo>("GET", "/info", { auth: false });
1793
1795
  }
1794
1796
 
1797
+ /**
1798
+ * Drop this browser's caches for this server if its database has been
1799
+ * REPLACED since the last visit, and report what happened.
1800
+ *
1801
+ * **Call it before opening any provider**, and await it. A deleted database
1802
+ * is not a tombstone — it is a peer that lost its memory — so a tab that
1803
+ * reconnects with stale IndexedDB re-pushes the old tree into the fresh one
1804
+ * and a seeder adds its own on top: every page twice, then three times. Once
1805
+ * a provider holds a store open, `deleteDatabase` blocks instead of deleting
1806
+ * and the damage is already queued; those stores come back in `blocked`,
1807
+ * which is a signal that this ran too late rather than something to ignore.
1808
+ *
1809
+ * Returns `null` when there is nothing to do — no `server_id`, no browser
1810
+ * storage, a first visit, or the same database as last time. It never
1811
+ * throws: an app must not fail to start because a cache could not be tidied.
1812
+ *
1813
+ * @see dropCachesIfServerReplaced for what is dropped and what is kept.
1814
+ */
1815
+ async ensureFreshServer(): Promise<ServerResetOutcome | null> {
1816
+ try {
1817
+ const info = await this.serverInfo();
1818
+ if (!info?.server_id) return null;
1819
+ // `host`, matching how providers scope their stores — the port is part
1820
+ // of a server's identity, so two servers on one machine do not share a
1821
+ // cache namespace.
1822
+ const host = new URL(this.wsUrl).host;
1823
+ return await dropCachesIfServerReplaced(host, info.server_id);
1824
+ } catch {
1825
+ return null;
1826
+ }
1827
+ }
1828
+
1795
1829
  /**
1796
1830
  * Fetch ICE server configuration for WebRTC peer connections.
1797
1831
  * Falls back to default Google STUN server if the endpoint is unavailable.
@@ -0,0 +1,222 @@
1
+ /**
2
+ * Detect that a server's database has been REPLACED, and drop this browser's
3
+ * caches for it before anything re-pushes them.
4
+ *
5
+ * ## The bug
6
+ *
7
+ * Deleting a backend's database does not give you a clean server. Every browser
8
+ * that was connected still holds that space's CRDT state in IndexedDB, and on
9
+ * reconnect it re-pushes the old tree into the fresh one. A seeder then adds its
10
+ * own on top and you get every page twice — `/about` AND `/about-1`. Repeat the
11
+ * cycle and it MULTIPLIES: `-2`, `-3`, `-4`.
12
+ *
13
+ * This is inherent to a CRDT and cannot be fixed downstream. A deleted database
14
+ * is not a tombstone; it is a peer that lost its memory, and the client is the
15
+ * one holding the newer state. No idempotency guard can see it — by the time one
16
+ * runs, the re-pushed tree looks exactly like real content.
17
+ *
18
+ * It is not a development-only annoyance. The expensive case is a production
19
+ * restore from backup, where the peers re-pushing stale trees are visitors who
20
+ * will never read a release note.
21
+ *
22
+ * ## Why the server can be believed
23
+ *
24
+ * The server mints a `server_id` and persists it beside its database. It
25
+ * survives restarts and changes when, and only when, that database is replaced.
26
+ * So it states outright what a CRDT cannot work out for itself: *the peer you
27
+ * are syncing with is not the one you have been talking to.*
28
+ *
29
+ * ## What gets dropped
30
+ *
31
+ * Everything this SDK scopes to a server, which is more than the document
32
+ * caches:
33
+ *
34
+ * | store | written by |
35
+ * |---|---|
36
+ * | `abracadabra:<host>/<docId>` | {@link OfflineStore} |
37
+ * | `abracadabra:meta-cache:<host>` | `DocumentCache` |
38
+ * | `abracadabra:files:<host>` | `FileBlobStore` |
39
+ * | `abracadabra:bgsync:<host>` | `BackgroundSyncPersistence` |
40
+ * | `abracadabra:search:<host>` | `SearchIndex` |
41
+ *
42
+ * One ANCHORED rule covers all five shapes, so nothing here has to stay in step
43
+ * with how each store builds its key. Anchored rather than a substring test on
44
+ * purpose — see {@link isServerScopedStore}, where the naive version would have
45
+ * cleared a different server's caches.
46
+ *
47
+ * `abracadabra:identity` is deliberately NOT dropped. It is this browser's
48
+ * keypair across every server it talks to; clearing it would sign the user out
49
+ * of all of them because one of them was reinstalled.
50
+ */
51
+
52
+ /** Where the last-seen id for a host is remembered. */
53
+ const STORAGE_PREFIX = "abracadabra:server-id:";
54
+
55
+ /**
56
+ * Stores that belong to no particular server and must survive a reset.
57
+ *
58
+ * `abracadabra:identity` is this browser's keypair for EVERY server it talks to,
59
+ * so dropping it because one server was reinstalled would sign the user out of
60
+ * all of them. Listed explicitly rather than relying on the anchored match, so
61
+ * that a future store named after a host cannot take it by accident.
62
+ */
63
+ const GLOBAL_STORES = new Set(["abracadabra:identity", "abracadabra:softkey"]);
64
+
65
+ export interface ServerResetOutcome {
66
+ /** The id previously seen for this host, if any. */
67
+ previousServerId: string | null;
68
+ /** The id the server reports now. */
69
+ serverId: string;
70
+ /** Databases deleted because they belonged to the replaced server. */
71
+ cleared: string[];
72
+ /**
73
+ * Databases whose deletion was BLOCKED by an open connection.
74
+ *
75
+ * This is a failure, not a warning to swallow: the stale state is still in
76
+ * the tab and will be re-pushed. It happens when a provider opened the store
77
+ * before this ran, which means the guard was called too late. Callers should
78
+ * surface it rather than assume a clean result.
79
+ */
80
+ blocked: string[];
81
+ }
82
+
83
+ function storageAvailable(): boolean {
84
+ try {
85
+ return (
86
+ typeof globalThis !== "undefined" &&
87
+ "localStorage" in globalThis &&
88
+ "indexedDB" in globalThis
89
+ );
90
+ } catch {
91
+ return false;
92
+ }
93
+ }
94
+
95
+ /**
96
+ * Does this database belong to the given server?
97
+ *
98
+ * The match is ANCHORED, and it has to be. A plain `name.includes(host)` looks
99
+ * right and is wrong in a way that destroys data: `other.example.com:3011`
100
+ * contains `example.com:3011`, so clearing one server's caches would delete a
101
+ * DIFFERENT server's — the exact "too broad" failure this guard exists to avoid.
102
+ * A unit test covers that pair.
103
+ *
104
+ * Three anchored shapes are needed, because the stores are NOT consistently
105
+ * scoped and pretending otherwise silently misses some:
106
+ *
107
+ * - `<host>/…` — {@link OfflineStore}, keyed `<host>/<docId>`
108
+ * - `…:<host>` — a namespaced store handed a bare host
109
+ * - `…://<host>` — a namespaced store handed a full URL. Real, not hypothetical:
110
+ * `@abraca/nuxt` passes `serverUrl` to `FileBlobStore`, so the database is
111
+ * named `abracadabra:files:http://example.com:3011`. Measured in a live
112
+ * browser; a rule written only for the first two shapes left it behind, which
113
+ * is a whole file cache surviving a wipe.
114
+ */
115
+ export function isServerScopedStore(name: string, host: string): boolean {
116
+ if (!name.startsWith("abracadabra:")) return false;
117
+ if (GLOBAL_STORES.has(name)) return false;
118
+ const rest = name.slice("abracadabra:".length);
119
+ return (
120
+ rest === host ||
121
+ rest.startsWith(`${host}/`) ||
122
+ rest.endsWith(`:${host}`) ||
123
+ rest.endsWith(`://${host}`)
124
+ );
125
+ }
126
+
127
+ /**
128
+ * Compare the server's identity against the one this browser last saw, and drop
129
+ * every cache belonging to it if the database has been replaced.
130
+ *
131
+ * **Call this before opening any provider.** Once a provider holds an IndexedDB
132
+ * handle, `deleteDatabase` blocks instead of deleting and the stale tree is
133
+ * already queued for re-push — the deletion completes later, having achieved
134
+ * nothing. Any store in that position comes back in `blocked`.
135
+ *
136
+ * Conservative by design:
137
+ *
138
+ * - the FIRST time a host is seen, the id is recorded and nothing is deleted —
139
+ * a new visitor must not have caches cleared for having no history;
140
+ * - a browser with no `indexedDB`/`localStorage` is a no-op;
141
+ * - it never throws. Failing to tidy a cache must not stop an app from starting.
142
+ *
143
+ * @param host The server's `host` (`example.com:3011`) — the same value
144
+ * providers scope their stores by. Not the full origin: the
145
+ * scheme is not part of a server's cache identity here.
146
+ * @param serverId `server_id` from `GET /info`.
147
+ */
148
+ export async function dropCachesIfServerReplaced(
149
+ host: string,
150
+ serverId: string,
151
+ ): Promise<ServerResetOutcome | null> {
152
+ if (!storageAvailable() || !host || !serverId) return null;
153
+
154
+ const key = STORAGE_PREFIX + host;
155
+ let previousServerId: string | null = null;
156
+ try {
157
+ previousServerId = globalThis.localStorage.getItem(key);
158
+ } catch {
159
+ return null;
160
+ }
161
+
162
+ // First sighting, or the same server we have always been talking to.
163
+ if (previousServerId === null) {
164
+ try {
165
+ globalThis.localStorage.setItem(key, serverId);
166
+ } catch {
167
+ /* private mode, quota — not worth failing over */
168
+ }
169
+ return null;
170
+ }
171
+ if (previousServerId === serverId) return null;
172
+
173
+ const cleared: string[] = [];
174
+ const blocked: string[] = [];
175
+ try {
176
+ const databases = (await globalThis.indexedDB.databases?.()) ?? [];
177
+ const doomed = databases
178
+ .map((d) => d.name)
179
+ .filter((n): n is string => !!n && isServerScopedStore(n, host));
180
+
181
+ await Promise.all(
182
+ doomed.map(
183
+ (name) =>
184
+ new Promise<void>((resolve) => {
185
+ const request = globalThis.indexedDB.deleteDatabase(name);
186
+ request.onsuccess = () => {
187
+ cleared.push(name);
188
+ resolve();
189
+ };
190
+ request.onerror = () => resolve();
191
+ // Still open somewhere. The delete stays pending and the stale
192
+ // state is still live in this tab — report it, do not hang the
193
+ // page waiting for a handle we do not own.
194
+ request.onblocked = () => {
195
+ blocked.push(name);
196
+ resolve();
197
+ };
198
+ }),
199
+ ),
200
+ );
201
+ } catch {
202
+ /* enumeration unsupported or denied — nothing safely deletable */
203
+ }
204
+
205
+ try {
206
+ globalThis.localStorage.setItem(key, serverId);
207
+ } catch {
208
+ /* see above */
209
+ }
210
+
211
+ return { previousServerId, serverId, cleared, blocked };
212
+ }
213
+
214
+ /** Forget what we know about a host, so the next check treats it as new. */
215
+ export function forgetServerIdentity(host: string): void {
216
+ if (!storageAvailable() || !host) return;
217
+ try {
218
+ globalThis.localStorage.removeItem(STORAGE_PREFIX + host);
219
+ } catch {
220
+ /* nothing to do */
221
+ }
222
+ }
package/src/index.ts CHANGED
@@ -13,6 +13,7 @@ export type {
13
13
  DeviceSessionStorage,
14
14
  } from "./TokenManager.ts";
15
15
  export * from "./OfflineStore.ts";
16
+ export * from "./ServerReset.ts";
16
17
  export * from "./auth.ts";
17
18
  export * from "./CloseEvents.ts";
18
19
  export * from "./awarenessStatesToArray.ts";
package/src/types.ts CHANGED
@@ -433,6 +433,16 @@ export interface HealthStatus {
433
433
  export interface ServerInfo {
434
434
  /** Human-readable server name set by the operator. */
435
435
  name?: string;
436
+ /**
437
+ * Identity of this server's DATABASE, persisted beside it.
438
+ *
439
+ * Stable across restarts and upgrades; it changes only when the database is
440
+ * replaced — a wipe, or a restore from backup. That makes it the one signal a
441
+ * client can use to know its cached CRDT state belongs to a peer that no
442
+ * longer exists, which a CRDT cannot work out for itself. See
443
+ * {@link dropCachesIfServerReplaced}.
444
+ */
445
+ server_id?: string;
436
446
  /** Server version string. */
437
447
  version?: string;
438
448
  /** Hocuspocus wire protocol version (currently 2). */