Skip to content

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

Add core/client interface config to mobile app (#2159)

Leendert de Borstf344e9646cd9
diff --git a/apps/mobile-app/platform/MobilePlatform.ts b/apps/mobile-app/platform/MobilePlatform.ts
new file mode 100644
index 000000000..d53473801
--- /dev/null
+++ b/apps/mobile-app/platform/MobilePlatform.ts
@@ -0,0 +1,69 @@
+import { setPlatform, TranslatableMessage } from '@aliasvault/client/platform';
+import { unavailableService } from '@aliasvault/client/platform/InMemoryPlatform';
+
+import type { IClientPlatform, IKeyValueStore, ISqliteEngine } from '@aliasvault/client/platform';
+
+import i18n from '@/i18n';
+import { nativeRustCore } from '@/platform/NativeRustCore';
+import { MobileAppIdentity } from '@/utils/AppInfo';
+
+/**
+ * Which translation key backs each of the client core's own messages.
+ */
+const TRANSLATION_KEYS: Record<TranslatableMessage, string> = {
+ [TranslatableMessage.UnnamedSharedVault]: 'items.sharedFolderName',
+ [TranslatableMessage.ClientOutdated]: 'vault.errors.appOutdated',
+ [TranslatableMessage.SharedFolderDeleteRefused]: 'items.deleteSharedFolderHint',
+};
+
+/*
+ * Only the client core's repositories and Rust wrappers run on mobile. Tokens, sync state and the vault itself live
+ * in native storage and the vault database is native too, so the core's key-value storage and in-JS SQLite engine
+ * are not provided and instead will throw an error in case they are called (by mistake).
+ */
+const mobilePlatform: IClientPlatform = {
+ storage: unavailableService<IKeyValueStore>('key-value storage'),
+ logger: {
+ /**
+ * Log a dev trace.
+ */
+ log: (message: string, ...args: unknown[]): void => {
+ if (__DEV__) {
+ console.debug(message, ...args);
+ }
+ },
+ /**
+ * Log a dev warning.
+ */
+ warn: (message: string, ...args: unknown[]): void => {
+ if (__DEV__) {
+ console.warn(message, ...args);
+ }
+ },
+ /**
+ * Log a dev error.
+ */
+ error: (message: string, ...args: unknown[]): void => {
+ if (__DEV__) {
+ console.error(message, ...args);
+ }
+ },
+ },
+ app: {
+ version: MobileAppIdentity.VERSION,
+ clientName: MobileAppIdentity.CLIENT_NAME,
+ isDevelopment: __DEV__,
+ },
+ rustCore: nativeRustCore,
+ sqlite: unavailableService<ISqliteEngine>('SQLite engine'),
+ /**
+ * Translate one of the core's own messages through the app's i18n.
+ */
+ translate: async (message: TranslatableMessage): Promise<string> => i18n.t(TRANSLATION_KEYS[message]),
+ /**
+ * The app's UI language.
+ */
+ deviceLanguage: (): string => i18n.language || 'en',
+};
+
+setPlatform(mobilePlatform);
diff --git a/apps/mobile-app/platform/NativeDatabaseClient.ts b/apps/mobile-app/platform/NativeDatabaseClient.ts
new file mode 100644
index 000000000..4576adbdb
--- /dev/null
+++ b/apps/mobile-app/platform/NativeDatabaseClient.ts
@@ -0,0 +1,124 @@
+import { Buffer } from 'buffer';
+
+import type { IDatabaseClient, SqliteBindValue } from '@aliasvault/client/database/BaseRepository';
+
+import NativeVaultManager from '@/specs/NativeVaultManager';
+
+/**
+ * Prefix the bridge puts in front of a base64 BLOB result, so it is not mistaken for text.
+ */
+const BLOB_RESULT_PREFIX = 'av-blob-base64:';
+
+/**
+ * The client core's database client over the native vault store. Every call crosses the React Native bridge, so
+ * every call is asynchronous, and the native store persists the vault and marks it dirty when a transaction commits.
+ */
+export class NativeDatabaseClient implements IDatabaseClient {
+ /**
+ * Native only persists the vault on commit, so a write outside a transaction gets one of its own.
+ */
+ public readonly persistsOnCommit = true;
+
+ private transactionOpen = false;
+
+ /**
+ * Run a SELECT and return its rows, with BLOB columns as bytes.
+ */
+ public async executeQuery<T>(query: string, params: SqliteBindValue[] = []): Promise<T[]> {
+ try {
+ const rows = (await NativeVaultManager.executeQuery(query, toBridgeParams(params))) as unknown as Record<string, unknown>[];
+ return rows.map(decodeBlobColumns) as T[];
+ } catch (error) {
+ throw withStatement(error, query, 'Error executing query:');
+ }
+ }
+
+ /**
+ * Run an INSERT, UPDATE or DELETE and return the number of rows it changed.
+ */
+ public async executeUpdate(query: string, params: SqliteBindValue[] = []): Promise<number> {
+ try {
+ return await NativeVaultManager.executeUpdate(query, toBridgeParams(params));
+ } catch (error) {
+ throw withStatement(error, query, 'Error executing update:');
+ }
+ }
+
+ /**
+ * Begin a transaction.
+ */
+ public async beginTransaction(): Promise<void> {
+ await NativeVaultManager.beginTransaction();
+ this.transactionOpen = true;
+ }
+
+ /**
+ * Commit the transaction, which persists the vault and marks it dirty.
+ */
+ public async commitTransaction(): Promise<void> {
+ await NativeVaultManager.commitTransaction();
+ this.transactionOpen = false;
+ }
+
+ /**
+ * Roll the transaction back.
+ */
+ public async rollbackTransaction(): Promise<void> {
+ try {
+ await NativeVaultManager.rollbackTransaction();
+ } finally {
+ this.transactionOpen = false;
+ }
+ }
+
+ /**
+ * Whether a transaction opened through this client is still open.
+ */
+ public isInTransaction(): boolean {
+ return this.transactionOpen;
+ }
+
+ /**
+ * TODO: implement multi-manifest group support.
+ */
+ public getActiveManifestId(): string | null {
+ return null;
+ }
+
+ /**
+ * The personal manifest id, as the last sync recorded it in the native sync engine state.
+ */
+ public getPersonalManifestId(): Promise<string | null> {
+ return NativeVaultManager.getPersonalManifestId();
+ }
+}
+
+/**
+ * Encode parameters for the bridge, which only carries strings, numbers and null. Bytes travel as base64 behind a
+ * prefix the native side recognizes and binds as a BLOB again.
+ */
+function toBridgeParams(params: SqliteBindValue[]): (string | number | null)[] {
+ return params.map((param) => param instanceof Uint8Array ? 'av-base64-to-blob:' + Buffer.from(param).toString('base64') : param);
+}
+
+/**
+ * Turn the BLOB columns of a result row, which the bridge sends as prefixed base64, back into bytes.
+ */
+function decodeBlobColumns(row: Record<string, unknown>): Record<string, unknown> {
+ for (const [column, value] of Object.entries(row)) {
+ if (typeof value === 'string' && value.startsWith(BLOB_RESULT_PREFIX)) {
+ row[column] = new Uint8Array(Buffer.from(value.slice(BLOB_RESULT_PREFIX.length), 'base64'));
+ }
+ }
+ return row;
+}
+
+/**
+ * Attach the failing statement to a bridge error, so the log shows which SQL failed.
+ */
+function withStatement(error: unknown, query: string, logPrefix: string): Error {
+ const enriched = new Error(error instanceof Error ? error.message : String(error));
+ enriched.stack = `SQL: ${query.trim().substring(0, 200)}\n\n${error instanceof Error && error.stack ? error.stack : ''}`;
+ console.error(logPrefix, enriched.message);
+ return enriched;
+}