Skip to content

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

Refactor and move legacy logic to explicit legacy layer (#2159)

Leendert de Borst9be0b8e89ccf
diff --git a/apps/browser-extension/src/entrypoints/content.ts b/apps/browser-extension/src/entrypoints/content.ts
index 2e666e107..8e1a444da 100644
--- a/apps/browser-extension/src/entrypoints/content.ts
+++ b/apps/browser-extension/src/entrypoints/content.ts
@@ -555,10 +555,9 @@ export default defineContentScript({
/*
* Honour av-suppress-save: skip the popup (and the icon) when there is no stored entry
- * that would actually fill this specific field — credentials for the credentials popup,
- * TOTP-enabled credentials for the TOTP popup — so we don't invite the user to
- * "create new" on pages where storing isn't desired by default (e.g. AliasVault's own
- * login / unlock / Enable 2FA forms).
+ * that would actually fill this specific field. TOTP-enabled credentials for the TOTP
+ * popup so we don't invite the user to create new TOTP codes on pages where storing
+ * isn't desired by default (e.g. AliasVault's own login / unlock / Enable 2FA forms).
*/
if (isAvSuppressSave(inputElement) && !await hasMatchForCurrentUrl(popupType)) {
devLog('[Autofill] focusin skipped: av-suppress-save active and no matching vault items');
diff --git a/apps/browser-extension/src/entrypoints/popup/components/EmailPreview.tsx b/apps/browser-extension/src/entrypoints/popup/components/EmailPreview.tsx
index e52c7c8e8..a6807afd0 100644
--- a/apps/browser-extension/src/entrypoints/popup/components/EmailPreview.tsx
+++ b/apps/browser-extension/src/entrypoints/popup/components/EmailPreview.tsx
@@ -9,7 +9,7 @@ import { AppInfo } from '@/utils/AppInfo';
import { StorageKeys } from '@/utils/constants/storageKeys';
import type { ApiErrorResponse, MailboxEmail } from '@/utils/dist/core/models/webapi';
import { EncryptionUtility } from '@/utils/EncryptionUtility';
-import { getItemWithFallback } from '@/utils/StorageUtility';
+import { getStorageItem } from '@/utils/StorageUtility';
type EmailPreviewProps = {
email: string;
@@ -57,7 +57,7 @@ export const EmailPreview: React.FC<EmailPreviewProps> = ({ email }) => {
*/
const isPublicDomain = async (emailAddress: string): Promise<boolean> => {
// Get metadata from storage
- const publicEmailDomains = await getItemWithFallback<string[]>(StorageKeys.PUBLIC_EMAIL_DOMAINS) ?? [];
+ const publicEmailDomains = await getStorageItem<string[]>(StorageKeys.PUBLIC_EMAIL_DOMAINS) ?? [];
return publicEmailDomains.some(domain => emailAddress.toLowerCase().endsWith(`@${domain.toLowerCase()}`));
};
@@ -66,7 +66,7 @@ export const EmailPreview: React.FC<EmailPreviewProps> = ({ email }) => {
*/
const isPrivateDomain = async (emailAddress: string): Promise<boolean> => {
// Get metadata from storage
- const privateEmailDomains = await getItemWithFallback<string[]>(StorageKeys.PRIVATE_EMAIL_DOMAINS) ?? [];
+ const privateEmailDomains = await getStorageItem<string[]>(StorageKeys.PRIVATE_EMAIL_DOMAINS) ?? [];
return privateEmailDomains.some(domain => emailAddress.toLowerCase().endsWith(`@${domain.toLowerCase()}`));
};
diff --git a/apps/browser-extension/src/entrypoints/popup/components/Items/ItemFilterDropdown.tsx b/apps/browser-extension/src/entrypoints/popup/components/Items/ItemFilterDropdown.tsx
index e1c5ba584..b45369145 100644
--- a/apps/browser-extension/src/entrypoints/popup/components/Items/ItemFilterDropdown.tsx
+++ b/apps/browser-extension/src/entrypoints/popup/components/Items/ItemFilterDropdown.tsx
@@ -15,7 +15,7 @@ type ItemFilterDropdownProps = {
title: string;
/** Count shown next to the title on the trigger. Pass undefined to hide. */
count?: number;
- /** Currently active selection — used to highlight the matching menu row. */
+ /** Currently active selection used to highlight the matching menu row. */
activeFilter: ItemFilterSelection;
/** Number of items currently in the Recently Deleted page (badge). */
recentlyDeletedCount: number;
diff --git a/apps/browser-extension/src/entrypoints/popup/context/DbContext.tsx b/apps/browser-extension/src/entrypoints/popup/context/DbContext.tsx
index f801e06f4..c36743b3a 100644
--- a/apps/browser-extension/src/entrypoints/popup/context/DbContext.tsx
+++ b/apps/browser-extension/src/entrypoints/popup/context/DbContext.tsx
@@ -5,7 +5,7 @@ import type { EncryptionKeyDerivationParams } from '@/utils/dist/core/models/met
import EncryptionUtility from '@/utils/EncryptionUtility';
import { onMessage, sendMessage } from '@/utils/messaging/ExtensionMessaging';
import SqliteClient from '@/utils/SqliteClient';
-import { getItemWithFallback } from '@/utils/StorageUtility';
+import { getStorageItem } from '@/utils/StorageUtility';
import { AppErrorCode, formatErrorWithCode } from '@/utils/types/errors/AppErrorCodes';
import type { VaultResponse as messageVaultResponse } from '@/utils/types/messaging/VaultResponse';
import { vaultRequiresManifestMigration } from '@/utils/VaultManifestMigration';
@@ -319,9 +319,9 @@ export const DbProvider: React.FC<{ children: React.ReactNode }> = ({ children }
const getVaultMetadata = useCallback(async () : Promise<VaultMetadata | null> => {
try {
// Use fallback for keys migrated from session: to local: in v0.26.0
- const publicEmailDomains = await getItemWithFallback<string[]>(StorageKeys.PUBLIC_EMAIL_DOMAINS);
- const privateEmailDomains = await getItemWithFallback<string[]>(StorageKeys.PRIVATE_EMAIL_DOMAINS);
- const hiddenPrivateEmailDomains = await getItemWithFallback<string[]>(StorageKeys.HIDDEN_PRIVATE_EMAIL_DOMAINS);
+ const publicEmailDomains = await getStorageItem<string[]>(StorageKeys.PUBLIC_EMAIL_DOMAINS);
+ const privateEmailDomains = await getStorageItem<string[]>(StorageKeys.PRIVATE_EMAIL_DOMAINS);
+ const hiddenPrivateEmailDomains = await getStorageItem<string[]>(StorageKeys.HIDDEN_PRIVATE_EMAIL_DOMAINS);
const revision = await storage.getItem(StorageKeys.SERVER_REVISION) as number | null;
if (!publicEmailDomains && !privateEmailDomains) {
diff --git a/apps/browser-extension/src/utils/ItemFilters.ts b/apps/browser-extension/src/utils/ItemFilters.ts
index 883ff1b5f..d7068b3d8 100644
--- a/apps/browser-extension/src/utils/ItemFilters.ts
+++ b/apps/browser-extension/src/utils/ItemFilters.ts
@@ -38,7 +38,7 @@ export function parseItemFilterType(value: string | null | undefined): ItemFilte
/**
* Apply the active type/feature filter to a list of items.
* Used both for the visible item list and for computing folder badge counts so they
- * stay consistent — when a filter is active, folder counts only include matching items.
+ * stay consistent when a filter is active, folder counts only include matching items.
*/
export function applyTypeFilter(items: Item[], filterType: ItemFilterType): Item[] {
if (filterType === 'all') {
diff --git a/apps/browser-extension/src/utils/LegacyVaultKeyMigration.ts b/apps/browser-extension/src/utils/LegacyVaultKeyMigration.ts
deleted file mode 100644
index a764c9e80..000000000
--- a/apps/browser-extension/src/utils/LegacyVaultKeyMigration.ts
+++ /dev/null
@@ -1,12 +0,0 @@
-import { VaultKeyService } from '@/utils/VaultKeyService';
-
-/**
- * One-time KEK/VEK migration: vaults created before the vault key existed have to create one, which happens as
- * part of their next full push (see `handleUploadVault`).
- *
- * TODO: this file is the legacy part of the /manifest-migration gate. This can be deleted once all users have
- * migrated to the manifest-v1 storage model.
- */
-export async function requiresLegacyVaultKeyMigration(): Promise<boolean> {
- return !await VaultKeyService.hasLocalVaultKey();
-}
diff --git a/apps/browser-extension/src/utils/StorageUtility.ts b/apps/browser-extension/src/utils/StorageUtility.ts
index 2cce6a68f..b93760f6c 100644
--- a/apps/browser-extension/src/utils/StorageUtility.ts
+++ b/apps/browser-extension/src/utils/StorageUtility.ts
@@ -1,53 +1,18 @@
import { storage } from 'wxt/utils/storage';
-import { type StorageKey, StorageKeys } from '@/utils/constants/storageKeys';
+import type { StorageKey } from '@/utils/constants/storageKeys';
+import { readLegacyStorageFallback } from '@/utils/legacy/LegacyStorageKeyFallbacks';
/**
- * Storage keys that were migrated from session: to local: storage in v0.26.0 for offline mode support.
- * This mapping enables backward compatibility for users upgrading from older versions where data
- * was stored in session: storage. The fallback can be removed in v0.27.0+.
- *
- * Format: local key -> session fallback key
+ * Read a storage item, including legacy fallback for keys that have ever lived somewhere else.
+ * @param key - the storage key to read
*/
-const MIGRATED_STORAGE_KEYS: Record<string, StorageKey> = {
- [StorageKeys.PUBLIC_EMAIL_DOMAINS]: StorageKeys.LEGACY_SESSION_PUBLIC_EMAIL_DOMAINS,
- [StorageKeys.PRIVATE_EMAIL_DOMAINS]: StorageKeys.LEGACY_SESSION_PRIVATE_EMAIL_DOMAINS,
- [StorageKeys.HIDDEN_PRIVATE_EMAIL_DOMAINS]: StorageKeys.LEGACY_SESSION_HIDDEN_PRIVATE_EMAIL_DOMAINS,
- [StorageKeys.ENCRYPTION_KEY_DERIVATION_PARAMS]: StorageKeys.LEGACY_SESSION_ENCRYPTION_KEY_DERIVATION_PARAMS,
-};
-
-/**
- * Get a storage item with fallback to the legacy session: storage location.
- * This is used for keys that were migrated from session: to local: storage in v0.26.0.
- *
- * @param key The local: storage key to retrieve
- * @returns The value from local: storage, or from session: storage as fallback, or null if not found
- *
- * @example
- * // Instead of:
- * const domains = await storage.getItem(StorageKeys.PUBLIC_EMAIL_DOMAINS);
- *
- * // Use:
- * const domains = await getItemWithFallback(StorageKeys.PUBLIC_EMAIL_DOMAINS);
- *
- * @note This fallback can be removed in v0.27.0+ after users have had time to upgrade
- */
-export async function getItemWithFallback<T>(key: StorageKey): Promise<T | null> {
- // Try the current (local:) key first
- let value = await storage.getItem(key) as T | null;
-
- // If not found and this is a migrated key, try the fallback
- if (value === null && key in MIGRATED_STORAGE_KEYS) {
- const fallbackKey = MIGRATED_STORAGE_KEYS[key];
- value = await storage.getItem(fallbackKey) as T | null;
-
- // If found in fallback, migrate to new location for future use
- if (value !== null) {
- await storage.setItem(key, value);
- // Remove the fallback key
- await storage.removeItem(fallbackKey);
- }
+export async function getStorageItem<T>(key: StorageKey): Promise<T | null> {
+ const value = await storage.getItem(key) as T | null;
+ if (value !== null) {
+ return value;
}
- return value;
+ // LEGACY: delete this line later together with `@/utils/legacy/LegacyStorageKeyFallbacks`.
+ return readLegacyStorageFallback<T>(key);
}
diff --git a/apps/browser-extension/src/utils/VaultManifestMigration.ts b/apps/browser-extension/src/utils/VaultManifestMigration.ts
index 19d5583ec..e28f5f80a 100644
--- a/apps/browser-extension/src/utils/VaultManifestMigration.ts
+++ b/apps/browser-extension/src/utils/VaultManifestMigration.ts
@@ -1,18 +1,18 @@
-import { requiresLegacyVaultKeyMigration } from '@/utils/LegacyVaultKeyMigration';
+import { requiresLegacyAccountKeyMigration } from '@/utils/legacy/LegacyStorageModelMigration';
import type { SqliteClient } from '@/utils/SqliteClient';
/**
- * Whether the vault still has to run the manifest migration — the predicate behind the /manifest-migration gate,
+ * Whether the vault still has to run the manifest migration. The predicate behind the /manifest-migration gate,
* answered entirely from local state.
*
* Two conditions, carried independently of each other:
* 1. A stale local schema, rebuilt via `VaultSyncService.migrateVaultToCurrentSchema`. This is the permanent path:
* it delivered the initial sqlite-blob to manifest-v1 transition and fires again after every schema change we ship.
- * 2. A missing vault key ({@link requiresLegacyVaultKeyMigration}), one-time and deletable — see that file.
+ * 2. A missing account key hierarchy ({@link requiresLegacyAccountKeyMigration}), one-time and deletable.
*
* Callers must check `requiresLegacySqliteBlobMigration()` FIRST — a pre-2.0.0 vault has to walk the sqlite-blob upgrade chain before either condition here can be acted on.
* @param sqliteClient - the open local vault
*/
export async function vaultRequiresManifestMigration(sqliteClient: SqliteClient): Promise<boolean> {
- return await sqliteClient.requiresSchemaMigration() || await requiresLegacyVaultKeyMigration();
+ return await sqliteClient.requiresSchemaMigration() || await requiresLegacyAccountKeyMigration();
}
diff --git a/apps/browser-extension/src/utils/VaultSyncService.ts b/apps/browser-extension/src/utils/VaultSyncService.ts
index 154f09f34..d3402d24d 100644
--- a/apps/browser-extension/src/utils/VaultSyncService.ts
+++ b/apps/browser-extension/src/utils/VaultSyncService.ts
@@ -12,11 +12,11 @@ import type { VaultResponse } from '@/utils/dist/core/models/webapi';
import { VaultSqlGenerator } from '@/utils/dist/core/vault';
import { buildEmailRouting } from '@/utils/EmailRouting';
import { EncryptionUtility } from '@/utils/EncryptionUtility';
+import { completeLegacyAccountKeyMigration, isLegacySqliteBlobSnapshot, legacyUnstampedRowAdoption, openLegacySqliteBlobSnapshot, prepareLegacyAccountKeyMigration, withOutdatedServerGuard, type LegacyAccountKeyMigration, type LegacySqliteBlobSnapshot } from '@/utils/legacy/LegacyStorageModelMigration';
import {vaultCodecComputeCiphertextHash, vaultCodecComputeContentFingerprint, vaultCodecCanonicalizeFromSqlite, vaultCodecExtractEncryptionKeyForPublicKey, vaultCodecGenerateManifestSalt, vaultCodecUnpackPayload, vaultCodecMaterializeAsSqlite, vaultCodecPackPayload, vaultCodecValidateManifest, vaultCodecValidateDataBucket, type CodecBlobEntry, type CodecCanonicalized, type CodecManifest, type CodecManifestSpec} from '@/utils/RustCore';
import { SharingService, type SessionSharedManifest } from '@/utils/SharingService';
import { SqliteClient } from '@/utils/SqliteClient';
-import { getItemWithFallback } from '@/utils/StorageUtility';
-import { ServerUpdateRequiredError } from '@/utils/types/errors/ServerUpdateRequiredError';
+import { getStorageItem } from '@/utils/StorageUtility';
import { VaultProcessingError } from '@/utils/types/errors/VaultProcessingError';
import { type VaultManifest, type VaultDataBucket, VaultCodec } from '@/utils/VaultCodec';
import { VaultKeyService } from '@/utils/VaultKeyService';
@@ -27,16 +27,6 @@ const BLOBS_VAULT_ENDPOINT = 'Vault/blobs';
const BLOBS_MISSING_ENDPOINT = 'Vault/blobs/missing';
const BLOBS_DOWNLOAD_ENDPOINT = 'Vault/blobs/download';
-/**
- * True when an error from WebApiService is an HTTP 404. WebApiService surfaces non-2xx responses as a generic
- * Error whose message carries the status code (`HTTP error! status: 404`). A 404 on a v2 endpoint means the
- * server does not support the v2 API (outdated self-hosted install), surfaced as {@link ServerUpdateRequiredError}.
- * @param e - the caught error
- */
-function isNotFoundError(e: unknown): boolean {
- return e instanceof Error && e.message.includes('status: 404');
-}
-
/**
* Human-readable size for the push/pull size logs. Lengths are base64/JSON characters, which map ~1:1 to
* bytes on the wire.
@@ -138,10 +128,7 @@ export type PushResult = {
status: 'ok' | 'outdated' | 'missing-blobs' | 'rejected';
newManifestRevision: number | null;
reasons?: string[];
- /**
- * Set when this push performed the KEK/VEK migration: the freshly generated VEK the caller must adopt as the
- * session encryption key (the old password-derived key is now only the KEK).
- */
+ /** The new encryption key (set by legacy migration). */
newEncryptionKey?: string;
};
@@ -208,11 +195,6 @@ function selectPersonalManifest(snapshot: GetResponseDto | undefined | null): Ma
return personalId ? (snapshot?.manifests ?? []).find(m => m.manifestId === personalId) : undefined;
}
-/**
- * Numeric value of the server StorageFormat enum for the manifest-v1 format (SqliteBlob = 0, Manifest = 1).
- */
-export const STORAGE_FORMAT_MANIFEST = 1;
-
/** The manifest's VEK hangs off the account key hierarchy: the unlock chain produced it, nothing travels on the wire. */
const MANIFEST_KEY_TYPE_ACCOUNT = 'accountkey';
@@ -220,17 +202,11 @@ const MANIFEST_KEY_TYPE_ACCOUNT = 'accountkey';
const MANIFEST_KEY_TYPE_GRANT = 'grantkey';
/**
- * Raw snapshot returned by GET /v2/Vault.
+ * Raw snapshot returned by GET /v2/Vault. The `storageFormat` / `legacyVaultBlob` / `legacyRevision` / `version`
+ * fields are only populated for a not-yet-migrated user and are declared by {@link LegacySqliteBlobSnapshot}.
*/
-export type GetResponseDto = {
+export type GetResponseDto = LegacySqliteBlobSnapshot & {
status: number;
- /** The server's storage format (0 = sqlite-blob, 1 = manifest-v1). */
- storageFormat?: number;
- /** The legacy encrypted SQLite blob (for not-yet-migrated users). */
- legacyVaultBlob?: string | null;
- version?: string | null;
- /** The legacy sqlite-blob revision (set only on the sqlite-blob path). */
- legacyRevision?: number | null;
/**
* The caller's personal manifest id: the one manifest owned by their personal group, every other entry being a
* shared one. Also set on the sqlite-blob path, where the manifests list is empty.
@@ -258,10 +234,7 @@ type ManifestWriteDto = {
currentRevision: number;
credentialsCount: number;
blobReferences: BlobRefDto[];
- /**
- * The newly generated VEK encrypted with the password-derived KEK. Set on the personal-manifest write of a legacy user's first manifest-v1 push.
- * TODO: can be deleted once all users have migrated to manifest-v1.
- */
+ /** The new VEK (set by legacy migration). */
encryptedVek?: string;
};
@@ -360,37 +333,19 @@ export class VaultSyncService {
* can surface the real technical detail in a copyable report instead of a misleading "server unreachable".
*/
try {
- if (snapshot.storageFormat === STORAGE_FORMAT_MANIFEST) {
- // Manifest-v1 user: materialize the manifest + metadata + blobs into a SQLite blob, then encrypt it.
- devLog('[V2Pull] Step 2/4: manifest format: decrypting and reassembling local SQLite...');
- const pull = await this.materializeFromSnapshot(snapshot, encryptionKey);
- devLog(`[V2Pull] Step 3/4: materialized SQLite (${pull.sqliteBase64.length} base64 chars); re-encrypting for local storage...`);
- const encryptedVault = await EncryptionUtility.symmetricEncrypt(pull.sqliteBase64, encryptionKey);
- devLog('[V2Pull] Step 4/4: re-encryption done, returning VaultResponse.');
- return this.buildResponse(encryptedVault, '2.0.0', pull.manifestRevision, snapshot);
+ // LEGACY: a not-yet-migrated user's blob is passed through unchanged.
+ if (isLegacySqliteBlobSnapshot(snapshot)) {
+ const legacy = await openLegacySqliteBlobSnapshot(snapshot);
+ return this.buildResponse(legacy.encryptedBlob, legacy.version, legacy.revision, snapshot);
}
- /*
- * Not-yet-migrated (sqlite-blob fallback) user: the server returned the legacy encrypted SQLite blob. It's already in the stored
- * format (encrypted SQLite), so we pass it through unchanged: the on-open schema upgrade handles the rest.
- * There is no manifest-v1 server state, so drop any stale content fingerprints.
- */
- await storage.removeItem(StorageKeys.VAULT_CONTENT_FINGERPRINTS);
-
- /*
- * Legacy user: the vault has never been materialized, so it carries no record of which manifest is
- * ours. Persist it in local storage so the first migration canonicalize step can stamp rows with it.
- */
- if (snapshot.personalManifestId) {
- await storage.setItem(StorageKeys.VAULT_PERSONAL_MANIFEST_ID, snapshot.personalManifestId);
- }
- devLog('[V2Pull] Step 2/4: legacy blob pass-through (user not yet migrated), returning as-is.');
- return this.buildResponse(
- snapshot.legacyVaultBlob ?? '',
- snapshot.version ?? '',
- typeof snapshot.legacyRevision === 'number' ? snapshot.legacyRevision : 0,
- snapshot
- );
+ // Manifest-v1 user: materialize the manifest + metadata + blobs into a SQLite blob, then encrypt it.
+ devLog('[V2Pull] Step 2/4: manifest format: decrypting and reassembling local SQLite...');
+ const pull = await this.materializeFromSnapshot(snapshot, encryptionKey);
+ devLog(`[V2Pull] Step 3/4: materialized SQLite (${pull.sqliteBase64.length} base64 chars); re-encrypting for local storage...`);
+ const encryptedVault = await EncryptionUtility.symmetricEncrypt(pull.sqliteBase64, encryptionKey);
+ devLog('[V2Pull] Step 4/4: re-encryption done, returning VaultResponse.');
+ return this.buildResponse(encryptedVault, '2.0.0', pull.manifestRevision, snapshot);
} catch (error) {
devError('[V2Pull] FAILED: the last logged step above is where it broke:', error);
throw new VaultProcessingError('vault-pull', error);
@@ -411,12 +366,8 @@ export class VaultSyncService {
devLog('[ManifestMigration] Migrating local vault onto the current schema (local round-trip, no server involved)...');
try {
- /*
- * For legacy sqlite-blob migration: the manifest that unstamped rows are adopted into.
- * TODO: delete this field once the migration is complete.
- */
- const ownManifestId = await this.resolvePersonalManifestId();
- const { canonicalized } = await this.canonicalizeVault(sqliteClient, { adoptUnstampedInto: ownManifestId });
+ // LEGACY: a sqlite-blob vault's rows carry no ManifestId yet, so this one canonicalize adopts them.
+ const { canonicalized } = await this.canonicalizeVault(sqliteClient, legacyUnstampedRowAdoption(await this.resolvePersonalManifestId()));
/*
* Canonicalize already handed us every extracted favicon/attachment as plaintext bytes, so materialize can
@@ -443,27 +394,11 @@ export class VaultSyncService {
}
}
- /**
- * Run a write against the v2 API and translate the outdated-server 404 into {@link ServerUpdateRequiredError}.
- * TODO: this wrapper can be deleted once enough time has passed since the v2 API was introduced (so all self-hosted installs have had time to upgrade).
- * @param fn - the write to run
- */
- private async withOutdatedServerGuard<T>(fn: () => Promise<T>): Promise<T> {
- try {
- return await fn();
- } catch (e) {
- if (isNotFoundError(e)) {
- throw new ServerUpdateRequiredError();
- }
- throw e;
- }
- }
-
/**
* Fetch the raw snapshot (GET /v2/Vault) without decrypting/reassembling. Throws error if the server predates the v2 API.
*/
private async fetchSnapshot(): Promise<GetResponseDto> {
- return this.withOutdatedServerGuard(() => new WebApiService().get<GetResponseDto>(VAULT_ENDPOINT));
+ return withOutdatedServerGuard(() => new WebApiService().get<GetResponseDto>(VAULT_ENDPOINT));
}
/**
@@ -704,18 +639,6 @@ export class VaultSyncService {
const manifestJson = await verifyDecryptUnpack(dto.blob!, vek, dto.ciphertextHash, isPersonal ? 'manifest' : `shared manifest ${dto.manifestId}`);
const manifest = JSON.parse(manifestJson) as VaultManifest;
- /*
- * Bind the payload's self-declared identity to the row the server served it from. This is the only place the
- * two meet: the id inside the blob is what the codec stamps every row of this manifest with (see
- * `claim_manifest_scope`), and the server can never check it — the blob is opaque to it and the id on the row
- * is simply what the creating client sent alongside (POST /v2/Sharing/manifests).
- *
- * Without this check, anyone could create a manifest of their own, embed *another* manifest's id inside it and
- * share it with one of that manifest's members: the recipient would stamp the attacker's rows with the embedded
- * id, and their next push would split those rows straight into a manifest the attacker holds no key for. A
- * revoked member still knows the id (it is stamped on every row of the copy they kept), so revocation alone
- * does not close that door.
- */
if (!manifestIdsEqual(manifest.manifestId, dto.manifestId)) {
throw new Error(`VaultSyncService: manifest ${dto.manifestId} declares a different id (${manifest.manifestId}) inside its encrypted payload, refusing to open it.`);
}
@@ -861,7 +784,7 @@ export class VaultSyncService {
username: string,
options?: { createVaultKey?: boolean; forceFullWrite?: boolean }
): Promise<PushResult> {
- return this.withOutdatedServerGuard(() => this.pushInternal(sqliteClient, vek, username, options));
+ return withOutdatedServerGuard(() => this.pushInternal(sqliteClient, vek, username, options));
}
/**
@@ -877,27 +800,9 @@ export class VaultSyncService {
username: string,
options?: { createVaultKey?: boolean; forceFullWrite?: boolean }
): Promise<PushResult> {
- /*
- * KEK/VEK migration: on the first push after this feature ships, generate a fresh VEK and encrypt everything
- * with it; the passed-in password-derived key becomes the KEK that encrypts the VEK. On a normal push the
- * passed-in key IS the VEK and is used directly.
- */
- const migrateToVaultKey = options?.createVaultKey === true;
- const contentKey = migrateToVaultKey ? EncryptionUtility.generateVaultEncryptionKey() : vek;
-
- /*
- * The full account-key hierarchy is created in one shot: a random Account Key encrypted with the KEK, the VEK
- * encrypted with the AK, and the account keypair whose private half is encrypted with the AK too.
- */
- const accountKey = migrateToVaultKey ? EncryptionUtility.generateVaultEncryptionKey() : null;
- const accountKeyPair = migrateToVaultKey ? await EncryptionUtility.generateRsaKeyPair() : null;
- const encryptedVek = accountKey ? await EncryptionUtility.encryptVaultEncryptionKey(contentKey, accountKey) : null;
- const accountKeys = accountKey && accountKeyPair ? {
- encryptedAccountKey: await EncryptionUtility.encryptVaultEncryptionKey(accountKey, vek),
- accountPublicKey: accountKeyPair.publicKey,
- encryptedAccountPrivateKey: await EncryptionUtility.symmetricEncrypt(accountKeyPair.privateKey, accountKey),
- } : null;
- if (migrateToVaultKey) {
+ const migration: LegacyAccountKeyMigration | null = options?.createVaultKey === true ? await prepareLegacyAccountKeyMigration(vek) : null;
+ const contentKey = migration?.contentKey ?? vek;
+ if (migration) {
devLog('[V2Push] Account-key migration: generated new VEK, AK and account keypair; vault content and all blobs will be re-encrypted and re-uploaded.');
}
@@ -910,7 +815,7 @@ export class VaultSyncService {
const { canonicalized, manifestRecords } = cachedSet ?? await this.canonicalizeVault(sqliteClient);
// Personal manifest first by construction (see `resolveManifestRecords`), which is also the order canonicalize requires.
const [personalRecord, ...sharedRecords] = manifestRecords;
- const privateEmailDomains = (await getItemWithFallback<string[]>(StorageKeys.PRIVATE_EMAIL_DOMAINS)) ?? [];
+ const privateEmailDomains = (await getStorageItem<string[]>(StorageKeys.PRIVATE_EMAIL_DOMAINS)) ?? [];
const emailRouting = buildEmailRouting(canonicalized.manifests.map(m => m.manifest), personalRecord.manifestId, privateEmailDomains);
/*
@@ -948,11 +853,9 @@ export class VaultSyncService {
*/
const revisionOf = (record: ManifestRecord): number => record.isPersonal ? currentManifestRevision : storedSharedRevisions[record.manifestId] ?? record.revision;
- /*
- * Every manifest canonicalize produced, joined to its record: one candidate list the whole write is derived
- * from. A canonicalized manifest with no record is one this vault cannot write — its grant was not resolved on
- * the last pull — and is dropped rather than pushed with a key or revision we would have to invent.
- */
+ // Every manifest canonicalize produced, joined to its record: one candidate list the whole write is derived from.
+ // A canonicalized manifest with no record is one this vault cannot write and is dropped rather than pushed with a
+ // key or revision we would have to invent.
const recordByManifestId = new Map(manifestRecords.map(r => [r.manifestId, r]));
const candidates: PushManifest[] = canonicalized.manifests.flatMap(({ manifest, blobs }): PushManifest[] => {
const record = recordByManifestId.get(manifest.manifestId);
@@ -995,7 +898,7 @@ export class VaultSyncService {
const fingerprintKey = fingerprintBucketKey(bucket.manifestId, bucket.category);
const bucketPlaintext = JSON.stringify(bucket);
const bucketFingerprint = await vaultCodecComputeContentFingerprint(bucketPlaintext);
- if (!forceFullWrite && !migrateToVaultKey && fingerprints[fingerprintKey] === bucketFingerprint) {
+ if (!forceFullWrite && !migration && fingerprints[fingerprintKey] === bucketFingerprint) {
devLog(`[V2Push] ${label} unchanged versus server baseline, leaving it out of this write.`);
continue;
}
@@ -1040,7 +943,7 @@ export class VaultSyncService {
* A KEK/VEK migration re-keys the personal manifest and all buckets (their ciphertext must be re-encrypted with
* the new VEK even when the content is unchanged) but not the shared manifests, which keep their own VEK.
*/
- if (!forceFullWrite && !(migrateToVaultKey && candidate.isPersonal) && fingerprints[fingerprintManifestKey(candidate.manifestId)] === fingerprint) {
+ if (!forceFullWrite && !(migration && candidate.isPersonal) && fingerprints[fingerprintManifestKey(candidate.manifestId)] === fingerprint) {
devLog(`[V2Push] ${label} unchanged versus server baseline, leaving it out of this write.`);
continue;
}
@@ -1073,7 +976,7 @@ export class VaultSyncService {
* Set only on the KEK/VEK migration push, where the server creates the vault key alongside this personal-manifest revision.
* A migration always forces a personal-manifest write (see the gate above), so the key can never be stranded without one.
*/
- ...(candidate.isPersonal && encryptedVek ? { encryptedVek } : {}),
+ ...(candidate.isPersonal && migration ? { encryptedVek: migration.encryptedVek } : {}),
});
writtenManifestFingerprints[candidate.manifestId] = fingerprint;
}
@@ -1100,7 +1003,7 @@ export class VaultSyncService {
let personalToUpload: string[] = [];
let sharedToUpload: string[] = [];
- if (migrateToVaultKey) {
+ if (migration) {
personalToUpload = personalHashes;
const sharedCandidates = sharedHashes.filter(h => !knownServerHashes.has(h));
if (sharedCandidates.length > 0) {
@@ -1119,10 +1022,10 @@ export class VaultSyncService {
sharedToUpload = sharedHashes.filter(h => toUploadSet.has(h));
}
- devLog(`[V2Push] Blob diff: ${allBlobHashes.length} blobs across ${candidates.length} manifest(s), uploading ${personalToUpload.length} personal + ${sharedToUpload.length} shared${migrateToVaultKey ? ' (personal manifest re-encrypted, VEK migration)' : ''}.`);
+ devLog(`[V2Push] Blob diff: ${allBlobHashes.length} blobs across ${candidates.length} manifest(s), uploading ${personalToUpload.length} personal + ${sharedToUpload.length} shared${migration ? ' (personal manifest re-encrypted, VEK migration)' : ''}.`);
// Pre-upload the missing bytes so the write below carries references only; each staged entry carries its own key.
- const uploadedCiphertexts = await this.uploadBlobs(webApi, blobEntries, personalToUpload, migrateToVaultKey);
+ const uploadedCiphertexts = await this.uploadBlobs(webApi, blobEntries, personalToUpload, migration !== null);
for (const [hash, ciphertext] of await this.uploadBlobs(webApi, blobEntries, sharedToUpload)) {
uploadedCiphertexts.set(hash, ciphertext);
}
@@ -1164,7 +1067,8 @@ export class VaultSyncService {
emailRouting,
userEncryptionPublicKey: primaryKey?.PublicKey ?? '',
sharedManifestEncryptionPublicKeys,
- accountKeys,
+ // LEGACY: only the one-time KEK/VEK migration push carries a key hierarchy for the server to store.
+ accountKeys: migration?.accountKeys ?? null,
};
let resp = await webApi.post<typeof payload, VaultWriteResponseDto>(VAULT_ENDPOINT, payload);
@@ -1181,7 +1085,7 @@ export class VaultSyncService {
}
devWarn(`[V2Sync] Server reported ${resp.missingBlobHashes.length} missing blob(s); uploading and retrying once.`);
- const retriedPersonal = await this.uploadBlobs(webApi, blobEntries, resp.missingBlobHashes.filter(h => blobEntries.get(h)?.fromPersonal === true), migrateToVaultKey);
+ const retriedPersonal = await this.uploadBlobs(webApi, blobEntries, resp.missingBlobHashes.filter(h => blobEntries.get(h)?.fromPersonal === true), migration !== null);
const retriedShared = await this.uploadBlobs(webApi, blobEntries, resp.missingBlobHashes.filter(h => blobEntries.get(h)?.fromPersonal === false));
for (const [hash, ciphertext] of [...retriedPersonal, ...retriedShared]) {
uploadedCiphertexts.set(hash, ciphertext);
@@ -1258,19 +1162,8 @@ export class VaultSyncService {
}
await this.saveBlobCache(newCache);
- /*
- * Account-key migration completed: cache the whole blob chain for offline unlock, stage the session account
- * private key, and hand the new VEK to the caller, which must adopt it as the session encryption key and
- * re-encrypt the locally stored vault with it.
- */
- if (migrateToVaultKey && encryptedVek && accountKeys && accountKeyPair) {
- await VaultKeyService.adoptLocalAccountKeys({
- encryptedAccountKey: accountKeys.encryptedAccountKey,
- encryptedVek,
- accountPublicKey: accountKeys.accountPublicKey,
- encryptedAccountPrivateKey: accountKeys.encryptedAccountPrivateKey,
- accountPrivateKey: accountKeyPair.privateKey,
- });
+ if (migration) {
+ await completeLegacyAccountKeyMigration(migration);
devLog('[V2Push] Account-key migration complete: hierarchy created server-side, blob chain cached locally.');
}
@@ -1280,7 +1173,7 @@ export class VaultSyncService {
const totalChars = manifestChars + bucketChars + uploadedBlobChars;
devLog(`[V2Push] Total pushed (encrypted): ${manifestWrites.length} manifest(s) ${formatKb(manifestChars)} + ${bucketDtos.length} buckets ${formatKb(bucketChars)} + ${uploadedCiphertexts.size} blobs ${formatKb(uploadedBlobChars)} = ${formatKb(totalChars)}.`);
- return { status: 'ok', newManifestRevision: newPersonalRevision, newEncryptionKey: migrateToVaultKey ? contentKey : undefined };
+ return { status: 'ok', newManifestRevision: newPersonalRevision, newEncryptionKey: migration ? contentKey : undefined };
}
/**
@@ -1360,7 +1253,7 @@ export class VaultSyncService {
* @param username - the user's username (the unified write cross-checks it against the auth session)
*/
public async pushDataBucketOnly(bucket: VaultDataBucket, vek: string, username: string): Promise<{ status: 'ok' | 'outdated'; revision: number }> {
- return this.withOutdatedServerGuard(() => this.pushDataBucketOnlyInternal(bucket, vek, username));
+ return withOutdatedServerGuard(() => this.pushDataBucketOnlyInternal(bucket, vek, username));
}
/**
diff --git a/apps/browser-extension/src/utils/__tests__/EncryptionUtility.crypto.test.ts b/apps/browser-extension/src/utils/__tests__/EncryptionUtility.crypto.test.ts
index b275eb57c..6f177f0dc 100644
--- a/apps/browser-extension/src/utils/__tests__/EncryptionUtility.crypto.test.ts
+++ b/apps/browser-extension/src/utils/__tests__/EncryptionUtility.crypto.test.ts
@@ -197,11 +197,9 @@ describe('email RSA private key cache', () => {
});
it('skips undecryptable emails instead of failing the whole batch', async () => {
- /*
- * A mailbox can legitimately contain a message this user has no key for — mail delivered to an alias before
- * it moved into a shared manifest is encrypted with the owner's personal key. The server filters those out,
- * but if one slips through it must cost that single row, not blank the entire mailbox.
- */
+ // A mailbox can legitimately contain a message this user has no key for. Mail delivered to an alias before
+ // it moved into a shared manifest is encrypted with the owner's personal key. The server filters those out,
+ // but if one slips through it must cost that single row, not blank the entire mailbox.
const keyPair = await EncryptionUtility.generateRsaKeyPair();
const strangerKeyPair = await EncryptionUtility.generateRsaKeyPair();
const encryptionKey: EncryptionKey = {
diff --git a/apps/browser-extension/src/utils/autofill/Autofill.ts b/apps/browser-extension/src/utils/autofill/Autofill.ts
index d7fe1e966..86fd13017 100644
--- a/apps/browser-extension/src/utils/autofill/Autofill.ts
+++ b/apps/browser-extension/src/utils/autofill/Autofill.ts
@@ -6,7 +6,7 @@
* even when the rest of the app stays disabled. A second flag,
* `av-suppress-save="true"`, can be combined with `av-enable` to keep autofill
* available for matching credentials while hiding the "save this login" and
- * "create new" affordances — useful on pages where storing the credential
+ * "create new" affordances. Useful on pages where storing the credential
* shouldn't be encouraged (e.g. AliasVault's own login form).
*/
diff --git a/apps/browser-extension/src/utils/constants/legacyStorageKeys.ts b/apps/browser-extension/src/utils/constants/legacyStorageKeys.ts
new file mode 100644
index 000000000..4882bd1b2
--- /dev/null
+++ b/apps/browser-extension/src/utils/constants/legacyStorageKeys.ts
@@ -0,0 +1,38 @@
+/**
+ * Storage keys that ONLY exist to read state written by an older extension version. Nothing writes them any
+ * more: every one of them is read once, migrated onto its current {@link StorageKeys} counterpart, and then
+ * dropped. They live apart from `storageKeys.ts` so the current key set stays readable at a glance.
+ *
+ * Deleting this file is the whole cleanup for these one-time reads: the compiler then points at every
+ * remaining reader (all of which live in `@/utils/legacy/LegacyStorageKeyFallbacks`).
+ */
+
+import type { StorageKey } from '@/utils/constants/storageKeys';
+
+export const LegacyStorageKeys = {
+ /** Pre-v0.20 revision key, in the string format `"250"` or `"250+1"`; migrated to `StorageKeys.SERVER_REVISION`. */
+ VAULT_REVISION_NUMBER: 'local:vaultRevisionNumber',
+ /** Pre-v0.22 encryption key location; read as a fallback for `StorageKeys.ENCRYPTION_KEY`. */
+ DERIVED_KEY: 'session:derivedKey',
+
+ /*
+ * -- Session locations migrated to local: in v0.26.0, removable in v0.27.0+ (see readLegacyStorageFallback) --
+ */
+
+ /** Fallback for `StorageKeys.PUBLIC_EMAIL_DOMAINS`. */
+ SESSION_PUBLIC_EMAIL_DOMAINS: 'session:publicEmailDomains',
+ /** Fallback for `StorageKeys.PRIVATE_EMAIL_DOMAINS`. */
+ SESSION_PRIVATE_EMAIL_DOMAINS: 'session:privateEmailDomains',
+ /** Fallback for `StorageKeys.HIDDEN_PRIVATE_EMAIL_DOMAINS`. */
+ SESSION_HIDDEN_PRIVATE_EMAIL_DOMAINS: 'session:hiddenPrivateEmailDomains',
+ /** Fallback for `StorageKeys.ENCRYPTION_KEY_DERIVATION_PARAMS`. */
+ SESSION_ENCRYPTION_KEY_DERIVATION_PARAMS: 'session:encryptionKeyDerivationParams',
+} as const satisfies Record<string, StorageKey>;
+
+/**
+ * Legacy keys holding vault data or state derived from it, spread into `allVaultDataStorageKeys()` so a logout
+ * clears them alongside the current ones.
+ */
+export const LEGACY_VAULT_DATA_STORAGE_KEYS: readonly StorageKey[] = [
+ LegacyStorageKeys.VAULT_REVISION_NUMBER,
+];
diff --git a/apps/browser-extension/src/utils/constants/storageKeys.ts b/apps/browser-extension/src/utils/constants/storageKeys.ts
index 8dbd985b2..bf3e64b34 100644
--- a/apps/browser-extension/src/utils/constants/storageKeys.ts
+++ b/apps/browser-extension/src/utils/constants/storageKeys.ts
@@ -3,6 +3,7 @@
* change the key names without breaking the code and track shared storage keys in one place.
*/
+import { LEGACY_VAULT_DATA_STORAGE_KEYS } from '@/utils/constants/legacyStorageKeys';
import { ALL_VAULT_MUTATION_SCOPES, type VaultMutationScope } from '@/utils/types/VaultMutationScope';
/** A WXT storage key, scoped to either the persisted (local) or the memory-only (session) area. */
@@ -34,8 +35,6 @@ export const StorageKeys = {
ENCRYPTED_VAULT: 'local:encryptedVault',
/** Revision number of the personal manifest as known by the server. */
SERVER_REVISION: 'local:serverRevision',
- /** Legacy (pre-v0.20) revision key, only read during migration to {@link StorageKeys.SERVER_REVISION}. */
- LEGACY_VAULT_REVISION_NUMBER: 'local:vaultRevisionNumber',
/** Public email domains supported by the server. */
PUBLIC_EMAIL_DOMAINS: 'local:publicEmailDomains',
/** Private email domains supported by the server. */
@@ -93,8 +92,6 @@ export const StorageKeys = {
ENCRYPTION_KEY: 'session:encryptionKey',
/** The decrypted account private key (JWK). Session-only: it must never persist to disk. */
ACCOUNT_PRIVATE_KEY: 'session:accountPrivateKey',
- /** Legacy (pre-v0.19) encryption key location, only read as a fallback. */
- LEGACY_DERIVED_KEY: 'session:derivedKey',
/** Encrypted form values persisted while the popup is closed. */
PERSISTED_FORM_VALUES: 'session:persistedFormValues',
/** Route the popup was on when it was last closed. */
@@ -110,19 +107,6 @@ export const StorageKeys = {
/** The item that was most recently autofilled, used to prioritize it in the list. */
RECENTLY_SELECTED_ITEM: 'session:aliasvault_recently_selected_item',
- /*
- * -- Legacy session locations, migrated to local: in v0.26.0 (see StorageUtility) --
- */
-
- /** @deprecated Fallback for {@link StorageKeys.PUBLIC_EMAIL_DOMAINS}, removable in v0.27.0+. */
- LEGACY_SESSION_PUBLIC_EMAIL_DOMAINS: 'session:publicEmailDomains',
- /** @deprecated Fallback for {@link StorageKeys.PRIVATE_EMAIL_DOMAINS}, removable in v0.27.0+. */
- LEGACY_SESSION_PRIVATE_EMAIL_DOMAINS: 'session:privateEmailDomains',
- /** @deprecated Fallback for {@link StorageKeys.HIDDEN_PRIVATE_EMAIL_DOMAINS}, removable in v0.27.0+. */
- LEGACY_SESSION_HIDDEN_PRIVATE_EMAIL_DOMAINS: 'session:hiddenPrivateEmailDomains',
- /** @deprecated Fallback for {@link StorageKeys.ENCRYPTION_KEY_DERIVATION_PARAMS}, removable in v0.27.0+. */
- LEGACY_SESSION_ENCRYPTION_KEY_DERIVATION_PARAMS: 'session:encryptionKeyDerivationParams',
-
/*
* -- App preferences --
*/
@@ -277,7 +261,6 @@ export const allVaultDataStorageKeys = (): StorageKey[] => [
StorageKeys.PRIVATE_EMAIL_DOMAINS,
StorageKeys.HIDDEN_PRIVATE_EMAIL_DOMAINS,
StorageKeys.SERVER_REVISION,
- StorageKeys.LEGACY_VAULT_REVISION_NUMBER,
StorageKeys.SERVER_MANIFEST_REVISIONS,
StorageKeys.VAULT_BUCKET_REVISIONS,
StorageKeys.VAULT_MANIFEST_SALT,
@@ -295,4 +278,5 @@ export const allVaultDataStorageKeys = (): StorageKey[] => [
StorageKeys.ENCRYPTED_ACCOUNT_PRIVATE_KEY,
StorageKeys.USERNAME,
...ALL_VAULT_MUTATION_SCOPES.map(scope => dirtyScopeStorageKey(scope)),
+ ...LEGACY_VAULT_DATA_STORAGE_KEYS,
];
diff --git a/apps/browser-extension/src/utils/legacy/LegacyStorageKeyFallbacks.ts b/apps/browser-extension/src/utils/legacy/LegacyStorageKeyFallbacks.ts
new file mode 100644
index 000000000..8ff2f4c86
--- /dev/null
+++ b/apps/browser-extension/src/utils/legacy/LegacyStorageKeyFallbacks.ts
@@ -0,0 +1,72 @@
+/**
+ * One-time reads of browser storage written by an OLDER extension version. Each function reads a
+ * {@link LegacyStorageKeys} entry, migrates the value onto its current {@link StorageKeys} counterpart and
+ * drops the old one; nothing here is written by the current code.
+ *
+ * TODO: delete this file (plus `@/utils/constants/legacyStorageKeys`) once every install has upgraded past the
+ * versions listed per function.
+ */
+
+import { storage } from 'wxt/utils/storage';
+
+import { LegacyStorageKeys } from '@/utils/constants/legacyStorageKeys';
+import { type StorageKey, StorageKeys } from '@/utils/constants/storageKeys';
+
+/**
+ * Storage keys that moved from session: to local: storage in v0.26.0 for offline mode support, as
+ * `current local key -> legacy session key`. Removable in v0.27.0+.
+ */
+const MIGRATED_STORAGE_KEYS: Record<string, StorageKey> = {
+ [StorageKeys.PUBLIC_EMAIL_DOMAINS]: LegacyStorageKeys.SESSION_PUBLIC_EMAIL_DOMAINS,
+ [StorageKeys.PRIVATE_EMAIL_DOMAINS]: LegacyStorageKeys.SESSION_PRIVATE_EMAIL_DOMAINS,
+ [StorageKeys.HIDDEN_PRIVATE_EMAIL_DOMAINS]: LegacyStorageKeys.SESSION_HIDDEN_PRIVATE_EMAIL_DOMAINS,
+ [StorageKeys.ENCRYPTION_KEY_DERIVATION_PARAMS]: LegacyStorageKeys.SESSION_ENCRYPTION_KEY_DERIVATION_PARAMS,
+};
+
+/**
+ * The value a key held at its pre-v0.26.0 session: location, migrated across to its current location on the way
+ * out so this fallback is only ever paid once. Reached from {@link getStorageItem} after the current location
+ * came up empty.
+ * @param key - the current local: storage key that came up empty
+ * @returns The migrated value, or null when this key never lived elsewhere or the old location is empty too
+ */
+export async function readLegacyStorageFallback<T>(key: StorageKey): Promise<T | null> {
+ if (!(key in MIGRATED_STORAGE_KEYS)) {
+ return null;
+ }
+
+ const fallbackKey = MIGRATED_STORAGE_KEYS[key];
+ const legacyValue = await storage.getItem(fallbackKey) as T | null;
+ if (legacyValue !== null) {
+ await storage.setItem(key, legacyValue);
+ await storage.removeItem(fallbackKey);
+ }
+
+ return legacyValue;
+}
+
+/**
+ * The session encryption key as stored before v0.22.0, when it lived under a different key name. Read only
+ * after {@link StorageKeys.ENCRYPTION_KEY} came up empty.
+ */
+export async function readLegacySessionEncryptionKey(): Promise<string | null> {
+ return await storage.getItem(LegacyStorageKeys.DERIVED_KEY) as string | null;
+}
+
+/**
+ * The server revision as stored before v0.20, where it was a string in the `"250"` or `"250+1"` format (server
+ * revision plus local edit count). Migrates whatever it finds onto {@link StorageKeys.SERVER_REVISION}. Read
+ * only after that key came up empty.
+ * @returns The migrated server revision, or null when no legacy value exists
+ */
+export async function readLegacyServerRevision(): Promise<number | null> {
+ const legacyRevision = await storage.getItem(LegacyStorageKeys.VAULT_REVISION_NUMBER) as string | number | null;
+ if (legacyRevision === null) {
+ return null;
+ }
+
+ // Only the server part before the '+' is the server revision; the suffix counted unpushed local edits.
+ const revision = typeof legacyRevision === 'number' ? legacyRevision : parseInt(legacyRevision.split('+')[0], 10) || 0;
+ await storage.setItem(StorageKeys.SERVER_REVISION, revision);
+ return revision;
+}
diff --git a/apps/browser-extension/src/utils/legacy/LegacyStorageModelMigration.ts b/apps/browser-extension/src/utils/legacy/LegacyStorageModelMigration.ts
new file mode 100644
index 000000000..6a0b8a202
--- /dev/null
+++ b/apps/browser-extension/src/utils/legacy/LegacyStorageModelMigration.ts
@@ -0,0 +1,192 @@
+/**
+ * Legacy storage model migration specific logic.
+ *
+ * TODO: these methods and file can be deleted later once all users have migrated from sqlite-blob to manifest-v1.
+ */
+
+import { storage } from 'wxt/utils/storage';
+
+import { StorageKeys } from '@/utils/constants/storageKeys';
+import { devLog } from '@/utils/devLogger/DevLogger';
+import { EncryptionUtility } from '@/utils/EncryptionUtility';
+import { ServerUpdateRequiredError } from '@/utils/types/errors/ServerUpdateRequiredError';
+import { VaultKeyService } from '@/utils/VaultKeyService';
+
+/*
+ * -- 1. Servers predating the v2 vault API --
+ */
+
+/**
+ * True when an error from WebApiService is an HTTP 404. WebApiService surfaces non-2xx responses as a generic
+ * Error whose message carries the status code (`HTTP error! status: 404`).
+ * @param e - the caught error
+ */
+function isNotFoundError(e: unknown): boolean {
+ return e instanceof Error && e.message.includes('status: 404');
+}
+
+/**
+ * Run a v2 API call, translating the outdated-server 404 into {@link ServerUpdateRequiredError}. Such a server
+ * answers every v2 endpoint with a 404, which is indistinguishable from a routing error unless we translate it,
+ * so the UI can surface "update your server" (E-903) instead. Every other failure propagates unchanged.
+ * @param fn - the call to run
+ */
+export async function withOutdatedServerGuard<T>(fn: () => Promise<T>): Promise<T> {
+ try {
+ return await fn();
+ } catch (e) {
+ if (isNotFoundError(e)) {
+ throw new ServerUpdateRequiredError();
+ }
+ throw e;
+ }
+}
+
+/*
+ * -- 2. The sqlite-blob storage model --
+ */
+
+/** Numeric value of the server StorageFormat enum for the manifest-v1 format (SqliteBlob = 0, Manifest = 1). */
+const STORAGE_FORMAT_MANIFEST = 1;
+
+/**
+ * The GET /v2/Vault fields that only a legacy sqlite-blob response carries. Structurally satisfied by the full
+ * snapshot type, so callers pass the snapshot itself.
+ */
+export type LegacySqliteBlobSnapshot = {
+ /** The server's storage format (0 = sqlite-blob, 1 = manifest-v1). Absent on servers predating the field. */
+ storageFormat?: number;
+ /** The legacy encrypted SQLite blob. */
+ legacyVaultBlob?: string | null;
+ /** The legacy sqlite-blob revision. */
+ legacyRevision?: number | null;
+ /** Data-model version string of the legacy blob. */
+ version?: string | null;
+ /** The manifest id the server has already reserved for this user's personal manifest. */
+ personalManifestId?: string | null;
+};
+
+/** The already-encrypted blob to store locally, plus the metadata a VaultResponse needs alongside it. */
+export type LegacySqliteBlobPassthrough = {
+ encryptedBlob: string;
+ version: string;
+ revision: number;
+};
+
+/**
+ * Whether the server answered with anything other than manifest-v1, which means the legacy sqlite-blob format
+ * (including a server too old to report the field at all).
+ * @param snapshot - the raw GET /v2/Vault response
+ */
+export function isLegacySqliteBlobSnapshot(snapshot: LegacySqliteBlobSnapshot): boolean {
+ return snapshot.storageFormat !== STORAGE_FORMAT_MANIFEST;
+}
+
+/**
+ * Take a legacy snapshot apart for local storage. The blob is already in the stored format (encrypted SQLite),
+ * so it passes through untouched and the on-open schema upgrade handles the rest; this only resets the local
+ * state that manifest-v1 owns and records the manifest id the migration push will stamp rows with.
+ * @param snapshot - the raw GET /v2/Vault response
+ */
+export async function openLegacySqliteBlobSnapshot(snapshot: LegacySqliteBlobSnapshot): Promise<LegacySqliteBlobPassthrough> {
+ // There is no manifest-v1 server state behind this snapshot, so any content fingerprint we hold is stale.
+ await storage.removeItem(StorageKeys.VAULT_CONTENT_FINGERPRINTS);
+
+ /*
+ * The vault has never been materialized, so it carries no record of which manifest is ours. Persist the
+ * server's id for it so the first migration canonicalize can stamp rows with it.
+ */
+ if (snapshot.personalManifestId) {
+ await storage.setItem(StorageKeys.VAULT_PERSONAL_MANIFEST_ID, snapshot.personalManifestId);
+ }
+
+ devLog('[V2Pull] Legacy sqlite-blob pass-through (user not yet migrated), returning the blob as-is.');
+
+ return {
+ encryptedBlob: snapshot.legacyVaultBlob ?? '',
+ version: snapshot.version ?? '',
+ revision: typeof snapshot.legacyRevision === 'number' ? snapshot.legacyRevision : 0,
+ };
+}
+
+/**
+ * Canonicalize options that adopt rows carrying no ManifestId into the personal manifest. Only the one-time
+ * migration of a legacy sqlite-blob vault may pass these: every other canonicalize must reject unstamped rows
+ * rather than silently claim them (see `claim_manifest_scope` in the Rust codec).
+ * @param personalManifestId - the manifest unstamped rows are adopted into
+ */
+export function legacyUnstampedRowAdoption(personalManifestId: string): { adoptUnstampedInto: string } {
+ return { adoptUnstampedInto: personalManifestId };
+}
+
+/*
+ * -- 3. The missing KEK/VEK account key hierarchy --
+ */
+
+/**
+ * The freshly minted key hierarchy for one migration push. Held across the push so
+ * {@link completeLegacyAccountKeyMigration} can cache exactly what the server committed.
+ */
+export type LegacyAccountKeyMigration = {
+ /** The new VEK: everything this push writes is encrypted with it, and the caller adopts it as the session key. */
+ contentKey: string;
+ /** The new VEK encrypted with the Account Key; sent on the personal-manifest write so the server stores it. */
+ encryptedVek: string;
+ /** The rest of the hierarchy, sent as-is in the write payload. */
+ accountKeys: {
+ /** The Account Key encrypted with the password-derived KEK. */
+ encryptedAccountKey: string;
+ /** Public half of the new account keypair, used by others to grant this user access to a shared manifest. */
+ accountPublicKey: string;
+ /** Private half of the new account keypair, encrypted with the Account Key. */
+ encryptedAccountPrivateKey: string;
+ };
+ /** Plaintext private half of the new account keypair, staged into the session once the push commits. */
+ accountPrivateKey: string;
+};
+
+/**
+ * Whether this vault still has to run the migration, answered entirely from local state: no cached vault key
+ * means no hierarchy exists yet.
+ */
+export async function requiresLegacyAccountKeyMigration(): Promise<boolean> {
+ return !await VaultKeyService.hasLocalVaultKey();
+}
+
+/**
+ * Mint the full account key hierarchy for a migration push: a random Account Key (AK) encrypted with the
+ * password-derived key, which from then on is only the KEK; a fresh VEK encrypted with the AK; and the account
+ * keypair whose private half is encrypted with the AK too.
+ * @param kek - the password-derived key this vault is currently encrypted with, which becomes the KEK
+ */
+export async function prepareLegacyAccountKeyMigration(kek: string): Promise<LegacyAccountKeyMigration> {
+ const contentKey = EncryptionUtility.generateVaultEncryptionKey();
+ const accountKey = EncryptionUtility.generateVaultEncryptionKey();
+ const accountKeyPair = await EncryptionUtility.generateRsaKeyPair();
+
+ return {
+ contentKey,
+ encryptedVek: await EncryptionUtility.encryptVaultEncryptionKey(contentKey, accountKey),
+ accountKeys: {
+ encryptedAccountKey: await EncryptionUtility.encryptVaultEncryptionKey(accountKey, kek),
+ accountPublicKey: accountKeyPair.publicKey,
+ encryptedAccountPrivateKey: await EncryptionUtility.symmetricEncrypt(accountKeyPair.privateKey, accountKey),
+ },
+ accountPrivateKey: accountKeyPair.privateKey,
+ };
+}
+
+/**
+ * Adopt the hierarchy the migration push just committed: cache the whole encrypted blob chain for offline unlock
+ * and stage the account private key into the session.
+ * @param migration - the hierarchy that was pushed
+ */
+export async function completeLegacyAccountKeyMigration(migration: LegacyAccountKeyMigration): Promise<void> {
+ await VaultKeyService.adoptLocalAccountKeys({
+ encryptedAccountKey: migration.accountKeys.encryptedAccountKey,
+ encryptedVek: migration.encryptedVek,
+ accountPublicKey: migration.accountKeys.accountPublicKey,
+ encryptedAccountPrivateKey: migration.accountKeys.encryptedAccountPrivateKey,
+ accountPrivateKey: migration.accountPrivateKey,
+ });
+}