Skip to content

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

Update settings storage (#2159)

Leendert de Borst50f0baa14064
diff --git a/apps/browser-extension/src/utils/SqliteClient.ts b/apps/browser-extension/src/utils/SqliteClient.ts
index 7372afd49..b6d16f5a2 100644
--- a/apps/browser-extension/src/utils/SqliteClient.ts
+++ b/apps/browser-extension/src/utils/SqliteClient.ts
@@ -1,5 +1,6 @@
import initSqlJs from 'sql.js';
+import { StorageKeys } from '@/utils/constants/storageKeys';
import type { VaultVersion } from '@/utils/dist/core/vault';
import { VaultSqlGenerator, checkVersionCompatibility, extractVersionFromMigrationId } from '@/utils/dist/core/vault';
import { VaultVersionIncompatibleError } from '@/utils/types/errors/VaultVersionIncompatibleError';
@@ -18,6 +19,8 @@ import {
import type { IDatabaseClient, SqliteBindValue } from './db/BaseRepository';
import type { Database } from 'sql.js';
+import { storage } from '#imports';
+
/**
* Core SQLite database client.
* Provides low-level database operations and exposes repositories for domain-specific operations.
@@ -32,6 +35,11 @@ export class SqliteClient implements IDatabaseClient {
*/
private activeManifestId: string | null = null;
+ /**
+ * The id of the user's personal manifest.
+ */
+ private personalManifestId: string | null = null;
+
// Lazy-initialized repositories
private _items: ItemRepository | null = null;
private _passkeys: PasskeyRepository | null = null;
@@ -58,6 +66,15 @@ export class SqliteClient implements IDatabaseClient {
this.activeManifestId = manifestId;
}
+ /**
+ * The id of the user's personal manifest, as reported by the last pull. Every write that cannot inherit a
+ * manifest from a parent row falls back to it.
+ * @returns The personal manifest id, or null when no pull has recorded one yet
+ */
+ public getPersonalManifestId(): string | null {
+ return this.personalManifestId;
+ }
+
/**
* Repository for Item CRUD operations.
*/
@@ -143,6 +160,9 @@ export class SqliteClient implements IDatabaseClient {
// Create database from the binary data
this.db = new SQL.Database(bytes);
+ // Get the personal manifest id from local storage
+ this.personalManifestId = (await storage.getItem(StorageKeys.VAULT_PERSONAL_MANIFEST_ID)) as string | null;
+
// Reset repository instances when database changes
this._items = null;
this._passkeys = null;
diff --git a/apps/browser-extension/src/utils/VaultSyncService.ts b/apps/browser-extension/src/utils/VaultSyncService.ts
index 1c64aab33..b33546bf6 100644
--- a/apps/browser-extension/src/utils/VaultSyncService.ts
+++ b/apps/browser-extension/src/utils/VaultSyncService.ts
@@ -7,13 +7,12 @@
import { storage } from 'wxt/utils/storage';
import { bucketRevisionStorageKey, StorageKeys } from '@/utils/constants/storageKeys';
-import { BaseQueries } from '@/utils/db/queries/BaseQueries';
import { devError, devLog, devWarn } from '@/utils/devLogger/DevLogger';
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 {vaultCodecComputeCiphertextHash, vaultCodecComputeContentFingerprint, vaultCodecCanonicalizeFromSqlite, vaultCodecExtractEncryptionKeyForPublicKey, vaultCodecGenerateManifestSalt, vaultCodecUnpackPayload, vaultCodecMaterializeAsSqlite, vaultCodecPackPayload, vaultCodecValidateManifest, vaultCodecValidateDataBucket, type CodecBlobEntry, type CodecCanonicalized, type CodecManifest, type CodecManifestSpec, type CodecMaterialized} from '@/utils/RustCore';
+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';
@@ -323,35 +322,6 @@ type CanonicalizedVaultSet = {
manifestRecords: ManifestRecord[];
};
-/**
- * Write the caller's own manifest id into the `Settings` rows of a materialized vault, so every later
- * local query and write can resolve it offline. Left untouched when it is already correct: the row is
- * ordinary synced user data, and rewriting its timestamp on every pull would make each pull look like
- * a change and trigger a push.
- * @param materialized - the table set about to be inserted into the fresh vault DB
- * @param manifestId - the id of the manifest the server reported as the caller's own
- */
-function recordOwnManifestId(materialized: CodecMaterialized, manifestId: string): void {
- let settings = materialized.tables.find(t => t.name === 'Settings');
- if (!settings) {
- settings = { name: 'Settings', records: [] };
- materialized.tables.push(settings);
- }
-
- const now = new Date().toISOString();
-
- const existing = settings.records.find(r => r.Key === BaseQueries.PERSONAL_MANIFEST_SETTING_KEY);
- if (existing && existing.Value === manifestId && !existing.IsDeleted) {
- return;
- }
-
- if (existing) {
- Object.assign(existing, { Value: manifestId, UpdatedAt: now, IsDeleted: 0 });
- return;
- }
- settings.records.push({ Key: BaseQueries.PERSONAL_MANIFEST_SETTING_KEY, Value: manifestId, CreatedAt: now, UpdatedAt: now, IsDeleted: 0 });
-}
-
let canonicalizeCache: ({ client: SqliteClient; mutationSequence: number } & CanonicalizedVaultSet) | null = null;
/**
@@ -445,8 +415,8 @@ export class VaultSyncService {
* 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(sqliteClient);
- const { canonicalized, manifestRecords } = await this.canonicalizeVault(sqliteClient, { adoptUnstampedInto: ownManifestId });
+ const ownManifestId = await this.resolvePersonalManifestId();
+ const { canonicalized } = await this.canonicalizeVault(sqliteClient, { adoptUnstampedInto: ownManifestId });
/*
* Canonicalize already handed us every extracted favicon/attachment as plaintext bytes, so materialize can
@@ -463,15 +433,6 @@ export class VaultSyncService {
const schemaColumns = await VaultCodec.getSchemaColumns(schemaSql);
const materialized = await vaultCodecMaterializeAsSqlite(canonicalized.manifests.map(m => m.manifest), canonicalized.dataBuckets, schemaColumns);
- /*
- * Record which manifest is ours in the migrated vault, exactly as a pull does. A legacy vault has
- * never been materialized and so carries no such row, while the write path resolves the stamp for
- * a new row from it (see `BaseQueries.GET_PERSONAL_MANIFEST_ID`). Without this, every top-level insert
- * between the migration and the next pull resolves its stamp to NULL and is rejected outright by
- * the column's NOT NULL constraint.
- */
- recordOwnManifestId(materialized, manifestRecords[0].manifestId);
-
const sqliteBase64 = await VaultCodec.insertTables(materialized, blobMap, schemaSql);
devLog(`[ManifestMigration] Migration complete: ${blobMap.size} blobs re-embedded, ${sqliteBase64.length} base64 chars.`);
@@ -566,8 +527,9 @@ export class VaultSyncService {
if (isPersonal) {
/*
- * Persist the personal manifest's blob salt locally so subsequent canonicalizes hash blobs the same way, and the personal
- * manifest id so a push can resolve it even before the vault DB records it (see `recordOwnManifestId`).
+ * Persist the personal manifest's blob salt locally so subsequent canonicalizes hash blobs the same way, and the
+ * personal manifest id, which is the sole record of it: it is server-reported client state, not vault content, so
+ * it stays out of the vault (`SqliteClient` hydrates it from here whenever the database is opened).
*/
await storage.setItem(StorageKeys.VAULT_MANIFEST_SALT, entry.manifest.manifestSalt);
await storage.setItem(StorageKeys.VAULT_PERSONAL_MANIFEST_ID, entry.manifestId);
@@ -719,14 +681,6 @@ export class VaultSyncService {
devWarn(`[V2Pull] Newer-schema data preserved as overflow: ${overflowTableCount} unknown table(s), unknown columns on [${overflowColumnTables.join(', ')}]. It will round-trip on push but is not usable locally until the app is updated.`);
}
- /*
- * Record which of these manifests is ours, inside the vault we are assembling. The codec treats
- * every manifest alike: a user may own several, and which one a client calls home is its own
- * state. So this comes from what the server reported in this snapshot, and it is what the local
- * write path stamps new rows with (see `BaseQueries.GET_PERSONAL_MANIFEST_ID`).
- */
- recordOwnManifestId(materialized, personal.manifestId);
-
const sqliteBase64 = await VaultCodec.insertTables(materialized, blobMap, schemaSql);
devLog('[V2Pull] Codec reassembly complete.');
@@ -1453,7 +1407,7 @@ export class VaultSyncService {
}
const records: ManifestRecord[] = [{
- manifestId: await this.resolvePersonalManifestId(sqliteClient),
+ manifestId: await this.resolvePersonalManifestId(),
isPersonal: true,
salt: manifestSalt,
folderId: null,
@@ -1493,15 +1447,14 @@ export class VaultSyncService {
}
/**
- * The id of this vault's own (personal) manifest. The vault DB's own setting is the durable source (written on each
- * materialize); the storage copy covers the one case where no materialize has run yet: the local schema
- * migration of a legacy sqlite-blob vault, which canonicalizes before it records the setting row.
- * @param sqliteClient - the open local vault DB
+ * The id of this vault's own (personal) manifest, as reported by the server on the last pull. It is client state
+ * rather than vault content, so local storage is its only home; the vault carries no copy that could go stale or
+ * outlive the account.
*/
- private async resolvePersonalManifestId(sqliteClient: SqliteClient): Promise<string> {
- const personalManifestId = sqliteClient.settings.getPersonalManifestId() ?? ((await storage.getItem(StorageKeys.VAULT_PERSONAL_MANIFEST_ID)) as string | null);
+ private async resolvePersonalManifestId(): Promise<string> {
+ const personalManifestId = (await storage.getItem(StorageKeys.VAULT_PERSONAL_MANIFEST_ID)) as string | null;
if (!personalManifestId) {
- throw new Error('VaultSyncService: no personal manifest id available (no vault setting and no snapshot baseline); pull once before pushing.');
+ throw new Error('VaultSyncService: no personal manifest id available (no snapshot baseline recorded); pull once before pushing.');
}
return personalManifestId;
}
diff --git a/apps/browser-extension/src/utils/db/BaseRepository.ts b/apps/browser-extension/src/utils/db/BaseRepository.ts
index 6d8b474bf..a915e66ce 100644
--- a/apps/browser-extension/src/utils/db/BaseRepository.ts
+++ b/apps/browser-extension/src/utils/db/BaseRepository.ts
@@ -17,6 +17,7 @@ export interface IDatabaseClient {
commitTransaction(): Promise<void>;
rollbackTransaction(): void;
getActiveManifestId(): string | null;
+ getPersonalManifestId(): string | null;
}
/**
@@ -183,21 +184,18 @@ export abstract class BaseRepository {
protected activeManifestId(): string {
const manifestId = this.client.getActiveManifestId() ?? this.personalManifestId();
if (!manifestId) {
- throw new Error('BaseRepository: the vault has no manifest recorded yet (no active manifest and no personal manifest); sync once before writing.');
+ throw new Error('BaseRepository: this client has no manifest recorded yet (no active manifest and no personal manifest); sync once before writing.');
}
return manifestId;
}
/**
- * Get the id of the user's personal manifest, as recorded by the last pull.
+ * Get the id of the user's personal manifest, as recorded by the last pull. It is client state rather than
+ * vault content, so it is read off the client instead of out of the database.
* @returns The personal manifest id, or null when absent
*/
protected personalManifestId(): string | null {
- if (!this.tableExists('Settings')) {
- return null;
- }
- const results = this.client.executeQuery<{ Id: string }>(BaseQueries.GET_PERSONAL_MANIFEST_ID);
- return results.length > 0 ? results[0].Id : null;
+ return this.client.getPersonalManifestId();
}
/**
diff --git a/apps/browser-extension/src/utils/db/queries/BaseQueries.ts b/apps/browser-extension/src/utils/db/queries/BaseQueries.ts
index 36b41316f..5b7c6939b 100644
--- a/apps/browser-extension/src/utils/db/queries/BaseQueries.ts
+++ b/apps/browser-extension/src/utils/db/queries/BaseQueries.ts
@@ -2,24 +2,6 @@
* SQL query constants for generic base operations.
*/
export class BaseQueries {
- /**
- * The settings key holding the id of the manifest this client treats as its personal one: the vault
- * the server hands the user at registration, and the default target for anything they create.
- *
- * It lives in Settings rather than in the Manifests bookkeeping table because it is not a property
- * of the vault. The codec treats every manifest alike and a user may own several; which of them is
- * *this* client's home is the client's own state, told to it by the server on each pull.
- */
- public static readonly PERSONAL_MANIFEST_SETTING_KEY = 'PersonalManifestId';
-
- /**
- * The vault's personal manifest id, written by the sync service from what the server reports on each
- * pull. It is the default the active manifest falls back to.
- */
- public static readonly GET_PERSONAL_MANIFEST_ID = `
- SELECT Value AS Id FROM Settings
- WHERE Key = '${BaseQueries.PERSONAL_MANIFEST_SETTING_KEY}' AND IsDeleted = 0 LIMIT 1`;
-
/**
* SQL fragment resolving the manifest a row placed in the folder bound to its first `?` (possibly
* NULL) belongs to: that folder's manifest, or the manifest bound to its second `?` when the row sits
diff --git a/apps/browser-extension/src/utils/db/repositories/SettingsRepository.ts b/apps/browser-extension/src/utils/db/repositories/SettingsRepository.ts
index 9d2d70684..211e3008e 100644
--- a/apps/browser-extension/src/utils/db/repositories/SettingsRepository.ts
+++ b/apps/browser-extension/src/utils/db/repositories/SettingsRepository.ts
@@ -105,14 +105,6 @@ export class SettingsRepository extends BaseRepository {
return this.client.executeQuery<EncryptionKey>(EncryptionKeyQueries.GET_ALL);
}
- /**
- * Get the id of the vault's own (personal) manifest.
- * @returns The personal manifest id, or null when not known yet
- */
- public getPersonalManifestId(): string | null {
- return this.personalManifestId();
- }
-
/**
* Get the user's active personal keypair.
* @returns The active personal keypair, or null when absent