@abraca/dabra 2.81.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.
@@ -3542,6 +3542,174 @@ var AbracadabraProvider = class AbracadabraProvider extends AbracadabraBaseProvi
3542
3542
  }
3543
3543
  };
3544
3544
 
3545
+ //#endregion
3546
+ //#region packages/provider/src/ServerReset.ts
3547
+ /**
3548
+ * Detect that a server's database has been REPLACED, and drop this browser's
3549
+ * caches for it before anything re-pushes them.
3550
+ *
3551
+ * ## The bug
3552
+ *
3553
+ * Deleting a backend's database does not give you a clean server. Every browser
3554
+ * that was connected still holds that space's CRDT state in IndexedDB, and on
3555
+ * reconnect it re-pushes the old tree into the fresh one. A seeder then adds its
3556
+ * own on top and you get every page twice — `/about` AND `/about-1`. Repeat the
3557
+ * cycle and it MULTIPLIES: `-2`, `-3`, `-4`.
3558
+ *
3559
+ * This is inherent to a CRDT and cannot be fixed downstream. A deleted database
3560
+ * is not a tombstone; it is a peer that lost its memory, and the client is the
3561
+ * one holding the newer state. No idempotency guard can see it — by the time one
3562
+ * runs, the re-pushed tree looks exactly like real content.
3563
+ *
3564
+ * It is not a development-only annoyance. The expensive case is a production
3565
+ * restore from backup, where the peers re-pushing stale trees are visitors who
3566
+ * will never read a release note.
3567
+ *
3568
+ * ## Why the server can be believed
3569
+ *
3570
+ * The server mints a `server_id` and persists it beside its database. It
3571
+ * survives restarts and changes when, and only when, that database is replaced.
3572
+ * So it states outright what a CRDT cannot work out for itself: *the peer you
3573
+ * are syncing with is not the one you have been talking to.*
3574
+ *
3575
+ * ## What gets dropped
3576
+ *
3577
+ * Everything this SDK scopes to a server, which is more than the document
3578
+ * caches:
3579
+ *
3580
+ * | store | written by |
3581
+ * |---|---|
3582
+ * | `abracadabra:<host>/<docId>` | {@link OfflineStore} |
3583
+ * | `abracadabra:meta-cache:<host>` | `DocumentCache` |
3584
+ * | `abracadabra:files:<host>` | `FileBlobStore` |
3585
+ * | `abracadabra:bgsync:<host>` | `BackgroundSyncPersistence` |
3586
+ * | `abracadabra:search:<host>` | `SearchIndex` |
3587
+ *
3588
+ * One ANCHORED rule covers all five shapes, so nothing here has to stay in step
3589
+ * with how each store builds its key. Anchored rather than a substring test on
3590
+ * purpose — see {@link isServerScopedStore}, where the naive version would have
3591
+ * cleared a different server's caches.
3592
+ *
3593
+ * `abracadabra:identity` is deliberately NOT dropped. It is this browser's
3594
+ * keypair across every server it talks to; clearing it would sign the user out
3595
+ * of all of them because one of them was reinstalled.
3596
+ */
3597
+ /** Where the last-seen id for a host is remembered. */
3598
+ const STORAGE_PREFIX = "abracadabra:server-id:";
3599
+ /**
3600
+ * Stores that belong to no particular server and must survive a reset.
3601
+ *
3602
+ * `abracadabra:identity` is this browser's keypair for EVERY server it talks to,
3603
+ * so dropping it because one server was reinstalled would sign the user out of
3604
+ * all of them. Listed explicitly rather than relying on the anchored match, so
3605
+ * that a future store named after a host cannot take it by accident.
3606
+ */
3607
+ const GLOBAL_STORES = new Set(["abracadabra:identity", "abracadabra:softkey"]);
3608
+ function storageAvailable() {
3609
+ try {
3610
+ return typeof globalThis !== "undefined" && "localStorage" in globalThis && "indexedDB" in globalThis;
3611
+ } catch {
3612
+ return false;
3613
+ }
3614
+ }
3615
+ /**
3616
+ * Does this database belong to the given server?
3617
+ *
3618
+ * The match is ANCHORED, and it has to be. A plain `name.includes(host)` looks
3619
+ * right and is wrong in a way that destroys data: `other.example.com:3011`
3620
+ * contains `example.com:3011`, so clearing one server's caches would delete a
3621
+ * DIFFERENT server's — the exact "too broad" failure this guard exists to avoid.
3622
+ * A unit test covers that pair.
3623
+ *
3624
+ * Three anchored shapes are needed, because the stores are NOT consistently
3625
+ * scoped and pretending otherwise silently misses some:
3626
+ *
3627
+ * - `<host>/…` — {@link OfflineStore}, keyed `<host>/<docId>`
3628
+ * - `…:<host>` — a namespaced store handed a bare host
3629
+ * - `…://<host>` — a namespaced store handed a full URL. Real, not hypothetical:
3630
+ * `@abraca/nuxt` passes `serverUrl` to `FileBlobStore`, so the database is
3631
+ * named `abracadabra:files:http://example.com:3011`. Measured in a live
3632
+ * browser; a rule written only for the first two shapes left it behind, which
3633
+ * is a whole file cache surviving a wipe.
3634
+ */
3635
+ function isServerScopedStore(name, host) {
3636
+ if (!name.startsWith("abracadabra:")) return false;
3637
+ if (GLOBAL_STORES.has(name)) return false;
3638
+ const rest = name.slice(12);
3639
+ return rest === host || rest.startsWith(`${host}/`) || rest.endsWith(`:${host}`) || rest.endsWith(`://${host}`);
3640
+ }
3641
+ /**
3642
+ * Compare the server's identity against the one this browser last saw, and drop
3643
+ * every cache belonging to it if the database has been replaced.
3644
+ *
3645
+ * **Call this before opening any provider.** Once a provider holds an IndexedDB
3646
+ * handle, `deleteDatabase` blocks instead of deleting and the stale tree is
3647
+ * already queued for re-push — the deletion completes later, having achieved
3648
+ * nothing. Any store in that position comes back in `blocked`.
3649
+ *
3650
+ * Conservative by design:
3651
+ *
3652
+ * - the FIRST time a host is seen, the id is recorded and nothing is deleted —
3653
+ * a new visitor must not have caches cleared for having no history;
3654
+ * - a browser with no `indexedDB`/`localStorage` is a no-op;
3655
+ * - it never throws. Failing to tidy a cache must not stop an app from starting.
3656
+ *
3657
+ * @param host The server's `host` (`example.com:3011`) — the same value
3658
+ * providers scope their stores by. Not the full origin: the
3659
+ * scheme is not part of a server's cache identity here.
3660
+ * @param serverId `server_id` from `GET /info`.
3661
+ */
3662
+ async function dropCachesIfServerReplaced(host, serverId) {
3663
+ if (!storageAvailable() || !host || !serverId) return null;
3664
+ const key = STORAGE_PREFIX + host;
3665
+ let previousServerId = null;
3666
+ try {
3667
+ previousServerId = globalThis.localStorage.getItem(key);
3668
+ } catch {
3669
+ return null;
3670
+ }
3671
+ if (previousServerId === null) {
3672
+ try {
3673
+ globalThis.localStorage.setItem(key, serverId);
3674
+ } catch {}
3675
+ return null;
3676
+ }
3677
+ if (previousServerId === serverId) return null;
3678
+ const cleared = [];
3679
+ const blocked = [];
3680
+ try {
3681
+ const doomed = (await globalThis.indexedDB.databases?.() ?? []).map((d) => d.name).filter((n) => !!n && isServerScopedStore(n, host));
3682
+ await Promise.all(doomed.map((name) => new Promise((resolve) => {
3683
+ const request = globalThis.indexedDB.deleteDatabase(name);
3684
+ request.onsuccess = () => {
3685
+ cleared.push(name);
3686
+ resolve();
3687
+ };
3688
+ request.onerror = () => resolve();
3689
+ request.onblocked = () => {
3690
+ blocked.push(name);
3691
+ resolve();
3692
+ };
3693
+ })));
3694
+ } catch {}
3695
+ try {
3696
+ globalThis.localStorage.setItem(key, serverId);
3697
+ } catch {}
3698
+ return {
3699
+ previousServerId,
3700
+ serverId,
3701
+ cleared,
3702
+ blocked
3703
+ };
3704
+ }
3705
+ /** Forget what we know about a host, so the next check treats it as new. */
3706
+ function forgetServerIdentity(host) {
3707
+ if (!storageAvailable() || !host) return;
3708
+ try {
3709
+ globalThis.localStorage.removeItem(STORAGE_PREFIX + host);
3710
+ } catch {}
3711
+ }
3712
+
3545
3713
  //#endregion
3546
3714
  //#region node_modules/@noble/hashes/utils.js
3547
3715
  /**
@@ -11729,6 +11897,34 @@ var AbracadabraClient = class {
11729
11897
  return this.request("GET", "/info", { auth: false });
11730
11898
  }
11731
11899
  /**
11900
+ * Drop this browser's caches for this server if its database has been
11901
+ * REPLACED since the last visit, and report what happened.
11902
+ *
11903
+ * **Call it before opening any provider**, and await it. A deleted database
11904
+ * is not a tombstone — it is a peer that lost its memory — so a tab that
11905
+ * reconnects with stale IndexedDB re-pushes the old tree into the fresh one
11906
+ * and a seeder adds its own on top: every page twice, then three times. Once
11907
+ * a provider holds a store open, `deleteDatabase` blocks instead of deleting
11908
+ * and the damage is already queued; those stores come back in `blocked`,
11909
+ * which is a signal that this ran too late rather than something to ignore.
11910
+ *
11911
+ * Returns `null` when there is nothing to do — no `server_id`, no browser
11912
+ * storage, a first visit, or the same database as last time. It never
11913
+ * throws: an app must not fail to start because a cache could not be tidied.
11914
+ *
11915
+ * @see dropCachesIfServerReplaced for what is dropped and what is kept.
11916
+ */
11917
+ async ensureFreshServer() {
11918
+ try {
11919
+ const info = await this.serverInfo();
11920
+ if (!info?.server_id) return null;
11921
+ const host = new URL(this.wsUrl).host;
11922
+ return await dropCachesIfServerReplaced(host, info.server_id);
11923
+ } catch {
11924
+ return null;
11925
+ }
11926
+ }
11927
+ /**
11732
11928
  * Fetch ICE server configuration for WebRTC peer connections.
11733
11929
  * Falls back to default Google STUN server if the endpoint is unavailable.
11734
11930
  * No auth required.
@@ -22033,5 +22229,5 @@ var DocumentManager = class {
22033
22229
  };
22034
22230
 
22035
22231
  //#endregion
22036
- export { AbracadabraBaseProvider, AbracadabraClient, AbracadabraProvider, AbracadabraWS, AbracadabraWebRTC, AuthMessageType, AwarenessError, BackgroundSyncManager, BackgroundSyncPersistence, BroadcastChannelSync, CHANNEL_NAMES, ChannelKeyResolver, ChatClient, ConnectionTimeout, ContentManager, CryptoIdentityKeystore, DEFAULT_FILE_CHUNK_SIZE, DEFAULT_ICE_SERVERS, DataChannelRouter, DevicePairingChannel, DeviceRegistrationService, DocKeyManager, DocumentCache, DocumentManager, E2EAbracadabraProvider, E2EEChannel, E2EOfflineStore, EncryptedChatClient, EncryptedYMap, EncryptedYText, FileBlobStore, FileTransferChannel, FileTransferHandle, Forbidden, GEO_TYPE_META_SCHEMAS, HocuspocusProvider, HocuspocusProviderWebsocket, IdentityDocProvider, KEY_EXCHANGE_CHANNEL, Kind, LocalStorageDeviceSessionStorage, ManualSignaling, MessageTooBig, MessageType, MetaManager, MetaValidationError, NotificationsClient, OfflineStore, PAGE_TYPES, PeerConnection, QUERY_PREFIX, QueryClient, QueryError, RPC_PREFIX, ResetConnection, RpcClient, RpcError, SERVER_ROOT_ID, SearchIndex, SignalingSocket, SubdocMessage, TYPE_ALIASES, TokenManager, TreeManager, TypedDocTypeMismatchError, Unauthorized, WebSocketStatus, 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, 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 };
22232
+ export { AbracadabraBaseProvider, AbracadabraClient, AbracadabraProvider, AbracadabraWS, AbracadabraWebRTC, AuthMessageType, AwarenessError, BackgroundSyncManager, BackgroundSyncPersistence, BroadcastChannelSync, CHANNEL_NAMES, ChannelKeyResolver, ChatClient, ConnectionTimeout, ContentManager, CryptoIdentityKeystore, DEFAULT_FILE_CHUNK_SIZE, DEFAULT_ICE_SERVERS, DataChannelRouter, DevicePairingChannel, DeviceRegistrationService, DocKeyManager, DocumentCache, DocumentManager, E2EAbracadabraProvider, E2EEChannel, E2EOfflineStore, EncryptedChatClient, EncryptedYMap, EncryptedYText, FileBlobStore, FileTransferChannel, FileTransferHandle, Forbidden, GEO_TYPE_META_SCHEMAS, HocuspocusProvider, HocuspocusProviderWebsocket, IdentityDocProvider, KEY_EXCHANGE_CHANNEL, Kind, LocalStorageDeviceSessionStorage, ManualSignaling, MessageTooBig, MessageType, MetaManager, MetaValidationError, NotificationsClient, OfflineStore, PAGE_TYPES, PeerConnection, QUERY_PREFIX, QueryClient, QueryError, RPC_PREFIX, ResetConnection, RpcClient, RpcError, SERVER_ROOT_ID, SearchIndex, SignalingSocket, SubdocMessage, TYPE_ALIASES, TokenManager, TreeManager, TypedDocTypeMismatchError, Unauthorized, WebSocketStatus, 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, 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 };
22037
22233
  //# sourceMappingURL=abracadabra-provider.esm.js.map