Privacy-first password manager with built-in email aliasing. Fully encrypted and self-hostable.
Refactor settings structure (#2159)
Leendert de Borstca89a11a3278
diff --git a/apps/browser-extension/src/entrypoints/popup/components/EmailPreview.tsx b/apps/browser-extension/src/entrypoints/popup/components/EmailPreview.tsxindex 0c78aa397..e52c7c8e8 100644--- a/apps/browser-extension/src/entrypoints/popup/components/EmailPreview.tsx+++ b/apps/browser-extension/src/entrypoints/popup/components/EmailPreview.tsx@@ -148,7 +148,7 @@ export const EmailPreview: React.FC<EmailPreviewProps> = ({ email }) => {// Loop through all emails and decrypt them locallyconst decryptedEmails: MailboxEmail[] = await EncryptionUtility.decryptEmailList(allMails,- dbContext.sqliteClient!.settings.getAllEncryptionKeys()+ dbContext.sqliteClient!.encryptionKeys.getAll());if (loading && decryptedEmails.length > 0) {diff --git a/apps/browser-extension/src/entrypoints/popup/components/Items/Details/AttachmentBlock.tsx b/apps/browser-extension/src/entrypoints/popup/components/Items/Details/AttachmentBlock.tsxindex 9e5171d30..7e479fdf1 100644--- a/apps/browser-extension/src/entrypoints/popup/components/Items/Details/AttachmentBlock.tsx+++ b/apps/browser-extension/src/entrypoints/popup/components/Items/Details/AttachmentBlock.tsx@@ -57,7 +57,7 @@ const AttachmentBlock: React.FC<AttachmentBlockProps> = ({ itemId }) => {}try {- const attachmentList = dbContext.sqliteClient.settings.getAttachmentsForItem(itemId);+ const attachmentList = dbContext.sqliteClient.items.getAttachmentsForItem(itemId);setAttachments(attachmentList);} catch (error) {console.error('Error loading attachments:', error);diff --git a/apps/browser-extension/src/entrypoints/popup/components/Items/Details/TotpBlock.tsx b/apps/browser-extension/src/entrypoints/popup/components/Items/Details/TotpBlock.tsxindex 4b8cc01db..9ebcbfff4 100644--- a/apps/browser-extension/src/entrypoints/popup/components/Items/Details/TotpBlock.tsx+++ b/apps/browser-extension/src/entrypoints/popup/components/Items/Details/TotpBlock.tsx@@ -113,7 +113,7 @@ const TotpBlock: React.FC<TotpBlockProps> = ({ itemId }) => {}try {- const codes = dbContext.sqliteClient.settings.getTotpCodesForItem(itemId);+ const codes = dbContext.sqliteClient.items.getTotpCodesForItem(itemId);setTotpCodes(codes);} catch (error) {console.error('Error loading TOTP codes:', error);diff --git a/apps/browser-extension/src/entrypoints/popup/pages/emails/EmailDetails.tsx b/apps/browser-extension/src/entrypoints/popup/pages/emails/EmailDetails.tsxindex 3ea7601f7..ec8ec01e6 100644--- a/apps/browser-extension/src/entrypoints/popup/pages/emails/EmailDetails.tsx+++ b/apps/browser-extension/src/entrypoints/popup/pages/emails/EmailDetails.tsx@@ -73,7 +73,7 @@ const EmailDetails: React.FC = (): React.ReactElement => {const response = await webApi.get<Email>(`Email/${id}`);// Decrypt email locally using public/private key pairs- const encryptionKeys = dbContext.sqliteClient.settings.getAllEncryptionKeys();+ const encryptionKeys = dbContext.sqliteClient.encryptionKeys.getAll();const decryptedEmail = await EncryptionUtility.decryptEmail(response, encryptionKeys);setEmail(decryptedEmail);@@ -181,7 +181,7 @@ const EmailDetails: React.FC = (): React.ReactElement => {}// Get encryption keys for decryption- const encryptionKeys = dbContext.sqliteClient.settings.getAllEncryptionKeys();+ const encryptionKeys = dbContext.sqliteClient.encryptionKeys.getAll();// Decrypt the attachment using raw bytesconst decryptedBytes = await EncryptionUtility.decryptAttachment(encryptedBytes, email, encryptionKeys);diff --git a/apps/browser-extension/src/entrypoints/popup/pages/emails/EmailsList.tsx b/apps/browser-extension/src/entrypoints/popup/pages/emails/EmailsList.tsxindex 085d99d61..001faf725 100644--- a/apps/browser-extension/src/entrypoints/popup/pages/emails/EmailsList.tsx+++ b/apps/browser-extension/src/entrypoints/popup/pages/emails/EmailsList.tsx@@ -73,7 +73,7 @@ const EmailsList: React.FC = () => {});// Decrypt emails locally using private key associated with the email address.- const encryptionKeys = dbContext.sqliteClient.settings.getAllEncryptionKeys();+ const encryptionKeys = dbContext.sqliteClient.encryptionKeys.getAll();// Decrypt emails locally using public/private key pairs.const decryptedEmails = await EncryptionUtility.decryptEmailList(data.mails, encryptionKeys);@@ -117,7 +117,7 @@ const EmailsList: React.FC = () => {});// Decrypt emails locally- const encryptionKeys = dbContext.sqliteClient.settings.getAllEncryptionKeys();+ const encryptionKeys = dbContext.sqliteClient.encryptionKeys.getAll();const decryptedEmails = await EncryptionUtility.decryptEmailList(data.mails, encryptionKeys);// Append to existing emailsdiff --git a/apps/browser-extension/src/entrypoints/popup/pages/items/ItemAddEdit.tsx b/apps/browser-extension/src/entrypoints/popup/pages/items/ItemAddEdit.tsxindex f38f569ba..3e13d7e14 100644--- a/apps/browser-extension/src/entrypoints/popup/pages/items/ItemAddEdit.tsx+++ b/apps/browser-extension/src/entrypoints/popup/pages/items/ItemAddEdit.tsx@@ -464,7 +464,7 @@ const ItemAddEdit: React.FC = () => {setInitiallyVisibleFields(fieldsWithValues);// Load TOTP codes for this item- const itemTotpCodes = sqliteClient.settings.getTotpCodesForItem(id);+ const itemTotpCodes = sqliteClient.items.getTotpCodesForItem(id, result.ManifestId);setTotpCodes(itemTotpCodes);setOriginalTotpCodeIds(itemTotpCodes.map((tc) => tc.Id));if (itemTotpCodes.length > 0) {@@ -472,7 +472,7 @@ const ItemAddEdit: React.FC = () => {}// Load attachments for this item- const itemAttachments = sqliteClient.settings.getAttachmentsForItem(id);+ const itemAttachments = sqliteClient.items.getAttachmentsForItem(id, result.ManifestId);setAttachments(itemAttachments);setOriginalAttachmentIds(itemAttachments.map((a) => a.Id));if (itemAttachments.length > 0) {diff --git a/apps/browser-extension/src/utils/SqliteClient.ts b/apps/browser-extension/src/utils/SqliteClient.tsindex 62f05a1b0..2154161a1 100644--- a/apps/browser-extension/src/utils/SqliteClient.ts+++ b/apps/browser-extension/src/utils/SqliteClient.ts@@ -14,6 +14,7 @@ import {PasskeyRepository,FolderRepository,SettingsRepository,+ EncryptionKeyRepository,LogoRepository} from './db';@@ -47,6 +48,7 @@ export class SqliteClient implements IDatabaseClient {private _passkeys: PasskeyRepository | null = null;private _folders: FolderRepository | null = null;private _settings: SettingsRepository | null = null;+ private _encryptionKeys: EncryptionKeyRepository | null = null;private _logos: LogoRepository | null = null;/**@@ -118,7 +120,7 @@ export class SqliteClient implements IDatabaseClient {}/**- * Repository for Settings and auxiliary data operations.+ * Repository for the vault's user preferences.*/public get settings(): SettingsRepository {if (!this._settings) {@@ -127,6 +129,16 @@ export class SqliteClient implements IDatabaseClient {return this._settings;}+ /**+ * Repository for the per-manifest keypairs that receive mail.+ */+ public get encryptionKeys(): EncryptionKeyRepository {+ if (!this._encryptionKeys) {+ this._encryptionKeys = new EncryptionKeyRepository(this);+ }+ return this._encryptionKeys;+ }+/*** Repository for item logo operations (favicons, built-in logos and uploaded images alike).*/diff --git a/apps/browser-extension/src/utils/VaultSyncService.ts b/apps/browser-extension/src/utils/VaultSyncService.tsindex 8cbc42f40..154f09f34 100644--- a/apps/browser-extension/src/utils/VaultSyncService.ts+++ b/apps/browser-extension/src/utils/VaultSyncService.ts@@ -1130,7 +1130,7 @@ export class VaultSyncService {/** Publish the public half of the vault's active personal keypair, which is e.g. used by SMTP services to encrypt mail for personal aliases.*/- const primaryKey = sqliteClient.settings.getPrimaryEncryptionKey();+ const primaryKey = sqliteClient.encryptionKeys.getPrimary();/** Publish the public half of each shared manifest's email keypair that this user administers, which is e.g. used by SMTP services to encrypt@@ -1143,7 +1143,7 @@ export class VaultSyncService {if (!record.canAdminister) {continue;}- const manifestKey = sqliteClient.settings.getActiveManifestEncryptionKey(record.manifestId);+ const manifestKey = sqliteClient.encryptionKeys.getActiveForManifest(record.manifestId);if (manifestKey) {sharedManifestEncryptionPublicKeys.push({ manifestId: record.manifestId, publicKey: manifestKey.PublicKey });} else {diff --git a/apps/browser-extension/src/utils/db/index.ts b/apps/browser-extension/src/utils/db/index.tsindex 380ac30a4..05baf5084 100644--- a/apps/browser-extension/src/utils/db/index.ts+++ b/apps/browser-extension/src/utils/db/index.ts@@ -19,5 +19,6 @@ export { ItemRepository } from './repositories/ItemRepository';export { PasskeyRepository } from './repositories/PasskeyRepository';export { FolderRepository, type Folder } from './repositories/FolderRepository';export { SettingsRepository } from './repositories/SettingsRepository';+export { EncryptionKeyRepository } from './repositories/EncryptionKeyRepository';export { LogoRepository } from './repositories/LogoRepository';export { ItemStatsRepository, type ItemStats, type ItemUsageAction } from './repositories/ItemStatsRepository';diff --git a/apps/browser-extension/src/utils/db/queries/ItemQueries.ts b/apps/browser-extension/src/utils/db/queries/ItemQueries.tsindex 156afc3aa..c9c3eaf54 100644--- a/apps/browser-extension/src/utils/db/queries/ItemQueries.ts+++ b/apps/browser-extension/src/utils/db/queries/ItemQueries.ts@@ -432,10 +432,11 @@ export class FieldHistoryQueries {*/export class TotpCodeQueries {/**- * Get existing TOTP codes for an item.+ * Get an item's TOTP codes. Scoped by manifest as well as item: an id alone does not name one item,+ * so a bare `ItemId` match would pull in a same-id item's codes from another manifest.*/public static readonly GET_BY_ITEM_ID = `- SELECT Id, Name, SecretKey+ SELECT Id, Name, SecretKey, ItemIdFROM TotpCodesWHERE ItemId = ? AND ManifestId = ? AND IsDeleted = 0`;@@ -470,6 +471,22 @@ export class TotpCodeQueries {* SQL query constants for Attachment operations.*/export class AttachmentQueries {+ /**+ * Get an item's attachments. Scoped by manifest as well as item, for the same reason as+ * {@link TotpCodeQueries.GET_BY_ITEM_ID}.+ */+ public static readonly GET_BY_ITEM_ID = `+ SELECT+ Id,+ Filename,+ Blob,+ ItemId,+ CreatedAt,+ UpdatedAt,+ IsDeleted+ FROM Attachments+ WHERE ItemId = ? AND ManifestId = ? AND IsDeleted = 0`;+/*** Insert a new attachment, stamped with the manifest of the item it hangs off.*/diff --git a/apps/browser-extension/src/utils/db/queries/SettingsQueries.ts b/apps/browser-extension/src/utils/db/queries/SettingsQueries.tsindex 98e06d7b0..5e1f749be 100644--- a/apps/browser-extension/src/utils/db/queries/SettingsQueries.ts+++ b/apps/browser-extension/src/utils/db/queries/SettingsQueries.ts@@ -44,31 +44,4 @@ export class SettingsQueries {public static readonly INSERT_SETTING = `INSERT INTO Settings (ManifestId, Key, Value, CreatedAt, UpdatedAt, IsDeleted)VALUES (?, ?, ?, ?, ?, ?)`;-- /**- * Get TOTP codes for an item.- */- public static readonly GET_TOTP_FOR_ITEM = `- SELECT- Id,- Name,- SecretKey,- ItemId- FROM TotpCodes- WHERE ItemId = ? AND IsDeleted = 0`;-- /**- * Get attachments for an item.- */- public static readonly GET_ATTACHMENTS_FOR_ITEM = `- SELECT- Id,- Filename,- Blob,- ItemId,- CreatedAt,- UpdatedAt,- IsDeleted- FROM Attachments- WHERE ItemId = ? AND IsDeleted = 0`;}diff --git a/apps/browser-extension/src/utils/db/repositories/EncryptionKeyRepository.ts b/apps/browser-extension/src/utils/db/repositories/EncryptionKeyRepository.tsnew file mode 100644index 000000000..e3fa19822--- /dev/null+++ b/apps/browser-extension/src/utils/db/repositories/EncryptionKeyRepository.ts@@ -0,0 +1,78 @@+import type { EncryptionKey } from '@/utils/dist/core/models/vault';++import { BaseRepository } from '../BaseRepository';+import { EncryptionKeyQueries } from '../queries/EncryptionKeyQueries';++/**+ * Repository for the asymmetric keypairs that receive mail.+ *+ * Every manifest owns one active keypair whose public half is published to the server as that manifest's+ * delivery key; rotation demotes rather than deletes, so mail encrypted to a superseded key stays+ * readable. The user's personal keypair is simply the personal manifest's active one.+ */+export class EncryptionKeyRepository extends BaseRepository {+ /**+ * Fetch every keypair that can decrypt inbound mail (both personal manifest and optional shared manifest keys).+ * @returns Array of encryption keys+ */+ public getAll(): EncryptionKey[] {+ return this.client.executeQuery<EncryptionKey>(EncryptionKeyQueries.GET_ALL);+ }++ /**+ * Get the user's active personal keypair.+ * @returns The active personal keypair, or null when absent+ */+ public getPrimary(): EncryptionKey | null {+ const personalManifestId = this.personalManifestId();+ return personalManifestId ? this.getActiveForManifest(personalManifestId) : null;+ }++ /**+ * Get a manifest's active keypair, whose public half is published to the server as that manifest's delivery+ * key. Returns null for a manifest that has no keypair in this vault.+ * @param manifestId - The manifest id the keypair is stamped with+ * @returns The active keypair, or null when the manifest has none+ */+ public getActiveForManifest(manifestId: string): EncryptionKey | null {+ const results = this.client.executeQuery<EncryptionKey>(EncryptionKeyQueries.GET_ACTIVE_FOR_MANIFEST, [manifestId]);+ return results.length > 0 ? results[0] : null;+ }++ /**+ * Make the given keypair the manifest's active one, demoting (never deleting) whatever it supersedes so+ * mail received before the rotation stays decryptable.+ * @param manifestId - The manifest id to stamp the keypair with+ * @param publicKey - The public half, published to the server for delivery+ * @param privateKey - The private half, which never leaves the manifest+ */+ public setActiveForManifest(manifestId: string, publicKey: string, privateKey: string): void {+ const now = this.now();+ this.client.executeUpdate(EncryptionKeyQueries.DEMOTE_FOR_MANIFEST, [now, manifestId]);+ this.client.executeUpdate(EncryptionKeyQueries.INSERT_FOR_MANIFEST, [this.generateId(), manifestId, publicKey, privateKey, now, now]);+ }++ /**+ * Retain a copy of a keypair among the personal keys as a non-primary row.+ *+ * Used by the owner of a shared manifest to keep its delivery keys. The originals live only in the+ * shared manifest itself, so unsharing or deleting the anchor folder takes them out of the vault and would leave the+ * owner unable to decrypt mail their own alias received while it was shared.+ * @param publicKey - The public half, used as the identity of the key+ * @param privateKey - The private half+ */+ public retainNonPrimary(publicKey: string, privateKey: string): void {+ const personalManifestId = this.personalManifestId();+ if (!personalManifestId) {+ return;+ }++ const existing = this.client.executeQuery<{ count: number }>(EncryptionKeyQueries.COUNT_BY_PUBLIC_KEY, [personalManifestId, publicKey]);+ if ((existing[0]?.count ?? 0) > 0) {+ return;+ }++ const now = this.now();+ this.client.executeUpdate(EncryptionKeyQueries.INSERT_NON_PRIMARY, [this.generateId(), personalManifestId, publicKey, privateKey, now, now]);+ }+}diff --git a/apps/browser-extension/src/utils/db/repositories/ItemRepository.ts b/apps/browser-extension/src/utils/db/repositories/ItemRepository.tsindex 5e27a5f13..10cce7d9e 100644--- a/apps/browser-extension/src/utils/db/repositories/ItemRepository.ts+++ b/apps/browser-extension/src/utils/db/repositories/ItemRepository.ts@@ -622,6 +622,34 @@ export class ItemRepository extends BaseRepository {}}+ /**+ * Get an item's TOTP codes.+ * @param itemId - The ID of the item to get TOTP codes for+ * @param manifestId - The manifest the item belongs to, when known+ * @returns Array of TotpCode objects+ */+ public getTotpCodesForItem(itemId: string, manifestId?: string): TotpCode[] {+ const ref = this.resolveItemRef(itemId, manifestId);+ if (!ref) {+ return [];+ }+ return this.client.executeQuery<TotpCode>(TotpCodeQueries.GET_BY_ITEM_ID, [ref.Id, ref.ManifestId]);+ }++ /**+ * Get an item's attachments.+ * @param itemId - The ID of the item+ * @param manifestId - The manifest the item belongs to, when known+ * @returns Array of attachments for the item+ */+ public getAttachmentsForItem(itemId: string, manifestId?: string): Attachment[] {+ const ref = this.resolveItemRef(itemId, manifestId);+ if (!ref) {+ return [];+ }+ return this.client.executeQuery<Attachment>(AttachmentQueries.GET_BY_ITEM_ID, [ref.Id, ref.ManifestId]);+ }+/*** Get field history for a specific field.* @param itemId - The ID of the item@@ -1153,11 +1181,7 @@ export class ItemRepository extends BaseRepository {currentDateTime: string): void {// Fetch existing TOTP codes to compare values- const existingTotpCodes = this.client.executeQuery<{- Id: string;- Name: string;- SecretKey: string;- }>(TotpCodeQueries.GET_BY_ITEM_ID, [itemId, manifestId]);+ const existingTotpCodes = this.client.executeQuery<TotpCode>(TotpCodeQueries.GET_BY_ITEM_ID, [itemId, manifestId]);const existingByIdMap = new Map(existingTotpCodes.map(tc => [tc.Id, tc]));diff --git a/apps/browser-extension/src/utils/db/repositories/SettingsRepository.ts b/apps/browser-extension/src/utils/db/repositories/SettingsRepository.tsindex 5f99e015e..c7f863a8c 100644--- a/apps/browser-extension/src/utils/db/repositories/SettingsRepository.ts+++ b/apps/browser-extension/src/utils/db/repositories/SettingsRepository.ts@@ -1,9 +1,8 @@import { DEFAULT_PASSWORD_LENGTH, DEFAULT_WORD_COUNT, DEFAULT_LANGUAGE_CODE, matchAvailableLanguage } from '@/utils/dist/core/models/defaults';-import type { EncryptionKey, PasswordSettings, TotpCode, Attachment } from '@/utils/dist/core/models/vault';+import type { PasswordSettings } from '@/utils/dist/core/models/vault';import { getIdentityLanguages } from '@/utils/RustCore';import { BaseRepository } from '../BaseRepository';-import { EncryptionKeyQueries } from '../queries/EncryptionKeyQueries';import { SettingsQueries } from '../queries/SettingsQueries';/**@@ -12,7 +11,7 @@ import { SettingsQueries } from '../queries/SettingsQueries';export type CredentialSortOrder = 'OldestFirst' | 'NewestFirst' | 'Alphabetical';/**- * Repository for Settings and auxiliary data operations.+ * Repository for the vault's user preferences: the manifest-scoped key/value rows of the Settings table.*/export class SettingsRepository extends BaseRepository {/**@@ -97,110 +96,6 @@ export class SettingsRepository extends BaseRepository {this.updateSetting('PasswordGenerationSettings', JSON.stringify(settings));}- /**- * Fetch every keypair that can decrypt inbound mail (both personal manifest and optional shared manifest keys).- * @returns Array of encryption keys- */- public getAllEncryptionKeys(): EncryptionKey[] {- return this.client.executeQuery<EncryptionKey>(EncryptionKeyQueries.GET_ALL);- }-- /**- * Get the user's active personal keypair.- * @returns The active personal keypair, or null when absent- */- public getPrimaryEncryptionKey(): EncryptionKey | null {- const personalManifestId = this.personalManifestId();- return personalManifestId ? this.getActiveManifestEncryptionKey(personalManifestId) : null;- }-- /**- * Get a manifest's active keypair, whose public half is published to the server as that manifest's delivery- * key. Returns null for a manifest that has no keypair in this vault.- * @param manifestId - The manifest id the keypair is stamped with- * @returns The active keypair, or null when the manifest has none- */- public getActiveManifestEncryptionKey(manifestId: string): EncryptionKey | null {- const results = this.client.executeQuery<EncryptionKey>(EncryptionKeyQueries.GET_ACTIVE_FOR_MANIFEST, [manifestId]);- return results.length > 0 ? results[0] : null;- }-- /**- * Make the given keypair the manifest's active one, demoting (never deleting) whatever it supersedes so- * mail received before the rotation stays decryptable.- * @param manifestId - The manifest id to stamp the keypair with- * @param publicKey - The public half, published to the server for delivery- * @param privateKey - The private half, which never leaves the manifest- */- public setActiveManifestEncryptionKey(manifestId: string, publicKey: string, privateKey: string): void {- const now = this.now();- this.client.executeUpdate(EncryptionKeyQueries.DEMOTE_FOR_MANIFEST, [now, manifestId]);- this.client.executeUpdate(EncryptionKeyQueries.INSERT_FOR_MANIFEST, [this.generateId(), manifestId, publicKey, privateKey, now, now]);- }-- /**- * Retain a copy of a keypair among the personal keys as a non-primary row.- *- * Used by the owner of a shared manifest to keep its delivery keys. The originals live only in the- * shared manifest itself, so unsharing or deleting the anchor folder takes them out of the vault and would leave the- * owner unable to decrypt mail their own alias received while it was shared.- * @param publicKey - The public half, used as the identity of the key- * @param privateKey - The private half- */- public retainNonPrimaryEncryptionKey(publicKey: string, privateKey: string): void {- const personalManifestId = this.personalManifestId();- if (!personalManifestId) {- return;- }-- const existing = this.client.executeQuery<{ count: number }>(EncryptionKeyQueries.COUNT_BY_PUBLIC_KEY, [personalManifestId, publicKey]);- if ((existing[0]?.count ?? 0) > 0) {- return;- }-- const now = this.now();- this.client.executeUpdate(EncryptionKeyQueries.INSERT_NON_PRIMARY, [this.generateId(), personalManifestId, publicKey, privateKey, now, now]);- }-- /**- * Get TOTP codes for an item.- * @param itemId - The ID of the item to get TOTP codes for- * @returns Array of TotpCode objects- */- public getTotpCodesForItem(itemId: string): TotpCode[] {- try {- if (!this.tableExists('TotpCodes')) {- return [];- }-- return this.client.executeQuery<TotpCode>(SettingsQueries.GET_TOTP_FOR_ITEM, [itemId]);- } catch (error) {- console.error('Error getting TOTP codes for item:', error);- return [];- }- }-- /**- * Get attachments for an item.- * @param itemId - The ID of the item- * @returns Array of attachments for the item- */- public getAttachmentsForItem(itemId: string): Attachment[] {- try {- if (!this.tableExists('Attachments')) {- return [];- }-- return this.client.executeQuery<Attachment>(- SettingsQueries.GET_ATTACHMENTS_FOR_ITEM,- [itemId]- );- } catch (error) {- console.error('Error getting attachments for item:', error);- return [];- }- }-/*** Get the default email domain for new aliases.* @returns The default email domain or empty string if not set