Privacy-first password manager with built-in email aliasing. Fully encrypted and self-hostable.
Update core/client query structure to support both sync and async calls (#2159)
Leendert de Borst81ef962e370e
diff --git a/apps/browser-extension/README.md b/apps/browser-extension/README.mdindex 963388bf9..366ff8412 100644--- a/apps/browser-extension/README.md+++ b/apps/browser-extension/README.md@@ -6,7 +6,7 @@ The browser extension is built using WXT and React:The extension links the shared core packages (`core/client`, `core/models`, `core/vault`) as `file:`dependencies, so this folder expects to sit in the repository next to the `core` folder. `npm install`-also installs the dependencies of those linked packages (see `scripts/install-core-deps.mjs`), so one+also installs the dependencies of those linked packages (see `core/scripts/install-linked-deps.mjs`), so oneinstall in this directory is all that is needed.To build the browser extension, run the following command in this directory:diff --git a/apps/browser-extension/firefox-sources/README.md b/apps/browser-extension/firefox-sources/README.mdnew file mode 100644index 000000000..cf2d434e0--- /dev/null+++ b/apps/browser-extension/firefox-sources/README.md@@ -0,0 +1,36 @@+# AliasVault browser extension: source archive++This archive contains the source code of the AliasVault browser extension as submitted to+addons.mozilla.org, together with the shared packages that the extension is built from. It mirrors the+layout of the public repository at https://github.com/aliasvault/aliasvault, which also holds the+server and mobile app sources that are not needed to build the extension.++## Contents++| Path | Description |+| --- | --- |+| `apps/browser-extension` | The browser extension itself (WXT, React, TypeScript) |+| `core/client` | Shared client logic, linked as a `file:` dependency |+| `core/models` | Shared data models, linked as a `file:` dependency |+| `core/vault` | Shared vault schema definitions, linked as a `file:` dependency |+| `core/rust` | Rust sources of the WebAssembly module that the extension bundles |++## How to build++```bash+cd apps/browser-extension+npm install+npm run zip:firefox+```++This writes the unpacked extension to `apps/browser-extension/dist/firefox-mv2` and the packaged+extension to `apps/browser-extension/dist/aliasvault-browser-extension-<version>-firefox.zip`.++Node.js and npm are the only requirements; release builds are made with Node.js 24. The `npm install`+step also installs the dependencies of the linked `core/*` packages, so no other install is needed.++## WebAssembly module++`core/client/wasm` holds the prebuilt WebAssembly module that the extension bundles, and the build above+uses it as is. To rebuild it from the Rust sources in `core/rust`, install the Rust toolchain+(https://rustup.rs) and run `npm run build:rust` from `apps/browser-extension`.diff --git a/apps/browser-extension/package.json b/apps/browser-extension/package.jsonindex ff65e54db..19b991e90 100644--- a/apps/browser-extension/package.json+++ b/apps/browser-extension/package.json@@ -26,7 +26,7 @@"zip:firefox": "wxt zip -b firefox","zip:edge": "wxt zip -b edge","compile": "tsc --noEmit",- "preinstall": "node scripts/install-core-deps.mjs",+ "preinstall": "node ../../core/scripts/install-linked-deps.mjs","postinstall": "wxt prepare"},"dependencies": {diff --git a/apps/browser-extension/wxt.config.ts b/apps/browser-extension/wxt.config.tsindex 5b8647679..7db8b5ac0 100644--- a/apps/browser-extension/wxt.config.ts+++ b/apps/browser-extension/wxt.config.ts@@ -151,6 +151,7 @@ export default defineConfig({'core/client/**/*','core/models/**/*','core/vault/**/*',+ 'core/scripts/**/*','core/rust/**/*','core/rust/.cargo/**/*','LICENSE.md',diff --git a/core/client/src/database/BaseRepository.ts b/core/client/src/database/BaseRepository.tsindex d3230d8ce..bb9696a40 100644--- a/core/client/src/database/BaseRepository.ts+++ b/core/client/src/database/BaseRepository.ts@@ -1,22 +1,37 @@import * as dateFormatter from '../utilities/DateFormatter';+import { runAsync } from './DbOp';import { BaseQueries } from './queries/BaseQueries';+import type { DbOp, ManifestScope } from './DbOp';import type { ISqliteDatabase } from '../platform/SqliteEngine';export type SqliteBindValue = string | number | null | Uint8Array;/**- * Interface for the core database operations needed by repositories.+ * The database operations repositories need from their host. A host may answer synchronously (sql.js) or+ * asynchronously (the mobile native bridge); repositories reach it through DbOps and {@link BaseRepository.run}.*/export interface IDatabaseClient {+ executeQuery<T>(query: string, params?: SqliteBindValue[]): T[] | Promise<T[]>;+ executeUpdate(query: string, params?: SqliteBindValue[]): number | Promise<number>;+ beginTransaction(): void | Promise<void>;+ commitTransaction(): Promise<void>;+ rollbackTransaction(): void | Promise<void>;+ isInTransaction(): boolean;+ getActiveManifestId(): string | null;+ getPersonalManifestId(): string | null | Promise<string | null>;+}++/**+ * A database client that answers every call synchronously, like sql.js.+ */+export interface ISyncDatabaseClient extends IDatabaseClient {getDb(): ISqliteDatabase | null;executeQuery<T>(query: string, params?: SqliteBindValue[]): T[];executeUpdate(query: string, params?: SqliteBindValue[]): number;beginTransaction(): void;- commitTransaction(): Promise<void>;rollbackTransaction(): void;- getActiveManifestId(): string | null;getPersonalManifestId(): string | null;}@@ -24,12 +39,62 @@ export interface IDatabaseClient {* Base repository class with common database operations.* Provides transaction handling, soft delete, and other shared functionality.*/-export abstract class BaseRepository {+export abstract class BaseRepository<TClient extends IDatabaseClient = ISyncDatabaseClient> {/*** Constructor for the BaseRepository class.* @param client - The database client to use for the repository*/- public constructor(protected client: IDatabaseClient) {}+ public constructor(protected client: TClient) {}++ /**+ * Run a SELECT and return its rows.+ * @param sql - The statement+ * @param params - The bound parameters+ * @returns The rows+ */+ protected *query<T>(sql: string, params: SqliteBindValue[] = []): DbOp<T[]> {+ return (yield { kind: 'query', sql, params }) as T[];+ }++ /**+ * Run an INSERT, UPDATE or DELETE.+ * @param sql - The statement+ * @param params - The bound parameters+ * @returns The number of rows changed+ */+ protected *execute(sql: string, params: SqliteBindValue[] = []): DbOp<number> {+ return (yield { kind: 'execute', sql, params }) as number;+ }++ /**+ * The active and personal manifest ids of the client this op runs on.+ * @returns Both ids, each null when unknown+ */+ protected *manifestScope(): DbOp<ManifestScope> {+ return (yield { kind: 'manifestScope' }) as ManifestScope;+ }++ /**+ * The manifest new rows are written into: the active manifest, else the personal one.+ * @returns The manifest id+ */+ protected *writeManifestId(): DbOp<string> {+ const { active, personal } = yield* this.manifestScope();+ const manifestId = active ?? personal;+ if (!manifestId) {+ throw new Error('BaseRepository: this client has no manifest recorded yet (no active manifest and no personal manifest); sync once before writing.');+ }+ return manifestId;+ }++ /**+ * Run a DbOp from an async method, on whichever client this repository was given.+ * @param op - The op to run+ * @returns The op's result+ */+ protected run<T>(op: DbOp<T>): Promise<T> {+ return runAsync(op, this.client);+ }/*** Execute a function within a transaction.@@ -38,17 +103,25 @@ export abstract class BaseRepository {* @returns The result of the function*/protected async withTransaction<T>(fn: () => T | Promise<T>): Promise<T> {- this.client.beginTransaction();+ await this.client.beginTransaction();try {const result = await fn();await this.client.commitTransaction();return result;} catch (error) {- this.client.rollbackTransaction();+ await this.client.rollbackTransaction();throw error;}}+ /**+ * The client as a synchronous one, for the helpers below. Only repositories whose methods are not DbOps yet use+ * them, and those are only ever constructed on a synchronous client.+ */+ private get syncClient(): ISyncDatabaseClient {+ return this.client as unknown as ISyncDatabaseClient;+ }+/*** Soft delete a record by setting IsDeleted = 1.* @param table - The table name@@ -57,7 +130,7 @@ export abstract class BaseRepository {*/protected softDelete(table: string, id: string): number {const now = dateFormatter.now();- return this.client.executeUpdate(+ return this.syncClient.executeUpdate(`UPDATE ${table} SET IsDeleted = 1, UpdatedAt = ? WHERE Id = ?`,[now, id]);@@ -72,7 +145,7 @@ export abstract class BaseRepository {*/protected softDeleteByForeignKey(table: string, foreignKey: string, foreignKeyValue: string): number {const now = dateFormatter.now();- return this.client.executeUpdate(+ return this.syncClient.executeUpdate(`UPDATE ${table} SET IsDeleted = 1, UpdatedAt = ? WHERE ${foreignKey} = ?`,[now, foreignKeyValue]);@@ -85,7 +158,7 @@ export abstract class BaseRepository {* @returns Number of rows affected*/protected hardDelete(table: string, id: string): number {- return this.client.executeUpdate(`DELETE FROM ${table} WHERE Id = ?`, [id]);+ return this.syncClient.executeUpdate(`DELETE FROM ${table} WHERE Id = ?`, [id]);}/**@@ -96,7 +169,7 @@ export abstract class BaseRepository {* @returns Number of rows affected*/protected hardDeleteByForeignKey(table: string, foreignKey: string, foreignKeyValue: string): number {- return this.client.executeUpdate(+ return this.syncClient.executeUpdate(`DELETE FROM ${table} WHERE ${foreignKey} = ?`,[foreignKeyValue]);@@ -111,7 +184,7 @@ export abstract class BaseRepository {* @returns Number of rows affected*/protected hardDeleteByScopedForeignKey(table: string, foreignKey: string, foreignKeyValue: string, manifestId: string): number {- return this.client.executeUpdate(+ return this.syncClient.executeUpdate(`DELETE FROM ${table} WHERE ${foreignKey} = ? AND ManifestId = ?`,[foreignKeyValue, manifestId]);@@ -123,7 +196,7 @@ export abstract class BaseRepository {* @returns True if the table exists*/protected tableExists(tableName: string): boolean {- const results = this.client.executeQuery<{ name: string }>(+ const results = this.syncClient.executeQuery<{ name: string }>(`SELECT name FROM sqlite_master WHERE type='table' AND name=?`,[tableName]);@@ -138,7 +211,7 @@ export abstract class BaseRepository {* @returns The manifest id, or null when no such row exists*/protected resolveRowManifestId(table: string, id: string, column: string = 'Id'): string | null {- const rows = this.client.executeQuery<{ ManifestId: string }>(+ const rows = this.syncClient.executeQuery<{ ManifestId: string }>(`SELECT ManifestId FROM ${table} WHERE ${column} = ? ORDER BY ManifestId`,[id]);@@ -146,7 +219,7 @@ export abstract class BaseRepository {return null;}- const activeId = this.client.getActiveManifestId() ?? this.personalManifestId();+ const activeId = this.syncClient.getActiveManifestId() ?? this.personalManifestId();return (rows.find(row => row.ManifestId === activeId) ?? rows[0]).ManifestId;}@@ -158,7 +231,7 @@ export abstract class BaseRepository {* @returns The manifest id to stamp the row with*/protected manifestOfFolder(folderId: string | null): string {- const rows = this.client.executeQuery<{ ManifestId: string | null }>(BaseQueries.GET_MANIFEST_OF_FOLDER, [folderId, this.activeManifestId()]);+ const rows = this.syncClient.executeQuery<{ ManifestId: string | null }>(BaseQueries.GET_MANIFEST_OF_FOLDER, [folderId, this.activeManifestId()]);const manifestId = rows[0]?.ManifestId;if (!manifestId) {throw new Error('BaseRepository: could not resolve the manifest for this write; refusing to write a row that names no manifest.');@@ -171,7 +244,7 @@ export abstract class BaseRepository {* @returns The manifest id new rows are stamped with*/protected activeManifestId(): string {- const manifestId = this.client.getActiveManifestId() ?? this.personalManifestId();+ const manifestId = this.syncClient.getActiveManifestId() ?? this.personalManifestId();if (!manifestId) {throw new Error('BaseRepository: this client has no manifest recorded yet (no active manifest and no personal manifest); sync once before writing.');}@@ -184,7 +257,7 @@ export abstract class BaseRepository {* @returns The personal manifest id, or null when absent*/protected personalManifestId(): string | null {- return this.client.getPersonalManifestId();+ return this.syncClient.getPersonalManifestId();}/**diff --git a/core/client/src/database/DbOp.ts b/core/client/src/database/DbOp.tsnew file mode 100644index 000000000..839e3263b--- /dev/null+++ b/core/client/src/database/DbOp.ts@@ -0,0 +1,221 @@+import type { IDatabaseClient, ISyncDatabaseClient, SqliteBindValue } from './BaseRepository';++/*+ * Repository methods are written once and can run on two kinds of host: synchronous (sql.js) and+ * asynchronous (mobile native vault store).+ */++/**+ * The active and personal manifest ids of the client an op runs on.+ */+export type ManifestScope = {+ active: string | null;+ personal: string | null;+};++/**+ * One database step a DbOp asks its host to perform.+ */+export type DbEffect =+ | { kind: 'query'; sql: string; params: SqliteBindValue[] }+ | { kind: 'execute'; sql: string; params: SqliteBindValue[] }+ | { kind: 'manifestScope' };++/**+ * A database operation that runs synchronously on sql.js and asynchronously over a native bridge.+ */+export type DbOp<T> = Generator<DbEffect, T, unknown>;++/**+ * How ops run on an asynchronous host.+ */+export type AsyncRunOptions = {+ /**+ * Wrap an op that writes outside a transaction in one, committed when the op returns. For hosts that only+ * persist the vault on commit, like the mobile native vault store.+ */+ commitWrites?: boolean;+};++/**+ * A repository as a synchronous host sees it: DbOp methods return their value, everything else is unchanged.+ */+export type SyncRepository<R> = {+ [K in keyof R]: R[K] extends (...args: infer A) => DbOp<infer T> ? (...args: A) => T : R[K];+};++/**+ * A repository as an asynchronous host sees it: DbOp methods return a Promise, everything else is unchanged.+ */+export type AsyncRepository<R> = {+ [K in keyof R]: R[K] extends (...args: infer A) => DbOp<infer T> ? (...args: A) => Promise<T> : R[K];+};++/**+ * Run an op to completion on a synchronous client.+ * @param op - The op to run+ * @param client - The client that performs its steps+ * @returns The op's result+ */+export function runSync<T>(op: DbOp<T>, client: ISyncDatabaseClient): T {+ let step = op.next();+ while (!step.done) {+ let result: unknown;+ try {+ result = performSync(step.value, client);+ } catch (error) {+ step = op.throw(error);+ continue;+ }+ step = op.next(result);+ }+ return step.value;+}++/**+ * Run an op to completion on any client, awaiting each step.+ * @param op - The op to run+ * @param client - The client that performs its steps+ * @param options - How to run it+ * @returns The op's result+ */+export async function runAsync<T>(op: DbOp<T>, client: IDatabaseClient, options: AsyncRunOptions = {}): Promise<T> {+ let ownsTransaction = false;+ try {+ let step = op.next();+ while (!step.done) {+ let result: unknown;+ try {+ if (options.commitWrites && step.value.kind === 'execute' && !ownsTransaction && !client.isInTransaction()) {+ await client.beginTransaction();+ ownsTransaction = true;+ }+ result = await performAsync(step.value, client);+ } catch (error) {+ step = op.throw(error);+ continue;+ }+ step = op.next(result);+ }++ if (ownsTransaction) {+ await client.commitTransaction();+ ownsTransaction = false;+ }+ return step.value;+ } catch (error) {+ if (ownsTransaction) {+ try {+ await client.rollbackTransaction();+ } catch {+ // The original error is the one worth reporting.+ }+ }+ throw error;+ }+}++/**+ * Wrap a repository for a synchronous client.+ * @param repository - The repository+ * @param client - The client its ops run on+ * @returns The repository with its DbOp methods returning plain values+ */+export function syncRepository<R extends object>(repository: R, client: ISyncDatabaseClient): SyncRepository<R> {+ return bindRepository(repository, (op) => runSync(op, client)) as SyncRepository<R>;+}++/**+ * Wrap a repository for an asynchronous client.+ * @param repository - The repository+ * @param client - The client its ops run on+ * @param options - How its ops run+ * @returns The repository with its DbOp methods returning Promises+ */+export function asyncRepository<R extends object>(repository: R, client: IDatabaseClient, options: AsyncRunOptions = {}): AsyncRepository<R> {+ return bindRepository(repository, (op) => runAsync(op, client, options)) as AsyncRepository<R>;+}++/**+ * Perform one step on a synchronous client.+ * @param effect - The step+ * @param client - The client+ * @returns The step's result+ */+function performSync(effect: DbEffect, client: ISyncDatabaseClient): unknown {+ switch (effect.kind) {+ case 'query':+ return client.executeQuery(effect.sql, effect.params);+ case 'execute':+ return client.executeUpdate(effect.sql, effect.params);+ case 'manifestScope':+ return { active: client.getActiveManifestId(), personal: client.getPersonalManifestId() } satisfies ManifestScope;+ }+}++/**+ * Perform one step on any client.+ * @param effect - The step+ * @param client - The client+ * @returns The step's result+ */+async function performAsync(effect: DbEffect, client: IDatabaseClient): Promise<unknown> {+ switch (effect.kind) {+ case 'query':+ return client.executeQuery(effect.sql, effect.params);+ case 'execute':+ return client.executeUpdate(effect.sql, effect.params);+ case 'manifestScope':+ return { active: client.getActiveManifestId(), personal: await client.getPersonalManifestId() } satisfies ManifestScope;+ }+}++/**+ * Put a repository behind a Proxy that runs every DbOp its methods return, and passes any other result through.+ * @param repository - The repository+ * @param run - How to run an op+ * @returns The proxied repository+ */+function bindRepository<R extends object>(repository: R, run: (op: DbOp<unknown>) => unknown): R {+ // One wrapper per method, so a method read twice is the same function (stable for React dependency lists).+ const wrappers = new Map<PropertyKey, (...args: unknown[]) => unknown>();++ return new Proxy(repository, {+ /**+ * Resolve a member, wrapping methods.+ */+ get: (target, property): unknown => {+ const value: unknown = Reflect.get(target, property, target);+ if (typeof value !== 'function') {+ return value;+ }++ let wrapper = wrappers.get(property);+ if (!wrapper) {+ const method = value as (...args: unknown[]) => unknown;+ /**+ * Call the method on the repository and run the op it returns.+ */+ wrapper = (...args: unknown[]): unknown => {+ const result = method.apply(target, args);+ return isDbOp(result) ? run(result) : result;+ };+ wrappers.set(property, wrapper);+ }+ return wrapper;+ },+ });+}++/**+ * Whether a value is a generator object, the shape every DbOp has.+ * @param value - The value+ * @returns True for a generator object+ */+function isDbOp(value: unknown): value is DbOp<unknown> {+ if (typeof value !== 'object' || value === null) {+ return false;+ }+ const candidate = value as Partial<Generator>;+ return typeof candidate.next === 'function' && typeof candidate.throw === 'function' && typeof candidate[Symbol.iterator] === 'function';+}diff --git a/core/client/src/database/SqliteClient.ts b/core/client/src/database/SqliteClient.tsindex 9f0392153..0b1504e26 100644--- a/core/client/src/database/SqliteClient.ts+++ b/core/client/src/database/SqliteClient.ts@@ -7,6 +7,8 @@ import { TranslatableMessage } from '../platform/TranslatableMessage';import { VaultCodec } from '../sync/VaultCodec';import { base64ToBytes, bytesToBase64 } from '../utilities/Base64';+import { syncRepository } from './DbOp';+import {ItemRepository,ItemStatsRepository,@@ -17,7 +19,8 @@ import {LogoRepository} from './index';-import type { IDatabaseClient, SqliteBindValue } from './BaseRepository';+import type { ISyncDatabaseClient, SqliteBindValue } from './BaseRepository';+import type { SyncRepository } from './DbOp';import type { ISqliteDatabase } from '../platform/SqliteEngine';import type { VaultVersion } from '@aliasvault/vault';@@ -31,9 +34,9 @@ const VACUUM_FREE_PAGE_RATIO = 10;* Core SQLite database client.* Provides low-level database operations and exposes repositories for domain-specific operations.*/-export class SqliteClient implements IDatabaseClient {+export class SqliteClient implements ISyncDatabaseClient {private db: ISqliteDatabase | null = null;- private isInTransaction: boolean = false;+ private transactionOpen: boolean = false;/*** The manifest this client writes new rows into, when the user has switched to one explicitly.@@ -51,7 +54,7 @@ export class SqliteClient implements IDatabaseClient {private _itemStats: ItemStatsRepository | null = null;private _passkeys: PasskeyRepository | null = null;private _folders: FolderRepository | null = null;- private _settings: SettingsRepository | null = null;+ private _settings: SyncRepository<SettingsRepository> | null = null;private _encryptionKeys: EncryptionKeyRepository | null = null;private _logos: LogoRepository | null = null;@@ -126,9 +129,9 @@ export class SqliteClient implements IDatabaseClient {/*** Repository for the vault's user preferences.*/- public get settings(): SettingsRepository {+ public get settings(): SyncRepository<SettingsRepository> {if (!this._settings) {- this._settings = new SettingsRepository(this);+ this._settings = syncRepository(new SettingsRepository(this), this);}return this._settings;}@@ -194,6 +197,13 @@ export class SqliteClient implements IDatabaseClient {}}+ /**+ * Whether a transaction is open.+ */+ public isInTransaction(): boolean {+ return this.transactionOpen;+ }+/*** Begin a new transaction.*/@@ -202,13 +212,13 @@ export class SqliteClient implements IDatabaseClient {throw new Error('Database not initialized');}- if (this.isInTransaction) {+ if (this.transactionOpen) {throw new Error('Transaction already in progress');}try {this.db.exec('BEGIN TRANSACTION');- this.isInTransaction = true;+ this.transactionOpen = true;} catch (error) {console.error('Error beginning transaction:', error);throw error;@@ -223,13 +233,13 @@ export class SqliteClient implements IDatabaseClient {throw new Error('Database not initialized');}- if (!this.isInTransaction) {+ if (!this.transactionOpen) {throw new Error('No transaction in progress');}try {this.db.exec('COMMIT');- this.isInTransaction = false;+ this.transactionOpen = false;} catch (error) {console.error('Error committing transaction:', error);throw error;@@ -244,13 +254,13 @@ export class SqliteClient implements IDatabaseClient {throw new Error('Database not initialized');}- if (!this.isInTransaction) {+ if (!this.transactionOpen) {throw new Error('No transaction in progress');}try {this.db.exec('ROLLBACK');- this.isInTransaction = false;+ this.transactionOpen = false;} catch (error) {console.error('Error rolling back transaction:', error);throw error;diff --git a/core/client/src/database/index.ts b/core/client/src/database/index.tsindex 05baf5084..15ca9e92c 100644--- a/core/client/src/database/index.ts+++ b/core/client/src/database/index.ts@@ -1,5 +1,6 @@// Base-export { BaseRepository, type IDatabaseClient, type SqliteBindValue } from './BaseRepository';+export { BaseRepository, type IDatabaseClient, type ISyncDatabaseClient, type SqliteBindValue } from './BaseRepository';+export { asyncRepository, runAsync, runSync, syncRepository, type AsyncRepository, type AsyncRunOptions, type DbOp, type SyncRepository } from './DbOp';// Mappersexport { FieldMapper, type FieldRow } from './mappers/FieldMapper';diff --git a/core/client/src/database/repositories/FolderRepository.ts b/core/client/src/database/repositories/FolderRepository.tsindex 6ee1c3e7a..a9a04aa27 100644--- a/core/client/src/database/repositories/FolderRepository.ts+++ b/core/client/src/database/repositories/FolderRepository.ts@@ -5,7 +5,7 @@ import { BaseRepository } from '../BaseRepository';import { BaseQueries } from '../queries/BaseQueries';import { FolderQueries } from '../queries/FolderQueries';-import type { IDatabaseClient } from '../BaseRepository';+import type { ISyncDatabaseClient } from '../BaseRepository';import type { LogoRepository } from './LogoRepository';/**@@ -28,7 +28,7 @@ export class FolderRepository extends BaseRepository {* @param client - The database client to use for the repository* @param logoRepository - The logo repository, to follow items across manifest boundaries*/- public constructor(client: IDatabaseClient, private logoRepository: LogoRepository) {+ public constructor(client: ISyncDatabaseClient, private logoRepository: LogoRepository) {super(client);}diff --git a/core/client/src/database/repositories/ItemRepository.ts b/core/client/src/database/repositories/ItemRepository.tsindex 0fb50c5ba..ef75a4543 100644--- a/core/client/src/database/repositories/ItemRepository.ts+++ b/core/client/src/database/repositories/ItemRepository.ts@@ -2,7 +2,7 @@ import { FieldKey, LogoKinds, MAX_FIELD_HISTORY_RECORDS, normalizeTotpAlgorithm,import { getFolderPath } from '../../items/FolderUtils';import { selectFaviconTarget, toUrlList } from '../../rust/RustCore';-import { BaseRepository, type IDatabaseClient } from '../BaseRepository';+import { BaseRepository, type ISyncDatabaseClient } from '../BaseRepository';import { itemKeyBindings, scopedKey, type DraftItem, type ItemRef } from '../ItemRef';import { FieldMapper, type FieldRow } from '../mappers/FieldMapper';import { ItemMapper, type ItemRow, type TagRow, type ItemWithArchivedAt, type ItemWithDeletedAt } from '../mappers/ItemMapper';@@ -30,7 +30,7 @@ export class ItemRepository extends BaseRepository {* @param logoRepository - The logo repository to use for the repository*/public constructor(- client: IDatabaseClient,+ client: ISyncDatabaseClient,private logoRepository: LogoRepository) {super(client);diff --git a/core/client/src/database/repositories/SettingsRepository.ts b/core/client/src/database/repositories/SettingsRepository.tsindex d2879d1b6..6cf37695b 100644--- a/core/client/src/database/repositories/SettingsRepository.ts+++ b/core/client/src/database/repositories/SettingsRepository.ts@@ -5,6 +5,8 @@ import { getIdentityLanguages } from '../../rust/RustCore';import { BaseRepository } from '../BaseRepository';import { SettingsQueries } from '../queries/SettingsQueries';+import type { IDatabaseClient } from '../BaseRepository';+import type { DbOp } from '../DbOp';import type { PasswordSettings } from '@aliasvault/models/vault';/**@@ -15,20 +17,21 @@ export type CredentialSortOrder = 'OldestFirst' | 'NewestFirst' | 'Alphabetical'/*** Repository for the vault's user preferences: the manifest-scoped key/value rows of the Settings table.*/-export class SettingsRepository extends BaseRepository {+export class SettingsRepository extends BaseRepository<IDatabaseClient> {/*** Get setting from database for a given key, from the manifest this client writes into.* @param key - The setting key* @param defaultValue - Default value if setting not found* @returns The setting value*/- public getSetting(key: string, defaultValue: string = ''): string {- const manifestId = this.client.getActiveManifestId() ?? this.personalManifestId();+ public *getSetting(key: string, defaultValue: string = ''): DbOp<string> {+ const { active, personal } = yield* this.manifestScope();+ const manifestId = active ?? personal;if (!manifestId) {return defaultValue;}- const results = this.client.executeQuery<{ Value: string }>(SettingsQueries.GET_SETTING, [manifestId, key]);+ const results = yield* this.query<{ Value: string }>(SettingsQueries.GET_SETTING, [manifestId, key]);return results.length > 0 ? results[0].Value : defaultValue;}@@ -36,32 +39,32 @@ export class SettingsRepository extends BaseRepository {* Get the default identity language from the database.* @returns The stored override value if set, otherwise empty string*/- public getDefaultIdentityLanguage(): string {- return this.getSetting('DefaultIdentityLanguage');+ public *getDefaultIdentityLanguage(): DbOp<string> {+ return yield* this.getSetting('DefaultIdentityLanguage');}/*** Get the default identity gender preference from the database.* @returns The gender preference or 'random' if not set*/- public getDefaultIdentityGender(): string {- return this.getSetting('DefaultIdentityGender', 'random');+ public *getDefaultIdentityGender(): DbOp<string> {+ return yield* this.getSetting('DefaultIdentityGender', 'random');}/*** Get the default identity age range from the database.* @returns The age range preference or 'random' if not set*/- public getDefaultIdentityAgeRange(): string {- return this.getSetting('DefaultIdentityAgeRange', 'random');+ public *getDefaultIdentityAgeRange(): DbOp<string> {+ return yield* this.getSetting('DefaultIdentityAgeRange', 'random');}/*** Get the password settings from the database.* @returns Password settings object*/- public getPasswordSettings(): PasswordSettings {- const settingsJson = this.getSetting('PasswordGenerationSettings');+ public *getPasswordSettings(): DbOp<PasswordSettings> {+ const settingsJson = yield* this.getSetting('PasswordGenerationSettings');const defaultSettings: PasswordSettings = {Length: DEFAULT_PASSWORD_LENGTH,@@ -95,16 +98,16 @@ export class SettingsRepository extends BaseRepository {* Mirrors the `PasswordGenerationSettings` key used by the other AliasVault clients.* @param settings - The password settings to store.*/- public setPasswordSettings(settings: PasswordSettings): void {- this.updateSetting('PasswordGenerationSettings', JSON.stringify(settings));+ public *setPasswordSettings(settings: PasswordSettings): DbOp<void> {+ yield* this.updateSetting('PasswordGenerationSettings', JSON.stringify(settings));}/*** Get the default email domain for new aliases.* @returns The default email domain or empty string if not set*/- public getDefaultEmailDomain(): string {- return this.getSetting('DefaultEmailDomain');+ public *getDefaultEmailDomain(): DbOp<string> {+ return yield* this.getSetting('DefaultEmailDomain');}/**@@ -115,7 +118,7 @@ export class SettingsRepository extends BaseRepository {* @returns The effective language code*/public async getEffectiveIdentityLanguage(): Promise<string> {- const storedLanguage = this.getDefaultIdentityLanguage();+ const storedLanguage = await this.run(this.getDefaultIdentityLanguage());if (storedLanguage) {return storedLanguage;}@@ -127,8 +130,8 @@ export class SettingsRepository extends BaseRepository {* Uses the same key the other clients use for cross-platform sync.* @returns The sort order preference*/- public getCredentialsSortOrder(): CredentialSortOrder {- const value = this.getSetting('CredentialsSortOrder', 'NewestFirst');+ public *getCredentialsSortOrder(): DbOp<CredentialSortOrder> {+ const value = yield* this.getSetting('CredentialsSortOrder', 'NewestFirst');// Validate the value is a valid sort orderif (value === 'OldestFirst' || value === 'NewestFirst' || value === 'Alphabetical') {return value;@@ -141,27 +144,18 @@ export class SettingsRepository extends BaseRepository {* @param key - The setting key* @param value - The setting value*/- public updateSetting(key: string, value: string): void {+ public *updateSetting(key: string, value: string): DbOp<void> {const now = this.now();- const manifestId = this.activeManifestId();+ const manifestId = yield* this.writeManifestId();// Check if setting exists within this manifest.- const results = this.client.executeQuery<{ count: number }>(- SettingsQueries.COUNT_BY_KEY,- [manifestId, key]- );+ const results = yield* this.query<{ count: number }>(SettingsQueries.COUNT_BY_KEY, [manifestId, key]);const exists = results[0]?.count > 0;if (exists) {- this.client.executeUpdate(- SettingsQueries.UPDATE_SETTING,- [value, now, manifestId, key]- );+ yield* this.execute(SettingsQueries.UPDATE_SETTING, [value, now, manifestId, key]);} else {- this.client.executeUpdate(- SettingsQueries.INSERT_SETTING,- [manifestId, key, value, now, now, 0]- );+ yield* this.execute(SettingsQueries.INSERT_SETTING, [manifestId, key, value, now, now, 0]);}}@@ -170,7 +164,7 @@ export class SettingsRepository extends BaseRepository {* Uses the same key the other clients use for cross-platform sync.* @param order - The sort order to set*/- public setCredentialsSortOrder(order: CredentialSortOrder): void {- this.updateSetting('CredentialsSortOrder', order);+ public *setCredentialsSortOrder(order: CredentialSortOrder): DbOp<void> {+ yield* this.updateSetting('CredentialsSortOrder', order);}}diff --git a/core/client/src/platform/InMemoryPlatform.ts b/core/client/src/platform/InMemoryPlatform.tsindex 6f008ce3c..3f92b64ce 100644--- a/core/client/src/platform/InMemoryPlatform.ts+++ b/core/client/src/platform/InMemoryPlatform.ts@@ -64,10 +64,10 @@ export class InMemoryKeyValueStore implements IKeyValueStore {}/**- * A Rust core or SQLite engine that refuses every call, for platforms that did not provide one.- * @param what - the member name, for the error message+ * A platform service that refuses every call, for hosts that do not provide it.+ * @param what - the service name, for the error message*/-function unavailable<T extends object>(what: string): T {+export function unavailableService<T extends object>(what: string): T {return new Proxy({} as T, {/** Every member access yields a rejecting function. */get: (_target, property): unknown => (): Promise<never> => Promise.reject(new Error(`No ${what} configured for this platform (${String(property)}).`)),@@ -91,8 +91,8 @@ export function createInMemoryPlatform(overrides: Partial<IClientPlatform> = {})error: (): void => {},},app: { version: '0.0.0-test', clientName: 'test', isDevelopment: false },- rustCore: unavailable<IRustCore>('Rust core'),- sqlite: unavailable<ISqliteEngine>('SQLite engine'),+ rustCore: unavailableService<IRustCore>('Rust core'),+ sqlite: unavailableService<ISqliteEngine>('SQLite engine'),/*** Echo the message id.*/diff --git a/apps/browser-extension/scripts/install-core-deps.mjs b/core/scripts/install-linked-deps.mjsold mode 100755new mode 100644similarity index 62%rename from apps/browser-extension/scripts/install-core-deps.mjsrename to core/scripts/install-linked-deps.mjsindex 1c5bfd21c..87237f892--- a/apps/browser-extension/scripts/install-core-deps.mjs+++ b/core/scripts/install-linked-deps.mjs@@ -1,30 +1,20 @@#!/usr/bin/env node-// Installs the dependencies of the core packages this extension links with `file:`+// Installs the dependencies of the core packages an app links with `file:`// references (core/client, core/models, core/vault).//-// npm symlinks a `file:` dependency but never installs that package's own-// dependencies, so core/client is left without `sql.js` and `otpauth`. Both are-// resolved from core/client's own node_modules when the extension is built (the-// linked package lives outside this project's node_modules tree), and-// wxt.config.ts copies the sql.js wasm file out of it, so the build fails without-// this step. Running it from `preinstall` also makes the Firefox sources archive,-// which ships core/* next to the extension, build with a plain `npm install`.-//-// Usage:-// node scripts/install-core-deps.mjs+// Usage, from the app directory (npm runs `preinstall` there):+// node ../../core/scripts/install-linked-deps.mjsimport { spawnSync } from "node:child_process";import { existsSync, readFileSync } from "node:fs";-import { fileURLToPath } from "node:url";import path from "node:path";-import { env, exit, platform } from "node:process";+import { cwd, env, exit, platform } from "node:process";-const scriptDir = path.dirname(fileURLToPath(import.meta.url));-const extensionDir = path.resolve(scriptDir, "..");+const appDir = cwd();/** npm exports its own project root to lifecycle scripts, and a nested npm picks that- * up over the cwd we hand it, which would install into the extension instead of the+ * up over the cwd we hand it, which would install into the app instead of the* core package. Drop the path-scoped config so the child install stays in its own* directory, and keep the rest (registry, cache, proxy) intact.*/@@ -59,18 +49,18 @@ function linkedDirs(packageDir, manifest) {}/**- * Collect every `file:` linked package reachable from the extension.+ * Collect every `file:` linked package reachable from the app.* @returns {string[]}*/function collectLinkedPackages() {- const extensionManifest = readManifest(extensionDir);- if (!extensionManifest) {+ const appManifest = readManifest(appDir);+ if (!appManifest) {return [];}const collected = [];- const seen = new Set([extensionDir]);- const queue = linkedDirs(extensionDir, extensionManifest);+ const seen = new Set([appDir]);+ const queue = linkedDirs(appDir, appManifest);while (queue.length > 0) {const packageDir = queue.shift();@@ -92,15 +82,13 @@ function collectLinkedPackages() {}/**- * List the registry dependencies of a package that are not installed in it yet.+ * List the dependencies of a package that are not installed in it yet.* @param {string} packageDir* @returns {string[]}*/function missingDependencies(packageDir) {const manifest = readManifest(packageDir);- return Object.entries(manifest?.dependencies ?? {})- .filter(([, spec]) => !(typeof spec === "string" && spec.startsWith("file:")))- .map(([name]) => name)+ return Object.keys(manifest?.dependencies ?? {}).filter((name) => !existsSync(path.join(packageDir, "node_modules", name)));}@@ -110,7 +98,7 @@ for (const packageDir of collectLinkedPackages()) {continue;}- const relativeDir = path.relative(extensionDir, packageDir);+ const relativeDir = path.relative(appDir, packageDir);console.log(`[core-deps] Installing dependencies for ${relativeDir} (missing: ${missing.join(", ")})`);const result = spawnSync("npm", ["install", "--omit=dev", "--no-audit", "--no-fund"], {