Privacy-first password manager with built-in email aliasing. Fully encrypted and self-hostable.
Add vault sync hold logic (#2159)
Leendert de Borst9d186b03dfc7
diff --git a/apps/browser-extension/src/entrypoints/background/VaultMessageHandler.ts b/apps/browser-extension/src/entrypoints/background/VaultMessageHandler.tsindex 2421f24cd..a1f176927 100644--- a/apps/browser-extension/src/entrypoints/background/VaultMessageHandler.ts+++ b/apps/browser-extension/src/entrypoints/background/VaultMessageHandler.ts@@ -52,6 +52,7 @@ import { clearDirtyScopes, getDirtyScopes } from '@/utils/VaultDirtyState';import { VaultKeyService } from '@/utils/VaultKeyService';import { vaultRequiresManifestMigration, VaultMigrationKind, type VaultMigrationStatus } from '@/utils/VaultManifestMigration';import { vaultMergeService } from '@/utils/VaultMergeService';+import { getVaultSyncHoldReason } from '@/utils/VaultSyncHold';import { type PullAndMergeResult, vaultSyncService, invalidateCanonicalizeCache, primeCanonicalizeCache } from '@/utils/VaultSyncService';import { WebApiService } from '@/utils/WebApiService';@@ -314,6 +315,10 @@ async function pushVaultToServer(sqliteClient: SqliteClient, options: { forceFul* Sync the vault with the server to check if a newer vault is available. If so, the vault will be updated.*/export async function handleSyncVault() : Promise<messageBoolResponse> {+ if (await syncIsOnHold()) {+ return { success: false };+ }+const webApi = new WebApiService();const statusResponse = await webApi.getStatus();const statusError = webApi.validateStatusResponse(statusResponse);@@ -1457,6 +1462,10 @@ function syncResult(overrides: Partial<FullVaultSyncResult> = {}): FullVaultSync* @param options - what the caller asks of the sync beyond what the revisions decide*/async function handleFullVaultSyncInternal(options?: FullVaultSyncOptions): Promise<FullVaultSyncResult> {+ if (await syncIsOnHold()) {+ return syncResult({ success: false });+ }+// Check if sync is already in progressif (isSyncInProgress) {// Mark that we need to sync again after current sync completes@@ -1618,7 +1627,7 @@ async function runSyncPreflight(webApi: WebApiService, options?: FullVaultSyncOpreturn abortSync({ success: false, requiresLogout, errorKey: statusError });}- // Check if the SRP salt has changed (password change detection)+ // A changed SRP salt means the password was changed on another device (this device's own change holds the sync hold).const storedEncryptionParams = await handleGetEncryptionKeyDerivationParams();if (storedEncryptionParams && statusResponse.srpSalt && statusResponse.srpSalt !== storedEncryptionParams.salt) {return abortSync({ success: false, requiresLogout: true, errorKey: 'passwordChanged' });@@ -1653,6 +1662,17 @@ async function runSyncPreflight(webApi: WebApiService, options?: FullVaultSyncOpreturn { proceed: true, statusResponse, syncState, needsPull };}+/**+ * Whether a sync has to yield to a held sync hold (see VaultSyncHold), logging what it yields to when it does.+ */+async function syncIsOnHold(): Promise<boolean> {+ const reason = await getVaultSyncHoldReason();+ if (reason) {+ devLog(`[VaultSync] Sync refused: on hold for ${reason}.`);+ }+ return reason !== null;+}+/*** Whether the stored vault holds rows for manifests this session cannot write, which a pull has to repair before* anything may be pushed (see {@link VaultSyncService.findUnwritableManifests}). A vault that cannot even be@@ -2888,7 +2908,7 @@ export async function handleGroupInviteMember(message: { groupId: string; manifereturn { success: false, apiErrorCode: 'INVITE_RECIPIENT_NOT_READY' };}- await SharingService.inviteMember(webApi, group.groupId, manifest.manifestId, member.userId, grant, EncryptionUtility.algorithmForPublicKey(member.publicKey!));+ await SharingService.inviteMember(webApi, group.groupId, manifest.manifestId, member.userId, grant, VaultKeyAlgorithm.RsaOaepSha256);devLog(`[Sharing] Invited ${member.userId} to vault ${manifest.manifestId} with its key encrypted for them.`);return { success: true };diff --git a/apps/browser-extension/src/utils/VaultSyncHold.ts b/apps/browser-extension/src/utils/VaultSyncHold.tsnew file mode 100644index 000000000..d82f40ab1--- /dev/null+++ b/apps/browser-extension/src/utils/VaultSyncHold.ts@@ -0,0 +1,48 @@+/**+ * VaultSyncHold.+ *+ * A hold that suspends vault syncing while an operation runs that is prone to race conditions, e.g. a master password change.+ */++import { storage } from 'wxt/utils/storage';++import { StorageKeys } from '@/utils/constants/storageKeys';++/**+ * The operations that take the hold, named so a refused sync can log what it yielded to.+ */+export enum VaultSyncHoldReason {+ PasswordChange = 'passwordChange',+}++/** How long a hold stays valid without being released, so a crashed holder is forgotten. */+export const VAULT_SYNC_HOLD_TTL_MS = 2 * 60 * 1000; // 2 minutes++/** What is stored while the hold is held. */+type VaultSyncHoldRecord = { reason: VaultSyncHoldReason; heldAt: number };++/**+ * Run an operation while holding the sync hold, releasing it however the operation ends.+ * @param reason - the operation taking the hold+ * @param operation - the work no sync may race+ */+export async function withVaultSyncHold<T>(reason: VaultSyncHoldReason, operation: () => Promise<T>): Promise<T> {+ const record: VaultSyncHoldRecord = { reason, heldAt: Date.now() };+ await storage.setItem(StorageKeys.VAULT_SYNC_HOLD, record);+ try {+ return await operation();+ } finally {+ await storage.removeItem(StorageKeys.VAULT_SYNC_HOLD);+ }+}++/**+ * The reason syncing is on hold, or null when no unexpired hold is held.+ */+export async function getVaultSyncHoldReason(): Promise<VaultSyncHoldReason | null> {+ const hold = await storage.getItem(StorageKeys.VAULT_SYNC_HOLD) as VaultSyncHoldRecord | null;+ if (!hold || Date.now() - hold.heldAt >= VAULT_SYNC_HOLD_TTL_MS) {+ return null;+ }+ return hold.reason;+}