Skip to content

Privacy-first password manager with built-in email aliasing. Fully encrypted and self-hostable.

Remove outdated server re-push login limited implementation (#2159)

Leendert de Borst35657cdac5bc
diff --git a/apps/browser-extension/src/entrypoints/background/VaultMessageHandler.ts b/apps/browser-extension/src/entrypoints/background/VaultMessageHandler.ts
index b8d886bdc..5266b2fc7 100644
--- a/apps/browser-extension/src/entrypoints/background/VaultMessageHandler.ts
+++ b/apps/browser-extension/src/entrypoints/background/VaultMessageHandler.ts
@@ -2,19 +2,19 @@
import * as OTPAuth from 'otpauth';
import { storage } from 'wxt/utils/storage';
-import { allVaultDataStorageKeys, AUTH_STORAGE_KEYS, dirtyScopeStorageKey, SESSION_STORAGE_KEYS, StorageKeys, VAULT_LOCK_STORAGE_KEYS } from '@/utils/constants/storageKeys';
+import { AUTH_STORAGE_KEYS, dirtyScopeStorageKey, SESSION_STORAGE_KEYS, StorageKeys, vaultDataStorageKeys, VAULT_LOCK_STORAGE_KEYS } from '@/utils/constants/storageKeys';
import { TRASH_RETENTION_DAYS } from '@/utils/constants/vault';
import type { ItemUsageAction } from '@/utils/db';
import type { DraftItem } from '@/utils/db/ItemRef';
import { devError, devLog, devWarn } from '@/utils/devLogger/DevLogger';
import type { EncryptionKeyDerivationParams } from '@/utils/dist/core/models/metadata';
import { FieldKey, ItemTypes, VaultDataBucketCategory, createSystemField, type Item, type PasswordSettings } from '@/utils/dist/core/models/vault';
-import type { VaultResponse, StatusResponseV2, ManifestRevision } from '@/utils/dist/core/models/webapi';
+import type { VaultResponse, ManifestRevision } from '@/utils/dist/core/models/webapi';
import { EncryptionUtility } from '@/utils/EncryptionUtility';
import { readLegacySessionEncryptionKey } from '@/utils/legacy/LegacyStorageKeyFallbacks';
import { requiresLegacyAccountKeyMigration } from '@/utils/legacy/LegacyStorageModelMigration';
import { LocalPreferencesService } from '@/utils/LocalPreferencesService';
-import { getManifestRevisions, getPersonalManifestId } from '@/utils/ManifestRevisions';
+import { getManifestRevisions, manifestsRequiringPull, toManifestRevisionMap } from '@/utils/ManifestRevisions';
import { sendMessage } from '@/utils/messaging/ExtensionMessaging';
import { RecentlySelectedItemService } from '@/utils/RecentlySelectedItemService';
import { filterItems, AutofillMatchingMode, extractRootDomain, isUrlAlreadyLinked, generatePassword, vaultCodecExtractBuckets, vaultCodecBucketLayout, vaultCodecOverflowTable } from '@/utils/RustCore';
@@ -65,45 +65,24 @@ let cachedSqliteClient: SqliteClient | null = null;
let cachedVaultBlob: string | null = null;
/**
- * The server revision of the user's personal manifest.
- * @param status - the status response from the server
- */
-function personalManifestRevision(status: StatusResponseV2): number {
- const personal = (status.manifestRevisions ?? []).find(m => m.manifestId === status.personalManifestId);
- return personal?.revision ?? 0;
-}
-
-/**
- * Whether the client should pull and re-materialize because the server's manifest set no longer matches what the
- * client has locally materialized. One map-versus-map comparison covers every manifest, the personal one included:
- * the server reports it by id like any other. Idempotent: after a successful materialize the local record matches
- * the server, so this returns false until the next server-side change.
- *
+ * Whether the client has to pull and re-materialize, i.e. whether any manifest's local state no longer matches what
+ * the server reports.
* @param serverManifests - the per-manifest revisions from the status response
* @param localRevisions - the client's last-known revision per manifest
*/
function serverManifestsNeedPull(serverManifests: ManifestRevision[], localRevisions: Record<string, number>): boolean {
- const serverRevisions = new Map((serverManifests ?? []).map(m => [m.manifestId, m.revision]));
-
- // Any manifest added or with a changed revision on the server.
- for (const [manifestId, revision] of serverRevisions) {
- const local = localRevisions[manifestId];
- if (local !== revision) {
- const reason = local === undefined ? `not tracked locally (server rev ${revision})` : `server rev ${revision} != local rev ${local}`;
- devLog(`[VaultSync] Pull needed: manifest ${manifestId} ${reason}.`);
- return true;
- }
- }
+ const serverRevisions = toManifestRevisionMap(serverManifests);
+ const requiringPull = manifestsRequiringPull(serverRevisions, localRevisions);
- // Any manifest the client still tracks but the server no longer lists (removed / revoked).
- const removed = Object.keys(localRevisions).find(manifestId => !serverRevisions.has(manifestId));
- if (removed) {
- devLog(`[VaultSync] Pull needed: manifest ${removed} (local rev ${localRevisions[removed]}) no longer listed by the server (revoked/removed).`);
- return true;
+ if (requiringPull.length === 0) {
+ devLog(`[VaultSync] No pull needed: ${Object.keys(serverRevisions).length} manifest(s) all match local revisions.`);
+ return false;
}
- devLog(`[VaultSync] No pull needed: ${serverRevisions.size} manifest(s) all match local revisions.`);
- return false;
+ /** One manifest as `id (local rev X, server rev Y)`, with "untracked"/"unlisted" for a one-sided manifest. */
+ const describe = (manifestId: string): string => `${manifestId} (local ${localRevisions[manifestId] ?? 'untracked'}, server ${serverRevisions[manifestId] ?? 'unlisted'})`;
+ devLog(`[VaultSync] Pull needed for ${requiringPull.length} manifest(s): ${requiringPull.map(describe).join(', ')}.`);
+ return true;
}
/**
@@ -250,8 +229,8 @@ type VaultPushOutcome = { status: number };
* Push the current SQLite vault to the server.
*
* @param sqliteClient - the in-memory SQLite client to upload
- * @param options - forceFullWrite bypasses the content-fingerprint gating and rewrites every manifest and bucket
- * (server rollback recovery); createVaultKey mints the VEK as part of this push (KEK/VEK migration)
+ * @param options - forceFullWrite bypasses the content-fingerprint gating and rewrites every manifest and bucket;
+ * createVaultKey mints the VEK as part of this push (KEK/VEK migration)
*/
async function pushVaultToServer(sqliteClient: SqliteClient, options: { forceFullWrite: boolean; createVaultKey: boolean }): Promise<VaultPushOutcome> {
const encryptionKey = await handleGetEncryptionKey();
@@ -383,8 +362,7 @@ export async function handleLockVault(): Promise<messageBoolResponse> {
}
/**
- * Clear session data (tokens and ephemeral data).
- * This is safe to call during forced logout as it preserves vault data.
+ * Clear session data: tokens, ephemeral data and the vault itself.
*/
export async function handleClearSession(): Promise<messageBoolResponse> {
// Clear auth tokens and last sync error
@@ -393,6 +371,9 @@ export async function handleClearSession(): Promise<messageBoolResponse> {
// Clear session-only data (security: encryption key must not persist)
await storage.removeItems([...SESSION_STORAGE_KEYS]);
+ // Clear the vault and every piece of state derived from it (sync bookkeeping, dirty flags, blob cache).
+ await storage.removeItems(vaultDataStorageKeys());
+
// Reset password unlock failed attempts counter on logout
await LocalPreferencesService.resetPasswordUnlockFailedAttempts();
@@ -408,8 +389,11 @@ export async function handleClearSession(): Promise<messageBoolResponse> {
* This removes all persistent vault storage and local preferences.
*/
export async function handleClearVaultData(): Promise<messageBoolResponse> {
- // Clear vault data and every piece of state derived from it (sync bookkeeping, dirty flags, bucket revisions)
- await storage.removeItems(allVaultDataStorageKeys());
+ /*
+ * Clear vault data and every piece of state derived from it (sync bookkeeping, dirty flags, bucket revisions),
+ * plus the username, which a forced logout keeps for the login prefill and a user-initiated logout drops.
+ */
+ await storage.removeItems([...vaultDataStorageKeys(), StorageKeys.USERNAME]);
// Clear all local preferences (site settings, login save settings, etc.)
await LocalPreferencesService.clearAll();
@@ -780,9 +764,10 @@ async function uploadDirtyBucketsOnly(sqliteClient: SqliteClient, scopes: VaultM
* are pushed. A dirty 'manifest' scope (or a dirty state with no recorded scopes) triggers the full upload path,
* whose content-fingerprint gating then narrows the write down to the manifests/buckets that actually changed.
*
- * @param options - set forceFullWrite to rewrite every manifest and bucket regardless of change detection
- * (server rollback recovery); set createVaultKey to mint the VEK as part of this push (the explicit storage
- * migration passes this, and it is the only caller that should)
+ * @param options - set forceFullWrite to rewrite every manifest and bucket regardless of change detection, for when
+ * the fingerprints cannot be trusted to describe the server's state (the legacy storage-format guard is the only
+ * caller); set createVaultKey to mint the VEK as part of this push (the explicit storage migration passes this,
+ * and it is the only caller that should)
*/
export async function handleUploadVault(
options?: { forceFullWrite?: boolean; createVaultKey?: boolean }
@@ -1416,16 +1401,9 @@ async function handleFullVaultSyncInternal(): Promise<FullVaultSyncResult> {
// Get current sync state
const syncState = await handleGetSyncState();
- const localRevisions = await getManifestRevisions();
- const personalManifestId = await getPersonalManifestId();
- const serverManifestRevision = personalManifestRevision(statusResponse);
- const localManifestRevision = personalManifestId ? localRevisions[personalManifestId] ?? 0 : 0;
-
- // A personal manifest that went backwards is a rolled-back server (restored backup), which we want to re-push.
- const serverRolledBack = serverManifestRevision < localManifestRevision;
- const needsPull = !serverRolledBack && serverManifestsNeedPull(statusResponse.manifestRevisions, localRevisions);
+ const needsPull = serverManifestsNeedPull(statusResponse.manifestRevisions, await getManifestRevisions());
- devLog(`[VaultSync] Status received (server main rev ${serverManifestRevision}, local rev ${localManifestRevision}, needsPull ${needsPull}, isDirty ${syncState.isDirty})`);
+ devLog(`[VaultSync] Status received (needsPull ${needsPull}, isDirty ${syncState.isDirty})`);
// Check if server is actually available (0.0.0 indicates connection error)
if (statusResponse.serverVersion === '0.0.0') {
@@ -1514,8 +1492,9 @@ async function handleFullVaultSyncInternal(): Promise<FullVaultSyncResult> {
try {
if (syncState.isDirty) {
/*
- * We have local changes AND server has newer vault.
- * Merge local vault with server vault, then upload the merged result.
+ * The server moved on some manifest while the local vault holds unpushed changes. Merge the local vault
+ * onto the freshly pulled one and upload the result; the push then writes exactly the manifests whose
+ * merged content differs from what the server just served.
*/
const localEncryptedVault = await storage.getItem(StorageKeys.ENCRYPTED_VAULT) as string | null;
@@ -1635,65 +1614,29 @@ async function handleFullVaultSyncInternal(): Promise<FullVaultSyncResult> {
AppErrorCode.VAULT_DECRYPT_FAILED
));
}
- } else if (serverManifestRevision === localManifestRevision) {
- /**
- * Server and local vault are at the same revision.
- * If we have pending local changes, upload them now.
- */
- if (syncState.isDirty) {
- const uploadResponse = await handleUploadVault();
- if (uploadResponse.success && uploadResponse.status === 0) {
- await handleMarkVaultClean({ mutationSeqAtStart: uploadResponse.mutationSeqAtStart! });
-
- /*
- * If expired trash items were pruned during upload, report the vault as new
- * so the popup reloads the pruned vault instead of resurrecting the items
- * from its stale in-memory copy on the next mutation.
- */
- return { success: true, hasNewVault: uploadResponse.vaultPruned === true, wasOffline: false, sqliteBlobUpgradeRequired: false, requiresLogout: false };
- } else if (uploadResponse.status === 2) {
- /**
- * Server returned Outdated - another device uploaded first.
- * Recursively call sync to fetch, merge, and retry.
- */
- return handleFullVaultSync();
- } else {
- console.error('Failed to upload pending vault:', uploadResponse.error);
- return { success: false, hasNewVault: false, wasOffline: false, sqliteBlobUpgradeRequired: false, requiresLogout: false, error: uploadResponse.error };
- }
- }
-
- return { success: true, hasNewVault: false, wasOffline: false, sqliteBlobUpgradeRequired: false, requiresLogout: false };
- } else if (serverRolledBack) {
+ } else if (syncState.isDirty) {
/**
- * Server revision DECREASED - server data loss/rollback detected.
- * Client has more advanced revision - upload to recover server state.
+ * Server and client agree on every manifest revision, so the pending local changes upload as-is.
*/
- console.warn(
- `Server data loss detected! Server at rev ${serverManifestRevision}, ` +
- `client at rev ${localManifestRevision}. Uploading to recover server state.`
- );
-
- /*
- * Force a full write: the server's content is behind the client's baselines, so the fingerprint gating
- * would wrongly report "unchanged" and skip exactly the targets that need to be restored.
- */
- const uploadResponse = await handleUploadVault({ forceFullWrite: true });
-
+ const uploadResponse = await handleUploadVault();
if (uploadResponse.success && uploadResponse.status === 0) {
await handleMarkVaultClean({ mutationSeqAtStart: uploadResponse.mutationSeqAtStart! });
- console.info(`Server recovery complete: server restored from client state (was at personal rev ${serverManifestRevision}, client at ${localManifestRevision}).`);
-
+ /*
+ * If expired trash items were pruned during upload, report the vault as new
+ * so the popup reloads the pruned vault instead of resurrecting the items
+ * from its stale in-memory copy on the next mutation.
+ */
return { success: true, hasNewVault: uploadResponse.vaultPruned === true, wasOffline: false, sqliteBlobUpgradeRequired: false, requiresLogout: false };
} else if (uploadResponse.status === 2) {
- // Another client recovered first
- devLog('[VaultSync] Another client recovered server first, re-syncing...');
+ /**
+ * Server returned Outdated - another device uploaded first.
+ * Recursively call sync to fetch, merge, and retry.
+ */
return handleFullVaultSync();
} else {
- console.error('Server recovery failed:', uploadResponse.error);
- // E-801: Upload failed during server recovery - preserve the upload error detail when available
- return { success: false, hasNewVault: false, wasOffline: false, sqliteBlobUpgradeRequired: false, requiresLogout: false, error: uploadResponse.error ?? formatErrorWithCode(await t('common.errors.unknownError'), AppErrorCode.UPLOAD_FAILED) };
+ console.error('Failed to upload pending vault:', uploadResponse.error);
+ return { success: false, hasNewVault: false, wasOffline: false, sqliteBlobUpgradeRequired: false, requiresLogout: false, error: uploadResponse.error };
}
}
diff --git a/apps/browser-extension/src/entrypoints/popup/context/AppContext.tsx b/apps/browser-extension/src/entrypoints/popup/context/AppContext.tsx
index bb5749a2c..b1b4ebed9 100644
--- a/apps/browser-extension/src/entrypoints/popup/context/AppContext.tsx
+++ b/apps/browser-extension/src/entrypoints/popup/context/AppContext.tsx
@@ -45,7 +45,7 @@ export const AppProvider: React.FC<{ children: React.ReactNode }> = ({ children
try {
isLoggingOutRef.current = true;
await webApi.revokeTokens();
- // Use forced logout to preserve orphaned vault
+ // Use forced logout, which keeps the username for the login prefill
await auth.clearAuthForced(errorMessage);
} catch (error) {
console.error('Error during logout:', error);
diff --git a/apps/browser-extension/src/entrypoints/popup/context/AuthContext.tsx b/apps/browser-extension/src/entrypoints/popup/context/AuthContext.tsx
index 179a576ee..77c69b14a 100644
--- a/apps/browser-extension/src/entrypoints/popup/context/AuthContext.tsx
+++ b/apps/browser-extension/src/entrypoints/popup/context/AuthContext.tsx
@@ -69,15 +69,15 @@ export const AuthProvider: React.FC<{ children: React.ReactNode }> = ({ children
/**
* Clear authentication data and tokens from storage (forced logout).
* This is called when the server forces a logout (401, token revocation, password change).
- * Preserves the encrypted vault + metadata for recovery on next login.
- * Keeps username for login page prefill and vault ownership verification.
+ * Clears the encrypted vault and everything derived from it; the next login pulls a fresh one.
+ * Keeps username for login page prefill, and the local preferences.
*
* This is the base logout function. clearAuthUserInitiated builds on top of this.
*
* @param errorMessage Optional error message to display on the login page
*/
const clearAuthForced = useCallback(async (errorMessage?: string) : Promise<void> => {
- // Clear session data (tokens + ephemeral data) - vault data is preserved for recovery
+ // Clear session data: tokens, ephemeral data and the vault itself
await sendMessage('CLEAR_SESSION');
// Clear in-memory database reference
@@ -101,15 +101,15 @@ export const AuthProvider: React.FC<{ children: React.ReactNode }> = ({ children
* Clear authentication data and tokens from storage (user-initiated logout).
* This is called when the user explicitly clicks the logout button.
*
- * Builds on clearAuthForced by also clearing vault data and username.
+ * Builds on clearAuthForced by also clearing the username and the local preferences.
*
* @param errorMessage Optional error message to display on the login page
*/
const clearAuthUserInitiated = useCallback(async (errorMessage?: string) : Promise<void> => {
- // First, perform the base forced logout (clears session, in-memory db, PIN)
+ // First, perform the base forced logout (clears session, vault, in-memory db, PIN)
await clearAuthForced(errorMessage);
- // Additionally clear vault data and username (forced logout preserves these for recovery)
+ // Additionally clear the username and local preferences, which a forced logout keeps
await sendMessage('CLEAR_VAULT_DATA');
setUsername(null);
diff --git a/apps/browser-extension/src/entrypoints/popup/pages/auth/Login.tsx b/apps/browser-extension/src/entrypoints/popup/pages/auth/Login.tsx
index 13f2465ba..3eee24d2f 100644
--- a/apps/browser-extension/src/entrypoints/popup/pages/auth/Login.tsx
+++ b/apps/browser-extension/src/entrypoints/popup/pages/auth/Login.tsx
@@ -21,7 +21,6 @@ import { SrpAuthService } from '@/utils/auth/SrpAuthService';
import { StorageKeys } from '@/utils/constants/storageKeys';
import type { VaultResponse, LoginResponse } from '@/utils/dist/core/models/webapi';
import { EncryptionUtility } from '@/utils/EncryptionUtility';
-import { getManifestRevisions } from '@/utils/ManifestRevisions';
import { sendMessage } from '@/utils/messaging/ExtensionMessaging';
import { ApiAuthError } from '@/utils/types/errors/ApiAuthError';
import { hasErrorCode, getErrorMessage } from '@/utils/types/errors/AppErrorCodes';
@@ -41,19 +40,6 @@ let usernamePrefillAttempted = false;
/** Track if 2FA state restoration has been attempted (only do it once on mount) */
let twoFactorStateRestoreAttempted = false;
-/**
- * Whether the local vault's last-known baselines cover everything the server holds: every server manifest is known
- * locally at the same (or a higher, i.e. server rolled back) revision, and the local vault tracks no manifest the
- * server has since removed (revoked share). Only then is preserving the local blob over the freshly pulled one safe.
- * @param localRevisions - the per-manifest baselines the local blob was built from (captured before the pull)
- * @param serverRevisions - the server's per-manifest revisions (what the pull just stored)
- */
-const localVaultCoversServer = (localRevisions: Record<string, number>, serverRevisions: Record<string, number>): boolean => {
- const serverCovered = Object.entries(serverRevisions).every(([manifestId, revision]) => (localRevisions[manifestId] ?? -1) >= revision);
- const nothingRevoked = Object.keys(localRevisions).every(manifestId => manifestId in serverRevisions);
- return serverCovered && nothingRevoked;
-};
-
/**
* Login page
*/
@@ -83,57 +69,10 @@ const Login: React.FC = () => {
const srpUtil = new SrpUtility(webApi);
/**
- * Helper to persist and load vault after successful authentication.
- * Checks if local vault exists from forced logout and preserves it if it still covers everything the server holds.
- * Also checks if the vault belongs to the same user - if different user, uses server vault.
- * @param preLoginRevisions - the per-manifest baselines as they were BEFORE the pull: the pull replaces the stored
- * map with the server's, so this captured copy is the only record of what the local blob was built from.
+ * Persist and load the vault the pull just produced. A login always adopts the server's vault as-is: logging out
+ * clears the local one either way, so there is never a second candidate to choose between here.
*/
- const persistAndLoadVault = async (vaultResponse: VaultResponse, encryptionKey: string, loginUsername: string, preLoginRevisions: Record<string, number>): Promise<void> => {
- // Check if there's existing vault data (from forced logout)
- const existingVault = await storage.getItem(StorageKeys.ENCRYPTED_VAULT) as string | null;
- const storedUsername = await storage.getItem(StorageKeys.USERNAME) as string | null;
-
- if (existingVault && Object.keys(preLoginRevisions).length > 0) {
- // Check if the existing vault belongs to a different user
- const normalizedLoginUsername = loginUsername.toLowerCase().trim();
- const normalizedStoredUsername = storedUsername?.toLowerCase().trim();
-
- if (storedUsername && normalizedStoredUsername !== normalizedLoginUsername) {
- // Different user
- console.info(
- `Existing vault belongs to different user (${storedUsername}), using server vault for ${loginUsername}`
- );
- } else {
- // Same user (or no stored username)
- try {
- const decryptedExisting = await EncryptionUtility.symmetricDecrypt(existingVault, encryptionKey);
-
- // The pull stored the server's per-manifest revisions; compare them against the pre-login baselines.
- if (localVaultCoversServer(preLoginRevisions, await getManifestRevisions())) {
- console.info('Existing local vault covers every server manifest, preserving it (pending local changes upload on the next sync)');
-
- // Update metadata and load existing vault
- await sendMessage('STORE_VAULT_METADATA', {
- publicEmailDomainList: vaultResponse.vault.publicEmailDomainList,
- privateEmailDomainList: vaultResponse.vault.privateEmailDomainList,
- hiddenPrivateEmailDomainList: vaultResponse.vault.hiddenPrivateEmailDomainList,
- });
-
- await dbContext.loadDatabase(decryptedExisting);
- return;
- }
-
- // Server is more advanced, fetch server vault
- console.info('Server has manifests ahead of (or unknown to) the local baselines, using server vault');
- } catch {
- // Decryption failed, password changed or corrupt vault
- console.info('Existing vault could not be decrypted (password changed), using server vault');
- }
- }
- }
-
- // Normal flow: persist server vault to local storage. The pull already recorded the per-manifest revisions.
+ const persistAndLoadVault = async (vaultResponse: VaultResponse, encryptionKey: string): Promise<void> => {
await sendMessage('STORE_ENCRYPTED_VAULT', { vaultBlob: vaultResponse.vault.blob });
await sendMessage('STORE_VAULT_METADATA', {
@@ -143,8 +82,7 @@ const Login: React.FC = () => {
});
// Decrypt and load the vault into memory
- const decryptedVault = await EncryptionUtility.symmetricDecrypt(vaultResponse.vault.blob, encryptionKey);
- await dbContext.loadDatabase(decryptedVault);
+ await dbContext.loadDatabase(await EncryptionUtility.symmetricDecrypt(vaultResponse.vault.blob, encryptionKey));
};
/**
@@ -174,21 +112,11 @@ const Login: React.FC = () => {
encryptionSettings: loginResponse.encryptionSettings
});
- // Capture the pre-pull revision baselines: the pull below replaces the stored map with the server's.
- const preLoginRevisions = await getManifestRevisions();
-
// Fetch the latest vault.
const vaultResponseJson = await vaultSyncService.pull(encryptionKey);
- /*
- * Persist and load the vault.
- * If there was a forced logout, persistAndLoadVault checks existing vault data:
- * - If different user > uses server vault
- * - If local vault still covers the server state > preserves it (will upload via sync in /reinitialize)
- * - If server is more advanced > uses server vault
- * - If password changed (can't decrypt) > uses server vault
- */
- await persistAndLoadVault(vaultResponseJson, encryptionKey, username, preLoginRevisions);
+ // Persist and load the vault.
+ await persistAndLoadVault(vaultResponseJson, encryptionKey);
// Reset prefill flag so next logout will prefill again
usernamePrefillAttempted = false;
@@ -484,14 +412,11 @@ const Login: React.FC = () => {
encryptionSettings: result.encryptionSettings,
});
- // Capture the pre-pull revision baselines: the pull below replaces the stored map with the server's.
- const preLoginRevisions = await getManifestRevisions();
-
// Fetch the latest vault.
const vaultResponse = await vaultSyncService.pull(mobileKey);
// Persist and load the vault
- await persistAndLoadVault(vaultResponse, mobileKey, result.username, preLoginRevisions);
+ await persistAndLoadVault(vaultResponse, mobileKey);
/*
* Navigate to reinitialize page which will:
diff --git a/apps/browser-extension/src/utils/ManifestRevisions.ts b/apps/browser-extension/src/utils/ManifestRevisions.ts
index a33829323..325d5ffb8 100644
--- a/apps/browser-extension/src/utils/ManifestRevisions.ts
+++ b/apps/browser-extension/src/utils/ManifestRevisions.ts
@@ -7,6 +7,33 @@
import { storage } from 'wxt/utils/storage';
import { StorageKeys } from '@/utils/constants/storageKeys';
+import type { ManifestRevision } from '@/utils/dist/core/models/webapi';
+
+/**
+ * Index a revision list as reported by the server (status call) by manifest id.
+ * @param revisions - the per-manifest revisions from the server
+ */
+export function toManifestRevisionMap(revisions: ManifestRevision[] | null | undefined): Record<string, number> {
+ return Object.fromEntries((revisions ?? []).map(m => [m.manifestId, m.revision]));
+}
+
+/**
+ * The manifests whose local state no longer matches what the server reports, so the client has to pull and
+ * re-materialize. Every manifest is judged on its own, the personal one included: the server reports it by id like
+ * any other, and with shared folders in play only some of them move at a time.
+ *
+ * Idempotent: right after a successful materialize both maps match, so this returns nothing until the next change.
+ * @param serverRevisions - the server's current revision per manifest
+ * @param localRevisions - the client's last-known revision per manifest
+ */
+export function manifestsRequiringPull(serverRevisions: Record<string, number>, localRevisions: Record<string, number>): string[] {
+ const requiringPull = Object.keys(serverRevisions).filter(manifestId => localRevisions[manifestId] !== serverRevisions[manifestId]);
+
+ // A manifest the client still tracks but the server no longer lists was removed or revoked; re-materializing drops it.
+ requiringPull.push(...Object.keys(localRevisions).filter(manifestId => !(manifestId in serverRevisions)));
+
+ return requiringPull;
+}
/**
* Every manifest's last-known server revision, keyed by manifest id; empty when nothing has been pulled yet.
diff --git a/apps/browser-extension/src/utils/constants/legacyStorageKeys.ts b/apps/browser-extension/src/utils/constants/legacyStorageKeys.ts
index 98df3d574..97f341850 100644
--- a/apps/browser-extension/src/utils/constants/legacyStorageKeys.ts
+++ b/apps/browser-extension/src/utils/constants/legacyStorageKeys.ts
@@ -31,7 +31,7 @@ export const LegacyStorageKeys = {
} as const satisfies Record<string, StorageKey>;
/**
- * Legacy keys holding vault data or state derived from it, spread into `allVaultDataStorageKeys()` so a logout
+ * Legacy keys holding vault data or state derived from it, spread into `vaultDataStorageKeys()` so a logout
* clears them alongside the current ones.
*/
export const LEGACY_VAULT_DATA_STORAGE_KEYS: readonly StorageKey[] = [
diff --git a/apps/browser-extension/src/utils/constants/storageKeys.ts b/apps/browser-extension/src/utils/constants/storageKeys.ts
index 8f3482c97..00d7aa493 100644
--- a/apps/browser-extension/src/utils/constants/storageKeys.ts
+++ b/apps/browser-extension/src/utils/constants/storageKeys.ts
@@ -197,10 +197,7 @@ export const dirtyScopeStorageKey = (scope: VaultMutationScope): `local:${string
*/
export const bucketRevisionKey = (manifestId: string, category: string): string => `${manifestId}:${category}`;
-/**
- * Keys that hold auth tokens and ephemeral error state. Cleared on logout; safe to clear during a forced
- * logout because no vault data is lost.
- */
+/** Keys that hold auth tokens and ephemeral error state. Cleared on any logout. */
export const AUTH_STORAGE_KEYS: readonly StorageKey[] = [
StorageKeys.ACCESS_TOKEN,
StorageKeys.REFRESH_TOKEN,
@@ -250,10 +247,11 @@ export const LOCAL_PREFERENCE_STORAGE_KEYS: readonly StorageKey[] = [
];
/**
- * Every key holding vault data or state derived from it, including the per-scope dynamic keys. Cleared when
- * the vault itself is cleared (logout), so no state from the previous account can leak into the next one.
+ * Every key holding vault data or state derived from it, including the per-scope dynamic keys. Cleared on ANY
+ * logout, forced or user-initiated: a session's vault never outlives it, so no stale blob, revision baseline or
+ * dirty flag can meet the vault the next login pulls.
*/
-export const allVaultDataStorageKeys = (): StorageKey[] => [
+export const vaultDataStorageKeys = (): StorageKey[] => [
StorageKeys.ENCRYPTED_VAULT,
StorageKeys.PUBLIC_EMAIL_DOMAINS,
StorageKeys.PRIVATE_EMAIL_DOMAINS,
@@ -273,7 +271,6 @@ export const allVaultDataStorageKeys = (): StorageKey[] => [
StorageKeys.ENCRYPTED_ACCOUNT_KEY,
StorageKeys.ACCOUNT_PUBLIC_KEY,
StorageKeys.ENCRYPTED_ACCOUNT_PRIVATE_KEY,
- StorageKeys.USERNAME,
...ALL_VAULT_MUTATION_SCOPES.map(scope => dirtyScopeStorageKey(scope)),
...LEGACY_VAULT_DATA_STORAGE_KEYS,
];