Skip to content

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 Borst2780e00cf621
diff --git a/core/client/eslint-rules/no-floating-db-op.mjs b/core/client/eslint-rules/no-floating-db-op.mjs
new file mode 100644
index 000000000..9b269ed76
--- /dev/null
+++ b/core/client/eslint-rules/no-floating-db-op.mjs
@@ -0,0 +1,46 @@
+/**
+ * Reports a DbOp (a repository generator, see src/database/DbOp.ts) called as a bare statement. A DbOp only runs
+ * when it is delegated with `yield*` or handed to a runner, so `this.execute(sql)` on its own silently does nothing.
+ */
+export default {
+ meta: {
+ type: "problem",
+ docs: {
+ description: "Require every DbOp to be delegated with yield* or run.",
+ },
+ messages: {
+ floating: "This DbOp never runs: delegate it with `yield*` or pass it to `this.run()`.",
+ },
+ schema: [],
+ },
+
+ /**
+ * Create the rule listeners.
+ * @param {import("eslint").Rule.RuleContext} context
+ */
+ create(context) {
+ const services = context.sourceCode.parserServices;
+ if (!services?.program || !services.esTreeNodeToTSNodeMap) {
+ return {};
+ }
+ const checker = services.program.getTypeChecker();
+
+ return {
+ /**
+ * Check a statement that consists of a single call.
+ * @param {import("estree").ExpressionStatement} node
+ */
+ ExpressionStatement(node) {
+ const expression = node.expression.type === "UnaryExpression" && node.expression.operator === "void" ? node.expression.argument : node.expression;
+ if (expression.type !== "CallExpression") {
+ return;
+ }
+
+ const type = checker.getTypeAtLocation(services.esTreeNodeToTSNodeMap.get(expression));
+ if (type.aliasSymbol?.getName() === "DbOp" || type.getSymbol()?.getName() === "Generator") {
+ context.report({ node, messageId: "floating" });
+ }
+ },
+ };
+ },
+};
diff --git a/core/client/eslint.config.mjs b/core/client/eslint.config.mjs
index f2d5775c5..89685d760 100644
--- a/core/client/eslint.config.mjs
+++ b/core/client/eslint.config.mjs
@@ -5,6 +5,8 @@ import importPlugin from "eslint-plugin-import";
import jsdocPlugin from "eslint-plugin-jsdoc";
import globals from "globals";
+import noFloatingDbOp from "./eslint-rules/no-floating-db-op.mjs";
+
export default [
{
ignores: [
@@ -115,4 +117,15 @@ export default [
},
},
},
+ {
+ // Repositories are written as DbOps (src/database/DbOp.ts): a DbOp or a Promise left unhandled never runs or loses its error.
+ files: ["src/database/**/*.ts"],
+ plugins: {
+ "local": { rules: { "no-floating-db-op": noFloatingDbOp } },
+ },
+ rules: {
+ "local/no-floating-db-op": "error",
+ "@typescript-eslint/no-floating-promises": "error",
+ },
+ },
];
diff --git a/core/client/package-lock.json b/core/client/package-lock.json
index 55789756d..b479aa592 100644
--- a/core/client/package-lock.json
+++ b/core/client/package-lock.json
@@ -11,6 +11,7 @@
"dependencies": {
"@aliasvault/models": "file:../models",
"@aliasvault/vault": "file:../vault",
+ "fflate": "^0.8.3",
"otpauth": "^9.3.6",
"sql.js": "^1.12.0"
},
@@ -2754,6 +2755,12 @@
}
}
},
+ "node_modules/fflate": {
+ "version": "0.8.3",
+ "resolved": "https://registry.npmjs.org/fflate/-/fflate-0.8.3.tgz",
+ "integrity": "sha512-tbZNuJrLwGUp3zshBtdy4W+ORxZuIh8a5ilyIEQDC5rY1f3U20JMry0Ll3WBzU58EZKsEuJFXhb5gwv8CsPvgA==",
+ "license": "MIT"
+ },
"node_modules/file-entry-cache": {
"version": "8.0.0",
"resolved": "https://registry.npmjs.org/file-entry-cache/-/file-entry-cache-8.0.0.tgz",
diff --git a/core/client/package.json b/core/client/package.json
index b854c7d2b..cf2bb330d 100644
--- a/core/client/package.json
+++ b/core/client/package.json
@@ -22,6 +22,7 @@
"dependencies": {
"@aliasvault/models": "file:../models",
"@aliasvault/vault": "file:../vault",
+ "fflate": "^0.8.3",
"otpauth": "^9.3.6",
"sql.js": "^1.12.0"
},
diff --git a/core/client/src/auth/MasterPasswordService.ts b/core/client/src/auth/MasterPasswordService.ts
index b969b5384..5269ec8ea 100644
--- a/core/client/src/auth/MasterPasswordService.ts
+++ b/core/client/src/auth/MasterPasswordService.ts
@@ -1,3 +1,4 @@
+import { AppErrorCode, extractErrorCode } from '../api/errors/AppErrorCodes';
import { StorageKeys } from '../constants/StorageKeys';
import { EncryptionUtility } from '../crypto/EncryptionUtility';
import { getPlatform } from '../platform/ClientPlatform';
@@ -34,6 +35,15 @@ export class PasswordChangedElsewhereError extends Error {
}
}
+/**
+ * Outcome of a local master password check.
+ */
+export enum PasswordVerificationResult {
+ Success = 'Success',
+ InvalidPassword = 'InvalidPassword',
+ VerificationError = 'VerificationError',
+}
+
/** The SRP challenge a server endpoint issues before it accepts a password-confirmed action. */
export type SrpChallenge = {
salt: string;
@@ -60,6 +70,36 @@ export class MasterPasswordService {
return getPlatform().storage.get<EncryptionKeyDerivationParams>(StorageKeys.ENCRYPTION_KEY_DERIVATION_PARAMS);
}
+ /**
+ * Verify the master password locally.
+ * @param password - the master password to check
+ */
+ public static async verifyPassword(password: string): Promise<PasswordVerificationResult> {
+ try {
+ const parameters = await MasterPasswordService.getStoredDerivationParams();
+ if (!parameters) {
+ return PasswordVerificationResult.VerificationError;
+ }
+
+ // Without a cached chain a derived key cannot be checked against anything.
+ if (!await VaultKeyService.hasLocalVaultKey()) {
+ return PasswordVerificationResult.VerificationError;
+ }
+
+ const prepared = await SrpAuthService.prepareCredentials(password, parameters.salt, parameters.encryptionSettings);
+ try {
+ await VaultKeyService.resolveEncryptionKeyOffline(prepared.passwordHashBase64);
+ return PasswordVerificationResult.Success;
+ } catch (error) {
+ const code = error instanceof Error ? extractErrorCode(error.message) : null;
+ return code === AppErrorCode.VAULT_DECRYPT_FAILED ? PasswordVerificationResult.InvalidPassword : PasswordVerificationResult.VerificationError;
+ }
+ } catch (error) {
+ console.error('Password verification failed unexpectedly.', error);
+ return PasswordVerificationResult.VerificationError;
+ }
+ }
+
/**
* Sanity check that a salt the server reports is still the one this device derived its keys from. Unknown on
* either side passes: there is nothing to compare yet.
diff --git a/core/client/src/auth/SrpLoginService.ts b/core/client/src/auth/SrpLoginService.ts
new file mode 100644
index 000000000..dba7c1312
--- /dev/null
+++ b/core/client/src/auth/SrpLoginService.ts
@@ -0,0 +1,115 @@
+import { ApiAuthError } from '../api/errors/ApiAuthError';
+import { throwIfServerPredatesV2Api } from '../sync/LegacyStorageModelMigration';
+
+import { SrpAuthService } from './SrpAuthService';
+
+import type { WebApiService } from '../api/WebApiService';
+import type { BadRequestResponse, LoginResponse, ValidateLoginRequest, ValidateLoginRequest2Fa, ValidateLoginResponse } from '@aliasvault/models/webapi';
+
+/**
+ * The part of an API client the login requests need.
+ */
+export type SrpLoginApi = Pick<WebApiService, 'rawFetch' | 'getApiUrl'>;
+
+/**
+ * The recovery code variant of the validate request.
+ */
+type ValidateLoginRequestRecoveryCode = ValidateLoginRequest & {
+ recoveryCode: string;
+};
+
+/**
+ * The SRP login requests: initiate, then validate with a password proof plus optionally a 2FA or recovery code.
+ */
+export class SrpLoginService {
+ /**
+ * Create the service.
+ * @param api - The API client the requests go through
+ */
+ public constructor(private readonly api: SrpLoginApi) {}
+
+ /**
+ * Initiate login with the server.
+ * @param username - The username
+ * @returns The server's login challenge
+ */
+ public async initiateLogin(username: string): Promise<LoginResponse> {
+ const normalizedUsername = SrpAuthService.normalizeUsername(username);
+ return this.parseAuthResponse<LoginResponse>(await this.post('Auth/login', { username: normalizedUsername }));
+ }
+
+ /**
+ * Validate login with the server using the locally generated ephemeral and session proof.
+ * @param username - The username
+ * @param passwordHashString - The password hash as uppercase hex
+ * @param rememberMe - Whether to request an extended token lifetime
+ * @param loginResponse - The initiate response
+ * @returns The validate response
+ */
+ public async validateLogin(username: string, passwordHashString: string, rememberMe: boolean, loginResponse: LoginResponse): Promise<ValidateLoginResponse> {
+ const normalizedUsername = SrpAuthService.normalizeUsername(username);
+ const proof = await SrpAuthService.deriveLoginProof(loginResponse, normalizedUsername, passwordHashString);
+ const model: ValidateLoginRequest = { username: normalizedUsername, rememberMe, ...proof };
+ return this.parseAuthResponse<ValidateLoginResponse>(await this.post('Auth/validate', model));
+ }
+
+ /**
+ * Validate login with a 2FA authenticator code.
+ * @param username - The username
+ * @param passwordHashString - The password hash as uppercase hex
+ * @param rememberMe - Whether to request an extended token lifetime
+ * @param loginResponse - The initiate response
+ * @param code2Fa - The authenticator code
+ * @returns The validate response
+ */
+ public async validateLogin2Fa(username: string, passwordHashString: string, rememberMe: boolean, loginResponse: LoginResponse, code2Fa: number): Promise<ValidateLoginResponse> {
+ const normalizedUsername = SrpAuthService.normalizeUsername(username);
+ const proof = await SrpAuthService.deriveLoginProof(loginResponse, normalizedUsername, passwordHashString);
+ const model: ValidateLoginRequest2Fa = { username: normalizedUsername, rememberMe, ...proof, code2Fa };
+ return this.parseAuthResponse<ValidateLoginResponse>(await this.post('Auth/validate-2fa', model));
+ }
+
+ /**
+ * Validate login with a 2FA recovery code.
+ * @param username - The username
+ * @param passwordHashString - The password hash as uppercase hex
+ * @param rememberMe - Whether to request an extended token lifetime
+ * @param loginResponse - The initiate response
+ * @param recoveryCode - The recovery code
+ * @returns The validate response
+ */
+ public async validateLoginRecoveryCode(username: string, passwordHashString: string, rememberMe: boolean, loginResponse: LoginResponse, recoveryCode: string): Promise<ValidateLoginResponse> {
+ const normalizedUsername = SrpAuthService.normalizeUsername(username);
+ const proof = await SrpAuthService.deriveLoginProof(loginResponse, normalizedUsername, passwordHashString);
+ const model: ValidateLoginRequestRecoveryCode = { username: normalizedUsername, rememberMe, ...proof, recoveryCode };
+ return this.parseAuthResponse<ValidateLoginResponse>(await this.post('Auth/validate-recovery-code', model));
+ }
+
+ /**
+ * Parse an auth response, turning a 400 into an ApiAuthError carrying the server's error code.
+ * @param response - The raw response
+ * @returns The parsed body
+ */
+ private async parseAuthResponse<T>(response: Response): Promise<T> {
+ await throwIfServerPredatesV2Api(response.status, await this.api.getApiUrl());
+ if (response.status === 400) {
+ const badRequestResponse = await response.json() as BadRequestResponse;
+ throw new ApiAuthError(badRequestResponse.title);
+ }
+ return await response.json() as T;
+ }
+
+ /**
+ * Post an auth request.
+ * @param path - The endpoint
+ * @param body - The request body
+ * @returns The raw response
+ */
+ private async post(path: string, body: unknown): Promise<Response> {
+ return this.api.rawFetch(path, {
+ method: 'POST',
+ headers: { 'Content-Type': 'application/json' },
+ body: JSON.stringify(body),
+ });
+ }
+}
diff --git a/core/client/src/database/BaseRepository.ts b/core/client/src/database/BaseRepository.ts
index bb9696a40..d9dbee7bb 100644
--- a/core/client/src/database/BaseRepository.ts
+++ b/core/client/src/database/BaseRepository.ts
@@ -9,10 +9,12 @@ import type { ISqliteDatabase } from '../platform/SqliteEngine';
export type SqliteBindValue = string | number | null | Uint8Array;
/**
- * 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}.
+ * The database operations repositories need from their host, answered synchronously (sql.js) or asynchronously
+ * (the mobile native bridge).
*/
export interface IDatabaseClient {
+ /** True when writes only persist once a transaction commits; a write outside a transaction then gets its own. */
+ readonly persistsOnCommit?: boolean;
executeQuery<T>(query: string, params?: SqliteBindValue[]): T[] | Promise<T[]>;
executeUpdate(query: string, params?: SqliteBindValue[]): number | Promise<number>;
beginTransaction(): void | Promise<void>;
@@ -37,14 +39,13 @@ export interface ISyncDatabaseClient extends IDatabaseClient {
/**
* Base repository class with common database operations.
- * Provides transaction handling, soft delete, and other shared functionality.
*/
-export abstract class BaseRepository<TClient extends IDatabaseClient = ISyncDatabaseClient> {
+export abstract class BaseRepository {
/**
* Constructor for the BaseRepository class.
* @param client - The database client to use for the repository
*/
- public constructor(protected client: TClient) {}
+ public constructor(protected client: IDatabaseClient) {}
/**
* Run a SELECT and return its rows.
@@ -74,6 +75,14 @@ export abstract class BaseRepository<TClient extends IDatabaseClient = ISyncData
return (yield { kind: 'manifestScope' }) as ManifestScope;
}
+ /**
+ * The id of the user's personal manifest, as recorded by the last pull.
+ * @returns The personal manifest id, or null when absent
+ */
+ protected *personalManifestId(): DbOp<string | null> {
+ return (yield* this.manifestScope()).personal;
+ }
+
/**
* The manifest new rows are written into: the active manifest, else the personal one.
* @returns The manifest id
@@ -87,122 +96,6 @@ export abstract class BaseRepository<TClient extends IDatabaseClient = ISyncData
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.
- * Automatically handles begin, commit, and rollback.
- * @param fn - The function to execute within the transaction
- * @returns The result of the function
- */
- protected async withTransaction<T>(fn: () => T | Promise<T>): Promise<T> {
- await this.client.beginTransaction();
- try {
- const result = await fn();
- await this.client.commitTransaction();
- return result;
- } catch (error) {
- 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
- * @param id - The record ID
- * @returns Number of rows affected
- */
- protected softDelete(table: string, id: string): number {
- const now = dateFormatter.now();
- return this.syncClient.executeUpdate(
- `UPDATE ${table} SET IsDeleted = 1, UpdatedAt = ? WHERE Id = ?`,
- [now, id]
- );
- }
-
- /**
- * Soft delete records by a foreign key.
- * @param table - The table name
- * @param foreignKey - The foreign key column name
- * @param foreignKeyValue - The foreign key value
- * @returns Number of rows affected
- */
- protected softDeleteByForeignKey(table: string, foreignKey: string, foreignKeyValue: string): number {
- const now = dateFormatter.now();
- return this.syncClient.executeUpdate(
- `UPDATE ${table} SET IsDeleted = 1, UpdatedAt = ? WHERE ${foreignKey} = ?`,
- [now, foreignKeyValue]
- );
- }
-
- /**
- * Hard delete a record permanently.
- * @param table - The table name
- * @param id - The record ID
- * @returns Number of rows affected
- */
- protected hardDelete(table: string, id: string): number {
- return this.syncClient.executeUpdate(`DELETE FROM ${table} WHERE Id = ?`, [id]);
- }
-
- /**
- * Hard delete records by a foreign key.
- * @param table - The table name
- * @param foreignKey - The foreign key column name
- * @param foreignKeyValue - The foreign key value
- * @returns Number of rows affected
- */
- protected hardDeleteByForeignKey(table: string, foreignKey: string, foreignKeyValue: string): number {
- return this.syncClient.executeUpdate(
- `DELETE FROM ${table} WHERE ${foreignKey} = ?`,
- [foreignKeyValue]
- );
- }
-
- /**
- * Hard delete manifest-scoped records by a foreign key, within one manifest.
- * @param table - The table name
- * @param foreignKey - The foreign key column name
- * @param foreignKeyValue - The foreign key value
- * @param manifestId - The manifest whose rows may be deleted
- * @returns Number of rows affected
- */
- protected hardDeleteByScopedForeignKey(table: string, foreignKey: string, foreignKeyValue: string, manifestId: string): number {
- return this.syncClient.executeUpdate(
- `DELETE FROM ${table} WHERE ${foreignKey} = ? AND ManifestId = ?`,
- [foreignKeyValue, manifestId]
- );
- }
-
- /**
- * Check if a table exists in the database.
- * @param tableName - The name of the table to check
- * @returns True if the table exists
- */
- protected tableExists(tableName: string): boolean {
- const results = this.syncClient.executeQuery<{ name: string }>(
- `SELECT name FROM sqlite_master WHERE type='table' AND name=?`,
- [tableName]
- );
- return results.length > 0;
- }
-
/**
* The manifest a manifest-scoped row belongs to, looked up from the row itself.
* @param table - The manifest-scoped table to look in
@@ -210,28 +103,26 @@ export abstract class BaseRepository<TClient extends IDatabaseClient = ISyncData
* @param column - The column `id` names, when it is not the primary key
* @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.syncClient.executeQuery<{ ManifestId: string }>(
- `SELECT ManifestId FROM ${table} WHERE ${column} = ? ORDER BY ManifestId`,
- [id]
- );
+ protected *resolveRowManifestId(table: string, id: string, column: string = 'Id'): DbOp<string | null> {
+ const rows = yield* this.query<{ ManifestId: string }>(`SELECT ManifestId FROM ${table} WHERE ${column} = ? ORDER BY ManifestId`, [id]);
if (rows.length === 0) {
return null;
}
- const activeId = this.syncClient.getActiveManifestId() ?? this.personalManifestId();
- return (rows.find(row => row.ManifestId === activeId) ?? rows[0]).ManifestId;
+ const { active, personal } = yield* this.manifestScope();
+ const preferredId = active ?? personal;
+ return (rows.find(row => row.ManifestId === preferredId) ?? rows[0]).ManifestId;
}
/**
- * The manifest a row placed in the given folder belongs to: that folder's, or the active manifest when
- * the row sits outside any folder. This is the value the write path stamps onto the row itself (see
- * {@link BaseQueries.MANIFEST_OF_FOLDER}), resolved here for callers that need it a step earlier.
+ * The manifest a row placed in the given folder belongs to: that folder's, or the write manifest when the row
+ * sits outside any folder. The same value the write path stamps (see {@link BaseQueries.MANIFEST_OF_FOLDER}).
* @param folderId - The folder the row is placed in, or null for none
* @returns The manifest id to stamp the row with
*/
- protected manifestOfFolder(folderId: string | null): string {
- const rows = this.syncClient.executeQuery<{ ManifestId: string | null }>(BaseQueries.GET_MANIFEST_OF_FOLDER, [folderId, this.activeManifestId()]);
+ protected *manifestOfFolder(folderId: string | null): DbOp<string> {
+ const fallbackManifestId = yield* this.writeManifestId();
+ const rows = yield* this.query<{ ManifestId: string | null }>(BaseQueries.GET_MANIFEST_OF_FOLDER, [folderId, fallbackManifestId]);
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.');
@@ -240,24 +131,42 @@ export abstract class BaseRepository<TClient extends IDatabaseClient = ISyncData
}
/**
- * The manifest this client is writing into (currently active manifest).
- * @returns The manifest id new rows are stamped with
+ * Hard delete manifest-scoped records by a foreign key, within one manifest.
+ * @param table - The table name
+ * @param foreignKey - The foreign key column name
+ * @param foreignKeyValue - The foreign key value
+ * @param manifestId - The manifest whose rows may be deleted
+ * @returns Number of rows affected
*/
- protected activeManifestId(): string {
- 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.');
- }
- return manifestId;
+ protected *hardDeleteByScopedForeignKey(table: string, foreignKey: string, foreignKeyValue: string, manifestId: string): DbOp<number> {
+ return yield* this.execute(`DELETE FROM ${table} WHERE ${foreignKey} = ? AND ManifestId = ?`, [foreignKeyValue, manifestId]);
}
/**
- * 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
+ * Run a DbOp from an async method.
+ * @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.
+ * Automatically handles begin, commit, and rollback.
+ * @param fn - The function to execute within the transaction
+ * @returns The result of the function
*/
- protected personalManifestId(): string | null {
- return this.syncClient.getPersonalManifestId();
+ protected async withTransaction<T>(fn: () => T | Promise<T>): Promise<T> {
+ await this.client.beginTransaction();
+ try {
+ const result = await fn();
+ await this.client.commitTransaction();
+ return result;
+ } catch (error) {
+ await this.client.rollbackTransaction();
+ throw error;
+ }
}
/**
@@ -275,16 +184,4 @@ export abstract class BaseRepository<TClient extends IDatabaseClient = ISyncData
protected now(): string {
return dateFormatter.now();
}
-
- /**
- * Build a parameterized IN clause for SQL queries.
- * @param values - Array of values for the IN clause
- * @returns Object with placeholders string and values array
- */
- protected buildInClause(values: string[]): { placeholders: string; values: string[] } {
- return {
- placeholders: values.map(() => '?').join(','),
- values
- };
- }
}
diff --git a/core/client/src/database/DbOp.ts b/core/client/src/database/DbOp.ts
index 839e3263b..ae0f29174 100644
--- a/core/client/src/database/DbOp.ts
+++ b/core/client/src/database/DbOp.ts
@@ -26,17 +26,6 @@ export type DbEffect =
*/
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.
*/
@@ -73,20 +62,20 @@ export function runSync<T>(op: DbOp<T>, client: ISyncDatabaseClient): T {
}
/**
- * Run an op to completion on any client, awaiting each step.
+ * Run an op to completion on any client, awaiting each step. On a client that persists on commit, an op that writes
+ * outside a transaction runs in one of its own.
* @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> {
+export async function runAsync<T>(op: DbOp<T>, client: IDatabaseClient): 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()) {
+ if (client.persistsOnCommit && step.value.kind === 'execute' && !ownsTransaction && !client.isInTransaction()) {
await client.beginTransaction();
ownsTransaction = true;
}
@@ -129,11 +118,10 @@ export function syncRepository<R extends object>(repository: R, client: ISyncDat
* 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>;
+export function asyncRepository<R extends object>(repository: R, client: IDatabaseClient): AsyncRepository<R> {
+ return bindRepository(repository, (op) => runAsync(op, client)) as AsyncRepository<R>;
}
/**
diff --git a/core/client/src/database/SqliteClient.ts b/core/client/src/database/SqliteClient.ts
index 0b1504e26..947c5235e 100644
--- a/core/client/src/database/SqliteClient.ts
+++ b/core/client/src/database/SqliteClient.ts
@@ -16,7 +16,7 @@ import {
FolderRepository,
SettingsRepository,
EncryptionKeyRepository,
- LogoRepository
+ LogoRepository,
} from './index';
import type { ISyncDatabaseClient, SqliteBindValue } from './BaseRepository';
@@ -50,13 +50,14 @@ export class SqliteClient implements ISyncDatabaseClient {
private personalManifestId: string | null = null;
// Lazy-initialized repositories
- private _items: ItemRepository | null = null;
- private _itemStats: ItemStatsRepository | null = null;
- private _passkeys: PasskeyRepository | null = null;
- private _folders: FolderRepository | null = null;
+ private _items: SyncRepository<ItemRepository> | null = null;
+ private _itemStats: SyncRepository<ItemStatsRepository> | null = null;
+ private _passkeys: SyncRepository<PasskeyRepository> | null = null;
+ private _folders: SyncRepository<FolderRepository> | null = null;
private _settings: SyncRepository<SettingsRepository> | null = null;
- private _encryptionKeys: EncryptionKeyRepository | null = null;
- private _logos: LogoRepository | null = null;
+ private _encryptionKeys: SyncRepository<EncryptionKeyRepository> | null = null;
+ private _logos: SyncRepository<LogoRepository> | null = null;
+ private _logoRepository: LogoRepository | null = null;
/**
* The manifest new rows are stamped with when they cannot inherit one from a parent row, or null when
@@ -89,9 +90,9 @@ export class SqliteClient implements ISyncDatabaseClient {
/**
* Repository for Item CRUD operations.
*/
- public get items(): ItemRepository {
+ public get items(): SyncRepository<ItemRepository> {
if (!this._items) {
- this._items = new ItemRepository(this, this.logos);
+ this._items = syncRepository(new ItemRepository(this, this.logoRepository), this);
}
return this._items;
}
@@ -99,9 +100,9 @@ export class SqliteClient implements ISyncDatabaseClient {
/**
* Repository for per-item usage statistics (last used, use counts).
*/
- public get itemStats(): ItemStatsRepository {
+ public get itemStats(): SyncRepository<ItemStatsRepository> {
if (!this._itemStats) {
- this._itemStats = new ItemStatsRepository(this);
+ this._itemStats = syncRepository(new ItemStatsRepository(this), this);
}
return this._itemStats;
}
@@ -109,9 +110,9 @@ export class SqliteClient implements ISyncDatabaseClient {
/**
* Repository for Passkey operations.
*/
- public get passkeys(): PasskeyRepository {
+ public get passkeys(): SyncRepository<PasskeyRepository> {
if (!this._passkeys) {
- this._passkeys = new PasskeyRepository(this);
+ this._passkeys = syncRepository(new PasskeyRepository(this), this);
}
return this._passkeys;
}
@@ -119,9 +120,9 @@ export class SqliteClient implements ISyncDatabaseClient {
/**
* Repository for Folder operations.
*/
- public get folders(): FolderRepository {
+ public get folders(): SyncRepository<FolderRepository> {
if (!this._folders) {
- this._folders = new FolderRepository(this, this.logos);
+ this._folders = syncRepository(new FolderRepository(this, this.logoRepository), this);
}
return this._folders;
}
@@ -139,9 +140,9 @@ export class SqliteClient implements ISyncDatabaseClient {
/**
* Repository for the per-manifest keypairs that receive mail.
*/
- public get encryptionKeys(): EncryptionKeyRepository {
+ public get encryptionKeys(): SyncRepository<EncryptionKeyRepository> {
if (!this._encryptionKeys) {
- this._encryptionKeys = new EncryptionKeyRepository(this);
+ this._encryptionKeys = syncRepository(new EncryptionKeyRepository(this), this);
}
return this._encryptionKeys;
}
@@ -149,13 +150,23 @@ export class SqliteClient implements ISyncDatabaseClient {
/**
* Repository for item logo operations (favicons, built-in logos and uploaded images alike).
*/
- public get logos(): LogoRepository {
+ public get logos(): SyncRepository<LogoRepository> {
if (!this._logos) {
- this._logos = new LogoRepository(this);
+ this._logos = syncRepository(this.logoRepository, this);
}
return this._logos;
}
+ /**
+ * The logo repository itself, which the item and folder repositories call into.
+ */
+ private get logoRepository(): LogoRepository {
+ if (!this._logoRepository) {
+ this._logoRepository = new LogoRepository(this);
+ }
+ return this._logoRepository;
+ }
+
// ===== IDatabaseClient Implementation =====
/**
diff --git a/core/client/src/database/index.ts b/core/client/src/database/index.ts
index 15ca9e92c..3aa3327d5 100644
--- a/core/client/src/database/index.ts
+++ b/core/client/src/database/index.ts
@@ -1,6 +1,6 @@
// Base
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';
+export { asyncRepository, runAsync, runSync, syncRepository, type AsyncRepository, type DbOp, type SyncRepository } from './DbOp';
// Mappers
export { FieldMapper, type FieldRow } from './mappers/FieldMapper';
diff --git a/core/client/src/database/queries/ItemQueries.ts b/core/client/src/database/queries/ItemQueries.ts
index 173efec71..1235c32b1 100644
--- a/core/client/src/database/queries/ItemQueries.ts
+++ b/core/client/src/database/queries/ItemQueries.ts
@@ -559,13 +559,13 @@ export class AttachmentQueries {
VALUES (?, ?, ?, ?, ${BaseQueries.MANIFEST_OF_ITEM}, ?, ?, ?)`;
/**
- * Soft delete an attachment. Also zeroes the Blob bytes so storage is reclaimed
+ * Soft delete an attachment. Also drops the Blob bytes so storage is reclaimed
* immediately while the row remains as a tombstone for LWW sync.
*/
public static readonly SOFT_DELETE = `
UPDATE Attachments
SET IsDeleted = 1,
- Blob = X'',
+ Blob = NULL,
UpdatedAt = ?
WHERE Id = ? AND ManifestId = ?`;
}
diff --git a/core/client/src/database/repositories/EncryptionKeyRepository.ts b/core/client/src/database/repositories/EncryptionKeyRepository.ts
index a7b46949f..4f3537ad8 100644
--- a/core/client/src/database/repositories/EncryptionKeyRepository.ts
+++ b/core/client/src/database/repositories/EncryptionKeyRepository.ts
@@ -1,6 +1,7 @@
import { BaseRepository } from '../BaseRepository';
import { EncryptionKeyQueries } from '../queries/EncryptionKeyQueries';
+import type { DbOp } from '../DbOp';
import type { EncryptionKey } from '@aliasvault/models/vault';
/**
@@ -15,8 +16,8 @@ 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);
+ public *getAll(): DbOp<EncryptionKey[]> {
+ return yield* this.query<EncryptionKey>(EncryptionKeyQueries.GET_ALL);
}
/**
@@ -25,8 +26,8 @@ export class EncryptionKeyRepository extends BaseRepository {
* @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]);
+ public *getActiveForManifest(manifestId: string): DbOp<EncryptionKey | null> {
+ const results = yield* this.query<EncryptionKey>(EncryptionKeyQueries.GET_ACTIVE_FOR_MANIFEST, [manifestId]);
return results.length > 0 ? results[0] : null;
}
@@ -35,12 +36,12 @@ export class EncryptionKeyRepository extends BaseRepository {
* @param publicKey - The public half the grant was encrypted for
* @returns The keypair, or null when this vault holds no account key with that public half
*/
- public getAccountKeypair(publicKey: string): EncryptionKey | null {
- const personalManifestId = this.personalManifestId();
+ public *getAccountKeypair(publicKey: string): DbOp<EncryptionKey | null> {
+ const personalManifestId = yield* this.personalManifestId();
if (!personalManifestId) {
return null;
}
- const results = this.client.executeQuery<EncryptionKey>(EncryptionKeyQueries.GET_ACCOUNT_KEY_BY_PUBLIC_KEY, [personalManifestId, publicKey]);
+ const results = yield* this.query<EncryptionKey>(EncryptionKeyQueries.GET_ACCOUNT_KEY_BY_PUBLIC_KEY, [personalManifestId, publicKey]);
return results.length > 0 ? results[0] : null;
}
@@ -51,9 +52,9 @@ export class EncryptionKeyRepository extends BaseRepository {
* @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 {
+ public *setActiveForManifest(manifestId: string, publicKey: string, privateKey: string): DbOp<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]);
+ yield* this.execute(EncryptionKeyQueries.DEMOTE_FOR_MANIFEST, [now, manifestId]);
+ yield* this.execute(EncryptionKeyQueries.INSERT_FOR_MANIFEST, [this.generateId(), manifestId, publicKey, privateKey, now, now]);
}
}
diff --git a/core/client/src/database/repositories/FolderRepository.ts b/core/client/src/database/repositories/FolderRepository.ts
index a9a04aa27..4b5ab54f3 100644
--- a/core/client/src/database/repositories/FolderRepository.ts
+++ b/core/client/src/database/repositories/FolderRepository.ts
@@ -5,7 +5,8 @@ import { BaseRepository } from '../BaseRepository';
import { BaseQueries } from '../queries/BaseQueries';
import { FolderQueries } from '../queries/FolderQueries';
-import type { ISyncDatabaseClient } from '../BaseRepository';
+import type { IDatabaseClient } from '../BaseRepository';
+import type { DbOp } from '../DbOp';
import type { LogoRepository } from './LogoRepository';
/**
@@ -28,7 +29,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: ISyncDatabaseClient, private logoRepository: LogoRepository) {
+ public constructor(client: IDatabaseClient, private logoRepository: LogoRepository) {
super(client);
}
@@ -44,17 +45,18 @@ export class FolderRepository extends BaseRepository {
return this.withTransaction(async () => {
const folderId = id ?? crypto.randomUUID();
const currentDateTime = this.now();
+ const manifestId = await this.run(this.writeManifestId());
- this.client.executeUpdate(FolderQueries.INSERT, [
+ await this.run(this.execute(FolderQueries.INSERT, [
folderId,
name,
parentFolderId || null,
// Second bind of the parent id, then the manifest a top-level folder joins (see INSERT).
parentFolderId || null,
- this.activeManifestId(),
+ manifestId,
currentDateTime,
currentDateTime
- ]);
+ ]));
return folderId;
});
@@ -64,9 +66,9 @@ export class FolderRepository extends BaseRepository {
* Get all folders.
* @returns Array of folder objects (empty array if Folders table doesn't exist yet)
*/
- public getAll(): Folder[] {
+ public *getAll(): DbOp<Folder[]> {
try {
- return this.client.executeQuery<Folder>(FolderQueries.GET_ALL);
+ return yield* this.query<Folder>(FolderQueries.GET_ALL);
} catch (error) {
// Table may not exist in older vault versions - return empty array
if (error instanceof Error && error.message.includes('no such table')) {
@@ -81,11 +83,8 @@ export class FolderRepository extends BaseRepository {
* @param folderId - The ID of the folder
* @returns Folder object or null if not found
*/
- public getById(folderId: string): Omit<Folder, 'Weight'> | null {
- const results = this.client.executeQuery<Omit<Folder, 'Weight'>>(
- FolderQueries.GET_BY_ID,
- [folderId]
- );
+ public *getById(folderId: string): DbOp<Omit<Folder, 'Weight'> | null> {
+ const results = yield* this.query<Omit<Folder, 'Weight'>>(FolderQueries.GET_BY_ID, [folderId]);
return results.length > 0 ? results[0] : null;
}
@@ -96,14 +95,7 @@ export class FolderRepository extends BaseRepository {
* @returns The number of rows updated
*/
public async update(folderId: string, name: string): Promise<number> {
- return this.withTransaction(async () => {
- const currentDateTime = this.now();
- return this.client.executeUpdate(FolderQueries.UPDATE_NAME, [
- name,
- currentDateTime,
- folderId
- ]);
- });
+ return this.withTransaction(() => this.run(this.execute(FolderQueries.UPDATE_NAME, [name, this.now(), folderId])));
}
/**
@@ -111,19 +103,15 @@ export class FolderRepository extends BaseRepository {
* @param folderId - The parent folder ID
* @returns Array of all descendant folder IDs
*/
- private getAllChildFolderIds(folderId: string): string[] {
- const directChildren = this.client.executeQuery<{ Id: string }>(
- FolderQueries.GET_CHILD_FOLDER_IDS,
- [folderId]
- );
+ private *getAllChildFolderIds(folderId: string): DbOp<string[]> {
+ const directChildren = yield* this.query<{ Id: string }>(FolderQueries.GET_CHILD_FOLDER_IDS, [folderId]);
const allChildIds: string[] = [];
for (const child of directChildren) {
allChildIds.push(child.Id);
// Recursively get all descendants
- const descendants = this.getAllChildFolderIds(child.Id);
- allChildIds.push(...descendants);
+ allChildIds.push(...(yield* this.getAllChildFolderIds(child.Id)));
}
return allChildIds;
@@ -140,48 +128,43 @@ export class FolderRepository extends BaseRepository {
*/
public async delete(folderId: string): Promise<number> {
await this.assertDeletable(folderId);
+ return this.withTransaction(() => this.run(this.deleteKeepingContents(folderId)));
+ }
- return this.withTransaction(async () => {
- const currentDateTime = this.now();
-
- // Get the parent folder of the folder being deleted
- const folder = this.getById(folderId);
- const targetParentId = folder?.ParentFolderId || null;
+ /**
+ * Soft delete a folder, moving its items and child folders up to its parent.
+ * @param folderId - The ID of the folder to delete
+ * @returns The number of rows updated
+ */
+ private *deleteKeepingContents(folderId: string): DbOp<number> {
+ const currentDateTime = this.now();
- // Move only items in this folder to the parent folder (or root if no parent)
- if (targetParentId) {
- // Has parent: move items to parent folder
- this.client.executeUpdate(FolderQueries.MOVE_ITEMS_TO_FOLDER, [
- targetParentId,
- // Second bind of the destination: the items adopt that folder's manifest.
- targetParentId,
- this.activeManifestId(),
- currentDateTime,
- folderId
- ]);
- } else {
- // No parent: move items to root (NULL)
- this.client.executeUpdate(FolderQueries.CLEAR_ITEMS_FOLDER, [
- // Out of every folder means into the default manifest.
- this.activeManifestId(),
- currentDateTime,
- folderId
- ]);
- }
+ // Get the parent folder of the folder being deleted
+ const folder = yield* this.getById(folderId);
+ const targetParentId = folder?.ParentFolderId || null;
+ const manifestId = yield* this.writeManifestId();
- // Move direct child folders to the parent of the deleted folder
- this.client.executeUpdate(FolderQueries.UPDATE_PARENT_FOLDER, [
+ // Move only items in this folder to the parent folder (or root if no parent)
+ if (targetParentId) {
+ // Has parent: move items to parent folder
+ yield* this.execute(FolderQueries.MOVE_ITEMS_TO_FOLDER, [
+ targetParentId,
+ // Second bind of the destination: the items adopt that folder's manifest.
targetParentId,
+ manifestId,
currentDateTime,
folderId
]);
+ } else {
+ // No parent: move items to root (NULL); out of every folder means into the default manifest.
+ yield* this.execute(FolderQueries.CLEAR_ITEMS_FOLDER, [manifestId, currentDateTime, folderId]);
+ }
- // Soft delete the folder
- return this.client.executeUpdate(FolderQueries.SOFT_DELETE, [
- currentDateTime,
- folderId
- ]);
- });
+ // Move direct child folders to the parent of the deleted folder
+ yield* this.execute(FolderQueries.UPDATE_PARENT_FOLDER, [targetParentId, currentDateTime, folderId]);
+
+ // Soft delete the folder
+ return yield* this.execute(FolderQueries.SOFT_DELETE, [currentDateTime, folderId]);
}
/**
@@ -194,47 +177,31 @@ export class FolderRepository extends BaseRepository {
*/
public async deleteWithContents(folderId: string): Promise<number> {
await this.assertDeletable(folderId);
+ return this.withTransaction(() => this.run(this.deleteFolderTree(folderId)));
+ }
- return this.withTransaction(async () => {
- const currentDateTime = this.now();
-
- // Get all child folder IDs recursively
- const allChildFolderIds = this.getAllChildFolderIds(folderId);
-
- let totalItemsDeleted = 0;
-
- // Move all items in this folder to trash
- totalItemsDeleted += this.client.executeUpdate(FolderQueries.TRASH_ITEMS_IN_FOLDER, [
- currentDateTime,
- currentDateTime,
- folderId
- ]);
+ /**
+ * Soft delete a folder and its child folders, moving every item inside them to the trash.
+ * @param folderId - The ID of the folder to delete
+ * @returns The number of items trashed
+ */
+ private *deleteFolderTree(folderId: string): DbOp<number> {
+ const currentDateTime = this.now();
+ const allChildFolderIds = yield* this.getAllChildFolderIds(folderId);
- // Move all items in child folders to trash
- for (const childFolderId of allChildFolderIds) {
- totalItemsDeleted += this.client.executeUpdate(FolderQueries.TRASH_ITEMS_IN_FOLDER, [
- currentDateTime,
- currentDateTime,
- childFolderId
- ]);
- }
+ let totalItemsDeleted = 0;
- // Soft delete all child folders
- for (const childFolderId of allChildFolderIds) {
- this.client.executeUpdate(FolderQueries.SOFT_DELETE, [
- currentDateTime,
- childFolderId
- ]);
- }
+ // Move all items in this folder and in its child folders to trash
+ for (const id of [folderId, ...allChildFolderIds]) {
+ totalItemsDeleted += yield* this.execute(FolderQueries.TRASH_ITEMS_IN_FOLDER, [currentDateTime, currentDateTime, id]);
+ }
- // Soft delete the parent folder
- this.client.executeUpdate(FolderQueries.SOFT_DELETE, [
- currentDateTime,
- folderId
- ]);
+ // Soft delete all child folders, then the folder itself
+ for (const id of [...allChildFolderIds, folderId]) {
+ yield* this.execute(FolderQueries.SOFT_DELETE, [currentDateTime, id]);
+ }
- return totalItemsDeleted;
- });
+ return totalItemsDeleted;
}
/**
@@ -242,7 +209,7 @@ export class FolderRepository extends BaseRepository {
* @param folderId - The folder about to be deleted
*/
private async assertDeletable(folderId: string): Promise<void> {
- const folder = this.getById(folderId);
+ const folder = await this.run(this.getById(folderId));
if (folder && multiManifestRendering.isManifestRoot(folder)) {
throw new Error(await getPlatform().translate(TranslatableMessage.SharedFolderDeleteRefused));
}
@@ -256,8 +223,8 @@ export class FolderRepository extends BaseRepository {
*/
public async restampSubtree(folderId: string, manifestId: string): Promise<number> {
return this.withTransaction(async () => {
- const folders = this.client.executeUpdate(BaseQueries.RESTAMP_SUBTREE_FOLDERS, [manifestId, folderId]);
- const items = this.client.executeUpdate(BaseQueries.RESTAMP_SUBTREE_ITEMS, [manifestId, folderId]);
+ const folders = await this.run(this.execute(BaseQueries.RESTAMP_SUBTREE_FOLDERS, [manifestId, folderId]));
+ const items = await this.run(this.execute(BaseQueries.RESTAMP_SUBTREE_ITEMS, [manifestId, folderId]));
// The items moved; the images they point at have to follow them into the new manifest.
await this.logoRepository.reconcileItemLogoScopes(this.now());
return folders + items;
@@ -273,14 +240,15 @@ export class FolderRepository extends BaseRepository {
public async moveItem(itemId: string, folderId: string | null): Promise<number> {
return this.withTransaction(async () => {
const currentDateTime = this.now();
- const moved = this.client.executeUpdate(FolderQueries.MOVE_ITEM, [
+ const manifestId = await this.run(this.writeManifestId());
+ const moved = await this.run(this.execute(FolderQueries.MOVE_ITEM, [
folderId,
// Second bind of the destination: the item adopts that folder's manifest.
folderId,
- this.activeManifestId(),
+ manifestId,
currentDateTime,
itemId
- ]);
+ ]));
// The destination folder may sit in another manifest; the item's logo has to follow it there.
await this.logoRepository.reconcileItemLogoScopes(currentDateTime);
return moved;
diff --git a/core/client/src/database/repositories/ItemRepository.ts b/core/client/src/database/repositories/ItemRepository.ts
index ef75a4543..b88ad9a4a 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 ISyncDatabaseClient } from '../BaseRepository';
+import { BaseRepository, type IDatabaseClient } 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';
@@ -15,6 +15,7 @@ import {
AttachmentQueries
} from '../queries/ItemQueries';
+import type { DbOp } from '../DbOp';
import type { Folder } from './FolderRepository';
import type { LogoRepository } from './LogoRepository';
import type { Item, ItemField, Attachment, TotpCode, FieldHistory, LogoSelection } from '@aliasvault/models/vault';
@@ -30,7 +31,7 @@ export class ItemRepository extends BaseRepository {
* @param logoRepository - The logo repository to use for the repository
*/
public constructor(
- client: ISyncDatabaseClient,
+ client: IDatabaseClient,
private logoRepository: LogoRepository
) {
super(client);
@@ -44,37 +45,12 @@ export class ItemRepository extends BaseRepository {
* manifest for the same reason: a parent link only ever resolves inside its own namespace.
* @returns Map of scoped folder key to path array
*/
- private buildFolderPaths(): Map<string, string[]> {
+ private *buildFolderPaths(): DbOp<Map<string, string[]>> {
const folderPathMap = new Map<string, string[]>();
+ let folders: (Folder & { ManifestId: string })[];
try {
- // Get all folders from database
- const folders = this.client.executeQuery<Folder & { ManifestId: string }>(
- 'SELECT Id, ManifestId, Name, ParentFolderId, Weight FROM Folders WHERE IsDeleted = 0'
- );
-
- if (folders.length === 0) {
- return folderPathMap;
- }
-
- // Use shared utility to build paths, one manifest's tree at a time
- const foldersByManifest = new Map<string, (Folder & { ManifestId: string })[]>();
- for (const folder of folders) {
- const siblings = foldersByManifest.get(folder.ManifestId) ?? [];
- siblings.push(folder);
- foldersByManifest.set(folder.ManifestId, siblings);
- }
-
- for (const [manifestId, manifestFolders] of foldersByManifest) {
- for (const folder of manifestFolders) {
- const path = getFolderPath(folder.Id, manifestFolders);
- if (path.length > 0) {
- folderPathMap.set(scopedKey(manifestId, folder.Id), path);
- }
- }
- }
-
- return folderPathMap;
+ folders = yield* this.query<Folder & { ManifestId: string }>('SELECT Id, ManifestId, Name, ParentFolderId, Weight FROM Folders WHERE IsDeleted = 0');
} catch (error) {
// Folders table may not exist in older vault versions
if (error instanceof Error && error.message.includes('no such table')) {
@@ -82,6 +58,25 @@ export class ItemRepository extends BaseRepository {
}
throw error;
}
+
+ // Use shared utility to build paths, one manifest's tree at a time
+ const foldersByManifest = new Map<string, (Folder & { ManifestId: string })[]>();
+ for (const folder of folders) {
+ const siblings = foldersByManifest.get(folder.ManifestId) ?? [];
+ siblings.push(folder);
+ foldersByManifest.set(folder.ManifestId, siblings);
+ }
+
+ for (const [manifestId, manifestFolders] of foldersByManifest) {
+ for (const folder of manifestFolders) {
+ const path = getFolderPath(folder.Id, manifestFolders);
+ if (path.length > 0) {
+ folderPathMap.set(scopedKey(manifestId, folder.Id), path);
+ }
+ }
+ }
+
+ return folderPathMap;
}
/**
@@ -89,17 +84,18 @@ export class ItemRepository extends BaseRepository {
* excluded; this is what both the main item list and autofill read.
* @returns Array of Item objects (empty array if Items table doesn't exist yet)
*/
- public getAll(): Item[] {
- return this.hydrateItems(this.selectItemRows(ItemQueries.GET_ALL_ACTIVE));
+ public *getAll(): DbOp<Item[]> {
+ const itemRows = yield* this.selectItemRows(ItemQueries.GET_ALL_ACTIVE);
+ return yield* this.hydrateItems(itemRows);
}
/**
* Fetch all archived items with their dynamic fields and tags.
* @returns Array of archived Item objects with ArchivedAt (empty array if Items table doesn't exist yet)
*/
- public getArchived(): ItemWithArchivedAt[] {
- const itemRows = this.selectItemRows(ItemQueries.GET_ARCHIVED);
- const items = this.hydrateItems(itemRows);
+ public *getArchived(): DbOp<ItemWithArchivedAt[]> {
+ const itemRows = yield* this.selectItemRows(ItemQueries.GET_ARCHIVED);
+ const items = yield* this.hydrateItems(itemRows);
return items.map((item, index) => ({ ...item, ArchivedAt: itemRows[index].ArchivedAt ?? undefined }));
}
@@ -107,9 +103,9 @@ export class ItemRepository extends BaseRepository {
* Get count of archived items.
* @returns Number of archived items
*/
- public getArchivedCount(): number {
+ public *getArchivedCount(): DbOp<number> {
try {
- const result = this.client.executeQuery<{ count: number }>(ItemQueries.COUNT_ARCHIVED);
+ const result = yield* this.query<{ count: number }>(ItemQueries.COUNT_ARCHIVED);
return result[0]?.count ?? 0;
} catch (error) {
if (error instanceof Error && error.message.includes('no such table')) {
@@ -124,9 +120,9 @@ export class ItemRepository extends BaseRepository {
* @param query - The item query to run
* @returns The raw item rows, or an empty array if the table does not exist yet
*/
- private selectItemRows(query: string): ItemRow[] {
+ private *selectItemRows(query: string): DbOp<ItemRow[]> {
try {
- return this.client.executeQuery<ItemRow>(query);
+ return yield* this.query<ItemRow>(query);
} catch (error) {
// Items table may not exist in older vault versions - return empty array
if (error instanceof Error && error.message.includes('no such table')) {
@@ -141,7 +137,7 @@ export class ItemRepository extends BaseRepository {
* @param itemRows - The raw item rows to hydrate
* @returns The hydrated Item objects, in the order the rows came in
*/
- private hydrateItems(itemRows: ItemRow[]): Item[] {
+ private *hydrateItems(itemRows: ItemRow[]): DbOp<Item[]> {
if (itemRows.length === 0) {
return [];
}
@@ -153,21 +149,15 @@ export class ItemRepository extends BaseRepository {
const itemRefs = itemRows.map(row => ({ Id: row.Id, ManifestId: row.ManifestId }));
// Get all field values
- const fieldRows = this.client.executeQuery<FieldRow>(
- ItemQueries.getFieldValuesForItems(itemRefs.length),
- itemKeyBindings(itemRefs)
- );
+ const fieldRows = yield* this.query<FieldRow>(ItemQueries.getFieldValuesForItems(itemRefs.length), itemKeyBindings(itemRefs));
const fieldsByItem = FieldMapper.processFieldRows(fieldRows);
// Get all tags
- const tagRows = this.client.executeQuery<TagRow>(
- ItemQueries.getTagsForItems(itemRefs.length),
- itemKeyBindings(itemRefs)
- );
+ const tagRows = yield* this.query<TagRow>(ItemQueries.getTagsForItems(itemRefs.length), itemKeyBindings(itemRefs));
const tagsByItem = ItemMapper.groupTagsByItem(tagRows);
// Build folder paths
- const folderPaths = this.buildFolderPaths();
+ const folderPaths = yield* this.buildFolderPaths();
return ItemMapper.mapRows(itemRows, fieldsByItem, tagsByItem, folderPaths);
}
@@ -178,35 +168,29 @@ export class ItemRepository extends BaseRepository {
* @param manifestId - The manifest the item belongs to, when known
* @returns Item object or null if not found
*/
- public getById(itemId: string, manifestId?: string): Item | null {
- const ref = this.resolveItemRef(itemId, manifestId);
+ public *getById(itemId: string, manifestId?: string): DbOp<Item | null> {
+ const ref = yield* this.resolveItemRef(itemId, manifestId);
if (!ref) {
return null;
}
- const results = this.client.executeQuery<ItemRow>(ItemQueries.GET_BY_ID, [ref.Id, ref.ManifestId]);
+ const results = yield* this.query<ItemRow>(ItemQueries.GET_BY_ID, [ref.Id, ref.ManifestId]);
if (results.length === 0) {
return null;
}
// Get field values
- const fieldRows = this.client.executeQuery<Omit<FieldRow, 'ItemId' | 'ManifestId'>>(
- ItemQueries.GET_FIELD_VALUES_FOR_ITEM,
- [ref.Id, ref.ManifestId]
- );
+ const fieldRows = yield* this.query<Omit<FieldRow, 'ItemId' | 'ManifestId'>>(ItemQueries.GET_FIELD_VALUES_FOR_ITEM, [ref.Id, ref.ManifestId]);
const fields = FieldMapper.processFieldRowsForSingleItem(fieldRows);
// Get tags
- const tagRows = this.client.executeQuery<Omit<TagRow, 'ItemId' | 'ManifestId'>>(
- ItemQueries.GET_TAGS_FOR_ITEM,
- [ref.Id, ref.ManifestId]
- );
+ const tagRows = yield* this.query<Omit<TagRow, 'ItemId' | 'ManifestId'>>(ItemQueries.GET_TAGS_FOR_ITEM, [ref.Id, ref.ManifestId]);
const tags = ItemMapper.mapTagRows(tagRows);
// Get folder path if item is in a folder
let folderPath: string[] | undefined;
if (results[0].FolderId) {
- const folderPaths = this.buildFolderPaths();
+ const folderPaths = yield* this.buildFolderPaths();
folderPath = folderPaths.get(scopedKey(results[0].ManifestId, results[0].FolderId));
}
@@ -219,12 +203,12 @@ export class ItemRepository extends BaseRepository {
* @param manifestId - The manifest the item belongs to, when known
* @returns The item reference, or null when no such item exists
*/
- private resolveItemRef(itemId: string, manifestId?: string): ItemRef | null {
+ private *resolveItemRef(itemId: string, manifestId?: string): DbOp<ItemRef | null> {
if (manifestId) {
return { Id: itemId, ManifestId: manifestId };
}
- const resolved = this.resolveRowManifestId('Items', itemId);
+ const resolved = yield* this.resolveRowManifestId('Items', itemId);
return resolved ? { Id: itemId, ManifestId: resolved } : null;
}
@@ -234,11 +218,8 @@ export class ItemRepository extends BaseRepository {
* client stops asking for its mailbox until it is switched back on.
* @returns Array of email addresses
*/
- public getRoutableEmailAddresses(): string[] {
- const results = this.client.executeQuery<{ Email: string }>(
- ItemQueries.GET_ROUTABLE_EMAIL_ADDRESSES,
- [FieldKey.LoginEmail]
- );
+ public *getRoutableEmailAddresses(): DbOp<string[]> {
+ const results = yield* this.query<{ Email: string }>(ItemQueries.GET_ROUTABLE_EMAIL_ADDRESSES, [FieldKey.LoginEmail]);
return results.map(row => row.Email);
}
@@ -248,11 +229,8 @@ export class ItemRepository extends BaseRepository {
* @param email - The full email address (local@domain) to check
* @returns True when at least one live, switched-on login email field carries this address
*/
- public isEmailAddressRoutable(email: string): boolean {
- const results = this.client.executeQuery<{ Count: number }>(
- ItemQueries.COUNT_ROUTABLE_EMAIL_FIELDS,
- [FieldKey.LoginEmail, email.trim().toLowerCase()]
- );
+ public *isEmailAddressRoutable(email: string): DbOp<boolean> {
+ const results = yield* this.query<{ Count: number }>(ItemQueries.COUNT_ROUTABLE_EMAIL_FIELDS, [FieldKey.LoginEmail, email.trim().toLowerCase()]);
return (results[0]?.Count ?? 0) > 0;
}
@@ -261,11 +239,8 @@ export class ItemRepository extends BaseRepository {
* @param email - The full email address (local@domain) to look up
* @returns Object with Id and Name, or null when no active item uses this address
*/
- public findIdByEmail(email: string): { Id: string; Name: string | null } | null {
- const results = this.client.executeQuery<{ Id: string; Name: string | null }>(
- ItemQueries.GET_ITEM_BY_EMAIL,
- [FieldKey.LoginEmail, email]
- );
+ public *findIdByEmail(email: string): DbOp<{ Id: string; Name: string | null } | null> {
+ const results = yield* this.query<{ Id: string; Name: string | null }>(ItemQueries.GET_ITEM_BY_EMAIL, [FieldKey.LoginEmail, email]);
return results.length > 0 ? results[0] : null;
}
@@ -291,7 +266,8 @@ export class ItemRepository extends BaseRepository {
const logoId = await this.resolveLogoId(item, currentDateTime, null, logoSelection);
// 2. Insert Item
- this.client.executeUpdate(ItemQueries.INSERT_ITEM, [
+ const manifestId = await this.run(this.writeManifestId());
+ await this.run(this.execute(ItemQueries.INSERT_ITEM, [
itemId,
item.Name ?? null,
item.ItemType,
@@ -299,22 +275,22 @@ export class ItemRepository extends BaseRepository {
item.FolderId ?? null,
// Second bind of the folder id, then the manifest an item outside any folder joins (see INSERT_ITEM).
item.FolderId ?? null,
- this.activeManifestId(),
+ manifestId,
currentDateTime,
currentDateTime,
0
- ]);
+ ]));
/*
* 3-5. Insert the child rows. Each stamps itself with the manifest of the item it hangs off
* (see BaseQueries.MANIFEST_OF_ITEM), which the INSERT above has just decided from the folder.
*/
if (item.Fields && item.Fields.length > 0) {
- this.insertFieldValues(itemId, item.Fields, item.ItemType, currentDateTime);
+ await this.run(this.insertFieldValues(itemId, item.Fields, item.ItemType, manifestId, currentDateTime));
}
- this.insertTotpCodes(itemId, totpCodes, currentDateTime);
- this.insertAttachments(itemId, attachments, currentDateTime);
+ await this.run(this.insertTotpCodes(itemId, totpCodes, manifestId, currentDateTime));
+ await this.run(this.insertAttachments(itemId, attachments, manifestId, currentDateTime));
return itemId;
});
@@ -327,111 +303,109 @@ export class ItemRepository extends BaseRepository {
* @returns The ID of the newly created item
*/
public async duplicate(itemId: string, manifestId?: string): Promise<string> {
- return this.withTransaction(async () => {
- const currentDateTime = this.now();
- const newItemId = this.generateId();
- const ref = this.resolveItemRef(itemId, manifestId);
- if (!ref) {
- throw new Error(`Item not found: ${itemId}`);
- }
+ return this.withTransaction(() => this.run(this.copyItem(itemId, manifestId)));
+ }
- const sourceRows = this.client.executeQuery<{ Name: string | null }>(
- 'SELECT Name FROM Items WHERE Id = ? AND ManifestId = ? AND IsDeleted = 0',
- [ref.Id, ref.ManifestId]
- );
- if (sourceRows.length === 0) {
- throw new Error(`Item not found: ${itemId}`);
- }
+ /**
+ * Copy an item and its child rows under fresh ids.
+ * @param itemId - The ID of the item to duplicate
+ * @param manifestId - The manifest the item belongs to, when known
+ * @returns The ID of the newly created item
+ */
+ private *copyItem(itemId: string, manifestId?: string): DbOp<string> {
+ const currentDateTime = this.now();
+ const newItemId = this.generateId();
+ const ref = yield* this.resolveItemRef(itemId, manifestId);
+ if (!ref) {
+ throw new Error(`Item not found: ${itemId}`);
+ }
- const existingNames = this.client.executeQuery<{ Name: string | null }>(
- 'SELECT Name FROM Items WHERE IsDeleted = 0 AND DeletedAt IS NULL'
- );
- const newName = ItemRepository.generateCopyName(
- sourceRows[0].Name,
- existingNames.map(row => row.Name)
- );
+ const sourceRows = yield* this.query<{ Name: string | null }>('SELECT Name FROM Items WHERE Id = ? AND ManifestId = ? AND IsDeleted = 0', [ref.Id, ref.ManifestId]);
+ if (sourceRows.length === 0) {
+ throw new Error(`Item not found: ${itemId}`);
+ }
- /*
- * 1. Copy the item row itself (same logo, folder and type).
- */
- this.client.executeUpdate(`
- INSERT INTO Items (Id, Name, ItemType, LogoId, FolderId, ManifestId, CreatedAt, UpdatedAt, IsDeleted)
- SELECT ?, ?, ItemType, LogoId, FolderId, ManifestId, ?, ?, 0 FROM Items WHERE Id = ? AND ManifestId = ?`,
- [newItemId, newName, currentDateTime, currentDateTime, ref.Id, ref.ManifestId]);
+ const existingNames = yield* this.query<{ Name: string | null }>('SELECT Name FROM Items WHERE IsDeleted = 0 AND DeletedAt IS NULL');
+ const newName = ItemRepository.generateCopyName(sourceRows[0].Name, existingNames.map(row => row.Name));
- /*
- * 2. Copy custom field definitions so later edits to the duplicate's
- * custom fields don't affect the original item.
- */
- const definitionRows = this.client.executeQuery<{ Id: string }>(
- `SELECT DISTINCT FieldDefinitionId as Id FROM FieldValues
- WHERE ItemId = ? AND ManifestId = ? AND IsDeleted = 0 AND FieldDefinitionId IS NOT NULL`,
- [ref.Id, ref.ManifestId]
- );
- const definitionIdMap = new Map<string, string>();
- for (const definition of definitionRows) {
- const newDefinitionId = this.generateId();
- definitionIdMap.set(definition.Id, newDefinitionId);
- this.client.executeUpdate(`
- INSERT INTO FieldDefinitions (Id, ManifestId, FieldType, Label, IsMultiValue, IsHidden, EnableHistory, Weight, ApplicableToTypes, CreatedAt, UpdatedAt, IsDeleted)
- SELECT ?, ManifestId, FieldType, Label, IsMultiValue, IsHidden, EnableHistory, Weight, ApplicableToTypes, ?, ?, 0
- FROM FieldDefinitions WHERE Id = ? AND ManifestId = ?`,
- [newDefinitionId, currentDateTime, currentDateTime, definition.Id, ref.ManifestId]);
- }
+ /*
+ * 1. Copy the item row itself (same logo, folder and type).
+ */
+ yield* this.execute(`
+ INSERT INTO Items (Id, Name, ItemType, LogoId, FolderId, ManifestId, CreatedAt, UpdatedAt, IsDeleted)
+ SELECT ?, ?, ItemType, LogoId, FolderId, ManifestId, ?, ?, 0 FROM Items WHERE Id = ? AND ManifestId = ?`,
+ [newItemId, newName, currentDateTime, currentDateTime, ref.Id, ref.ManifestId]);
- // 3. Copy field values, remapping custom fields to the copied definitions.
- const fieldValueRows = this.client.executeQuery<{ Id: string; FieldDefinitionId: string | null }>(
- 'SELECT Id, FieldDefinitionId FROM FieldValues WHERE ItemId = ? AND ManifestId = ? AND IsDeleted = 0',
- [ref.Id, ref.ManifestId]
- );
- for (const row of fieldValueRows) {
- this.client.executeUpdate(`
- INSERT INTO FieldValues (Id, ItemId, ManifestId, FieldDefinitionId, FieldKey, Value, Weight, CreatedAt, UpdatedAt, IsDeleted)
- SELECT ?, ?, ManifestId, ?, FieldKey, Value, Weight, ?, ?, 0 FROM FieldValues WHERE Id = ? AND ManifestId = ?`,
- [
- this.generateId(),
- newItemId,
- row.FieldDefinitionId ? definitionIdMap.get(row.FieldDefinitionId) ?? null : null,
- currentDateTime,
- currentDateTime,
- row.Id,
- ref.ManifestId
- ]);
- }
+ /*
+ * 2. Copy custom field definitions so later edits to the duplicate's
+ * custom fields don't affect the original item.
+ */
+ const definitionRows = yield* this.query<{ Id: string }>(
+ `SELECT DISTINCT FieldDefinitionId as Id FROM FieldValues
+ WHERE ItemId = ? AND ManifestId = ? AND IsDeleted = 0 AND FieldDefinitionId IS NOT NULL`,
+ [ref.Id, ref.ManifestId]
+ );
+ const definitionIdMap = new Map<string, string>();
+ for (const definition of definitionRows) {
+ const newDefinitionId = this.generateId();
+ definitionIdMap.set(definition.Id, newDefinitionId);
+ yield* this.execute(`
+ INSERT INTO FieldDefinitions (Id, ManifestId, FieldType, Label, IsMultiValue, IsHidden, EnableHistory, Weight, ApplicableToTypes, CreatedAt, UpdatedAt, IsDeleted)
+ SELECT ?, ManifestId, FieldType, Label, IsMultiValue, IsHidden, EnableHistory, Weight, ApplicableToTypes, ?, ?, 0
+ FROM FieldDefinitions WHERE Id = ? AND ManifestId = ?`,
+ [newDefinitionId, currentDateTime, currentDateTime, definition.Id, ref.ManifestId]);
+ }
- /*
- * 4. Copy remaining child rows with fresh IDs.
- */
- const childCopies = [
- {
- table: 'TotpCodes',
- sql: `INSERT INTO TotpCodes (Id, ItemId, ManifestId, Name, SecretKey, Algorithm, Digits, Period, CreatedAt, UpdatedAt, IsDeleted)
- SELECT ?, ?, ManifestId, Name, SecretKey, Algorithm, Digits, Period, ?, ?, 0 FROM TotpCodes WHERE Id = ? AND ManifestId = ?`,
- },
- {
- table: 'Attachments',
- sql: `INSERT INTO Attachments (Id, ItemId, ManifestId, Filename, Blob, CreatedAt, UpdatedAt, IsDeleted)
- SELECT ?, ?, ManifestId, Filename, Blob, ?, ?, 0 FROM Attachments WHERE Id = ? AND ManifestId = ?`,
- },
- {
- table: 'ItemTags',
- sql: `INSERT INTO ItemTags (Id, ItemId, ManifestId, TagId, CreatedAt, UpdatedAt, IsDeleted)
- SELECT ?, ?, ManifestId, TagId, ?, ?, 0 FROM ItemTags WHERE Id = ? AND ManifestId = ?`,
- },
- ];
-
- for (const copy of childCopies) {
- const rows = this.client.executeQuery<{ Id: string }>(
- `SELECT Id FROM ${copy.table} WHERE ItemId = ? AND ManifestId = ? AND IsDeleted = 0`,
- [ref.Id, ref.ManifestId]
- );
- for (const row of rows) {
- this.client.executeUpdate(copy.sql, [this.generateId(), newItemId, currentDateTime, currentDateTime, row.Id, ref.ManifestId]);
- }
+ // 3. Copy field values, remapping custom fields to the copied definitions.
+ const fieldValueRows = yield* this.query<{ Id: string; FieldDefinitionId: string | null }>(
+ 'SELECT Id, FieldDefinitionId FROM FieldValues WHERE ItemId = ? AND ManifestId = ? AND IsDeleted = 0',
+ [ref.Id, ref.ManifestId]
+ );
+ for (const row of fieldValueRows) {
+ yield* this.execute(`
+ INSERT INTO FieldValues (Id, ItemId, ManifestId, FieldDefinitionId, FieldKey, Value, Weight, CreatedAt, UpdatedAt, IsDeleted)
+ SELECT ?, ?, ManifestId, ?, FieldKey, Value, Weight, ?, ?, 0 FROM FieldValues WHERE Id = ? AND ManifestId = ?`,
+ [
+ this.generateId(),
+ newItemId,
+ row.FieldDefinitionId ? definitionIdMap.get(row.FieldDefinitionId) ?? null : null,
+ currentDateTime,
+ currentDateTime,
+ row.Id,
+ ref.ManifestId
+ ]);
+ }
+
+ /*
+ * 4. Copy remaining child rows with fresh IDs.
+ */
+ const childCopies = [
+ {
+ table: 'TotpCodes',
+ sql: `INSERT INTO TotpCodes (Id, ItemId, ManifestId, Name, SecretKey, Algorithm, Digits, Period, CreatedAt, UpdatedAt, IsDeleted)
+ SELECT ?, ?, ManifestId, Name, SecretKey, Algorithm, Digits, Period, ?, ?, 0 FROM TotpCodes WHERE Id = ? AND ManifestId = ?`,
+ },
+ {
+ table: 'Attachments',
+ sql: `INSERT INTO Attachments (Id, ItemId, ManifestId, Filename, Blob, CreatedAt, UpdatedAt, IsDeleted)
+ SELECT ?, ?, ManifestId, Filename, Blob, ?, ?, 0 FROM Attachments WHERE Id = ? AND ManifestId = ?`,
+ },
+ ];
+
+ for (const copy of childCopies) {
+ const rows = yield* this.query<{ Id: string }>(`SELECT Id FROM ${copy.table} WHERE ItemId = ? AND ManifestId = ? AND IsDeleted = 0`, [ref.Id, ref.ManifestId]);
+ for (const row of rows) {
+ yield* this.execute(copy.sql, [this.generateId(), newItemId, currentDateTime, currentDateTime, row.Id, ref.ManifestId]);
}
+ }
- return newItemId;
- });
+ // ItemTags has no Id of its own: a row is the (item, tag) pair, so the tags copy in one statement.
+ yield* this.execute(`
+ INSERT INTO ItemTags (ManifestId, ItemId, TagId, CreatedAt, UpdatedAt, IsDeleted)
+ SELECT ManifestId, ?, TagId, ?, ?, 0 FROM ItemTags WHERE ItemId = ? AND ManifestId = ? AND IsDeleted = 0`,
+ [newItemId, currentDateTime, currentDateTime, ref.Id, ref.ManifestId]);
+
+ return newItemId;
}
/**
@@ -476,21 +450,22 @@ export class ItemRepository extends BaseRepository {
const currentDateTime = this.now();
// Every row this write touches stays inside the item's own manifest.
- const ref = this.resolveItemRef(item.Id, item.ManifestId);
+ const ref = await this.run(this.resolveItemRef(item.Id, item.ManifestId));
if (!ref) {
return 0;
}
// 1. Read the stored item first: resolving the logo needs to know which one it already has.
- const existing = this.client.executeQuery<{
+ const existing = (await this.run(this.query<{
Name: string | null;
ItemType: number;
FolderId: string | null;
LogoId: string | null;
- }>(ItemQueries.GET_ITEM_FIELDS, [ref.Id, ref.ManifestId])[0];
+ }>(ItemQueries.GET_ITEM_FIELDS, [ref.Id, ref.ManifestId])))[0];
// 2. Handle the logo
const logoId = await this.resolveLogoId(item, currentDateTime, existing?.LogoId ?? null, logoSelection);
+ const manifestId = await this.run(this.writeManifestId());
if (existing) {
const nameChanged = (item.Name ?? null) !== existing.Name;
@@ -500,33 +475,33 @@ export class ItemRepository extends BaseRepository {
if (nameChanged || itemTypeChanged || folderIdChanged || logoIdChanged) {
// Use UPDATE_ITEM_WITH_LOGO to allow explicit clearing of LogoId
- this.client.executeUpdate(ItemQueries.UPDATE_ITEM_WITH_LOGO, [
+ await this.run(this.execute(ItemQueries.UPDATE_ITEM_WITH_LOGO, [
item.Name ?? null,
item.ItemType,
item.FolderId ?? null,
// Moving an item across a folder boundary moves it across a manifest boundary: re-stamp it.
item.FolderId ?? null,
- this.activeManifestId(),
+ manifestId,
logoId,
currentDateTime,
ref.Id,
// The row is addressed by the manifest it is in *now*; the SET above may move it.
ref.ManifestId
- ]);
+ ]));
}
}
// 3. Track history for fields that have EnableHistory=true before updating
- await this.trackFieldHistory(ref.Id, ref.ManifestId, item.Fields, currentDateTime);
+ await this.run(this.trackFieldHistory(ref.Id, ref.ManifestId, item.Fields, manifestId, currentDateTime));
// 4. Update field values
- this.updateFieldValues(item, ref.ManifestId, currentDateTime);
+ await this.run(this.updateFieldValues(item, ref.ManifestId, manifestId, currentDateTime));
// 5. Handle TOTP codes
- this.handleTotpCodes(ref.Id, ref.ManifestId, totpCodes, originalTotpCodeIds, currentDateTime);
+ await this.run(this.handleTotpCodes(ref.Id, ref.ManifestId, totpCodes, originalTotpCodeIds, manifestId, currentDateTime));
// 6. Handle attachments
- this.handleAttachments(ref.Id, ref.ManifestId, attachments, originalAttachmentIds, currentDateTime);
+ await this.run(this.handleAttachments(ref.Id, ref.ManifestId, attachments, originalAttachmentIds, manifestId, currentDateTime));
return 1;
});
@@ -541,16 +516,11 @@ export class ItemRepository extends BaseRepository {
public async trash(itemId: string, manifestId?: string): Promise<number> {
return this.withTransaction(async () => {
const currentDateTime = this.now();
- const ref = this.resolveItemRef(itemId, manifestId);
+ const ref = await this.run(this.resolveItemRef(itemId, manifestId));
if (!ref) {
return 0;
}
- return this.client.executeUpdate(ItemQueries.TRASH_ITEM, [
- currentDateTime,
- currentDateTime,
- ref.Id,
- ref.ManifestId
- ]);
+ return this.run(this.execute(ItemQueries.TRASH_ITEM, [currentDateTime, currentDateTime, ref.Id, ref.ManifestId]));
});
}
@@ -563,15 +533,11 @@ export class ItemRepository extends BaseRepository {
public async restore(itemId: string, manifestId?: string): Promise<number> {
return this.withTransaction(async () => {
const currentDateTime = this.now();
- const ref = this.resolveItemRef(itemId, manifestId);
+ const ref = await this.run(this.resolveItemRef(itemId, manifestId));
if (!ref) {
return 0;
}
- return this.client.executeUpdate(ItemQueries.RESTORE_ITEM, [
- currentDateTime,
- ref.Id,
- ref.ManifestId
- ]);
+ return this.run(this.execute(ItemQueries.RESTORE_ITEM, [currentDateTime, ref.Id, ref.ManifestId]));
});
}
@@ -585,16 +551,11 @@ export class ItemRepository extends BaseRepository {
public async archive(itemId: string, manifestId?: string): Promise<number> {
return this.withTransaction(async () => {
const currentDateTime = this.now();
- const ref = this.resolveItemRef(itemId, manifestId);
+ const ref = await this.run(this.resolveItemRef(itemId, manifestId));
if (!ref) {
return 0;
}
- return this.client.executeUpdate(ItemQueries.ARCHIVE_ITEM, [
- currentDateTime,
- currentDateTime,
- ref.Id,
- ref.ManifestId
- ]);
+ return this.run(this.execute(ItemQueries.ARCHIVE_ITEM, [currentDateTime, currentDateTime, ref.Id, ref.ManifestId]));
});
}
@@ -607,15 +568,11 @@ export class ItemRepository extends BaseRepository {
public async unarchive(itemId: string, manifestId?: string): Promise<number> {
return this.withTransaction(async () => {
const currentDateTime = this.now();
- const ref = this.resolveItemRef(itemId, manifestId);
+ const ref = await this.run(this.resolveItemRef(itemId, manifestId));
if (!ref) {
return 0;
}
- return this.client.executeUpdate(ItemQueries.UNARCHIVE_ITEM, [
- currentDateTime,
- ref.Id,
- ref.ManifestId
- ]);
+ return this.run(this.execute(ItemQueries.UNARCHIVE_ITEM, [currentDateTime, ref.Id, ref.ManifestId]));
});
}
@@ -628,22 +585,18 @@ export class ItemRepository extends BaseRepository {
public async permanentlyDelete(itemId: string, manifestId?: string): Promise<number> {
return this.withTransaction(async () => {
const currentDateTime = this.now();
- const ref = this.resolveItemRef(itemId, manifestId);
+ const ref = await this.run(this.resolveItemRef(itemId, manifestId));
if (!ref) {
return 0;
}
// Hard delete all related entities within this item's manifest.
for (const table of ['FieldValues', 'FieldHistories', 'Passkeys', 'TotpCodes', 'Attachments', 'ItemTags']) {
- this.hardDeleteByScopedForeignKey(table, 'ItemId', ref.Id, ref.ManifestId);
+ await this.run(this.hardDeleteByScopedForeignKey(table, 'ItemId', ref.Id, ref.ManifestId));
}
// Convert item to tombstone.
- return this.client.executeUpdate(ItemQueries.TOMBSTONE_ITEM, [
- currentDateTime,
- ref.Id,
- ref.ManifestId
- ]);
+ return this.run(this.execute(ItemQueries.TOMBSTONE_ITEM, [currentDateTime, ref.Id, ref.ManifestId]));
});
}
@@ -651,7 +604,7 @@ export class ItemRepository extends BaseRepository {
* Get all items in "Recently Deleted".
* @returns Array of trashed Item objects with DeletedAt
*/
- public getRecentlyDeleted(): ItemWithDeletedAt[] {
+ public *getRecentlyDeleted(): DbOp<ItemWithDeletedAt[]> {
let itemRows: (ItemRow & { DeletedAt: string })[];
try {
const query = `
@@ -673,7 +626,7 @@ export class ItemRepository extends BaseRepository {
WHERE i.IsDeleted = 0 AND i.DeletedAt IS NOT NULL
ORDER BY i.DeletedAt DESC`;
- itemRows = this.client.executeQuery(query);
+ itemRows = yield* this.query<ItemRow & { DeletedAt: string }>(query);
} catch (error) {
if (error instanceof Error && error.message.includes('no such table')) {
return [];
@@ -688,14 +641,11 @@ export class ItemRepository extends BaseRepository {
const itemRefs = itemRows.map(row => ({ Id: row.Id, ManifestId: row.ManifestId }));
// Get all field values
- const fieldRows = this.client.executeQuery<FieldRow>(
- ItemQueries.getFieldValuesForItems(itemRefs.length),
- itemKeyBindings(itemRefs)
- );
+ const fieldRows = yield* this.query<FieldRow>(ItemQueries.getFieldValuesForItems(itemRefs.length), itemKeyBindings(itemRefs));
const fieldsByItem = FieldMapper.processFieldRows(fieldRows);
// Build folder paths
- const folderPaths = this.buildFolderPaths();
+ const folderPaths = yield* this.buildFolderPaths();
return itemRows.map(row => ItemMapper.mapDeletedItemRow(
row,
@@ -708,9 +658,9 @@ export class ItemRepository extends BaseRepository {
* Get count of items in "Recently Deleted".
* @returns Number of trashed items
*/
- public getRecentlyDeletedCount(): number {
+ public *getRecentlyDeletedCount(): DbOp<number> {
try {
- const result = this.client.executeQuery<{ count: number }>(ItemQueries.COUNT_RECENTLY_DELETED);
+ const result = yield* this.query<{ count: number }>(ItemQueries.COUNT_RECENTLY_DELETED);
return result[0]?.count || 0;
} catch (error) {
if (error instanceof Error && error.message.includes('no such table')) {
@@ -726,12 +676,12 @@ export class ItemRepository extends BaseRepository {
* @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);
+ public *getTotpCodesForItem(itemId: string, manifestId?: string): DbOp<TotpCode[]> {
+ const ref = yield* this.resolveItemRef(itemId, manifestId);
if (!ref) {
return [];
}
- return this.client.executeQuery<TotpCode>(TotpCodeQueries.GET_BY_ITEM_ID, [ref.Id, ref.ManifestId]);
+ return yield* this.query<TotpCode>(TotpCodeQueries.GET_BY_ITEM_ID, [ref.Id, ref.ManifestId]);
}
/**
@@ -740,12 +690,12 @@ export class ItemRepository extends BaseRepository {
* @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);
+ public *getAttachmentsForItem(itemId: string, manifestId?: string): DbOp<Attachment[]> {
+ const ref = yield* this.resolveItemRef(itemId, manifestId);
if (!ref) {
return [];
}
- return this.client.executeQuery<Attachment>(AttachmentQueries.GET_BY_ITEM_ID, [ref.Id, ref.ManifestId]);
+ return yield* this.query<Attachment>(AttachmentQueries.GET_BY_ITEM_ID, [ref.Id, ref.ManifestId]);
}
/**
@@ -755,13 +705,13 @@ export class ItemRepository extends BaseRepository {
* @param manifestId - The manifest the item belongs to, when known
* @returns Array of field history records
*/
- public getFieldHistory(itemId: string, fieldKey: string, manifestId?: string): FieldHistory[] {
- const ref = this.resolveItemRef(itemId, manifestId);
+ public *getFieldHistory(itemId: string, fieldKey: string, manifestId?: string): DbOp<FieldHistory[]> {
+ const ref = yield* this.resolveItemRef(itemId, manifestId);
if (!ref) {
return [];
}
- const results = this.client.executeQuery<{
+ const results = yield* this.query<{
Id: string;
ItemId: string;
FieldKey: string;
@@ -790,16 +740,11 @@ export class ItemRepository extends BaseRepository {
*/
public async deleteFieldHistory(historyId: string, manifestId?: string): Promise<number> {
return this.withTransaction(async () => {
- const currentDateTime = this.now();
- const scope = manifestId ?? this.resolveRowManifestId('FieldHistories', historyId);
+ const scope = manifestId ?? await this.run(this.resolveRowManifestId('FieldHistories', historyId));
if (!scope) {
return 0;
}
- return this.client.executeUpdate(FieldHistoryQueries.SOFT_DELETE, [
- currentDateTime,
- historyId,
- scope
- ]);
+ return this.run(this.execute(FieldHistoryQueries.SOFT_DELETE, [this.now(), historyId, scope]));
});
}
@@ -826,13 +771,13 @@ export class ItemRepository extends BaseRepository {
existingLogoId: string | null = null,
selection?: LogoSelection
): Promise<string | null> {
- const scope = this.manifestOfFolder(item.FolderId ?? null);
+ const scope = await this.run(this.manifestOfFolder(item.FolderId ?? null));
if (selection && selection.Kind !== LogoKinds.Favicon) {
return this.resolveSelectedLogo(selection, scope, currentDateTime);
}
- const existing = existingLogoId ? this.logoRepository.getById(existingLogoId) : null;
+ const existing = existingLogoId ? await this.run(this.logoRepository.getById(existingLogoId)) : null;
if (!selection && existing && existing.Kind !== LogoKinds.Favicon) {
return this.logoRepository.adoptIntoScope(scope, existing.Kind, existing.Source, currentDateTime);
}
@@ -911,12 +856,13 @@ export class ItemRepository extends BaseRepository {
* Insert field values for a new item.
* Also creates history records for fields with EnableHistory=true.
*/
- private insertFieldValues(
+ private *insertFieldValues(
itemId: string,
fields: ItemField[],
itemType: string,
+ writeManifestId: string,
currentDateTime: string
- ): void {
+ ): DbOp<void> {
for (const field of fields) {
// Skip empty system fields, but always persist custom fields (even if empty)
const isEmpty = !field.Value || (typeof field.Value === 'string' && field.Value.trim() === '');
@@ -928,7 +874,7 @@ export class ItemRepository extends BaseRepository {
// For custom fields, create or get FieldDefinition
if (field.IsCustomField) {
- fieldDefinitionId = this.ensureFieldDefinition(field, itemId, itemType, currentDateTime);
+ fieldDefinitionId = yield* this.ensureFieldDefinition(field, itemId, itemType, writeManifestId, currentDateTime);
}
// Handle multi-value fields
@@ -941,11 +887,11 @@ export class ItemRepository extends BaseRepository {
: filteredValues;
for (const value of valuesToInsert) {
- this.client.executeUpdate(FieldValueQueries.INSERT, [
+ yield* this.execute(FieldValueQueries.INSERT, [
this.generateId(),
itemId,
itemId,
- this.activeManifestId(),
+ writeManifestId,
fieldDefinitionId,
field.IsCustomField ? null : field.FieldKey,
value,
@@ -958,17 +904,14 @@ export class ItemRepository extends BaseRepository {
// Create history record for fields with EnableHistory=true
if (field.EnableHistory && filteredValues.length > 0) {
- const historyId = this.generateId();
- const valueSnapshot = JSON.stringify(filteredValues);
-
- this.client.executeUpdate(FieldHistoryQueries.INSERT, [
- historyId,
+ yield* this.execute(FieldHistoryQueries.INSERT, [
+ this.generateId(),
itemId,
itemId,
- this.activeManifestId(),
+ writeManifestId,
null,
field.FieldKey,
- valueSnapshot,
+ JSON.stringify(filteredValues),
currentDateTime,
currentDateTime,
currentDateTime,
@@ -981,22 +924,20 @@ export class ItemRepository extends BaseRepository {
/**
* Ensure a field definition exists for a custom field.
*/
- private ensureFieldDefinition(
+ private *ensureFieldDefinition(
field: ItemField,
itemId: string,
itemType: string,
+ writeManifestId: string,
currentDateTime: string
- ): string {
- const existingDef = this.client.executeQuery<{ Id: string }>(
- FieldDefinitionQueries.EXISTS,
- [field.FieldKey, itemId, this.activeManifestId()]
- );
+ ): DbOp<string> {
+ const existingDef = yield* this.query<{ Id: string }>(FieldDefinitionQueries.EXISTS, [field.FieldKey, itemId, writeManifestId]);
if (existingDef.length === 0) {
- this.client.executeUpdate(FieldDefinitionQueries.INSERT, [
+ yield* this.execute(FieldDefinitionQueries.INSERT, [
field.FieldKey,
itemId,
- this.activeManifestId(),
+ writeManifestId,
field.FieldType,
field.Label,
0, // IsMultiValue
@@ -1016,9 +957,9 @@ export class ItemRepository extends BaseRepository {
/**
* Update field values for an existing item.
*/
- private updateFieldValues(item: DraftItem, manifestId: string, currentDateTime: string): void {
+ private *updateFieldValues(item: DraftItem, manifestId: string, writeManifestId: string, currentDateTime: string): DbOp<void> {
// Get existing FieldValues
- const existingFieldValues = this.client.executeQuery<{
+ const existingFieldValues = yield* this.query<{
Id: string;
FieldKey: string | null;
FieldDefinitionId: string | null;
@@ -1051,7 +992,7 @@ export class ItemRepository extends BaseRepository {
let fieldDefinitionId = null;
if (field.IsCustomField) {
- fieldDefinitionId = this.ensureOrUpdateFieldDefinition(field, item.Id, item.ItemType, currentDateTime);
+ fieldDefinitionId = yield* this.ensureOrUpdateFieldDefinition(field, item.Id, item.ItemType, writeManifestId, currentDateTime);
}
const values = Array.isArray(field.Value) ? field.Value : [field.Value];
@@ -1073,20 +1014,14 @@ export class ItemRepository extends BaseRepository {
processedIds.add(existing.Id);
const newWeight = field.DisplayOrder ?? 0;
if (existing.Value !== value || existing.Weight !== newWeight) {
- this.client.executeUpdate(FieldValueQueries.UPDATE, [
- value,
- newWeight,
- currentDateTime,
- existing.Id,
- manifestId
- ]);
+ yield* this.execute(FieldValueQueries.UPDATE, [value, newWeight, currentDateTime, existing.Id, manifestId]);
}
} else {
- this.client.executeUpdate(FieldValueQueries.INSERT, [
+ yield* this.execute(FieldValueQueries.INSERT, [
this.generateId(),
item.Id,
item.Id,
- this.activeManifestId(),
+ writeManifestId,
fieldDefinitionId,
field.IsCustomField ? null : field.FieldKey,
value,
@@ -1103,7 +1038,7 @@ export class ItemRepository extends BaseRepository {
// Soft-delete any FieldValues that were not processed
for (const fv of existingFieldValues) {
if (!processedIds.has(fv.Id)) {
- this.client.executeUpdate(FieldValueQueries.SOFT_DELETE, [currentDateTime, fv.Id, manifestId]);
+ yield* this.execute(FieldValueQueries.SOFT_DELETE, [currentDateTime, fv.Id, manifestId]);
}
}
}
@@ -1111,22 +1046,20 @@ export class ItemRepository extends BaseRepository {
/**
* Ensure a field definition exists and is up-to-date.
*/
- private ensureOrUpdateFieldDefinition(
+ private *ensureOrUpdateFieldDefinition(
field: ItemField,
itemId: string,
itemType: string,
+ writeManifestId: string,
currentDateTime: string
- ): string {
- const existingDef = this.client.executeQuery<{ Id: string }>(
- FieldDefinitionQueries.EXISTS_ACTIVE,
- [field.FieldKey, itemId, this.activeManifestId()]
- );
+ ): DbOp<string> {
+ const existingDef = yield* this.query<{ Id: string }>(FieldDefinitionQueries.EXISTS_ACTIVE, [field.FieldKey, itemId, writeManifestId]);
if (existingDef.length === 0) {
- this.client.executeUpdate(FieldDefinitionQueries.INSERT, [
+ yield* this.execute(FieldDefinitionQueries.INSERT, [
field.FieldKey,
itemId,
- this.activeManifestId(),
+ writeManifestId,
field.FieldType,
field.Label,
0,
@@ -1139,7 +1072,7 @@ export class ItemRepository extends BaseRepository {
0
]);
} else {
- this.client.executeUpdate(FieldDefinitionQueries.UPDATE, [
+ yield* this.execute(FieldDefinitionQueries.UPDATE, [
field.Label,
field.FieldType,
field.IsHidden ? 1 : 0,
@@ -1147,7 +1080,7 @@ export class ItemRepository extends BaseRepository {
currentDateTime,
field.FieldKey,
itemId,
- this.activeManifestId()
+ writeManifestId
]);
}
@@ -1162,16 +1095,14 @@ export class ItemRepository extends BaseRepository {
* it was first set). This ensures that during merge conflicts, no values are ever
* lost since history records sync independently via LWW and each has a unique ID.
*/
- private async trackFieldHistory(
+ private *trackFieldHistory(
itemId: string,
manifestId: string,
newFields: ItemField[],
+ writeManifestId: string,
currentDateTime: string
- ): Promise<void> {
- const existingFields = this.client.executeQuery<{ FieldKey: string; Value: string }>(
- FieldValueQueries.GET_FOR_HISTORY,
- [itemId, manifestId]
- );
+ ): DbOp<void> {
+ const existingFields = yield* this.query<{ FieldKey: string; Value: string }>(FieldValueQueries.GET_FOR_HISTORY, [itemId, manifestId]);
// Create a map of existing values by FieldKey
const existingValuesMap: { [key: string]: string[] } = {};
@@ -1203,24 +1134,21 @@ export class ItemRepository extends BaseRepository {
// Save new values to history when they change (ensures they survive merge conflicts)
if (valuesChanged && filteredNewValues.length > 0) {
- const historyId = this.generateId();
- const valueSnapshot = JSON.stringify(filteredNewValues);
-
- this.client.executeUpdate(FieldHistoryQueries.INSERT, [
- historyId,
+ yield* this.execute(FieldHistoryQueries.INSERT, [
+ this.generateId(),
itemId,
itemId,
- this.activeManifestId(),
+ writeManifestId,
null,
newField.FieldKey,
- valueSnapshot,
+ JSON.stringify(filteredNewValues),
currentDateTime,
currentDateTime,
currentDateTime,
0
]);
- await this.pruneFieldHistory(itemId, manifestId, newField.FieldKey, currentDateTime);
+ yield* this.pruneFieldHistory(itemId, manifestId, newField.FieldKey, currentDateTime);
}
}
}
@@ -1228,26 +1156,19 @@ export class ItemRepository extends BaseRepository {
/**
* Prune old field history records.
*/
- private async pruneFieldHistory(
+ private *pruneFieldHistory(
itemId: string,
manifestId: string,
fieldKey: string,
currentDateTime: string
- ): Promise<void> {
- const matchingHistory = this.client.executeQuery<{ Id: string; ChangedAt: string }>(
- FieldHistoryQueries.GET_FOR_PRUNING,
- [itemId, manifestId, fieldKey]
- );
+ ): DbOp<void> {
+ const matchingHistory = yield* this.query<{ Id: string; ChangedAt: string }>(FieldHistoryQueries.GET_FOR_PRUNING, [itemId, manifestId, fieldKey]);
if (matchingHistory.length > MAX_FIELD_HISTORY_RECORDS) {
- const recordsToDelete = matchingHistory.slice(MAX_FIELD_HISTORY_RECORDS);
- const idsToDelete = recordsToDelete.map(r => r.Id);
+ const idsToDelete = matchingHistory.slice(MAX_FIELD_HISTORY_RECORDS).map(r => r.Id);
if (idsToDelete.length > 0) {
- this.client.executeUpdate(
- FieldHistoryQueries.softDeleteOld(idsToDelete.length),
- [currentDateTime, manifestId, ...idsToDelete]
- );
+ yield* this.execute(FieldHistoryQueries.softDeleteOld(idsToDelete.length), [currentDateTime, manifestId, ...idsToDelete]);
}
}
}
@@ -1255,40 +1176,38 @@ export class ItemRepository extends BaseRepository {
/**
* Insert TOTP codes for a new item.
*/
- private insertTotpCodes(itemId: string, totpCodes: TotpCode[], currentDateTime: string): void {
+ private *insertTotpCodes(itemId: string, totpCodes: TotpCode[], writeManifestId: string, currentDateTime: string): DbOp<void> {
for (const totpCode of totpCodes) {
- this.client.executeUpdate(
- TotpCodeQueries.INSERT,
- [
- totpCode.Id || this.generateId(),
- totpCode.Name,
- totpCode.SecretKey,
- normalizeTotpAlgorithm(totpCode.Algorithm),
- normalizeTotpDigits(totpCode.Digits),
- normalizeTotpPeriod(totpCode.Period),
- itemId,
- itemId,
- this.activeManifestId(),
- currentDateTime,
- currentDateTime,
- 0
- ]
- );
+ yield* this.execute(TotpCodeQueries.INSERT, [
+ totpCode.Id || this.generateId(),
+ totpCode.Name,
+ totpCode.SecretKey,
+ normalizeTotpAlgorithm(totpCode.Algorithm),
+ normalizeTotpDigits(totpCode.Digits),
+ normalizeTotpPeriod(totpCode.Period),
+ itemId,
+ itemId,
+ writeManifestId,
+ currentDateTime,
+ currentDateTime,
+ 0
+ ]);
}
}
/**
* Handle TOTP code updates.
*/
- private handleTotpCodes(
+ private *handleTotpCodes(
itemId: string,
manifestId: string,
totpCodes: TotpCode[],
originalIds: string[],
+ writeManifestId: string,
currentDateTime: string
- ): void {
+ ): DbOp<void> {
// Fetch existing TOTP codes to compare values
- const existingTotpCodes = this.client.executeQuery<TotpCode>(TotpCodeQueries.GET_BY_ITEM_ID, [itemId, manifestId]);
+ const existingTotpCodes = yield* this.query<TotpCode>(TotpCodeQueries.GET_BY_ITEM_ID, [itemId, manifestId]);
const existingByIdMap = new Map(existingTotpCodes.map(tc => [tc.Id, tc]));
@@ -1297,10 +1216,7 @@ export class ItemRepository extends BaseRepository {
if (totpCode.IsDeleted) {
if (wasOriginal) {
- this.client.executeUpdate(
- TotpCodeQueries.SOFT_DELETE,
- [currentDateTime, totpCode.Id, manifestId]
- );
+ yield* this.execute(TotpCodeQueries.SOFT_DELETE, [currentDateTime, totpCode.Id, manifestId]);
}
} else if (wasOriginal) {
// Only update if values actually changed
@@ -1312,29 +1228,23 @@ export class ItemRepository extends BaseRepository {
existing.Algorithm !== algorithm || existing.Digits !== digits || existing.Period !== period);
if (changed) {
- this.client.executeUpdate(
- TotpCodeQueries.UPDATE,
- [totpCode.Name, totpCode.SecretKey, algorithm, digits, period, currentDateTime, totpCode.Id, manifestId]
- );
+ yield* this.execute(TotpCodeQueries.UPDATE, [totpCode.Name, totpCode.SecretKey, algorithm, digits, period, currentDateTime, totpCode.Id, manifestId]);
}
} else {
- this.client.executeUpdate(
- TotpCodeQueries.INSERT,
- [
- totpCode.Id || this.generateId(),
- totpCode.Name,
- totpCode.SecretKey,
- normalizeTotpAlgorithm(totpCode.Algorithm),
- normalizeTotpDigits(totpCode.Digits),
- normalizeTotpPeriod(totpCode.Period),
- itemId,
- itemId,
- this.activeManifestId(),
- currentDateTime,
- currentDateTime,
- 0
- ]
- );
+ yield* this.execute(TotpCodeQueries.INSERT, [
+ totpCode.Id || this.generateId(),
+ totpCode.Name,
+ totpCode.SecretKey,
+ normalizeTotpAlgorithm(totpCode.Algorithm),
+ normalizeTotpDigits(totpCode.Digits),
+ normalizeTotpPeriod(totpCode.Period),
+ itemId,
+ itemId,
+ writeManifestId,
+ currentDateTime,
+ currentDateTime,
+ 0
+ ]);
}
}
}
@@ -1342,49 +1252,42 @@ export class ItemRepository extends BaseRepository {
/**
* Insert attachments for a new item.
*/
- private insertAttachments(itemId: string, attachments: Attachment[], currentDateTime: string): void {
+ private *insertAttachments(itemId: string, attachments: Attachment[], writeManifestId: string, currentDateTime: string): DbOp<void> {
for (const attachment of attachments) {
- const blobData = attachment.Blob instanceof Uint8Array
- ? attachment.Blob
- : new Uint8Array(attachment.Blob);
+ const blobData = attachment.Blob instanceof Uint8Array ? attachment.Blob : new Uint8Array(attachment.Blob ?? []);
- this.client.executeUpdate(
- AttachmentQueries.INSERT,
- [
- attachment.Id || this.generateId(),
- attachment.Filename,
- blobData,
- itemId,
- itemId,
- this.activeManifestId(),
- currentDateTime,
- currentDateTime,
- 0
- ]
- );
+ yield* this.execute(AttachmentQueries.INSERT, [
+ attachment.Id || this.generateId(),
+ attachment.Filename,
+ blobData,
+ itemId,
+ itemId,
+ writeManifestId,
+ currentDateTime,
+ currentDateTime,
+ 0
+ ]);
}
}
/**
* Handle attachment updates.
*/
- private handleAttachments(
+ private *handleAttachments(
itemId: string,
manifestId: string,
attachments: Attachment[],
originalIds: string[],
+ writeManifestId: string,
currentDateTime: string
- ): void {
+ ): DbOp<void> {
// Track which original attachments are still present
const currentAttachmentIds = new Set(attachments.map(a => a.Id));
// Soft-delete any original attachments that are no longer in the list
for (const originalId of originalIds) {
if (!currentAttachmentIds.has(originalId)) {
- this.client.executeUpdate(
- AttachmentQueries.SOFT_DELETE,
- [currentDateTime, originalId, manifestId]
- );
+ yield* this.execute(AttachmentQueries.SOFT_DELETE, [currentDateTime, originalId, manifestId]);
}
}
@@ -1394,30 +1297,22 @@ export class ItemRepository extends BaseRepository {
if (attachment.IsDeleted) {
if (wasOriginal) {
- this.client.executeUpdate(
- AttachmentQueries.SOFT_DELETE,
- [currentDateTime, attachment.Id, manifestId]
- );
+ yield* this.execute(AttachmentQueries.SOFT_DELETE, [currentDateTime, attachment.Id, manifestId]);
}
} else if (!wasOriginal) {
- const blobData = attachment.Blob instanceof Uint8Array
- ? attachment.Blob
- : new Uint8Array(attachment.Blob);
-
- this.client.executeUpdate(
- AttachmentQueries.INSERT,
- [
- attachment.Id || this.generateId(),
- attachment.Filename,
- blobData,
- itemId,
- itemId,
- this.activeManifestId(),
- currentDateTime,
- currentDateTime,
- 0
- ]
- );
+ const blobData = attachment.Blob instanceof Uint8Array ? attachment.Blob : new Uint8Array(attachment.Blob ?? []);
+
+ yield* this.execute(AttachmentQueries.INSERT, [
+ attachment.Id || this.generateId(),
+ attachment.Filename,
+ blobData,
+ itemId,
+ itemId,
+ writeManifestId,
+ currentDateTime,
+ currentDateTime,
+ 0
+ ]);
}
}
}
diff --git a/core/client/src/database/repositories/ItemStatsRepository.ts b/core/client/src/database/repositories/ItemStatsRepository.ts
index 844ddf82b..2319c77d4 100644
--- a/core/client/src/database/repositories/ItemStatsRepository.ts
+++ b/core/client/src/database/repositories/ItemStatsRepository.ts
@@ -1,6 +1,8 @@
import { BaseRepository } from '../BaseRepository';
import { ItemStatsQueries } from '../queries/ItemStatsQueries';
+import type { DbOp } from '../DbOp';
+
/**
* The actions whose use of an item is recorded. Each maps to its own timestamp + counter pair alongside
* the aggregate `LastUsedAt` / `UseCount`, so a report can distinguish "filled into a page" from
@@ -39,8 +41,8 @@ export class ItemStatsRepository extends BaseRepository {
* @param action - What the user did with it
* @returns True when a use was recorded, false when no such item exists
*/
- public recordUsage(itemId: string, action: ItemUsageAction): boolean {
- const manifestId = this.itemManifestId(itemId);
+ public *recordUsage(itemId: string, action: ItemUsageAction): DbOp<boolean> {
+ const manifestId = yield* this.itemManifestId(itemId);
if (!manifestId) {
return false;
}
@@ -48,8 +50,8 @@ export class ItemStatsRepository extends BaseRepository {
const now = this.now();
const columns = ACTION_COLUMNS[action];
- this.client.executeUpdate(ItemStatsQueries.INSERT_ROW, [manifestId, itemId, now, now]);
- this.client.executeUpdate(ItemStatsQueries.forAction(columns.last, columns.count), [now, now, now, manifestId, itemId]);
+ yield* this.execute(ItemStatsQueries.INSERT_ROW, [manifestId, itemId, now, now]);
+ yield* this.execute(ItemStatsQueries.forAction(columns.last, columns.count), [now, now, now, manifestId, itemId]);
return true;
}
@@ -58,20 +60,20 @@ export class ItemStatsRepository extends BaseRepository {
* @param itemId - The item to read
* @returns The statistics, or null when the item has never been used
*/
- public getForItem(itemId: string): ItemStats | null {
- const manifestId = this.itemManifestId(itemId);
+ public *getForItem(itemId: string): DbOp<ItemStats | null> {
+ const manifestId = yield* this.itemManifestId(itemId);
if (!manifestId) {
return null;
}
- return this.client.executeQuery<ItemStats>(ItemStatsQueries.GET_FOR_ITEM, [manifestId, itemId])[0] ?? null;
+ return (yield* this.query<ItemStats>(ItemStatsQueries.GET_FOR_ITEM, [manifestId, itemId]))[0] ?? null;
}
/**
* Get the last-used timestamp of every item that has one, newest first.
* @returns One entry per used item
*/
- public getLastUsed(): { ManifestId: string; Id: string; LastUsedAt: string; UseCount: number }[] {
- return this.client.executeQuery(ItemStatsQueries.GET_LAST_USED_ALL);
+ public *getLastUsed(): DbOp<{ ManifestId: string; Id: string; LastUsedAt: string; UseCount: number }[]> {
+ return yield* this.query<{ ManifestId: string; Id: string; LastUsedAt: string; UseCount: number }>(ItemStatsQueries.GET_LAST_USED_ALL);
}
/**
@@ -79,7 +81,7 @@ export class ItemStatsRepository extends BaseRepository {
* @param itemId - The item id
* @returns The manifest id, or null when no such item exists
*/
- private itemManifestId(itemId: string): string | null {
- return this.client.executeQuery<{ ManifestId: string }>(ItemStatsQueries.GET_ITEM_MANIFEST, [itemId])[0]?.ManifestId ?? null;
+ private *itemManifestId(itemId: string): DbOp<string | null> {
+ return (yield* this.query<{ ManifestId: string }>(ItemStatsQueries.GET_ITEM_MANIFEST, [itemId]))[0]?.ManifestId ?? null;
}
}
diff --git a/core/client/src/database/repositories/LogoRepository.ts b/core/client/src/database/repositories/LogoRepository.ts
index 9d6f433cd..78ae5c24a 100644
--- a/core/client/src/database/repositories/LogoRepository.ts
+++ b/core/client/src/database/repositories/LogoRepository.ts
@@ -4,6 +4,7 @@ import { vaultCodecLogoContentHash, vaultCodecLogoIdFor } from '../../rust/RustC
import { BaseRepository } from '../BaseRepository';
import { LogoQueries } from '../queries/LogoQueries';
+import type { DbOp } from '../DbOp';
import type { ItemLogo, LogoKind } from '@aliasvault/models/vault';
/**
@@ -27,8 +28,8 @@ export class LogoRepository extends BaseRepository {
* The manifest the user's own logo library lives in: this client's own.
* @returns The manifest id, or the empty scope when it is not known yet
*/
- private ownScope(): string {
- return this.personalManifestId() ?? '';
+ private *ownScope(): DbOp<string> {
+ return (yield* this.personalManifestId()) ?? '';
}
/**
@@ -36,8 +37,8 @@ export class LogoRepository extends BaseRepository {
* @param source The normalized source domain (e.g., 'github.com')
* @returns True if any manifest holds a favicon for this domain
*/
- public hasFaviconForSource(source: string): boolean {
- const rows = this.client.executeQuery<{ Id: string }>(LogoQueries.FIND_ANY_ID_FOR_KEY, [LogoKinds.Favicon, source]);
+ public *hasFaviconForSource(source: string): DbOp<boolean> {
+ const rows = yield* this.query<{ Id: string }>(LogoQueries.FIND_ANY_ID_FOR_KEY, [LogoKinds.Favicon, source]);
return rows.length > 0;
}
@@ -46,8 +47,8 @@ export class LogoRepository extends BaseRepository {
* @param source The normalized source domain (e.g., 'github.com')
* @returns The favicon bytes, or null when no manifest holds one for this domain
*/
- public getFaviconData(source: string): Uint8Array | null {
- const row = this.client.executeQuery<{ FileData: Uint8Array | null }>(LogoQueries.GET_BEST_FOR_KEY, [LogoKinds.Favicon, source])[0];
+ public *getFaviconData(source: string): DbOp<Uint8Array | null> {
+ const row = (yield* this.query<{ FileData: Uint8Array | null }>(LogoQueries.GET_BEST_FOR_KEY, [LogoKinds.Favicon, source]))[0];
return row?.FileData && row.FileData.length > 0 ? new Uint8Array(row.FileData) : null;
}
@@ -58,8 +59,8 @@ export class LogoRepository extends BaseRepository {
* @param source The natural key within that kind
* @returns The logo id if found, null otherwise
*/
- public getIdForKey(manifestId: string, kind: LogoKind, source: string): string | null {
- const rows = this.client.executeQuery<{ Id: string }>(LogoQueries.GET_ID_FOR_KEY, [manifestId, kind, source]);
+ public *getIdForKey(manifestId: string, kind: LogoKind, source: string): DbOp<string | null> {
+ const rows = yield* this.query<{ Id: string }>(LogoQueries.GET_ID_FOR_KEY, [manifestId, kind, source]);
return rows.length > 0 ? rows[0].Id : null;
}
@@ -72,15 +73,15 @@ export class LogoRepository extends BaseRepository {
* @returns The logo id inside this manifest, or null when the vault holds no such logo at all
*/
public async adoptIntoScope(manifestId: string, kind: LogoKind, source: string, currentDateTime: string): Promise<string | null> {
- const inScope = this.getIdForKey(manifestId, kind, source);
+ const inScope = await this.run(this.getIdForKey(manifestId, kind, source));
if (inScope) {
return inScope;
}
- const origin = this.client.executeQuery<{ FileData: Uint8Array | null; MimeType: string | null; Name: string | null }>(
+ const origin = (await this.run(this.query<{ FileData: Uint8Array | null; MimeType: string | null; Name: string | null }>(
LogoQueries.GET_BEST_FOR_KEY,
[kind, source]
- )[0];
+ )))[0];
if (!origin) {
return null;
}
@@ -94,8 +95,8 @@ export class LogoRepository extends BaseRepository {
* @param logoId The logo id to look up
* @returns The logo, or null
*/
- public getById(logoId: string): ItemLogo | null {
- const rows = this.client.executeQuery<{ Id: string; Kind: LogoKind; Source: string; Name: string | null }>(LogoQueries.GET_BY_ID, [logoId]);
+ public *getById(logoId: string): DbOp<ItemLogo | null> {
+ const rows = yield* this.query<{ Id: string; Kind: LogoKind; Source: string; Name: string | null }>(LogoQueries.GET_BY_ID, [logoId]);
return rows.length > 0 ? rows[0] : null;
}
@@ -105,15 +106,15 @@ export class LogoRepository extends BaseRepository {
* @returns The number of items repointed
*/
public async reconcileItemLogoScopes(currentDateTime: string): Promise<number> {
- const foreign = this.client.executeQuery<{ Id: string; ManifestId: string; Kind: LogoKind; Source: string }>(
+ const foreign = await this.run(this.query<{ Id: string; ManifestId: string; Kind: LogoKind; Source: string }>(
LogoQueries.FIND_ITEMS_WITH_FOREIGN_LOGO
- );
+ ));
let repointed = 0;
for (const item of foreign) {
const logoId = await this.adoptIntoScope(item.ManifestId, item.Kind, item.Source, currentDateTime);
if (logoId) {
- repointed += this.client.executeUpdate(LogoQueries.REPOINT_ITEM_LOGO, [logoId, item.Id, item.ManifestId]);
+ repointed += await this.run(this.execute(LogoQueries.REPOINT_ITEM_LOGO, [logoId, item.Id, item.ManifestId]));
}
}
return repointed;
@@ -134,7 +135,7 @@ export class LogoRepository extends BaseRepository {
*/
public async getOrCreate(manifestId: string, kind: LogoKind, source: string, fileData: Uint8Array | null, currentDateTime: string, options: { mimeType?: string | null; name?: string | null } = {}): Promise<string> {
const logoId = await vaultCodecLogoIdFor(manifestId, kind, source);
- this.client.executeUpdate(LogoQueries.UPSERT, [
+ await this.run(this.execute(LogoQueries.UPSERT, [
logoId,
kind,
source,
@@ -144,7 +145,7 @@ export class LogoRepository extends BaseRepository {
options.name ?? null,
currentDateTime,
currentDateTime
- ]);
+ ]));
return logoId;
}
@@ -166,11 +167,9 @@ export class LogoRepository extends BaseRepository {
* The user's own library of uploaded logos, newest first.
* @returns The uploaded logos, with their image data
*/
- public listCustom(): CustomLogoEntry[] {
- const rows = this.client.executeQuery<{ Id: string; Kind: LogoKind; Source: string; Name: string | null; FileData: Uint8Array | null }>(
- LogoQueries.LIST_CUSTOM,
- [this.ownScope()]
- );
+ public *listCustom(): DbOp<CustomLogoEntry[]> {
+ const scope = yield* this.ownScope();
+ const rows = yield* this.query<{ Id: string; Kind: LogoKind; Source: string; Name: string | null; FileData: Uint8Array | null }>(LogoQueries.LIST_CUSTOM, [scope]);
return rows.map(row => ({ ...row, FileData: row.FileData ? new Uint8Array(row.FileData) : null }));
}
@@ -180,8 +179,8 @@ export class LogoRepository extends BaseRepository {
* @param currentDateTime The current date/time string for timestamps
* @returns The number of rows modified
*/
- public deleteById(logoId: string, currentDateTime: string): number {
- return this.client.executeUpdate(LogoQueries.SOFT_DELETE, [currentDateTime, logoId]);
+ public *deleteById(logoId: string, currentDateTime: string): DbOp<number> {
+ return yield* this.execute(LogoQueries.SOFT_DELETE, [currentDateTime, logoId]);
}
/**
diff --git a/core/client/src/database/repositories/PasskeyRepository.ts b/core/client/src/database/repositories/PasskeyRepository.ts
index 6c892ebd7..529f24c56 100644
--- a/core/client/src/database/repositories/PasskeyRepository.ts
+++ b/core/client/src/database/repositories/PasskeyRepository.ts
@@ -2,6 +2,7 @@ import { BaseRepository } from '../BaseRepository';
import { PasskeyMapper, type PasskeyRow, type PasskeyWithItemRow, type PasskeyWithItem } from '../mappers/PasskeyMapper';
import { PasskeyQueries } from '../queries/PasskeyQueries';
+import type { DbOp } from '../DbOp';
import type { Passkey } from '@aliasvault/models/vault';
/**
@@ -13,11 +14,8 @@ export class PasskeyRepository extends BaseRepository {
* @param rpId - The relying party identifier (domain)
* @returns Array of passkey objects with credential info
*/
- public getByRpId(rpId: string): PasskeyWithItem[] {
- const results = this.client.executeQuery<PasskeyWithItemRow>(
- PasskeyQueries.GET_BY_RP_ID,
- [rpId]
- );
+ public *getByRpId(rpId: string): DbOp<PasskeyWithItem[]> {
+ const results = yield* this.query<PasskeyWithItemRow>(PasskeyQueries.GET_BY_RP_ID, [rpId]);
return PasskeyMapper.mapRowsWithItem(results);
}
@@ -26,11 +24,8 @@ export class PasskeyRepository extends BaseRepository {
* @param passkeyId - The passkey ID
* @returns The passkey object or null if not found
*/
- public getById(passkeyId: string): PasskeyWithItem | null {
- const results = this.client.executeQuery<PasskeyWithItemRow>(
- PasskeyQueries.GET_BY_ID_WITH_ITEM,
- [passkeyId]
- );
+ public *getById(passkeyId: string): DbOp<PasskeyWithItem | null> {
+ const results = yield* this.query<PasskeyWithItemRow>(PasskeyQueries.GET_BY_ID_WITH_ITEM, [passkeyId]);
if (results.length === 0) {
return null;
@@ -45,16 +40,13 @@ export class PasskeyRepository extends BaseRepository {
* @param manifestId - The manifest the item belongs to, when known
* @returns Array of passkey objects
*/
- public getByItemId(itemId: string, manifestId?: string): Passkey[] {
- const scope = manifestId ?? this.resolveRowManifestId('Items', itemId);
+ public *getByItemId(itemId: string, manifestId?: string): DbOp<Passkey[]> {
+ const scope = manifestId ?? (yield* this.resolveRowManifestId('Items', itemId));
if (!scope) {
return [];
}
- const results = this.client.executeQuery<PasskeyRow>(
- PasskeyQueries.GET_BY_ITEM_ID,
- [itemId, scope]
- );
+ const results = yield* this.query<PasskeyRow>(PasskeyQueries.GET_BY_ITEM_ID, [itemId, scope]);
return PasskeyMapper.mapRows(results);
}
@@ -85,11 +77,12 @@ export class PasskeyRepository extends BaseRepository {
: new Uint8Array(passkey.UserHandle);
}
- this.client.executeUpdate(PasskeyQueries.INSERT, [
+ const manifestId = await this.run(this.writeManifestId());
+ await this.run(this.execute(PasskeyQueries.INSERT, [
passkey.Id,
passkey.ItemId,
passkey.ItemId,
- this.activeManifestId(),
+ manifestId,
passkey.RpId,
userHandleData,
passkey.PublicKey,
@@ -100,7 +93,7 @@ export class PasskeyRepository extends BaseRepository {
currentDateTime,
currentDateTime,
0
- ]);
+ ]));
});
}
@@ -112,16 +105,11 @@ export class PasskeyRepository extends BaseRepository {
*/
public async deleteById(passkeyId: string, manifestId?: string): Promise<number> {
return this.withTransaction(async () => {
- const currentDateTime = this.now();
- const scope = manifestId ?? this.resolveRowManifestId('Passkeys', passkeyId);
+ const scope = manifestId ?? await this.run(this.resolveRowManifestId('Passkeys', passkeyId));
if (!scope) {
return 0;
}
- return this.client.executeUpdate(PasskeyQueries.SOFT_DELETE, [
- currentDateTime,
- passkeyId,
- scope
- ]);
+ return this.run(this.execute(PasskeyQueries.SOFT_DELETE, [this.now(), passkeyId, scope]));
});
}
@@ -133,16 +121,11 @@ export class PasskeyRepository extends BaseRepository {
*/
public async deleteByItemId(itemId: string, manifestId?: string): Promise<number> {
return this.withTransaction(async () => {
- const currentDateTime = this.now();
- const scope = manifestId ?? this.resolveRowManifestId('Items', itemId);
+ const scope = manifestId ?? await this.run(this.resolveRowManifestId('Items', itemId));
if (!scope) {
return 0;
}
- return this.client.executeUpdate(PasskeyQueries.SOFT_DELETE_BY_ITEM, [
- currentDateTime,
- itemId,
- scope
- ]);
+ return this.run(this.execute(PasskeyQueries.SOFT_DELETE_BY_ITEM, [this.now(), itemId, scope]));
});
}
@@ -155,17 +138,11 @@ export class PasskeyRepository extends BaseRepository {
*/
public async updateDisplayName(passkeyId: string, displayName: string, manifestId?: string): Promise<number> {
return this.withTransaction(async () => {
- const currentDateTime = this.now();
- const scope = manifestId ?? this.resolveRowManifestId('Passkeys', passkeyId);
+ const scope = manifestId ?? await this.run(this.resolveRowManifestId('Passkeys', passkeyId));
if (!scope) {
return 0;
}
- return this.client.executeUpdate(PasskeyQueries.UPDATE_DISPLAY_NAME, [
- displayName,
- currentDateTime,
- passkeyId,
- scope
- ]);
+ return this.run(this.execute(PasskeyQueries.UPDATE_DISPLAY_NAME, [displayName, this.now(), passkeyId, scope]));
});
}
}
diff --git a/core/client/src/database/repositories/SettingsRepository.ts b/core/client/src/database/repositories/SettingsRepository.ts
index 6cf37695b..fad2e5d08 100644
--- a/core/client/src/database/repositories/SettingsRepository.ts
+++ b/core/client/src/database/repositories/SettingsRepository.ts
@@ -5,7 +5,6 @@ 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';
@@ -17,7 +16,7 @@ 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<IDatabaseClient> {
+export class SettingsRepository extends BaseRepository {
/**
* Get setting from database for a given key, from the manifest this client writes into.
* @param key - The setting key
diff --git a/core/client/src/items/OtpAuthUri.ts b/core/client/src/items/OtpAuthUri.ts
new file mode 100644
index 000000000..ff6e656f3
--- /dev/null
+++ b/core/client/src/items/OtpAuthUri.ts
@@ -0,0 +1,95 @@
+import { normalizeTotpAlgorithm, normalizeTotpDigits, normalizeTotpPeriod, TOTP_DEFAULT_ALGORITHM, TOTP_DEFAULT_DIGITS, TOTP_DEFAULT_PERIOD } from '@aliasvault/models/vault';
+
+import type { TotpParameters } from './TotpUtility';
+
+/**
+ * Parsed `otpauth://totp/` URI components.
+ */
+export type OtpAuthUri = {
+ /** URL-decoded path component, typically "Issuer:account". */
+ label: string;
+ /** The label without its "Issuer:" prefix. */
+ account: string;
+ /** Base32 secret from the `secret` query parameter. */
+ secret: string;
+ /** Optional `issuer` query parameter. */
+ issuer?: string;
+ /** HMAC algorithm from the `algorithm` parameter, normalized. */
+ algorithm: string;
+ /** Code length from the `digits` parameter, normalized. */
+ digits: number;
+ /** Time step from the `period` parameter, normalized. */
+ period: number;
+};
+
+/**
+ * Parse an `otpauth://totp/` URI (https://github.com/google/google-authenticator/wiki/Key-Uri-Format). HOTP URIs are
+ * rejected, the vault only stores TOTP codes. The Base32 alphabet of the secret is not validated here; callers do that.
+ * @param uri - The URI
+ * @returns The parsed components, or null when the input is not a TOTP otpauth URI carrying a secret
+ */
+export function parseOtpAuthUri(uri: string): OtpAuthUri | null {
+ const trimmed = uri.trim();
+ const prefix = 'otpauth://totp/';
+ if (trimmed.toLowerCase().slice(0, prefix.length) !== prefix) {
+ return null;
+ }
+
+ const rest = trimmed.slice(prefix.length);
+ const queryIdx = rest.indexOf('?');
+ const labelEncoded = queryIdx >= 0 ? rest.slice(0, queryIdx) : rest;
+ const queryString = queryIdx >= 0 ? rest.slice(queryIdx + 1) : '';
+
+ let label: string;
+ try {
+ label = decodeURIComponent(labelEncoded);
+ } catch {
+ label = labelEncoded;
+ }
+
+ const params = new URLSearchParams(queryString);
+ const secret = params.get('secret');
+ if (!secret) {
+ return null;
+ }
+
+ const issuer = params.get('issuer');
+ const issuerSeparator = label.indexOf(':');
+ return {
+ label,
+ account: issuerSeparator >= 0 ? label.slice(issuerSeparator + 1).trim() : label,
+ secret,
+ ...(issuer ? { issuer } : {}),
+ algorithm: normalizeTotpAlgorithm(params.get('algorithm')),
+ digits: normalizeTotpDigits(params.get('digits')),
+ period: normalizeTotpPeriod(params.get('period')),
+ };
+}
+
+/**
+ * Serialize a TOTP code back to an `otpauth://` URI. Non-default parameters are written out so a
+ * scanned QR reproduces the same codes.
+ *
+ * @param label - URL-encoded label, typically "Issuer:account"
+ * @param secretKey - Base32 secret
+ * @param issuer - Issuer name
+ * @param parameters - Stored algorithm/digits/period
+ * @returns The otpauth:// URI
+ */
+export function buildOtpAuthUri(label: string, secretKey: string, issuer: string, parameters?: TotpParameters): string {
+ const algorithm = normalizeTotpAlgorithm(parameters?.Algorithm);
+ const digits = normalizeTotpDigits(parameters?.Digits);
+ const period = normalizeTotpPeriod(parameters?.Period);
+
+ let uri = `otpauth://totp/${label}?secret=${secretKey}&issuer=${encodeURIComponent(issuer)}`;
+ if (algorithm !== TOTP_DEFAULT_ALGORITHM) {
+ uri += `&algorithm=${algorithm}`;
+ }
+ if (digits !== TOTP_DEFAULT_DIGITS) {
+ uri += `&digits=${digits}`;
+ }
+ if (period !== TOTP_DEFAULT_PERIOD) {
+ uri += `&period=${period}`;
+ }
+ return uri;
+}
diff --git a/core/client/src/items/TotpUtility.ts b/core/client/src/items/TotpUtility.ts
index c5b7f4a58..e20a2ce33 100644
--- a/core/client/src/items/TotpUtility.ts
+++ b/core/client/src/items/TotpUtility.ts
@@ -1,4 +1,4 @@
-import { normalizeTotpAlgorithm, normalizeTotpDigits, normalizeTotpPeriod, TOTP_DEFAULT_ALGORITHM, TOTP_DEFAULT_DIGITS, TOTP_DEFAULT_PERIOD } from '@aliasvault/models/vault';
+import { normalizeTotpAlgorithm, normalizeTotpDigits, normalizeTotpPeriod } from '@aliasvault/models/vault';
import * as OTPAuth from 'otpauth';
/**
@@ -67,31 +67,3 @@ export function getTotpElapsedPercentage(parameters?: TotpParameters): number {
const period = normalizeTotpPeriod(parameters?.Period);
return Math.floor(((period - getTotpRemainingSeconds(parameters)) / period) * 100);
}
-
-/**
- * Serialize a TOTP code back to an `otpauth://` URI. Non-default parameters are written out so a
- * scanned QR reproduces the same codes.
- *
- * @param label - URL-encoded label, typically "Issuer:account"
- * @param secretKey - Base32 secret
- * @param issuer - Issuer name
- * @param parameters - Stored algorithm/digits/period
- * @returns The otpauth:// URI
- */
-export function buildOtpAuthUri(label: string, secretKey: string, issuer: string, parameters?: TotpParameters): string {
- const algorithm = normalizeTotpAlgorithm(parameters?.Algorithm);
- const digits = normalizeTotpDigits(parameters?.Digits);
- const period = normalizeTotpPeriod(parameters?.Period);
-
- let uri = `otpauth://totp/${label}?secret=${secretKey}&issuer=${encodeURIComponent(issuer)}`;
- if (algorithm !== TOTP_DEFAULT_ALGORITHM) {
- uri += `&algorithm=${algorithm}`;
- }
- if (digits !== TOTP_DEFAULT_DIGITS) {
- uri += `&digits=${digits}`;
- }
- if (period !== TOTP_DEFAULT_PERIOD) {
- uri += `&period=${period}`;
- }
- return uri;
-}
diff --git a/core/client/src/utilities/PasswordLengthSlider.ts b/core/client/src/utilities/PasswordLengthSlider.ts
new file mode 100644
index 000000000..b4edcae0a
--- /dev/null
+++ b/core/client/src/utilities/PasswordLengthSlider.ts
@@ -0,0 +1,46 @@
+/**
+ * Password length slider with non-linear scaling: a power curve gives fine-grained control at the lengths most
+ * users pick (12-32) and coarser control at the long end (64-256).
+ */
+import { MIN_PASSWORD_LENGTH, MAX_PASSWORD_LENGTH } from '@aliasvault/models/defaults';
+
+/** Slider minimum value (internal representation) */
+export const SLIDER_MIN = 0;
+
+/** Slider maximum value (internal representation) */
+export const SLIDER_MAX = 100;
+
+/**
+ * Exponent for the power curve.
+ * Higher values = more precision at lower lengths.
+ * 2.0 gives a good balance where ~50% slider = ~70 chars
+ */
+const EXPONENT = 2.0;
+
+/**
+ * Convert a slider position (0-100) to an actual password length (8-256).
+ * Uses a power curve for non-linear scaling.
+ *
+ * @param sliderValue - The slider position (0-100)
+ * @returns The password length (8-256)
+ */
+export function sliderToLength(sliderValue: number): number {
+ const normalized = Math.max(0, Math.min(1, sliderValue / SLIDER_MAX));
+ const curved = Math.pow(normalized, EXPONENT);
+ const length = MIN_PASSWORD_LENGTH + curved * (MAX_PASSWORD_LENGTH - MIN_PASSWORD_LENGTH);
+ return Math.round(length);
+}
+
+/**
+ * Convert a password length (8-256) to a slider position (0-100).
+ * Inverse of sliderToLength.
+ *
+ * @param length - The password length (8-256)
+ * @returns The slider position (0-100)
+ */
+export function lengthToSlider(length: number): number {
+ const clampedLength = Math.max(MIN_PASSWORD_LENGTH, Math.min(MAX_PASSWORD_LENGTH, length));
+ const normalized = (clampedLength - MIN_PASSWORD_LENGTH) / (MAX_PASSWORD_LENGTH - MIN_PASSWORD_LENGTH);
+ const curved = Math.pow(normalized, 1 / EXPONENT);
+ return curved * SLIDER_MAX;
+}