Privacy-first password manager with built-in email aliasing. Fully encrypted and self-hostable.
Add BaseQueries.ts (#2159)
Leendert de Borst9ae3dcae189b
diff --git a/apps/browser-extension/src/utils/db/BaseRepository.ts b/apps/browser-extension/src/utils/db/BaseRepository.tsindex 7dd83922f..e03072922 100644--- a/apps/browser-extension/src/utils/db/BaseRepository.ts+++ b/apps/browser-extension/src/utils/db/BaseRepository.ts@@ -1,6 +1,6 @@import * as dateFormatter from '@/utils/DateFormatter';-import { SettingsQueries } from './queries/SettingsQueries';+import { BaseQueries } from './queries/BaseQueries';import type { Database } from 'sql.js';@@ -123,7 +123,7 @@ export abstract class BaseRepository {if (!this.tableExists('Manifests')) {return null;}- const results = this.client.executeQuery<{ Id: string }>(SettingsQueries.GET_ROOT_MANIFEST_ID);+ const results = this.client.executeQuery<{ Id: string }>(BaseQueries.GET_ROOT_MANIFEST_ID);return results.length > 0 ? results[0].Id : null;}diff --git a/apps/browser-extension/src/utils/db/queries/BaseQueries.ts b/apps/browser-extension/src/utils/db/queries/BaseQueries.tsnew file mode 100644index 000000000..af19e9797--- /dev/null+++ b/apps/browser-extension/src/utils/db/queries/BaseQueries.ts@@ -0,0 +1,36 @@+/**+ * SQL query constants for generic base operations.+ */+export class BaseQueries {+ /**+ * SQL fragment resolving the vault's root manifest id, for embedding in a larger statement (an+ * INSERT's VALUES list, a comparison). Use GET_ROOT_MANIFEST_ID to query it standalone.+ */+ public static readonly ROOT_MANIFEST_ID = `(SELECT Id FROM Manifests WHERE IsRoot = 1)`;++ /**+ * The vault's root manifest id, from the Manifests bookkeeping table (written by the codec on every+ * materialize, and by the app at fresh-vault creation).+ */+ public static readonly GET_ROOT_MANIFEST_ID = `+ SELECT Id FROM Manifests WHERE IsRoot = 1 LIMIT 1`;++ /**+ * Register the vault's root manifest row at fresh-vault creation (idempotent). Every later+ * materialize rewrites the table from the manifest set.+ */+ public static readonly INSERT_ROOT_MANIFEST = `+ INSERT OR REPLACE INTO Manifests (Id, IsRoot, AnchorFolderId)+ VALUES (?, 1, NULL)`;++ /**+ * SQL fragment resolving the scope of personal rows: rows stamped with the root manifest's id, plus+ * unstamped legacy rows the codec has not adopted yet (it restamps them at the next sync boundary).+ * @param alias - Table alias to qualify the ManifestId column with, or omitted for an unaliased query+ * @returns The predicate, for interpolation into a WHERE clause+ */+ public static personalScope(alias?: string): string {+ const column = alias ? `${alias}.ManifestId` : 'ManifestId';+ return `(${column} = ${BaseQueries.ROOT_MANIFEST_ID} OR ${column} IS NULL)`;+ }+}diff --git a/apps/browser-extension/src/utils/db/queries/EncryptionKeyQueries.ts b/apps/browser-extension/src/utils/db/queries/EncryptionKeyQueries.tsnew file mode 100644index 000000000..710f4af07--- /dev/null+++ b/apps/browser-extension/src/utils/db/queries/EncryptionKeyQueries.ts@@ -0,0 +1,77 @@+import { BaseQueries } from './BaseQueries';++/**+ * SQL query constants for encryption keypair operations.+ */+export class EncryptionKeyQueries {+ /**+ * Get every keypair in the vault, personal (root-stamped) and shared-manifest-stamped alike. Superseded+ * (rotated) keys are included as well, as mail received before a rotation is still encrypted with them.+ */+ public static readonly GET_ALL = `+ SELECT+ x.PublicKey,+ x.PrivateKey,+ x.IsPrimary+ FROM EncryptionKeys x+ WHERE x.IsDeleted = 0`;++ /**+ * Get the user's active personal keypair: the primary row stamped with the root manifest's id.+ */+ public static readonly GET_PRIMARY = `+ SELECT+ x.Id,+ x.PublicKey,+ x.PrivateKey,+ x.IsPrimary+ FROM EncryptionKeys x+ WHERE ${BaseQueries.personalScope('x')} AND x.IsPrimary = 1 AND x.IsDeleted = 0+ LIMIT 1`;++ /**+ * Count the personal (root-stamped) encryption keys carrying a given public key, to keep retained copies+ * idempotent.+ */+ public static readonly COUNT_BY_PUBLIC_KEY = `+ SELECT COUNT(*) as count+ FROM EncryptionKeys x+ WHERE x.PublicKey = ? AND ${BaseQueries.personalScope('x')}`;++ /**+ * Retain a copy of a key in the personal keys, explicitly NOT primary, stamped with the root manifest's id.+ */+ public static readonly INSERT_NON_PRIMARY = `+ INSERT INTO EncryptionKeys (Id, ManifestId, PublicKey, PrivateKey, IsPrimary, CreatedAt, UpdatedAt, IsDeleted)+ VALUES (?, ${BaseQueries.ROOT_MANIFEST_ID}, ?, ?, 0, ?, ?, 0)`;++ /**+ * Get one manifest's active keypair: the key whose public half is published for SMTP delivery.+ */+ public static readonly GET_ACTIVE_FOR_MANIFEST = `+ SELECT+ x.Id,+ x.PublicKey,+ x.PrivateKey,+ x.IsPrimary+ FROM EncryptionKeys x+ WHERE x.ManifestId = ? AND x.IsPrimary = 1 AND x.IsDeleted = 0+ LIMIT 1`;++ /**+ * Demote a manifest's current keypair. Rotation demotes rather than deletes, so mail received before the+ * rotation stays decryptable by the members who still hold the folder.+ */+ public static readonly DEMOTE_FOR_MANIFEST = `+ UPDATE EncryptionKeys+ SET IsPrimary = 0, UpdatedAt = ?+ WHERE ManifestId = ? AND IsPrimary = 1`;++ /**+ * Insert a manifest's new active keypair, stamped with the manifest's id so the codec routes it into that+ * manifest (private half encrypted under the manifest's VEK, readable by exactly its members).+ */+ public static readonly INSERT_FOR_MANIFEST = `+ INSERT INTO EncryptionKeys (Id, ManifestId, PublicKey, PrivateKey, IsPrimary, CreatedAt, UpdatedAt, IsDeleted)+ VALUES (?, ?, ?, ?, 1, ?, ?, 0)`;+}diff --git a/apps/browser-extension/src/utils/db/queries/FolderQueries.ts b/apps/browser-extension/src/utils/db/queries/FolderQueries.tsindex 24d89f19b..50aa8e12b 100644--- a/apps/browser-extension/src/utils/db/queries/FolderQueries.ts+++ b/apps/browser-extension/src/utils/db/queries/FolderQueries.ts@@ -1,3 +1,5 @@+import { BaseQueries } from './BaseQueries';+/*** SQL query constants for Folder operations.* Centralizes all folder-related queries to avoid duplication.@@ -26,7 +28,7 @@ export class FolderQueries {*/public static readonly INSERT = `INSERT INTO Folders (Id, Name, ParentFolderId, ManifestId, Weight, IsDeleted, CreatedAt, UpdatedAt)- VALUES (?, ?, ?, (SELECT Id FROM Manifests WHERE IsRoot = 1), 0, 0, ?, ?)`;+ VALUES (?, ?, ?, ${BaseQueries.ROOT_MANIFEST_ID}, 0, 0, ?, ?)`;/*** Update folder name.diff --git a/apps/browser-extension/src/utils/db/queries/LogoQueries.ts b/apps/browser-extension/src/utils/db/queries/LogoQueries.tsindex d4b2ed45f..81c2d4bbd 100644--- a/apps/browser-extension/src/utils/db/queries/LogoQueries.ts+++ b/apps/browser-extension/src/utils/db/queries/LogoQueries.ts@@ -1,3 +1,5 @@+import { BaseQueries } from './BaseQueries';+/*** SQL query constants for item logo operations.*@@ -7,10 +9,9 @@*/export class LogoQueries {/**- * SQL fragment resolving the personal scope: rows stamped with the root manifest's id (from the- * Manifests bookkeeping table), plus unstamped legacy rows the codec has not adopted yet.+ * The scope of personal rows in this file's queries, which address Logos unaliased.*/- private static readonly PERSONAL_SCOPE = `(ManifestId = (SELECT Id FROM Manifests WHERE IsRoot = 1) OR ManifestId IS NULL)`;+ private static readonly PERSONAL_SCOPE = BaseQueries.personalScope();/*** The logo of a given kind and key in the personal scope. Shared-manifest rows are deliberately@@ -36,7 +37,7 @@ export class LogoQueries {*/public static readonly UPSERT = `INSERT INTO Logos (Id, Kind, Source, ManifestId, FileData, MimeType, Name, CreatedAt, UpdatedAt, IsDeleted)- VALUES (?, ?, ?, (SELECT Id FROM Manifests WHERE IsRoot = 1), ?, ?, ?, ?, ?, 0)+ VALUES (?, ?, ?, ${BaseQueries.ROOT_MANIFEST_ID}, ?, ?, ?, ?, ?, 0)ON CONFLICT(Id) DO UPDATE SETFileData = excluded.FileData,MimeType = excluded.MimeType,diff --git a/apps/browser-extension/src/utils/db/queries/SettingsQueries.ts b/apps/browser-extension/src/utils/db/queries/SettingsQueries.tsindex d5ddcc59a..5c5bcc8db 100644--- a/apps/browser-extension/src/utils/db/queries/SettingsQueries.ts+++ b/apps/browser-extension/src/utils/db/queries/SettingsQueries.ts@@ -35,16 +35,6 @@ export class SettingsQueries {INSERT INTO Settings (Key, Value, CreatedAt, UpdatedAt, IsDeleted)VALUES (?, ?, ?, ?, ?)`;- /**- * Get all encryption keys.- */- public static readonly GET_ENCRYPTION_KEYS = `- SELECT- x.PublicKey,- x.PrivateKey,- x.IsPrimary- FROM EncryptionKeys x`;-/*** Get TOTP codes for an item.*/diff --git a/apps/browser-extension/src/utils/db/repositories/SettingsRepository.ts b/apps/browser-extension/src/utils/db/repositories/SettingsRepository.tsindex 0b76d29d8..8553dc7fa 100644--- a/apps/browser-extension/src/utils/db/repositories/SettingsRepository.ts+++ b/apps/browser-extension/src/utils/db/repositories/SettingsRepository.ts@@ -3,6 +3,8 @@ import type { EncryptionKey, PasswordSettings, TotpCode, Attachment } from '@/utimport { getIdentityLanguages } from '@/utils/RustCore';import { BaseRepository } from '../BaseRepository';+import { BaseQueries } from '../queries/BaseQueries';+import { EncryptionKeyQueries } from '../queries/EncryptionKeyQueries';import { SettingsQueries } from '../queries/SettingsQueries';/**@@ -101,7 +103,7 @@ export class SettingsRepository extends BaseRepository {* @returns Array of encryption keys*/public getAllEncryptionKeys(): EncryptionKey[] {- return this.client.executeQuery<EncryptionKey>(SettingsQueries.GET_ENCRYPTION_KEYS);+ return this.client.executeQuery<EncryptionKey>(EncryptionKeyQueries.GET_ALL);}/**@@ -118,7 +120,7 @@ export class SettingsRepository extends BaseRepository {* @param manifestId - The server-side id of the root manifest*/public setRootManifestId(manifestId: string): void {- this.client.executeUpdate(SettingsQueries.INSERT_ROOT_MANIFEST, [manifestId]);+ this.client.executeUpdate(BaseQueries.INSERT_ROOT_MANIFEST, [manifestId]);}/**@@ -128,7 +130,7 @@ export class SettingsRepository extends BaseRepository {* @returns The active personal keypair, or null when absent*/public getPrimaryEncryptionKey(): EncryptionKey | null {- const results = this.client.executeQuery<EncryptionKey>(SettingsQueries.GET_PRIMARY_ENCRYPTION_KEY);+ const results = this.client.executeQuery<EncryptionKey>(EncryptionKeyQueries.GET_PRIMARY);return results.length > 0 ? results[0] : null;}@@ -139,7 +141,7 @@ export class SettingsRepository extends BaseRepository {* @returns The active keypair, or null when the manifest has none*/public getActiveManifestEncryptionKey(manifestId: string): EncryptionKey | null {- const results = this.client.executeQuery<EncryptionKey>(SettingsQueries.GET_ACTIVE_MANIFEST_ENCRYPTION_KEY, [manifestId]);+ const results = this.client.executeQuery<EncryptionKey>(EncryptionKeyQueries.GET_ACTIVE_FOR_MANIFEST, [manifestId]);return results.length > 0 ? results[0] : null;}@@ -152,8 +154,8 @@ export class SettingsRepository extends BaseRepository {*/public setActiveManifestEncryptionKey(manifestId: string, publicKey: string, privateKey: string): void {const now = this.now();- this.client.executeUpdate(SettingsQueries.DEMOTE_MANIFEST_ENCRYPTION_KEYS, [now, manifestId]);- this.client.executeUpdate(SettingsQueries.INSERT_MANIFEST_ENCRYPTION_KEY, [this.generateId(), manifestId, publicKey, privateKey, now, now]);+ this.client.executeUpdate(EncryptionKeyQueries.DEMOTE_FOR_MANIFEST, [now, manifestId]);+ this.client.executeUpdate(EncryptionKeyQueries.INSERT_FOR_MANIFEST, [this.generateId(), manifestId, publicKey, privateKey, now, now]);}/**@@ -166,13 +168,13 @@ export class SettingsRepository extends BaseRepository {* @param privateKey - The private half*/public retainNonPrimaryEncryptionKey(publicKey: string, privateKey: string): void {- const existing = this.client.executeQuery<{ count: number }>(SettingsQueries.COUNT_ENCRYPTION_KEYS_BY_PUBLIC_KEY, [publicKey]);+ const existing = this.client.executeQuery<{ count: number }>(EncryptionKeyQueries.COUNT_BY_PUBLIC_KEY, [publicKey]);if ((existing[0]?.count ?? 0) > 0) {return;}const now = this.now();- this.client.executeUpdate(SettingsQueries.INSERT_NON_PRIMARY_ENCRYPTION_KEY, [this.generateId(), publicKey, privateKey, now, now]);+ this.client.executeUpdate(EncryptionKeyQueries.INSERT_NON_PRIMARY, [this.generateId(), publicKey, privateKey, now, now]);}/**