Skip to content

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

Simplify v2 handshake as storage migration combines VEK/KEK migration (#2159)

Leendert de Borstf75c5e2809df
diff --git a/apps/browser-extension/src/entrypoints/background/VaultMessageHandler.ts b/apps/browser-extension/src/entrypoints/background/VaultMessageHandler.ts
index 4797392a1..44b460766 100644
--- a/apps/browser-extension/src/entrypoints/background/VaultMessageHandler.ts
+++ b/apps/browser-extension/src/entrypoints/background/VaultMessageHandler.ts
@@ -275,12 +275,11 @@ async function uploadVaultV2(sqliteClient: SqliteClient): Promise<VaultPostRespo
const emailAddresses = await getEmailAddressesForVault(sqliteClient);
/*
- * KEK/VEK migration: when the server has no vault key yet, this push generates a VEK, re-encrypts everything
- * with it, and creates the vault key server-side (wrapping the VEK with the current password-derived key).
- * Guarded on vaultKeySupported: a server that predates vault keys would silently drop createVaultKey while
- * storing the VEK-encrypted payload, which would strand every other device. Such servers get a normal push.
+ * KEK/VEK migration: a not-yet-migrated (legacy sqlite-blob) user has no vault key, so their first manifest
+ * upload generates a VEK, re-encrypts everything with it, and creates the vault key server-side (wrapping the
+ * VEK with the current password-derived key).
*/
- const result = await vaultSyncService.push(sqliteClient, encryptionKey, username, emailAddresses, { createVaultKey: syncStatus.vaultKeySupported && !syncStatus.hasVaultKey });
+ const result = await vaultSyncService.push(sqliteClient, encryptionKey, username, emailAddresses, { createVaultKey: !syncStatus.isMigrated });
if (result.status === 'ok') {
if (result.newEncryptionKey) {
@@ -822,12 +821,12 @@ async function uploadDirtyBucketsOnly(sqliteClient: SqliteClient, scopes: VaultM
}
/*
- * A bucket-only push encrypts with the current session key. As long as the user has no vault key yet, the full
- * upload path must run instead so the KEK/VEK migration re-keys the whole vault in one atomic request.
+ * A bucket-only push encrypts with the current session key. A not-yet-migrated user has no vault key yet, so the
+ * full upload path must run instead to re-key the whole vault (KEK/VEK migration) in one atomic request.
*/
const syncStatus = await vaultSyncService.checkStatus();
- if (syncStatus.vaultKeySupported && !syncStatus.hasVaultKey) {
- devLog('[V2Push] User has no vault key yet, falling back to full vault upload to run the KEK/VEK migration.');
+ if (!syncStatus.isMigrated) {
+ devLog('[V2Push] User not yet migrated (no vault key), falling back to full vault upload to run the KEK/VEK migration.');
return (await uploadNewVaultToServer(sqliteClient)).response;
}
@@ -1272,14 +1271,19 @@ export async function handleGetServerRevision(): Promise<number> {
}
/**
- * Adopt a vault key created by another device (KEK/VEK migration race, or another client migrating while this one
- * holds a live session). When the server reports a vault key but this session still holds the raw password-derived
- * key (recognizable by the missing cached wrapped VEK), fetch the vault key, unwrap the VEK with the derived key,
- * swap the session key, and re-encrypt the locally persisted vault with the VEK. Returns false when adoption fails
- * (VEK cannot be unwrapped with the current session key): the caller must force a re-login.
- * @param statusResponse - the status response from the server
+ * Catch this device up when ANOTHER device performed the KEK/VEK migration.
+ *
+ * After another device migrates, the server reports hasVaultKey=true but this device may still be holding the old
+ * password-derived key (the KEK) as its session key, with no cached wrapped VEK. Rather than force a re-login, this
+ * fetches the wrapped VEK, unwraps it with the session key (= the KEK), re-encrypts the locally persisted vault
+ * under the VEK, swaps the session key to the VEK, and caches the wrapped VEK. A no-op when there is nothing to
+ * adopt (no server key, already on the VEK, or vault locked).
+ *
+ * TODO: this method can be removed once all users have migrated to the KEK/VEK model.
+ *
+ * @param statusResponse - the status response from the server (hasVaultKey signals another device migrated)
*/
-async function adoptRemoteVaultKeyIfNeeded(statusResponse: StatusResponseV2): Promise<boolean> {
+async function catchUpAfterRemoteVaultKeyMigration(statusResponse: StatusResponseV2): Promise<boolean> {
if (statusResponse.hasVaultKey !== true) {
return true;
}
@@ -1400,8 +1404,8 @@ export async function handleCheckSyncStatus(): Promise<SyncStatusCheckResult> {
return { success: false, hasNewerVault: false, hasDirtyChanges: false, isOffline: false, requiresLogout: true, errorKey: 'passwordChanged' };
}
- // Adopt a vault key created by another device before any sync work happens.
- if (!await adoptRemoteVaultKeyIfNeeded(statusResponse)) {
+ // If another device performed the KEK/VEK migration, catch up before any sync work happens.
+ if (!await catchUpAfterRemoteVaultKeyMigration(statusResponse)) {
return { success: false, hasNewerVault: false, hasDirtyChanges: false, isOffline: false, requiresLogout: true, errorKey: 'passwordChanged' };
}
@@ -1533,8 +1537,8 @@ async function handleFullVaultSyncInternal(): Promise<FullVaultSyncResult> {
return { success: false, hasNewVault: false, wasOffline: false, upgradeRequired: false, requiresLogout: true, errorKey: 'passwordChanged' };
}
- // Adopt a vault key created by another device before any sync work happens.
- if (!await adoptRemoteVaultKeyIfNeeded(statusResponse)) {
+ // If another device performed the KEK/VEK migration, catch up before any sync work happens.
+ if (!await catchUpAfterRemoteVaultKeyMigration(statusResponse)) {
return { success: false, hasNewVault: false, wasOffline: false, upgradeRequired: false, requiresLogout: true, errorKey: 'passwordChanged' };
}
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 f3dc1b7c5..e88bf8b49 100644
--- a/apps/browser-extension/src/entrypoints/popup/pages/auth/Login.tsx
+++ b/apps/browser-extension/src/entrypoints/popup/pages/auth/Login.tsx
@@ -467,7 +467,7 @@ const Login: React.FC = () => {
* keeps working, then upgrade the received key to the VEK when it turns out to be the KEK.
*/
await VaultKeyService.cacheWrappedVekFromServer(webApi);
- const { key: mobileKey } = await VaultKeyService.upgradeStoredKeyIfNeeded(result.decryptionKey);
+ const mobileKey = await VaultKeyService.resolveStoredUnlockKey(result.decryptionKey);
// Store the encryption key and derivation params
await dbContext.storeEncryptionKey(mobileKey);
diff --git a/apps/browser-extension/src/entrypoints/popup/pages/auth/Unlock.tsx b/apps/browser-extension/src/entrypoints/popup/pages/auth/Unlock.tsx
index ecc5b5985..9fcfbeb1e 100644
--- a/apps/browser-extension/src/entrypoints/popup/pages/auth/Unlock.tsx
+++ b/apps/browser-extension/src/entrypoints/popup/pages/auth/Unlock.tsx
@@ -426,14 +426,10 @@ const Unlock: React.FC = () => {
/*
* KEK/VEK: when the PIN was set up before the vault key migration, the PIN-protected key is the old
- * password-derived key (now the KEK). Upgrade to the VEK and refresh the PIN store so future PIN unlocks
+ * password-derived key (now the KEK). Upgrade to the VEK and re-seal the PIN store so future PIN unlocks
* return the VEK directly.
*/
- const upgrade = await VaultKeyService.upgradeStoredKeyIfNeeded(passwordHashBase64);
- if (upgrade.upgraded) {
- passwordHashBase64 = upgrade.key;
- await setupPin(pinToUse, passwordHashBase64);
- }
+ passwordHashBase64 = await VaultKeyService.resolveStoredUnlockKey(passwordHashBase64, key => setupPin(pinToUse, key));
// Check if we're online or offline (for offline mode flag)
const statusResult = await checkStatus();
@@ -587,7 +583,7 @@ const Unlock: React.FC = () => {
* keeps working, then upgrade the received key to the VEK when it turns out to be the KEK.
*/
await VaultKeyService.cacheWrappedVekFromServer(webApi);
- const { key: mobileKey } = await VaultKeyService.upgradeStoredKeyIfNeeded(result.decryptionKey);
+ const mobileKey = await VaultKeyService.resolveStoredUnlockKey(result.decryptionKey);
// Store the encryption key and derivation params
await dbContext.storeEncryptionKey(mobileKey);
diff --git a/apps/browser-extension/src/utils/VaultKeyService.ts b/apps/browser-extension/src/utils/VaultKeyService.ts
index def8ba075..7e42a237a 100644
--- a/apps/browser-extension/src/utils/VaultKeyService.ts
+++ b/apps/browser-extension/src/utils/VaultKeyService.ts
@@ -127,10 +127,24 @@ export class VaultKeyService {
}
/**
- * Given a key restored from an auxiliary unlock method (PIN, mobile QR), return the key to actually use.
+ * Resolve the key to actually use for a local additional unlock method (PIN, mobile QR), upgrading a pre-migration
+ * stored key (the old KEK) to the VEK when needed.
* @param storedKey - the key restored from the auxiliary unlock method
+ * @param onUpgraded - optional callback invoked with the upgraded VEK when the stored key was the old KEK
*/
- public static async upgradeStoredKeyIfNeeded(storedKey: string): Promise<{ key: string; upgraded: boolean }> {
+ public static async resolveStoredUnlockKey(storedKey: string, onUpgraded?: (vek: string) => Promise<void>): Promise<string> {
+ const { key, upgraded } = await VaultKeyService.upgradeStoredKeyIfNeeded(storedKey);
+ if (upgraded && onUpgraded) {
+ await onUpgraded(key);
+ }
+ return key;
+ }
+
+ /**
+ * Given a key restored from an auxiliary unlock method (PIN, mobile QR), return the key to actually use and whether it was upgraded.
+ * @param storedKey - the key restored from the auxiliary unlock method
+ */
+ private static async upgradeStoredKeyIfNeeded(storedKey: string): Promise<{ key: string; upgraded: boolean }> {
const wrappedVek = await storage.getItem(WRAPPED_VEK_STORAGE_KEY) as string | null;
if (!wrappedVek) {
return { key: storedKey, upgraded: false };
diff --git a/apps/browser-extension/src/utils/VaultSyncService.ts b/apps/browser-extension/src/utils/VaultSyncService.ts
index 2fab67a07..e06395ac2 100644
--- a/apps/browser-extension/src/utils/VaultSyncService.ts
+++ b/apps/browser-extension/src/utils/VaultSyncService.ts
@@ -114,16 +114,10 @@ const SETTINGS_BUCKET_CATEGORY = VaultDataBucketCategory.Settings;
* Status response from the server.
*/
export type VaultSyncStatus = {
- /** Whether the user has been migrated to manifest-v1 storage (false = still legacy, migrate on next save). */
- isMigrated: boolean;
- /** Whether the user has a vault key (KEK/VEK model). False = the next full upload must carry createVaultKey. */
- hasVaultKey: boolean;
/**
- * Whether the server understands vault keys at all (the hasVaultKey field was present in its status response).
- * A KEK/VEK migration must never be attempted against a server that would silently drop createVaultKey: the
- * upload would be VEK-encrypted while the wrapped VEK is never stored, stranding every other device.
+ * Whether the user has been migrated to manifest-v1 storage (false = still legacy, migrate on next save).
*/
- vaultKeySupported: boolean;
+ isMigrated: boolean;
manifestRevision: number | null;
settingsRevision: number | null;
};
@@ -226,7 +220,6 @@ type StatusResponseDto = {
storageFormat: number;
manifestRevisions: ManifestRevisionDto[];
bucketRevisions: BucketRevisionDto[];
- hasVaultKey?: boolean;
};
type UploadResponseDto = {
@@ -306,8 +299,6 @@ export class VaultSyncService {
const rootManifestRevision = revisions.find(m => m.isRoot)?.revision ?? null;
return {
isMigrated: dto.storageFormat === STORAGE_FORMAT_MANIFEST,
- hasVaultKey: dto.hasVaultKey === true,
- vaultKeySupported: dto.hasVaultKey !== undefined,
manifestRevision: rootManifestRevision,
settingsRevision,
};
diff --git a/apps/server/AliasVault.Api/Controllers/V2/VaultController.cs b/apps/server/AliasVault.Api/Controllers/V2/VaultController.cs
index bd501e1cd..6463fef0b 100644
--- a/apps/server/AliasVault.Api/Controllers/V2/VaultController.cs
+++ b/apps/server/AliasVault.Api/Controllers/V2/VaultController.cs
@@ -86,14 +86,11 @@ public class VaultController(
.Select(g => new BucketRevision { Category = g.Key, Revision = g.Max(b => b.RevisionNumber) })
.ToListAsync();
- var hasVaultKey = await context.VaultKeys.AnyAsync(x => x.UserId == user.Id && x.KeyType == AuthHelper.VaultKeyTypePassword);
-
return Ok(new StatusResponse
{
StorageFormat = manifestRevisions.Count > 0 ? StorageFormat.Manifest : StorageFormat.SqliteBlob,
ManifestRevisions = manifestRevisions,
BucketRevisions = bucketRevisions,
- HasVaultKey = hasVaultKey,
});
}
@@ -295,6 +292,13 @@ public class VaultController(
return BadRequest(ApiErrorCodeHelper.CreateValidationErrorResponse(ApiErrorCode.VAULT_KEY_ALREADY_EXISTS, 400));
}
+ // Sanity check that the user has a vault key (when not providing vault key creation request).
+ // TODO: remove this guard once every user has migrated to the KEK/VEK model (no keyless users remain).
+ if (model.CreateVaultKey == null && !hasExistingVaultKey)
+ {
+ return BadRequest(ApiErrorCodeHelper.CreateValidationErrorResponse(ApiErrorCode.VAULT_KEY_NOT_FOUND, 400));
+ }
+
// The DbContext uses a retrying execution strategy (EnableRetryOnFailure), which forbids user-initiated
// transactions unless the whole unit runs inside the strategy so it can be retried atomically.
var strategy = context.Database.CreateExecutionStrategy();
diff --git a/apps/server/Shared/AliasVault.Shared/Models/WebApi/V2/Auth/StatusResponse.cs b/apps/server/Shared/AliasVault.Shared/Models/WebApi/V2/Auth/StatusResponse.cs
index 327650481..0c42df9fa 100644
--- a/apps/server/Shared/AliasVault.Shared/Models/WebApi/V2/Auth/StatusResponse.cs
+++ b/apps/server/Shared/AliasVault.Shared/Models/WebApi/V2/Auth/StatusResponse.cs
@@ -42,7 +42,8 @@ public class StatusResponse
public required string SrpSalt { get; set; }
/// <summary>
- /// Gets or sets a value indicating whether the user has a vault key.
+ /// Gets or sets a value indicating whether the user has a vault key (KEK/VEK model).
+ /// TODO: remove once every user has migrated to the KEK/VEK model.
/// </summary>
public bool HasVaultKey { get; set; }
}
diff --git a/apps/server/Shared/AliasVault.Shared/Models/WebApi/V2/Vault/StatusResponse.cs b/apps/server/Shared/AliasVault.Shared/Models/WebApi/V2/Vault/StatusResponse.cs
index fff812e33..7d5ca4e7b 100644
--- a/apps/server/Shared/AliasVault.Shared/Models/WebApi/V2/Vault/StatusResponse.cs
+++ b/apps/server/Shared/AliasVault.Shared/Models/WebApi/V2/Vault/StatusResponse.cs
@@ -20,8 +20,4 @@ public class StatusResponse
/// <summary>Gets or sets the latest revision for each data-bucket kind the user has. Empty when none stored.</summary>
public List<BucketRevision> BucketRevisions { get; set; } = [];
-
- /// <summary>Gets or sets a value indicating whether the user has a vault key (KEK/VEK model). When false the
- /// client must perform the KEK/VEK migration on its next full vault upload via <see cref="UploadRequest.CreateVaultKey"/>.</summary>
- public bool HasVaultKey { get; set; }
}