fix(cloud-sync): persist sync base and snapshots in IndexedDB

Large vaults exceed Chromium's localStorage quota, so saving the
encrypted sync baseline after a successful cloud upload fails with
"Unable to persist sync base". Store those encrypted blobs in a
dedicated IndexedDB database, migrate leftover localStorage keys,
and keep the existing ciphertext format.

Fixes #4661
This commit is contained in:
陈大猫 committed 2026-12-03 12:03:08 +08:00
1 parent 73ee6c0f31
commit 758bbec0ac
8 files changed
+1039 -64

No files matched your search

+1 -1
View File
@@ -1028,7 +1028,7 @@ export class CloudSyncManager {
return reencryptSyncStorageImpl.call(this, oldKey, newKey, newConfig);
}
private clearSyncBase(): void {
private clearSyncBase(): Promise<void> {
return clearSyncBaseImpl.call(this);
}
@@ -28,13 +28,16 @@ import {
registerPluginProviderIdImpl,
unregisterPluginProviderIdImpl,
} from './stateAndSecurityMethods';
import { deleteSyncBlobsFromIdb } from './syncBlobIdbStorage';
const SYNC_REMOTE_ANCHOR_STORAGE_KEY = 'netcatty_sync_remote_anchor_v1';
export function clearProviderMergeStateImpl(this: any, provider: CloudProvider): void {
this.removeFromStorage(this.syncBaseKey(provider));
export function clearProviderMergeStateImpl(this: any, provider: CloudProvider): Promise<void> {
const baseKey = this.syncBaseKey(provider);
this.removeFromStorage(baseKey);
this.removeFromStorage(this.convergentProviderBaselineKey(provider));
this.clearSyncAnchor(provider);
return deleteSyncBlobsFromIdb([baseKey]);
}
export async function startProviderAuthImpl(this: any,
@@ -157,7 +160,7 @@ export async function completeGitHubAuthImpl(this: any,
const previousId = this.loadProviderAccountId('github') ?? previousAccount?.id ?? null;
const sameAccount = newId !== null && previousId !== null && newId === previousId;
if (!sameAccount) {
clearProviderMergeStateImpl.call(this, 'github');
await clearProviderMergeStateImpl.call(this, 'github');
}
if (newId) {
this.saveProviderAccountId('github', newId);
@@ -255,7 +258,7 @@ export async function completePKCEAuthImpl(this: any,
const previousId = this.loadProviderAccountId(provider) ?? previousAccount?.id ?? null;
const sameAccount = newId !== null && previousId !== null && newId === previousId;
if (!sameAccount) {
clearProviderMergeStateImpl.call(this, provider);
await clearProviderMergeStateImpl.call(this, provider);
}
if (newId) {
this.saveProviderAccountId(provider, newId);
@@ -303,7 +306,7 @@ export async function connectConfigProviderImpl(this: any,
await this.saveProviderConnection(provider, this.state.providers[provider]);
// Clear all trusted merge state when changing endpoint or bucket.
clearProviderMergeStateImpl.call(this, provider);
await clearProviderMergeStateImpl.call(this, provider);
this.emit({
type: 'AUTH_COMPLETED',
provider,
@@ -436,7 +439,7 @@ export async function connectPluginProviderImpl(
|| previousConfigFp !== nextConfigFp
|| previousCredentialFp !== nextCredentialFp
) {
clearProviderMergeStateImpl.call(this, providerId);
await clearProviderMergeStateImpl.call(this, providerId);
}
this.emit({
type: 'AUTH_COMPLETED',
@@ -537,7 +540,7 @@ export async function disconnectProviderImpl(this: any,provider: CloudProvider):
unregisterPluginProviderIdImpl.call(this, provider);
// Clear all trusted merge state so a later account/resource cannot reuse
// an unrelated snapshot or convergent baseline.
clearProviderMergeStateImpl.call(this, provider);
await clearProviderMergeStateImpl.call(this, provider);
this.removeFromStorage(this.providerAccountIdKey(provider));
const adapter = this.adapters.get(provider);
if (adapter) {
@@ -16,6 +16,12 @@ import {
decryptLocalStorageValue,
encryptLocalStorageValue,
} from './encryptedLocalStorage';
import {
idbDeleteSyncBlobs,
idbGetSyncBlob,
idbPutSyncBlob,
isSyncBlobIdbAvailable,
} from './syncBlobIdbStorage';
/** Built-ins plus any dynamic plugin providers currently in manager state. */
function listedProviders(manager: any): CloudProvider[] {
@@ -117,15 +123,29 @@ export function clearConvergentSyncStorageImpl(this: any, confirmed: boolean): v
}
}
function encryptedSyncStorageKeys(manager: any): string[] {
const keys = new Set<string>([
manager.syncBaseKey(),
manager.syncSnapshotsKey(),
SYNC_STORAGE_KEYS.CONVERGENT_REPLICA,
]);
for (const provider of listedProviders(manager)) {
function syncBlobStorageKeys(manager: any): string[] {
const keys = new Set<string>([manager.syncBaseKey()]);
if (typeof manager.syncSnapshotsKey === 'function') {
keys.add(manager.syncSnapshotsKey());
}
const providers = new Set<CloudProvider>(listedProviders(manager));
if (typeof manager?.listRegisteredPluginProviderIds === 'function') {
for (const id of manager.listRegisteredPluginProviderIds()) {
providers.add(id as CloudProvider);
}
}
for (const provider of providers) {
keys.add(manager.syncBaseKey(provider));
keys.add(manager.syncSnapshotsKey(provider));
if (typeof manager.syncSnapshotsKey === 'function') {
keys.add(manager.syncSnapshotsKey(provider));
}
}
return [...keys];
}
function localOnlyEncryptedSyncKeys(manager: any): string[] {
const keys = new Set<string>([SYNC_STORAGE_KEYS.CONVERGENT_REPLICA]);
for (const provider of listedProviders(manager)) {
keys.add(manager.convergentProviderBaselineKey(provider));
}
return [...keys];
@@ -143,54 +163,127 @@ export async function reencryptSyncStorageImpl(
newKey: CryptoKey,
newConfig: MasterKeyConfig,
): Promise<void> {
const keys = encryptedSyncStorageKeys(this);
const localOnlyKeys = localOnlyEncryptedSyncKeys(this);
const idbBlobKeys = syncBlobStorageKeys(this);
const idbAvailable = isSyncBlobIdbAvailable();
const previousConfig = (
this.loadFromStorage(SYNC_STORAGE_KEYS.MASTER_KEY_CONFIG)
?? this.state.masterKeyConfig
) as MasterKeyConfig | null;
const originals = new Map<string, string | null>();
const replacements = new Map<string, string>();
for (const key of keys) {
const localOriginals = new Map<string, unknown>();
const localReplacements = new Map<string, string>();
const idbOriginals = new Map<string, string | null>();
const idbReplacements = new Map<string, string>();
const legacyKeysToRemove: string[] = [];
for (const key of localOnlyKeys) {
const encoded = this.loadFromStorage(key) as unknown;
if (encoded == null) {
originals.set(key, null);
localOriginals.set(key, null);
continue;
}
if (typeof encoded !== 'string') throw new Error(`Encrypted sync record ${key} is invalid`);
originals.set(key, encoded);
localOriginals.set(key, encoded);
const value = await decryptLocalStorageValue<unknown>(encoded, oldKey);
replacements.set(key, await encryptLocalStorageValue(value, newKey));
localReplacements.set(key, await encryptLocalStorageValue(value, newKey));
}
for (const [key, original] of originals) {
for (const key of idbBlobKeys) {
const legacyEncoded = this.loadFromStorage(key) as unknown;
const idbEncoded = idbAvailable ? await idbGetSyncBlob(key) : null;
localOriginals.set(key, legacyEncoded ?? null);
if (idbAvailable) {
idbOriginals.set(key, idbEncoded);
}
if (idbEncoded !== null) {
const value = await decryptLocalStorageValue<unknown>(idbEncoded, oldKey);
idbReplacements.set(key, await encryptLocalStorageValue(value, newKey));
if (legacyEncoded != null) {
legacyKeysToRemove.push(key);
}
continue;
}
if (legacyEncoded == null) continue;
if (typeof legacyEncoded !== 'string') throw new Error(`Encrypted sync record ${key} is invalid`);
const value = await decryptLocalStorageValue<unknown>(legacyEncoded, oldKey);
const reencrypted = await encryptLocalStorageValue(value, newKey);
if (idbAvailable) {
idbReplacements.set(key, reencrypted);
legacyKeysToRemove.push(key);
} else {
localReplacements.set(key, reencrypted);
}
}
for (const [key, original] of localOriginals) {
const current = this.loadFromStorage(key) as unknown;
if ((current ?? null) !== original) {
throw new Error('Sync data changed while the master key was being rotated');
}
}
if (idbAvailable) {
for (const [key, original] of idbOriginals) {
const current = await idbGetSyncBlob(key);
if ((current ?? null) !== original) {
throw new Error('Sync data changed while the master key was being rotated');
}
}
}
const currentConfig = this.loadFromStorage(
SYNC_STORAGE_KEYS.MASTER_KEY_CONFIG,
) as MasterKeyConfig | null;
if (JSON.stringify(currentConfig) !== JSON.stringify(previousConfig)) {
throw new Error('Master key configuration changed while it was being rotated');
}
const committed: string[] = [];
const committedLocal: string[] = [];
const committedIdb: string[] = [];
try {
for (const [key, replacement] of replacements) {
for (const [key, replacement] of localReplacements) {
if (this.saveToStorage(key, replacement) === false) {
throw new Error(`Unable to persist re-encrypted sync record: ${key}`);
}
committed.push(key);
committedLocal.push(key);
}
for (const [key, replacement] of idbReplacements) {
await idbPutSyncBlob(key, replacement, {
errorLabel: `re-encrypted sync record (${key})`,
});
committedIdb.push(key);
}
if (this.saveToStorage(SYNC_STORAGE_KEYS.MASTER_KEY_CONFIG, newConfig) === false) {
throw new Error('Unable to persist the new master key configuration');
}
} catch (error) {
for (const key of committed.reverse()) {
const original = originals.get(key);
if (original !== undefined) this.saveToStorage(key, original);
for (const key of committedIdb.reverse()) {
const original = idbOriginals.get(key) ?? null;
try {
if (original !== null) {
await idbPutSyncBlob(key, original);
} else {
await idbDeleteSyncBlobs([key]);
}
} catch (rollbackError) {
console.warn(`[CloudSyncManager] Failed to roll back IndexedDB sync record ${key}`, rollbackError);
}
}
for (const key of committedLocal.reverse()) {
const original = localOriginals.get(key);
if (original !== undefined && original !== null) this.saveToStorage(key, original);
}
if (previousConfig) this.saveToStorage(SYNC_STORAGE_KEYS.MASTER_KEY_CONFIG, previousConfig);
else this.removeFromStorage(SYNC_STORAGE_KEYS.MASTER_KEY_CONFIG);
throw error;
}
for (const key of legacyKeysToRemove) {
try {
this.removeFromStorage(key);
} catch (removeError) {
console.warn(`[CloudSyncManager] Failed to remove migrated legacy sync record ${key}`, removeError);
}
}
}
@@ -41,6 +41,7 @@ import {
import type { CloudAdapter } from '../adapters';
import type { SyncManagerState } from '../CloudSyncManager';
import { getConvergentSyncLocalConfig } from '../convergentSyncConfig';
import { deleteSyncBlobsFromIdb } from './syncBlobIdbStorage';
const SYNC_HISTORY_STORAGE_KEY = 'netcatty_sync_history_v1';
@@ -743,7 +744,9 @@ export function handleStorageEventImpl(this: any, event: StorageEvent): void {
// config/resource changes do on the connect path (authMethods).
if (credentialChanged) {
try {
this.removeFromStorage(this.syncBaseKey(provider));
const baseKey = this.syncBaseKey(provider);
this.removeFromStorage(baseKey);
void deleteSyncBlobsFromIdb([baseKey]);
this.removeFromStorage(this.convergentProviderBaselineKey(provider));
this.clearSyncAnchor(provider);
} catch {
@@ -27,6 +27,11 @@ import type {
} from "../../../domain/sync.ts";
import { setConvergentSyncLocalConfig } from "../convergentSyncConfig.ts";
import { saveProviderConnectionImpl } from "./stateAndSecurityMethods.ts";
import {
SYNC_BLOB_IDB_STORE_NAME,
resetSyncBlobIdbForTests,
} from "./syncBlobIdbStorage.ts";
import { installFakeIndexedDb } from "../../../application/state/testSupport/fakeIndexedDb.ts";
function payload(hostId: string): SyncPayload {
return payloadWithHosts([hostId]);
@@ -680,6 +685,8 @@ test("commitRemoteInspection does not advance the remote anchor when saving the
test("saveSyncBase reports storage failures so callers do not advance anchors", async () => {
const originalWarn = console.warn;
resetSyncBlobIdbForTests();
const fakeIdb = installFakeIndexedDb({ failOpen: true });
const manager = {
state: {
unlockedKey: {
@@ -691,24 +698,25 @@ test("saveSyncBase reports storage failures so callers do not advance anchors",
},
},
syncBaseKey: () => "sync-base",
saveToStorage: () => {
throw new Error("storage full");
},
};
console.warn = () => {};
try {
await assert.rejects(
() => saveSyncBaseImpl.call(manager, payload("cloud"), "github"),
/storage full/,
/Unable to persist local sync baseline in IndexedDB/,
);
} finally {
console.warn = originalWarn;
resetSyncBlobIdbForTests();
fakeIdb.restore();
}
});
test("guarded provider saves cannot recreate state cleared during an await", async () => {
const stored = new Map<string, unknown>();
resetSyncBlobIdbForTests();
const fakeIdb = installFakeIndexedDb();
const key = await crypto.subtle.generateKey(
{ name: "AES-GCM", length: 256 }, true, ["encrypt", "decrypt"],
);
@@ -726,6 +734,9 @@ test("guarded provider saves cannot recreate state cleared during an await", asy
stored.set(storageKey, value);
return true;
},
removeFromStorage: (storageKey: string) => {
stored.delete(storageKey);
},
createSyncedFileSignature: () => new Promise<string>((resolve) => {
setImmediate(() => resolve("signature"));
}),
@@ -739,10 +750,14 @@ test("guarded provider saves cannot recreate state cleared during an await", asy
providerChanged = true;
stored.delete("base:github");
stored.delete("snapshots:github");
const idbStore = fakeIdb.db.getOrCreateStore(SYNC_BLOB_IDB_STORE_NAME);
idbStore.delete("base:github");
idbStore.delete("snapshots:github");
});
await assert.rejects(baseSave, /provider changed/);
assert.equal(stored.has("base:github"), false);
assert.equal(stored.has("snapshots:github"), false);
assert.deepEqual(fakeIdb.db.dumpStore(SYNC_BLOB_IDB_STORE_NAME), []);
providerChanged = false;
const anchorSave = saveSyncAnchorImpl.call(
@@ -792,6 +807,8 @@ test("guarded provider saves cannot recreate state cleared during an await", asy
assert.equal(savedConnection.tokens.accessToken, "fresh");
} finally {
console.warn = originalWarn;
resetSyncBlobIdbForTests();
fakeIdb.restore();
}
});
@@ -810,6 +827,8 @@ test("saveSyncBase reports a missing local encryption key", async () => {
test("saveSyncBase keeps a bounded encrypted snapshot history before replacing the base", async () => {
const stored = new Map<string, string>();
resetSyncBlobIdbForTests();
const fakeIdb = installFakeIndexedDb();
const key = await crypto.subtle.generateKey(
{ name: "AES-GCM", length: 256 },
true,
@@ -821,20 +840,27 @@ test("saveSyncBase keeps a bounded encrypted snapshot history before replacing t
syncSnapshotsKey: (provider?: CloudProvider) => `snapshots-${provider ?? "default"}`,
saveToStorage: (storageKey: string, value: string) => stored.set(storageKey, value),
loadFromStorage: (storageKey: string) => stored.get(storageKey),
removeFromStorage: (storageKey: string) => stored.delete(storageKey),
};
await saveSyncBaseImpl.call(manager, payload("base-0"), "github");
for (let i = 1; i <= 7; i += 1) {
await saveSyncBaseImpl.call(manager, payload(`base-${i}`), "github");
try {
await saveSyncBaseImpl.call(manager, payload("base-0"), "github");
for (let i = 1; i <= 7; i += 1) {
await saveSyncBaseImpl.call(manager, payload(`base-${i}`), "github");
}
const snapshots = await loadSyncSnapshotsImpl.call(manager, "github");
assert.equal(snapshots.length, 5);
assert.deepEqual(
snapshots.map((snapshot) => snapshot.payload.hosts[0]?.id),
["base-6", "base-5", "base-4", "base-3", "base-2"],
);
assert.equal(stored.size, 0);
} finally {
resetSyncBlobIdbForTests();
fakeIdb.restore();
}
const snapshots = await loadSyncSnapshotsImpl.call(manager, "github");
assert.equal(snapshots.length, 5);
assert.deepEqual(
snapshots.map((snapshot) => snapshot.payload.hosts[0]?.id),
["base-6", "base-5", "base-4", "base-3", "base-2"],
);
});
test("syncAllProviders builds provider-specific sync metadata from each provider base", async () => {
@@ -41,6 +41,13 @@ import {
decryptLocalStorageValue,
encryptLocalStorageValue,
} from './encryptedLocalStorage';
import {
deleteSyncBlobsFromIdb,
idbGetSyncBlob,
idbPutSyncBlob,
idbPutSyncBlobIfAbsent,
isSyncBlobIdbAvailable,
} from './syncBlobIdbStorage';
function getSyncSecurityGeneration(manager: any): number | undefined {
return typeof manager.getSyncSecurityGeneration === 'function'
@@ -135,12 +142,77 @@ function persistedProviderIdentity(provider: CloudProvider, connection: Provider
async function loadRawSyncBase(this: any, provider?: CloudProvider): Promise<SyncPayload | null> {
const key = this.state.unlockedKey?.derivedKey;
if (!key || typeof this.loadFromStorage !== 'function') return null;
const encoded = this.loadFromStorage(this.syncBaseKey(provider));
if (!key) return null;
const storageKey = this.syncBaseKey(provider);
let encoded: unknown = null;
if (isSyncBlobIdbAvailable()) {
try {
encoded = await idbGetSyncBlob(storageKey);
} catch {
encoded = null;
}
}
if (!encoded && typeof this.loadFromStorage === 'function') {
encoded = this.loadFromStorage(storageKey);
}
if (!encoded || typeof encoded !== 'string') return null;
return decryptLocalStorageValue<SyncPayload>(encoded, key);
}
async function loadEncryptedSyncBlobWithMigration<T>(
manager: any,
storageKey: string,
key: CryptoKey,
isValid?: (value: T) => boolean,
): Promise<T | null> {
let idbEncoded: string | null = null;
let idbReadable = false;
if (isSyncBlobIdbAvailable()) {
try {
idbEncoded = await idbGetSyncBlob(storageKey);
idbReadable = true;
} catch (error) {
console.warn(
`[CloudSyncManager] Failed to read ${storageKey} from IndexedDB; falling back to legacy localStorage`,
error,
);
}
}
if (idbEncoded !== null) {
const value = await decryptLocalStorageValue<T>(idbEncoded, key);
if (isValid && !isValid(value)) return null;
return value;
}
const legacyEncoded = typeof manager.loadFromStorage === 'function'
? (manager.loadFromStorage(storageKey) as unknown)
: null;
if (!legacyEncoded || typeof legacyEncoded !== 'string') return null;
const decrypted = await decryptLocalStorageValue<T>(legacyEncoded, key);
if (isValid && !isValid(decrypted)) return null;
if (idbReadable) {
try {
await idbPutSyncBlobIfAbsent(storageKey, legacyEncoded);
try {
manager.removeFromStorage?.(storageKey);
} catch (removeError) {
console.warn(
`[CloudSyncManager] Failed to remove migrated legacy sync key ${storageKey}`,
removeError,
);
}
} catch (migrateError) {
console.warn(
`[CloudSyncManager] Failed to migrate ${storageKey} to IndexedDB; keeping legacy localStorage copy`,
migrateError,
);
}
}
return decrypted;
}
async function rememberCurrentSyncBaseSnapshot(this: any,
provider?: CloudProvider,
assertCanPersist?: () => void,
@@ -1204,8 +1276,18 @@ export async function saveSyncBaseImpl(this: any,
}
const encrypted = await encryptLocalStorageValue(payload, key);
assertCanPersist?.();
if (this.saveToStorage(this.syncBaseKey(provider), encrypted) === false) {
throw new Error('Unable to persist sync base');
const storageKey = this.syncBaseKey(provider);
await idbPutSyncBlob(storageKey, encrypted, {
assertCanWrite: assertCanPersist,
errorLabel: 'sync baseline',
});
try {
this.removeFromStorage?.(storageKey);
} catch (removeError) {
console.warn(
`[CloudSyncManager] Failed to remove legacy sync base key ${storageKey}`,
removeError,
);
}
} catch (error) {
console.warn('[CloudSyncManager] Failed to save sync base', error);
@@ -1217,9 +1299,11 @@ export async function loadSyncBaseImpl(this: any,provider?: CloudProvider): Prom
const key = this.state.unlockedKey?.derivedKey;
if (!key) return null;
try {
const encoded = this.loadFromStorage(this.syncBaseKey(provider)) as unknown;
if (!encoded || typeof encoded !== 'string') return null;
return decryptLocalStorageValue<SyncPayload>(encoded, key);
return await loadEncryptedSyncBlobWithMigration<SyncPayload>(
this,
this.syncBaseKey(provider),
key,
);
} catch {
return null;
}
@@ -1234,10 +1318,13 @@ export async function loadSyncSnapshotsImpl(this: any,provider?: CloudProvider):
const key = this.state.unlockedKey?.derivedKey;
if (!key) return [];
try {
const encoded = this.loadFromStorage(this.syncSnapshotsKey(provider)) as unknown;
if (!encoded || typeof encoded !== 'string') return [];
const snapshots = await decryptLocalStorageValue<SyncSnapshotEntry[]>(encoded, key);
return Array.isArray(snapshots) ? snapshots : [];
const snapshots = await loadEncryptedSyncBlobWithMigration<SyncSnapshotEntry[]>(
this,
this.syncSnapshotsKey(provider),
key,
(value) => Array.isArray(value),
);
return snapshots ?? [];
} catch {
return [];
}
@@ -1254,15 +1341,40 @@ export async function saveSyncSnapshotsImpl(this: any,
}
const encrypted = await encryptLocalStorageValue(snapshots.slice(0, SYNC_SNAPSHOT_LIMIT), key);
assertCanPersist?.();
if (this.saveToStorage(this.syncSnapshotsKey(provider), encrypted) === false) {
throw new Error('Unable to persist sync snapshots');
const storageKey = this.syncSnapshotsKey(provider);
await idbPutSyncBlob(storageKey, encrypted, {
assertCanWrite: assertCanPersist,
errorLabel: 'sync snapshots',
});
try {
this.removeFromStorage?.(storageKey);
} catch (removeError) {
console.warn(
`[CloudSyncManager] Failed to remove legacy sync snapshots key ${storageKey}`,
removeError,
);
}
}
export function clearSyncBaseImpl(this: any): void {
export function clearSyncBaseImpl(this: any): Promise<void> {
const idbKeys = new Set<string>([
SYNC_STORAGE_KEYS.SYNC_BASE_PAYLOAD,
SYNC_SNAPSHOTS_STORAGE_KEY,
]);
this.removeFromStorage(SYNC_STORAGE_KEYS.SYNC_BASE_PAYLOAD);
if (typeof this.syncBaseKey === 'function') {
const defaultBaseKey = this.syncBaseKey();
if (defaultBaseKey) {
idbKeys.add(defaultBaseKey);
if (defaultBaseKey !== SYNC_STORAGE_KEYS.SYNC_BASE_PAYLOAD) {
this.removeFromStorage(defaultBaseKey);
}
}
}
if (typeof this.syncSnapshotsKey === 'function') {
this.removeFromStorage(this.syncSnapshotsKey());
const defaultSnapshotsKey = this.syncSnapshotsKey();
idbKeys.add(defaultSnapshotsKey);
this.removeFromStorage(defaultSnapshotsKey);
}
const providers = new Set<CloudProvider>([
'github', 'google', 'onedrive', 'webdav', 's3',
@@ -1276,13 +1388,18 @@ export function clearSyncBaseImpl(this: any): void {
}
}
for (const p of providers) {
this.removeFromStorage(this.syncBaseKey(p));
const baseKey = this.syncBaseKey(p);
idbKeys.add(baseKey);
this.removeFromStorage(baseKey);
this.removeFromStorage(this.convergentProviderBaselineKey(p));
if (typeof this.syncSnapshotsKey === 'function') {
this.removeFromStorage(this.syncSnapshotsKey(p));
const snapshotsKey = this.syncSnapshotsKey(p);
idbKeys.add(snapshotsKey);
this.removeFromStorage(snapshotsKey);
}
}
this.clearSyncAnchor();
return deleteSyncBlobsFromIdb([...idbKeys]);
}
export function addSyncHistoryEntryImpl(this: any,entry: Omit<SyncHistoryEntry, 'id'>): void {
@@ -1303,7 +1420,7 @@ export function resetLocalVersionImpl(this: any): void {
this.state.syncHistory = [];
this.saveSyncConfig();
this.saveToStorage(SYNC_HISTORY_STORAGE_KEY, []);
this.clearSyncBase();
void this.clearSyncBase();
this.clearSyncAnchor();
this.notifyStateChange();
}
@@ -0,0 +1,500 @@
import assert from 'node:assert/strict';
import test from 'node:test';
import {
SYNC_STORAGE_KEYS,
type CloudProvider,
type MasterKeyConfig,
type SyncPayload,
type SyncSnapshotEntry,
} from '../../../domain/sync.ts';
import {
FakeTransaction,
installFakeIndexedDb,
} from '../../../application/state/testSupport/fakeIndexedDb.ts';
import {
clearSyncBaseImpl,
loadSyncBaseImpl,
loadSyncSnapshotsImpl,
saveSyncBaseImpl,
saveSyncSnapshotsImpl,
syncBaseKeyImpl,
syncSnapshotsKeyImpl,
} from './syncAllStorageMethods.ts';
import { clearProviderMergeStateImpl } from './authMethods.ts';
import { reencryptSyncStorageImpl } from './convergentSyncStorageMethods.ts';
import {
decryptLocalStorageValue,
encryptLocalStorageValue,
} from './encryptedLocalStorage.ts';
import {
SYNC_BLOB_IDB_STORE_NAME,
idbGetSyncBlob,
idbPutSyncBlob,
idbPutSyncBlobIfAbsent,
resetSyncBlobIdbForTests,
} from './syncBlobIdbStorage.ts';
const NOW = 1_700_000_000_000;
async function generateTestKey(): Promise<CryptoKey> {
return crypto.subtle.generateKey(
{ name: 'AES-GCM', length: 256 },
true,
['encrypt', 'decrypt'],
);
}
function makePayload(hostId: string): SyncPayload {
return {
hosts: [
{
id: hostId,
label: hostId,
hostname: `${hostId}.example.com`,
port: 22,
username: 'root',
tags: [],
os: 'linux',
},
],
keys: [],
snippets: [],
customGroups: [],
syncedAt: NOW,
};
}
function makeSnapshot(id: string, provider?: CloudProvider): SyncSnapshotEntry {
return {
id,
timestamp: NOW,
...(provider ? { provider } : {}),
payload: makePayload(`host-${id}`),
};
}
function createHarness(
derivedKey: CryptoKey | null,
options: {
legacyStorage?: Map<string, unknown>;
pluginProviders?: string[];
} = {},
) {
const legacyStorage = options.legacyStorage ?? new Map<string, unknown>();
const savedToLocalStorage: string[] = [];
const removedFromLocalStorage: string[] = [];
const clearedAnchors: Array<CloudProvider | undefined> = [];
const manager = {
state: {
unlockedKey: derivedKey ? { derivedKey } : null,
providers: {} as Record<string, unknown>,
masterKeyConfig: null as MasterKeyConfig | null,
},
loadFromStorage(key: string) {
return legacyStorage.has(key) ? legacyStorage.get(key) : null;
},
saveToStorage(key: string, value: unknown) {
savedToLocalStorage.push(key);
legacyStorage.set(key, value);
return true;
},
removeFromStorage(key: string) {
removedFromLocalStorage.push(key);
legacyStorage.delete(key);
},
syncBaseKey(provider?: CloudProvider) {
return syncBaseKeyImpl.call(this, provider);
},
syncSnapshotsKey(provider?: CloudProvider) {
return syncSnapshotsKeyImpl.call(this, provider);
},
convergentProviderBaselineKey(provider: CloudProvider) {
return `${SYNC_STORAGE_KEYS.CONVERGENT_PROVIDER_BASELINE}_${provider}`;
},
listRegisteredPluginProviderIds() {
return options.pluginProviders ?? [];
},
clearSyncAnchor(provider?: CloudProvider) {
clearedAnchors.push(provider);
},
};
return {
manager,
legacyStorage,
savedToLocalStorage,
removedFromLocalStorage,
clearedAnchors,
};
}
test('save and load round-trip sync base and snapshots via IndexedDB without touching localStorage', async () => {
resetSyncBlobIdbForTests();
const fakeIdb = installFakeIndexedDb();
try {
const key = await generateTestKey();
const { manager, legacyStorage, savedToLocalStorage } = createHarness(key);
const googlePayload = makePayload('google-host');
const unsuffixedPayload = makePayload('default-host');
const googleSnapshots = [makeSnapshot('snap-1', 'google'), makeSnapshot('snap-2', 'google')];
await saveSyncBaseImpl.call(manager, googlePayload, 'google');
await saveSyncBaseImpl.call(manager, unsuffixedPayload);
await saveSyncSnapshotsImpl.call(manager, googleSnapshots, 'google');
assert.deepEqual(savedToLocalStorage, []);
assert.equal(legacyStorage.size, 0);
const loadedGoogle = await loadSyncBaseImpl.call(manager, 'google');
const loadedUnsuffixed = await loadSyncBaseImpl.call(manager);
const loadedSnapshots = await loadSyncSnapshotsImpl.call(manager, 'google');
assert.deepEqual(loadedGoogle, googlePayload);
assert.deepEqual(loadedUnsuffixed, unsuffixedPayload);
assert.deepEqual(loadedSnapshots, googleSnapshots);
// Confirm ciphertext stored in IDB remains compatible with decryptLocalStorageValue.
const rawGoogleCiphertext = await idbGetSyncBlob(manager.syncBaseKey('google'));
assert.equal(typeof rawGoogleCiphertext, 'string');
assert.deepEqual(await decryptLocalStorageValue(rawGoogleCiphertext!, key), googlePayload);
} finally {
resetSyncBlobIdbForTests();
fakeIdb.restore();
}
});
test('load migrates legacy localStorage sync base and snapshots into IndexedDB and removes legacy keys', async () => {
resetSyncBlobIdbForTests();
const fakeIdb = installFakeIndexedDb();
try {
const key = await generateTestKey();
const legacyBase = makePayload('legacy-google');
const legacySnapshots = [makeSnapshot('legacy-snap', 'google')];
const legacyBaseKey = syncBaseKeyImpl.call({}, 'google');
const legacySnapshotsKey = syncSnapshotsKeyImpl.call({}, 'google');
const legacyBaseCiphertext = await encryptLocalStorageValue(legacyBase, key);
const legacySnapshotsCiphertext = await encryptLocalStorageValue(legacySnapshots, key);
const legacyStorage = new Map<string, unknown>([
[legacyBaseKey, legacyBaseCiphertext],
[legacySnapshotsKey, legacySnapshotsCiphertext],
]);
const { manager } = createHarness(key, { legacyStorage });
const loadedBase = await loadSyncBaseImpl.call(manager, 'google');
const loadedSnapshots = await loadSyncSnapshotsImpl.call(manager, 'google');
assert.deepEqual(loadedBase, legacyBase);
assert.deepEqual(loadedSnapshots, legacySnapshots);
// Legacy localStorage keys are reclaimed after successful IDB migration.
assert.equal(legacyStorage.has(legacyBaseKey), false);
assert.equal(legacyStorage.has(legacySnapshotsKey), false);
// Subsequent reads come directly from IndexedDB.
assert.equal(await idbGetSyncBlob(legacyBaseKey), legacyBaseCiphertext);
assert.equal(await idbGetSyncBlob(legacySnapshotsKey), legacySnapshotsCiphertext);
assert.deepEqual(await loadSyncBaseImpl.call(manager, 'google'), legacyBase);
assert.deepEqual(await loadSyncSnapshotsImpl.call(manager, 'google'), legacySnapshots);
} finally {
resetSyncBlobIdbForTests();
fakeIdb.restore();
}
});
test('load keeps legacy localStorage copy intact if IndexedDB migration write fails', async () => {
resetSyncBlobIdbForTests();
const fakeIdb = installFakeIndexedDb();
const originalWarn = console.warn;
console.warn = () => {};
try {
const key = await generateTestKey();
const legacyBase = makePayload('legacy-keep');
const legacyBaseKey = syncBaseKeyImpl.call({}, 'google');
const legacyCiphertext = await encryptLocalStorageValue(legacyBase, key);
const legacyStorage = new Map<string, unknown>([[legacyBaseKey, legacyCiphertext]]);
const { manager } = createHarness(key, { legacyStorage });
// Let readonly get succeed, then fail readwrite migration transaction.
const originalTx = fakeIdb.db.transaction.bind(fakeIdb.db);
fakeIdb.db.transaction = (storeName: string, mode?: string) => {
if (mode === 'readwrite') {
return new FakeTransaction(fakeIdb.db, storeName, true);
}
return originalTx(storeName, mode);
};
const loaded = await loadSyncBaseImpl.call(manager, 'google');
assert.deepEqual(loaded, legacyBase);
assert.equal(legacyStorage.get(legacyBaseKey), legacyCiphertext);
} finally {
console.warn = originalWarn;
resetSyncBlobIdbForTests();
fakeIdb.restore();
}
});
test('idbPutSyncBlobIfAbsent does not overwrite a newer IndexedDB record', async () => {
resetSyncBlobIdbForTests();
const fakeIdb = installFakeIndexedDb();
try {
await idbPutSyncBlob('netcatty_sync_base_payload_v1_google', 'newer-ciphertext');
const inserted = await idbPutSyncBlobIfAbsent('netcatty_sync_base_payload_v1_google', 'stale-legacy');
assert.equal(inserted, false);
assert.equal(await idbGetSyncBlob('netcatty_sync_base_payload_v1_google'), 'newer-ciphertext');
} finally {
resetSyncBlobIdbForTests();
fakeIdb.restore();
}
});
test('save removes pre-existing legacy localStorage keys after successful IndexedDB write', async () => {
resetSyncBlobIdbForTests();
const fakeIdb = installFakeIndexedDb();
try {
const key = await generateTestKey();
const baseKey = syncBaseKeyImpl.call({}, 'google');
const snapshotsKey = syncSnapshotsKeyImpl.call({}, 'google');
const oldBase = makePayload('legacy-before-save');
const newBase = makePayload('fresh-idb-base');
const newSnapshots = [makeSnapshot('fresh-snap', 'google')];
const legacyStorage = new Map<string, unknown>([
[baseKey, await encryptLocalStorageValue(oldBase, key)],
[snapshotsKey, await encryptLocalStorageValue([makeSnapshot('old-snap', 'google')], key)],
]);
const { manager, savedToLocalStorage } = createHarness(key, { legacyStorage });
await saveSyncBaseImpl.call(manager, newBase, 'google');
assert.equal(legacyStorage.has(baseKey), false);
assert.equal(legacyStorage.has(snapshotsKey), false);
assert.deepEqual(savedToLocalStorage, []);
assert.deepEqual(await loadSyncBaseImpl.call(manager, 'google'), newBase);
// Also test direct saveSyncSnapshotsImpl cleanup of an unmigrated legacy key.
legacyStorage.set(snapshotsKey, 'stale-legacy-snapshots');
await saveSyncSnapshotsImpl.call(manager, newSnapshots, 'google');
assert.equal(legacyStorage.has(snapshotsKey), false);
assert.deepEqual(await loadSyncSnapshotsImpl.call(manager, 'google'), newSnapshots);
} finally {
resetSyncBlobIdbForTests();
fakeIdb.restore();
}
});
test('save fails clearly when IndexedDB is unavailable or rejects writes and keeps legacy key intact', async () => {
const originalIndexedDb = (globalThis as { indexedDB?: IDBFactory }).indexedDB;
const originalWarn = console.warn;
console.warn = () => {};
try {
const key = await generateTestKey();
const baseKey = syncBaseKeyImpl.call({}, 'google');
const snapshotsKey = syncSnapshotsKeyImpl.call({}, 'google');
// Case 1: IndexedDB completely unavailable.
resetSyncBlobIdbForTests();
delete (globalThis as { indexedDB?: IDBFactory }).indexedDB;
const legacyStorage = new Map<string, unknown>([
[baseKey, 'existing-legacy-base'],
[snapshotsKey, 'existing-legacy-snapshots'],
]);
const { manager, savedToLocalStorage } = createHarness(key, { legacyStorage });
await assert.rejects(
() => saveSyncBaseImpl.call(manager, makePayload('new-base'), 'google'),
/Unable to persist local sync baseline in IndexedDB: IndexedDB is unavailable/,
);
await assert.rejects(
() => saveSyncSnapshotsImpl.call(manager, [makeSnapshot('s1', 'google')], 'google'),
/Unable to persist local sync snapshots in IndexedDB: IndexedDB is unavailable/,
);
assert.deepEqual(savedToLocalStorage, []);
assert.equal(legacyStorage.get(baseKey), 'existing-legacy-base');
assert.equal(legacyStorage.get(snapshotsKey), 'existing-legacy-snapshots');
// Case 2: IndexedDB transaction fails during write.
resetSyncBlobIdbForTests();
const fakeIdb = installFakeIndexedDb();
try {
const originalTx = fakeIdb.db.transaction.bind(fakeIdb.db);
fakeIdb.db.transaction = (storeName: string, mode?: string) => {
if (mode === 'readwrite') {
return new FakeTransaction(fakeIdb.db, storeName, true);
}
return originalTx(storeName, mode);
};
await assert.rejects(
() => saveSyncBaseImpl.call(manager, makePayload('tx-fail'), 'google'),
/Unable to persist local sync baseline in IndexedDB/,
);
assert.equal(legacyStorage.get(baseKey), 'existing-legacy-base');
} finally {
resetSyncBlobIdbForTests();
fakeIdb.restore();
}
} finally {
console.warn = originalWarn;
resetSyncBlobIdbForTests();
(globalThis as { indexedDB?: IDBFactory }).indexedDB = originalIndexedDb;
}
});
test('clearSyncBase removes IndexedDB records and legacy keys for provider-suffixed and unsuffixed names', async () => {
resetSyncBlobIdbForTests();
const fakeIdb = installFakeIndexedDb();
try {
const key = await generateTestKey();
const pluginProvider = 'plugin:com.example.sync:vault' as CloudProvider;
const legacyStorage = new Map<string, unknown>();
const { manager } = createHarness(key, {
legacyStorage,
pluginProviders: [pluginProvider],
});
const providers: Array<CloudProvider | undefined> = [
undefined,
'github',
'google',
'onedrive',
'webdav',
's3',
pluginProvider,
];
for (const provider of providers) {
const baseKey = manager.syncBaseKey(provider);
const snapshotsKey = manager.syncSnapshotsKey(provider);
await idbPutSyncBlob(baseKey, await encryptLocalStorageValue(makePayload(`idb-${provider ?? 'root'}`), key));
await idbPutSyncBlob(snapshotsKey, await encryptLocalStorageValue([makeSnapshot(`snap-${provider ?? 'root'}`, provider)], key));
legacyStorage.set(baseKey, 'leftover-legacy-base');
legacyStorage.set(snapshotsKey, 'leftover-legacy-snapshots');
}
await clearSyncBaseImpl.call(manager);
assert.deepEqual(fakeIdb.db.dumpStore(SYNC_BLOB_IDB_STORE_NAME), []);
for (const provider of providers) {
assert.equal(legacyStorage.has(manager.syncBaseKey(provider)), false);
assert.equal(legacyStorage.has(manager.syncSnapshotsKey(provider)), false);
assert.equal(await loadSyncBaseImpl.call(manager, provider), null);
assert.deepEqual(await loadSyncSnapshotsImpl.call(manager, provider), []);
}
} finally {
resetSyncBlobIdbForTests();
fakeIdb.restore();
}
});
test('unawaited clearSyncBase and clearProviderMergeState serialize before subsequent IDB reads', async () => {
resetSyncBlobIdbForTests();
const fakeIdb = installFakeIndexedDb();
try {
const key = await generateTestKey();
const legacyStorage = new Map<string, unknown>();
const { manager } = createHarness(key, { legacyStorage });
await saveSyncBaseImpl.call(manager, makePayload('google-host'), 'google');
await saveSyncBaseImpl.call(manager, makePayload('github-host'), 'github');
// Clear only google via clearProviderMergeStateImpl without awaiting first.
void clearProviderMergeStateImpl.call(manager, 'google');
assert.equal(await loadSyncBaseImpl.call(manager, 'google'), null);
assert.deepEqual(await loadSyncBaseImpl.call(manager, 'github'), makePayload('github-host'));
// Clear all without awaiting; immediate read must still observe deletion.
void clearSyncBaseImpl.call(manager);
assert.equal(await loadSyncBaseImpl.call(manager, 'github'), null);
} finally {
resetSyncBlobIdbForTests();
fakeIdb.restore();
}
});
test('reencryptSyncStorage rotates IDB sync bases and snapshots, migrates legacy keys, and rolls back on failure', async () => {
resetSyncBlobIdbForTests();
const fakeIdb = installFakeIndexedDb();
try {
const oldKey = await generateTestKey();
const newKey = await generateTestKey();
const oldConfig: MasterKeyConfig = {
verificationHash: 'old',
salt: 'old-salt',
kdf: 'PBKDF2',
createdAt: NOW,
};
const newConfig: MasterKeyConfig = {
...oldConfig,
verificationHash: 'new',
salt: 'new-salt',
};
const legacyStorage = new Map<string, unknown>([
[SYNC_STORAGE_KEYS.MASTER_KEY_CONFIG, oldConfig],
]);
const { manager } = createHarness(oldKey, { legacyStorage });
const unsuffixedBaseKey = manager.syncBaseKey();
const googleBaseKey = manager.syncBaseKey('google');
const googleSnapshotsKey = manager.syncSnapshotsKey('google');
const githubLegacyBaseKey = manager.syncBaseKey('github');
const unsuffixedOriginal = await encryptLocalStorageValue(makePayload('root-base'), oldKey);
const googleBaseOriginal = await encryptLocalStorageValue(makePayload('google-base'), oldKey);
const googleSnapshotsOriginal = await encryptLocalStorageValue([makeSnapshot('s1', 'google')], oldKey);
const githubLegacyOriginal = await encryptLocalStorageValue(makePayload('github-legacy'), oldKey);
await idbPutSyncBlob(unsuffixedBaseKey, unsuffixedOriginal);
await idbPutSyncBlob(googleBaseKey, googleBaseOriginal);
await idbPutSyncBlob(googleSnapshotsKey, googleSnapshotsOriginal);
legacyStorage.set(githubLegacyBaseKey, githubLegacyOriginal);
// 1. Simulate failure committing MASTER_KEY_CONFIG -> verify full IDB + legacy rollback.
let failConfigOnce = true;
const origSave = manager.saveToStorage.bind(manager);
manager.saveToStorage = (storageKey: string, value: unknown) => {
if (storageKey === SYNC_STORAGE_KEYS.MASTER_KEY_CONFIG && failConfigOnce) {
failConfigOnce = false;
return false;
}
return origSave(storageKey, value);
};
await assert.rejects(
() => reencryptSyncStorageImpl.call(manager, oldKey, newKey, newConfig),
/Unable to persist the new master key configuration/,
);
assert.equal(await idbGetSyncBlob(unsuffixedBaseKey), unsuffixedOriginal);
assert.equal(await idbGetSyncBlob(googleBaseKey), googleBaseOriginal);
assert.equal(await idbGetSyncBlob(googleSnapshotsKey), googleSnapshotsOriginal);
assert.equal(await idbGetSyncBlob(githubLegacyBaseKey), null);
assert.equal(legacyStorage.get(githubLegacyBaseKey), githubLegacyOriginal);
assert.deepEqual(legacyStorage.get(SYNC_STORAGE_KEYS.MASTER_KEY_CONFIG), oldConfig);
// 2. Retry rotation -> succeeds, re-encrypts IDB copies, migrates legacy copy & removes legacy key.
await reencryptSyncStorageImpl.call(manager, oldKey, newKey, newConfig);
assert.deepEqual(legacyStorage.get(SYNC_STORAGE_KEYS.MASTER_KEY_CONFIG), newConfig);
assert.equal(legacyStorage.has(githubLegacyBaseKey), false);
for (const [k, expected] of [
[unsuffixedBaseKey, makePayload('root-base')],
[googleBaseKey, makePayload('google-base')],
[googleSnapshotsKey, [makeSnapshot('s1', 'google')]],
[githubLegacyBaseKey, makePayload('github-legacy')],
] as const) {
const rotated = await idbGetSyncBlob(k);
assert.equal(typeof rotated, 'string');
assert.deepEqual(await decryptLocalStorageValue(rotated!, newKey), expected);
await assert.rejects(() => decryptLocalStorageValue(rotated!, oldKey));
}
} finally {
resetSyncBlobIdbForTests();
fakeIdb.restore();
}
});
@@ -0,0 +1,233 @@
/**
* Dedicated IndexedDB persistence for large encrypted cloud-sync blobs:
* - `netcatty_sync_base_payload_v1` / `netcatty_sync_base_payload_v1_<provider>`
* - `netcatty_sync_snapshots_v1` / `netcatty_sync_snapshots_v1_<provider>`
*
* Storing the encrypted baseline and snapshot history in localStorage hits
* Chromium's ~5-10 MB per-origin quota on large vaults (#4661). Moving only
* these blob key families to a dedicated IndexedDB database removes the
* localStorage ceiling while keeping the AES-GCM ciphertext format identical.
*/
export const SYNC_BLOB_IDB_NAME = 'netcatty_sync_blobs';
export const SYNC_BLOB_IDB_VERSION = 1;
export const SYNC_BLOB_IDB_STORE_NAME = 'blobs';
interface SyncBlobRecord {
key: string;
value: string;
}
let cachedDb: IDBDatabase | null = null;
let openPromise: Promise<IDBDatabase> | null = null;
let opQueue: Promise<void> = Promise.resolve();
export function isSyncBlobIdbAvailable(): boolean {
return typeof indexedDB !== 'undefined' && indexedDB !== null;
}
function forgetSyncBlobIdb(): void {
const db = cachedDb;
cachedDb = null;
openPromise = null;
try {
db?.close();
} catch {
// Connection is already closing or closed.
}
}
function requestToPromise<T>(request: IDBRequest<T>): Promise<T> {
return new Promise((resolve, reject) => {
request.onsuccess = () => resolve(request.result);
request.onerror = () => reject(request.error ?? new Error('IndexedDB request failed'));
});
}
function transactionDone(transaction: IDBTransaction): Promise<void> {
return new Promise((resolve, reject) => {
let settled = false;
const finish = (fn: () => void) => {
if (settled) return;
settled = true;
fn();
};
transaction.oncomplete = () => finish(() => resolve());
transaction.onabort = () => finish(() => reject(transaction.error ?? new Error('IndexedDB transaction aborted')));
transaction.onerror = () => finish(() => reject(transaction.error ?? new Error('IndexedDB transaction failed')));
});
}
function enqueueIdbOp<T>(task: () => Promise<T>): Promise<T> {
const result = opQueue.then(task, task);
opQueue = result.then(() => undefined, () => undefined);
return result;
}
export function openSyncBlobIdb(): Promise<IDBDatabase> {
if (!isSyncBlobIdbAvailable()) {
return Promise.reject(new Error('IndexedDB is unavailable'));
}
if (cachedDb) {
return Promise.resolve(cachedDb);
}
if (!openPromise) {
openPromise = new Promise<IDBDatabase>((resolve, reject) => {
let request: IDBOpenDBRequest;
try {
request = indexedDB.open(SYNC_BLOB_IDB_NAME, SYNC_BLOB_IDB_VERSION);
} catch (error) {
openPromise = null;
reject(error instanceof Error ? error : new Error(String(error)));
return;
}
request.onupgradeneeded = () => {
const db = request.result;
if (!db.objectStoreNames.contains(SYNC_BLOB_IDB_STORE_NAME)) {
db.createObjectStore(SYNC_BLOB_IDB_STORE_NAME, { keyPath: 'key' });
}
};
request.onsuccess = () => {
const db = request.result;
cachedDb = db;
db.onclose = () => {
if (cachedDb === db) cachedDb = null;
openPromise = null;
};
db.onversionchange = () => {
if (cachedDb === db) cachedDb = null;
openPromise = null;
try {
db.close();
} catch {
// Already closed.
}
};
resolve(db);
};
request.onerror = () => {
openPromise = null;
reject(request.error ?? new Error('Failed to open IndexedDB'));
};
request.onblocked = () => {
openPromise = null;
};
});
}
return openPromise;
}
export function resetSyncBlobIdbForTests(): void {
forgetSyncBlobIdb();
opQueue = Promise.resolve();
}
export function idbGetSyncBlob(key: string): Promise<string | null> {
return enqueueIdbOp(async () => {
const db = await openSyncBlobIdb();
try {
const tx = db.transaction(SYNC_BLOB_IDB_STORE_NAME, 'readonly');
const store = tx.objectStore(SYNC_BLOB_IDB_STORE_NAME);
const record = await requestToPromise(
store.get(key) as IDBRequest<SyncBlobRecord | undefined>,
);
return typeof record?.value === 'string' ? record.value : null;
} catch (error) {
forgetSyncBlobIdb();
throw error;
}
});
}
function formatPersistError(label: string, error: unknown): Error {
const detail = error instanceof Error && error.message ? error.message : String(error);
return new Error(`Unable to persist local ${label} in IndexedDB: ${detail}`, { cause: error });
}
export function idbPutSyncBlob(
key: string,
value: string,
options?: { assertCanWrite?: () => void; errorLabel?: string },
): Promise<void> {
return enqueueIdbOp(async () => {
let db: IDBDatabase;
try {
db = await openSyncBlobIdb();
} catch (error) {
throw options?.errorLabel ? formatPersistError(options.errorLabel, error) : error;
}
// Caller-supplied guard (e.g. provider/master-key stability check) must
// propagate its own error unchanged rather than looking like an IDB failure.
options?.assertCanWrite?.();
try {
const tx = db.transaction(SYNC_BLOB_IDB_STORE_NAME, 'readwrite');
const store = tx.objectStore(SYNC_BLOB_IDB_STORE_NAME);
store.put({ key, value } satisfies SyncBlobRecord);
await transactionDone(tx);
} catch (error) {
forgetSyncBlobIdb();
throw options?.errorLabel ? formatPersistError(options.errorLabel, error) : error;
}
});
}
/**
* Insert a migrated legacy blob only if IndexedDB does not already hold a
* record for `key`. Prevents a legacy fallback read from overwriting a newer
* concurrent save.
*/
export function idbPutSyncBlobIfAbsent(key: string, value: string): Promise<boolean> {
return enqueueIdbOp(async () => {
const db = await openSyncBlobIdb();
try {
let inserted = false;
const tx = db.transaction(SYNC_BLOB_IDB_STORE_NAME, 'readwrite');
const store = tx.objectStore(SYNC_BLOB_IDB_STORE_NAME);
const request = store.get(key) as IDBRequest<SyncBlobRecord | undefined>;
request.onsuccess = () => {
if (request.result === undefined) {
inserted = true;
store.put({ key, value } satisfies SyncBlobRecord);
}
};
await transactionDone(tx);
return inserted;
} catch (error) {
forgetSyncBlobIdb();
throw error;
}
});
}
export function idbDeleteSyncBlobs(keys: readonly string[]): Promise<void> {
if (keys.length === 0) return Promise.resolve();
return enqueueIdbOp(async () => {
const db = await openSyncBlobIdb();
try {
const tx = db.transaction(SYNC_BLOB_IDB_STORE_NAME, 'readwrite');
const store = tx.objectStore(SYNC_BLOB_IDB_STORE_NAME);
for (const key of keys) {
store.delete(key);
}
await transactionDone(tx);
} catch (error) {
forgetSyncBlobIdb();
throw error;
}
});
}
/**
* Best-effort deletion for fire-and-forget clear paths (e.g. resetLocalVersion,
* disconnect, cross-window credential change). Returns a Promise that never
* rejects so unawaited calls cannot cause unhandled rejections, while async
* callers and tests can await completion.
*/
export async function deleteSyncBlobsFromIdb(keys: readonly string[]): Promise<void> {
if (keys.length === 0 || !isSyncBlobIdbAvailable()) return;
try {
await idbDeleteSyncBlobs(keys);
} catch (error) {
console.warn('[CloudSyncManager] Failed to delete sync blobs from IndexedDB', error);
}
}