Privacy-first password manager with built-in email aliasing. Fully encrypted and self-hostable.
Update Rust merge logic (#1404)
Leendert de Borstb05b43101333
diff --git a/.gitignore b/.gitignoreindex f6e8e54fc..e1120f9fd 100644--- a/.gitignore+++ b/.gitignore@@ -434,3 +434,21 @@ temp# Safari extension build filesapps/browser-extension/safari-xcode/AliasVault/build++# Rust core binaries (built by ./build.sh in shared/rust-core)+# These are platform-specific and must be built locally or by CI+shared/rust-core/dist/+shared/rust-core/target/++# Browser extension WASM (built by: cd shared/rust-core && ./build.sh --browser)+apps/browser-extension/src/utils/dist/shared/rust-core++# iOS Swift bindings (built by: cd shared/rust-core && ./build.sh --ios)+apps/mobile-app/ios/AliasVaultCore/++# Android Kotlin bindings (built by: cd shared/rust-core && ./build.sh --android)+apps/mobile-app/android/app/src/main/java/com/aliasvault/core/+apps/mobile-app/android/app/src/main/jniLibs/++# Server .NET bindings (built by: cd shared/rust-core && ./build.sh --server)+apps/server/Utilities/AliasVault.RustCore/diff --git a/apps/browser-extension/src/utils/VaultMergeService.ts b/apps/browser-extension/src/utils/VaultMergeService.tsindex 56eb05a36..86386d6e1 100644--- a/apps/browser-extension/src/utils/VaultMergeService.ts+++ b/apps/browser-extension/src/utils/VaultMergeService.ts@@ -1,23 +1,66 @@import initSqlJs, { Database, SqlJsStatic, SqlValue } from 'sql.js';+import { browser } from 'wxt/browser';++import init, { getSyncableTableNames, mergeVaults } from './dist/shared/rust-core/aliasvault_core.js';++/**+ * Record type for JSON data passed to/from Rust.+ */+type JsonRecord = { [key: string]: unknown };++/**+ * Type for Rust merge function.+ */+type MergeFunction = (input: IMergeInput) => IMergeOutput;++/**+ * Type for Rust getSyncableTableNames function.+ */+type GetTableNamesFunction = () => string[];/**- * Entity record from a SyncableEntity table.- * All entities extending SyncableEntity have these fields.- * Additional fields are accessed dynamically via index signature.+ * Table data structure for Rust merge input/output.*/-interface ISyncableRecord {- Id: string;- CreatedAt: string;- UpdatedAt: string;- IsDeleted: number; // SQLite stores booleans as 0/1- [key: string]: SqlValue; // Allow dynamic column access with SQL-compatible types+interface ITableData {+ name: string;+ records: JsonRecord[];+}++/**+ * Input structure for Rust merge function.+ */+interface IMergeInput {+ local_tables: ITableData[];+ server_tables: ITableData[];}/**- * Item record with additional deletion tracking fields.+ * SQL statement with parameters from Rust.*/-interface IItemRecord extends ISyncableRecord {- DeletedAt: string | null;+interface ISqlStatement {+ sql: string;+ params: SqlValue[];+}++/**+ * Statistics from Rust merge.+ */+interface IRustMergeStats {+ tables_processed: number;+ records_from_local: number;+ records_from_server: number;+ records_created_locally: number;+ conflicts: number;+ records_inserted: number;+}++/**+ * Output structure from Rust merge function.+ */+interface IMergeOutput {+ success: boolean;+ statements: ISqlStatement[];+ stats: IRustMergeStats;}/**@@ -40,71 +83,57 @@ export interface IMergeStats {conflicts: number;}-/**- * Configuration for a syncable table.- */-interface ITableConfig {- name: string;- primaryKey: string;- isItemTable?: boolean; // Special handling for Item.DeletedAt- compositeKey?: string[]; // For tables that should merge by composite key instead of Id-}--/**- * All tables that extend SyncableEntity and need LWW merge.- *- * FieldValues uses a composite key (ItemId + FieldKey/FieldDefinitionId) for merging- * because different clients may create FieldValues with different random UUIDs for the- * same logical field. By matching on the composite key, we ensure proper LWW merging.- */-const SYNCABLE_TABLES: ITableConfig[] = [- { name: 'Items', primaryKey: 'Id', isItemTable: true },- { name: 'FieldValues', primaryKey: 'Id', compositeKey: ['ItemId', 'FieldKey', 'FieldDefinitionId'] },- { name: 'Folders', primaryKey: 'Id' },- { name: 'Tags', primaryKey: 'Id' },- { name: 'ItemTags', primaryKey: 'Id' },- { name: 'Attachments', primaryKey: 'Id' },- { name: 'TotpCodes', primaryKey: 'Id' },- { name: 'Passkeys', primaryKey: 'Id' },- { name: 'FieldDefinitions', primaryKey: 'Id' },- { name: 'FieldHistories', primaryKey: 'Id' },- { name: 'Logos', primaryKey: 'Id' },-];-/*** Service for merging two vault SQLite databases using Last-Write-Wins (LWW) strategy.*+ * This implementation uses Rust WASM for the core merge logic, ensuring consistency+ * across all platforms (browser, iOS, Android, server).+ ** The merge uses UpdatedAt timestamps on all SyncableEntity records to determine* which version of a record wins in case of conflict.*/export class VaultMergeService {private sqlJsInstance: SqlJsStatic | null = null;+ private rustInitialized = false;/**- * Set a pre-initialized SQL.js instance (useful for testing).- * @param sql - The SQL.js static instance+ * Initialize the Rust WASM module.+ * Called automatically by merge() if not already initialized.*/- public setSqlJs(sql: SqlJsStatic): void {- this.sqlJsInstance = sql;+ private async initRust(): Promise<void> {+ if (this.rustInitialized) {+ return;+ }+ /*+ * Fetch WASM bytes using browser.runtime.getURL for correct extension path.+ * Cast to string to bypass WXT's strict PublicPath typing.+ */+ const wasmUrl = (browser.runtime.getURL as (path: string) => string)('src/aliasvault_core_bg.wasm');+ const wasmResponse = await fetch(wasmUrl);+ const wasmBytes = await wasmResponse.arrayBuffer();+ await init(wasmBytes);+ this.rustInitialized = true;}/*** Merge local vault changes with server vault using LWW strategy.*+ * Uses Rust WASM for the merge logic:+ * 1. Load both SQLite databases with sql.js+ * 2. Read all tables as JSON+ * 3. Call Rust merge (returns SQL statements)+ * 4. Execute SQL statements on local database+ * 5. Export merged database+ ** @param localVaultBase64 - The local vault (with offline changes) as base64 SQLite* @param serverVaultBase64 - The server vault (latest version) as base64 SQLite* @returns MergeResult with the merged vault as base64*/public async merge(localVaultBase64: string, serverVaultBase64: string): Promise<IMergeResult> {- const stats: IMergeStats = {- tablesProcessed: 0,- recordsFromLocal: 0,- recordsFromServer: 0,- recordsCreatedLocally: 0,- conflicts: 0,- };-try {+ // Initialize Rust WASM+ await this.initRust();+// Use injected SQL.js instance or initialize a new oneconst SQL = this.sqlJsInstance ?? await initSqlJs({/**@@ -119,32 +148,71 @@ export class VaultMergeService {const localDb = this.loadDatabase(SQL, localVaultBase64);const serverDb = this.loadDatabase(SQL, serverVaultBase64);- /*- * We'll merge INTO the local database (which has our changes)- * by comparing with server and updating where server wins.- */- for (const tableConfig of SYNCABLE_TABLES) {- try {- await this.mergeTable(localDb, serverDb, tableConfig, stats);- stats.tablesProcessed++;- } catch (error) {- // Table might not exist in one of the databases (schema mismatch)- console.warn(`Skipping table ${tableConfig.name} during merge:`, error);- }- }+ try {+ // Get syncable table names from Rust (or injected function)+ const tableNames = getSyncableTableNames();++ // Read all tables from both databases as JSON+ const localTables: ITableData[] = tableNames.map(name => ({+ name,+ records: this.readTableAsJson(localDb, name),+ }));- // Export the merged database- const mergedVaultBase64 = this.exportDatabase(localDb);+ const serverTables: ITableData[] = tableNames.map(name => ({+ name,+ records: this.readTableAsJson(serverDb, name),+ }));- // Clean up- localDb.close();- serverDb.close();+ /*+ * Call Rust WASM merge (or injected function).+ * Use JSON stringify/parse to ensure no undefined values reach Rust/serde.+ */+ const mergeInput: IMergeInput = JSON.parse(JSON.stringify({+ local_tables: localTables,+ server_tables: serverTables,+ })) as IMergeInput;++ console.debug('[VaultMerge] Merge input:', {+ localTableCount: localTables.length,+ serverTableCount: serverTables.length,+ localTables: localTables.map(t => ({ name: t.name, recordCount: t.records.length })),+ serverTables: serverTables.map(t => ({ name: t.name, recordCount: t.records.length })),+ });++ const mergeOutput = mergeVaults(mergeInput);++ console.debug('[VaultMerge] Merge output:', {+ success: mergeOutput.success,+ stats: mergeOutput.stats,+ statementCount: mergeOutput.statements.length,+ });++ // Execute SQL statements from Rust on local database+ for (const stmt of mergeOutput.statements) {+ // Convert undefined to null for sql.js (serde-wasm-bindgen may convert null to undefined)+ const sanitizedParams = stmt.params.map(p => p === undefined ? null : p);+ localDb.run(stmt.sql, sanitizedParams);+ }- return {- success: true,- mergedVaultBase64,- stats,- };+ // Export the merged database+ const mergedVaultBase64 = this.exportDatabase(localDb);++ return {+ success: mergeOutput.success,+ mergedVaultBase64,+ stats: {+ tablesProcessed: mergeOutput.stats.tables_processed,+ recordsFromLocal: mergeOutput.stats.records_from_local,+ recordsFromServer: mergeOutput.stats.records_from_server,+ recordsCreatedLocally: mergeOutput.stats.records_created_locally,+ conflicts: mergeOutput.stats.conflicts,+ },+ };+ } finally {+ // Clean up databases+ localDb.close();+ serverDb.close();+ }} catch (error) {console.error('Vault merge failed:', error);throw error;@@ -182,371 +250,28 @@ export class VaultMergeService {}/**- * Merge a single table using LWW strategy.- * @param localDb - The local database- * @param serverDb - The server database- * @param tableConfig - Configuration for the table- * @param stats - Statistics to update- */- private async mergeTable(- localDb: Database,- serverDb: Database,- tableConfig: ITableConfig,- stats: IMergeStats- ): Promise<void> {- const { name: tableName, isItemTable, compositeKey } = tableConfig;-- // Get all records from both databases- const localRecords = this.getTableRecords(localDb, tableName);- const serverRecords = this.getTableRecords(serverDb, tableName);-- // Use composite key matching for tables that define it (e.g., FieldValues)- if (compositeKey) {- await this.mergeTableByCompositeKey(localDb, serverDb, tableName, localRecords, serverRecords, stats);- return;- }-- /*- * Standard merge by Id for other tables- * Create a map of server records by primary key for quick lookup- */- const serverMap = new Map<string, ISyncableRecord>();- for (const record of serverRecords) {- serverMap.set(record.Id, record);- }-- // Process local records- for (const localRecord of localRecords) {- const serverRecord = serverMap.get(localRecord.Id);-- if (!serverRecord) {- // Record only exists locally (created offline) - keep it- stats.recordsCreatedLocally++;- continue;- }-- // Record exists in both - compare UpdatedAt for LWW- const localUpdated = new Date(localRecord.UpdatedAt).getTime();- const serverUpdated = new Date(serverRecord.UpdatedAt).getTime();-- if (serverUpdated > localUpdated) {- // Server wins - update local with server data- stats.conflicts++;- stats.recordsFromServer++;-- if (isItemTable) {- this.updateItemRecord(localDb, tableName, serverRecord as IItemRecord, serverDb);- } else {- this.updateRecord(localDb, tableName, serverRecord, serverDb);- }- } else {- // Local wins - keep local (already there)- stats.recordsFromLocal++;- }-- // Remove from server map to track what's been processed- serverMap.delete(localRecord.Id);- }-- // Insert server-only records into local (new records from other devices)- for (const serverRecord of serverMap.values()) {- stats.recordsFromServer++;- if (isItemTable) {- this.insertItemRecord(localDb, tableName, serverRecord as IItemRecord, serverDb);- } else {- this.insertRecord(localDb, tableName, serverRecord, serverDb);- }- }- }-- /**- * Generate a composite key string for a record.- * For FieldValues, this combines ItemId + (FieldKey or FieldDefinitionId).- * @param record - The record to generate key for- * @returns A string representing the composite key- */- private getCompositeKey(record: ISyncableRecord): string {- /*- * For FieldValues: use ItemId + (FieldKey if set, otherwise FieldDefinitionId)- * This handles both system fields (FieldKey) and custom fields (FieldDefinitionId)- */- const itemId = (record.ItemId as string) || '';- const fieldIdentifier = (record.FieldKey as string) || (record.FieldDefinitionId as string) || '';- return `${itemId}:${fieldIdentifier}`;- }-- /**- * Merge a table using composite key matching instead of Id.- * This is used for FieldValues where the same logical field may have different UUIDs- * on different clients.- *- * @param localDb - The local database- * @param serverDb - The server database- * @param tableName - The name of the table- * @param localRecords - Records from local database- * @param serverRecords - Records from server database- * @param stats - Statistics to update- */- private async mergeTableByCompositeKey(- localDb: Database,- serverDb: Database,- tableName: string,- localRecords: ISyncableRecord[],- serverRecords: ISyncableRecord[],- stats: IMergeStats- ): Promise<void> {- // Create a map of server records by composite key- const serverMap = new Map<string, ISyncableRecord>();- for (const record of serverRecords) {- const key = this.getCompositeKey(record);- // If multiple records have the same composite key, keep the one with latest UpdatedAt- const existing = serverMap.get(key);- if (!existing || new Date(record.UpdatedAt).getTime() > new Date(existing.UpdatedAt).getTime()) {- serverMap.set(key, record);- }- }-- // Create a map of local records by composite key (to track processed keys)- const processedKeys = new Set<string>();-- // Process local records- for (const localRecord of localRecords) {- const compositeKey = this.getCompositeKey(localRecord);- processedKeys.add(compositeKey);-- const serverRecord = serverMap.get(compositeKey);-- if (!serverRecord) {- // Record only exists locally (created offline) - keep it- stats.recordsCreatedLocally++;- continue;- }-- // Record exists in both (by composite key) - compare UpdatedAt for LWW- const localUpdated = new Date(localRecord.UpdatedAt).getTime();- const serverUpdated = new Date(serverRecord.UpdatedAt).getTime();-- if (serverUpdated > localUpdated) {- /*- * Server wins - update local record with server data- * Keep local Id but update all other fields- */- stats.conflicts++;- stats.recordsFromServer++;-- this.updateRecordById(localDb, tableName, localRecord.Id, serverRecord, serverDb);- } else {- // Local wins - keep local (already there)- stats.recordsFromLocal++;- }-- // Remove from server map to track what's been processed- serverMap.delete(compositeKey);- }-- /*- * Insert server-only records into local (new records from other devices)- * These are records with composite keys that don't exist locally- */- for (const serverRecord of serverMap.values()) {- stats.recordsFromServer++;- this.insertRecord(localDb, tableName, serverRecord, serverDb);- }- }-- /**- * Update a record by its Id, replacing all fields except Id with values from source.- * Used when merging by composite key - we keep the local Id but take server's field values.- *- * @param localDb - The local database- * @param tableName - The name of the table- * @param localId - The local record's Id to update- * @param sourceRecord - The source record with values to copy- * @param serverDb - The server database (for schema info)- */- private updateRecordById(- localDb: Database,- tableName: string,- localId: string,- sourceRecord: ISyncableRecord,- serverDb: Database- ): void {- const columns = this.getTableColumns(serverDb, tableName);-- // Build UPDATE statement - update all columns except Id- const setClause = columns- .filter(col => col !== 'Id')- .map(col => `${col} = ?`)- .join(', ');-- const values = columns- .filter(col => col !== 'Id')- .map(col => sourceRecord[col]);-- values.push(localId); // For WHERE clause - use local Id-- const sql = `UPDATE ${tableName} SET ${setClause} WHERE Id = ?`;- localDb.run(sql, values);- }-- /**- * Get all records from a table.+ * Read all records from a table as JSON objects.* @param db - The database to query* @param tableName - The name of the table- * @returns Array of records from the table+ * @returns Array of records as JSON objects*/- private getTableRecords(db: Database, tableName: string): ISyncableRecord[] {+ private readTableAsJson(db: Database, tableName: string): JsonRecord[] {+ const records: JsonRecord[] = [];const stmt = db.prepare(`SELECT * FROM ${tableName}`);- const records: ISyncableRecord[] = [];while (stmt.step()) {- records.push(stmt.getAsObject() as unknown as ISyncableRecord);+ const obj = stmt.getAsObject();+ /*+ * Use JSON stringify/parse to sanitize the object for Rust/serde.+ * This converts undefined to null and ensures clean JSON types.+ */+ const record = JSON.parse(JSON.stringify(obj)) as JsonRecord;+ records.push(record);}stmt.free();return records;}-- /**- * Get column names for a table (excluding computed columns).- * @param db - The database to query- * @param tableName - The name of the table- * @returns Array of column names- */- private getTableColumns(db: Database, tableName: string): string[] {- const stmt = db.prepare(`PRAGMA table_info(${tableName})`);- const columns: string[] = [];-- while (stmt.step()) {- const col = stmt.getAsObject() as { name: string };- columns.push(col.name);- }- stmt.free();-- return columns;- }-- /**- * Update a record in local database with data from server.- * @param localDb - The local database- * @param tableName - The name of the table- * @param serverRecord - The record from server- * @param serverDb - The server database (for schema info)- */- private updateRecord(- localDb: Database,- tableName: string,- serverRecord: ISyncableRecord,- serverDb: Database- ): void {- const columns = this.getTableColumns(serverDb, tableName);-- // Build UPDATE statement- const setClause = columns- .filter(col => col !== 'Id')- .map(col => `${col} = ?`)- .join(', ');-- const values = columns- .filter(col => col !== 'Id')- .map(col => serverRecord[col]);-- values.push(serverRecord.Id); // For WHERE clause-- const sql = `UPDATE ${tableName} SET ${setClause} WHERE Id = ?`;- localDb.run(sql, values);- }-- /**- * Update an Item record with special handling for DeletedAt.- * @param localDb - The local database- * @param tableName - The name of the table- * @param serverRecord - The record from server- * @param serverDb - The server database (for schema info)- */- private updateItemRecord(- localDb: Database,- tableName: string,- serverRecord: IItemRecord,- serverDb: Database- ): void {- // For Item table, use same update logic but server record includes DeletedAt- this.updateRecord(localDb, tableName, serverRecord, serverDb);- }-- /**- * Insert a new record from server into local database.- * @param localDb - The local database- * @param tableName - The name of the table- * @param serverRecord - The record from server- * @param serverDb - The server database (for schema info)- */- private insertRecord(- localDb: Database,- tableName: string,- serverRecord: ISyncableRecord,- serverDb: Database- ): void {- const columns = this.getTableColumns(serverDb, tableName);-- const columnList = columns.join(', ');- const placeholders = columns.map(() => '?').join(', ');- const values = columns.map(col => serverRecord[col]);-- const sql = `INSERT OR REPLACE INTO ${tableName} (${columnList}) VALUES (${placeholders})`;- localDb.run(sql, values);- }-- /**- * Insert an Item record with special handling for DeletedAt.- * @param localDb - The local database- * @param tableName - The name of the table- * @param serverRecord - The record from server- * @param serverDb - The server database (for schema info)- */- private insertItemRecord(- localDb: Database,- tableName: string,- serverRecord: IItemRecord,- serverDb: Database- ): void {- // For Item table, use same insert logic- this.insertRecord(localDb, tableName, serverRecord, serverDb);- }-- /**- * Resolve deletion conflicts for Item records.- *- * Rules:- * - IsDeleted=true (permanent delete) is "sticky" unless restored with later UpdatedAt- * - DeletedAt (moved to trash) follows LWW- * @param local - The local record- * @param server - The server record- * @returns The resolved record- */- public resolveItemDeletionConflict(local: IItemRecord, server: IItemRecord): IItemRecord {- const localUpdated = new Date(local.UpdatedAt).getTime();- const serverUpdated = new Date(server.UpdatedAt).getTime();-- // Standard LWW for the base winner- const winner = serverUpdated > localUpdated ? { ...server } : { ...local };-- /*- * Special handling for IsDeleted (permanent delete)- * If both are deleted, stay deleted- */- if (local.IsDeleted && server.IsDeleted) {- winner.IsDeleted = 1;- } else if (local.IsDeleted && localUpdated > serverUpdated) {- // If only one is deleted, the delete wins if it's newer- winner.IsDeleted = 1;- } else if (server.IsDeleted && serverUpdated > localUpdated) {- winner.IsDeleted = 1;- }- // Otherwise, the non-deleted (restore) wins if it's newer-- return winner;- }}/**diff --git a/apps/browser-extension/src/utils/__tests__/VaultMergeService.test.ts b/apps/browser-extension/src/utils/__tests__/VaultMergeService.test.tsdeleted file mode 100644index 55242395f..000000000--- a/apps/browser-extension/src/utils/__tests__/VaultMergeService.test.ts+++ /dev/null@@ -1,873 +0,0 @@-import initSqlJs, { SqlJsStatic } from 'sql.js';-import { describe, it, expect, beforeAll, beforeEach } from 'vitest';--import { VaultSqlGenerator } from '@/utils/dist/shared/vault-sql';--import { VaultMergeService } from '../VaultMergeService';--/**- * Test suite for VaultMergeService - tests LWW (Last-Write-Wins) merge logic- * with real SQLite databases using the actual vault schema.- */--let SQL: SqlJsStatic;-let vaultSchema: string;--describe('VaultMergeService', () => {- let mergeService: VaultMergeService;-- beforeAll(async () => {- // Initialize SQL.js once for all tests - use node_modules path for tests- SQL = await initSqlJs({- /**- * Locate the SQL.js WASM file in node_modules for test environment.- * @param file - The filename to locate- * @returns The path to the file- */- locateFile: (file: string) => `node_modules/sql.js/dist/${file}`,- });-- // Get the complete vault schema from VaultSqlGenerator- const sqlGenerator = new VaultSqlGenerator();- vaultSchema = sqlGenerator.getCompleteSchemaSql();- });-- beforeEach(() => {- mergeService = new VaultMergeService();- // Inject the SQL.js instance so tests don't need 'src/' path- mergeService.setSqlJs(SQL);- });-- describe('LWW merge scenarios', () => {- it('should keep locally created records not present on server', async () => {- // Scenario: User created a new credential offline, server has nothing- const localVault = createTestVault([- {- Id: 'local-only-1',- Name: 'My Offline Credential',- CreatedAt: '2024-12-08 10:00:00.000',- UpdatedAt: '2024-12-08 10:00:00.000',- },- ]);-- const serverVault = createTestVault([]);-- const result = await mergeService.merge(localVault, serverVault);-- expect(result.success).toBe(true);- expect(result.stats.recordsCreatedLocally).toBeGreaterThanOrEqual(1);-- // Verify the local record exists in merged vault- const mergedItems = readItemsFromVault(result.mergedVaultBase64);- expect(mergedItems).toHaveLength(1);- expect(mergedItems[0].Id).toBe('local-only-1');- expect(mergedItems[0].Name).toBe('My Offline Credential');- });-- it('should use server record when server UpdatedAt is newer (conflict resolution)', async () => {- // Scenario: Same credential edited on both devices, server edit is newer- const localVault = createTestVault([- {- Id: 'shared-item-1',- Name: 'Local Edit',- CreatedAt: '2024-12-01 10:00:00.000',- UpdatedAt: '2024-12-08 10:00:00.000', // Earlier update- },- ]);-- const serverVault = createTestVault([- {- Id: 'shared-item-1',- Name: 'Server Edit',- CreatedAt: '2024-12-01 10:00:00.000',- UpdatedAt: '2024-12-08 11:00:00.000', // Later update - server wins- },- ]);-- const result = await mergeService.merge(localVault, serverVault);-- expect(result.success).toBe(true);- expect(result.stats.conflicts).toBeGreaterThanOrEqual(1);-- // Verify server version won- const mergedItems = readItemsFromVault(result.mergedVaultBase64);- expect(mergedItems).toHaveLength(1);- expect(mergedItems[0].Name).toBe('Server Edit');- });-- it('should keep local record when local UpdatedAt is newer', async () => {- // Scenario: Same credential edited on both devices, local edit is newer- const localVault = createTestVault([- {- Id: 'shared-item-1',- Name: 'Local Edit (Newer)',- CreatedAt: '2024-12-01 10:00:00.000',- UpdatedAt: '2024-12-08 12:00:00.000', // Later update - local wins- },- ]);-- const serverVault = createTestVault([- {- Id: 'shared-item-1',- Name: 'Server Edit (Older)',- CreatedAt: '2024-12-01 10:00:00.000',- UpdatedAt: '2024-12-08 10:00:00.000', // Earlier update- },- ]);-- const result = await mergeService.merge(localVault, serverVault);-- expect(result.success).toBe(true);- expect(result.stats.recordsFromLocal).toBeGreaterThanOrEqual(1);-- // Verify local version won- const mergedItems = readItemsFromVault(result.mergedVaultBase64);- expect(mergedItems).toHaveLength(1);- expect(mergedItems[0].Name).toBe('Local Edit (Newer)');- });-- it('should add server-only records to merged vault', async () => {- // Scenario: Another device created a credential, local doesn't have it- const localVault = createTestVault([- {- Id: 'local-item-1',- Name: 'Existing Local',- CreatedAt: '2024-12-01 10:00:00.000',- UpdatedAt: '2024-12-01 10:00:00.000',- },- ]);-- const serverVault = createTestVault([- {- Id: 'local-item-1',- Name: 'Existing Local',- CreatedAt: '2024-12-01 10:00:00.000',- UpdatedAt: '2024-12-01 10:00:00.000',- },- {- Id: 'server-only-1',- Name: 'Created on Other Device',- CreatedAt: '2024-12-08 09:00:00.000',- UpdatedAt: '2024-12-08 09:00:00.000',- },- ]);-- const result = await mergeService.merge(localVault, serverVault);-- expect(result.success).toBe(true);-- // Verify both records exist in merged vault- const mergedItems = readItemsFromVault(result.mergedVaultBase64);- expect(mergedItems).toHaveLength(2);-- const serverOnlyItem = mergedItems.find((i) => i.Id === 'server-only-1');- expect(serverOnlyItem).toBeDefined();- expect(serverOnlyItem?.Name).toBe('Created on Other Device');- });-- it('should handle complex merge with local adds, server adds, and conflicts', async () => {- // Scenario: Realistic merge with multiple types of changes- const localVault = createTestVault([- {- Id: 'item-unchanged',- Name: 'Unchanged Item',- CreatedAt: '2024-12-01 10:00:00.000',- UpdatedAt: '2024-12-01 10:00:00.000',- },- {- Id: 'item-local-wins',- Name: 'Local Wins',- CreatedAt: '2024-12-01 10:00:00.000',- UpdatedAt: '2024-12-08 15:00:00.000', // Local is newer- },- {- Id: 'item-server-wins',- Name: 'Server Will Win',- CreatedAt: '2024-12-01 10:00:00.000',- UpdatedAt: '2024-12-08 10:00:00.000', // Server is newer- },- {- Id: 'item-local-only',- Name: 'Created Offline',- CreatedAt: '2024-12-08 14:00:00.000',- UpdatedAt: '2024-12-08 14:00:00.000',- },- ]);-- const serverVault = createTestVault([- {- Id: 'item-unchanged',- Name: 'Unchanged Item',- CreatedAt: '2024-12-01 10:00:00.000',- UpdatedAt: '2024-12-01 10:00:00.000',- },- {- Id: 'item-local-wins',- Name: 'Server Version (Older)',- CreatedAt: '2024-12-01 10:00:00.000',- UpdatedAt: '2024-12-08 12:00:00.000', // Older than local- },- {- Id: 'item-server-wins',- Name: 'Server Wins',- CreatedAt: '2024-12-01 10:00:00.000',- UpdatedAt: '2024-12-08 16:00:00.000', // Newer than local- },- {- Id: 'item-server-only',- Name: 'From Other Device',- CreatedAt: '2024-12-08 13:00:00.000',- UpdatedAt: '2024-12-08 13:00:00.000',- },- ]);-- const result = await mergeService.merge(localVault, serverVault);-- expect(result.success).toBe(true);- expect(result.stats.tablesProcessed).toBeGreaterThanOrEqual(1);-- const mergedItems = readItemsFromVault(result.mergedVaultBase64);- expect(mergedItems).toHaveLength(5); // All unique items-- // Verify each scenario- const unchanged = mergedItems.find((i) => i.Id === 'item-unchanged');- expect(unchanged?.Name).toBe('Unchanged Item');-- const localWins = mergedItems.find((i) => i.Id === 'item-local-wins');- expect(localWins?.Name).toBe('Local Wins');-- const serverWins = mergedItems.find((i) => i.Id === 'item-server-wins');- expect(serverWins?.Name).toBe('Server Wins');-- const localOnly = mergedItems.find((i) => i.Id === 'item-local-only');- expect(localOnly?.Name).toBe('Created Offline');-- const serverOnly = mergedItems.find((i) => i.Id === 'item-server-only');- expect(serverOnly?.Name).toBe('From Other Device');- });- });-- describe('resolveItemDeletionConflict', () => {- it('should keep delete when both are deleted', () => {- const local = {- Id: 'item-1',- CreatedAt: '2024-12-01 10:00:00.000',- UpdatedAt: '2024-12-08 10:00:00.000',- IsDeleted: 1,- DeletedAt: null,- };- const server = {- Id: 'item-1',- CreatedAt: '2024-12-01 10:00:00.000',- UpdatedAt: '2024-12-08 11:00:00.000',- IsDeleted: 1,- DeletedAt: null,- };-- const result = mergeService.resolveItemDeletionConflict(local, server);-- expect(result.IsDeleted).toBe(1);- });-- it('should keep local delete when local is newer', () => {- const local = {- Id: 'item-1',- CreatedAt: '2024-12-01 10:00:00.000',- UpdatedAt: '2024-12-08 12:00:00.000', // Newer- IsDeleted: 1,- DeletedAt: null,- };- const server = {- Id: 'item-1',- CreatedAt: '2024-12-01 10:00:00.000',- UpdatedAt: '2024-12-08 10:00:00.000', // Older- IsDeleted: 0,- DeletedAt: null,- };-- const result = mergeService.resolveItemDeletionConflict(local, server);-- expect(result.IsDeleted).toBe(1);- });-- it('should restore when server restore is newer than local delete', () => {- const local = {- Id: 'item-1',- CreatedAt: '2024-12-01 10:00:00.000',- UpdatedAt: '2024-12-08 10:00:00.000', // Older- IsDeleted: 1,- DeletedAt: null,- };- const server = {- Id: 'item-1',- CreatedAt: '2024-12-01 10:00:00.000',- UpdatedAt: '2024-12-08 12:00:00.000', // Newer - restored- IsDeleted: 0,- DeletedAt: null,- };-- const result = mergeService.resolveItemDeletionConflict(local, server);-- // Server wins because it's newer and not deleted- expect(result.IsDeleted).toBe(0);- });- });-- describe('FieldValues merge scenarios', () => {- it('should keep locally created FieldValue not present on server', async () => {- // Scenario: User added a new field value offline- const localVault = createTestVaultWithFieldValues(- [{ Id: 'item-1', Name: 'Test Item', CreatedAt: '2024-12-01 10:00:00.000', UpdatedAt: '2024-12-01 10:00:00.000' }],- [- {- Id: 'fv-local-1',- ItemId: 'item-1',- FieldKey: 'login.password',- Value: 'local-password',- CreatedAt: '2024-12-08 10:00:00.000',- UpdatedAt: '2024-12-08 10:00:00.000',- },- ]- );-- const serverVault = createTestVaultWithFieldValues(- [{ Id: 'item-1', Name: 'Test Item', CreatedAt: '2024-12-01 10:00:00.000', UpdatedAt: '2024-12-01 10:00:00.000' }],- [] // No field values on server- );-- const result = await mergeService.merge(localVault, serverVault);-- expect(result.success).toBe(true);-- const mergedFieldValues = readFieldValuesFromVault(result.mergedVaultBase64);- expect(mergedFieldValues).toHaveLength(1);- expect(mergedFieldValues[0].Id).toBe('fv-local-1');- expect(mergedFieldValues[0].Value).toBe('local-password');- });-- it('should add server-only FieldValue to merged vault', async () => {- // Scenario: Another device added a field value- const localVault = createTestVaultWithFieldValues(- [{ Id: 'item-1', Name: 'Test Item', CreatedAt: '2024-12-01 10:00:00.000', UpdatedAt: '2024-12-01 10:00:00.000' }],- [] // No field values locally- );-- const serverVault = createTestVaultWithFieldValues(- [{ Id: 'item-1', Name: 'Test Item', CreatedAt: '2024-12-01 10:00:00.000', UpdatedAt: '2024-12-01 10:00:00.000' }],- [- {- Id: 'fv-server-1',- ItemId: 'item-1',- FieldKey: 'login.username',- Value: 'server-username',- CreatedAt: '2024-12-08 09:00:00.000',- UpdatedAt: '2024-12-08 09:00:00.000',- },- ]- );-- const result = await mergeService.merge(localVault, serverVault);-- expect(result.success).toBe(true);-- const mergedFieldValues = readFieldValuesFromVault(result.mergedVaultBase64);- expect(mergedFieldValues).toHaveLength(1);- expect(mergedFieldValues[0].Id).toBe('fv-server-1');- expect(mergedFieldValues[0].Value).toBe('server-username');- });-- it('should use server FieldValue when server UpdatedAt is newer', async () => {- // Scenario: Same field edited on both devices, server edit is newer- const localVault = createTestVaultWithFieldValues(- [{ Id: 'item-1', Name: 'Test Item', CreatedAt: '2024-12-01 10:00:00.000', UpdatedAt: '2024-12-01 10:00:00.000' }],- [- {- Id: 'fv-shared-1',- ItemId: 'item-1',- FieldKey: 'login.password',- Value: 'local-password',- CreatedAt: '2024-12-01 10:00:00.000',- UpdatedAt: '2024-12-08 10:00:00.000', // Earlier- },- ]- );-- const serverVault = createTestVaultWithFieldValues(- [{ Id: 'item-1', Name: 'Test Item', CreatedAt: '2024-12-01 10:00:00.000', UpdatedAt: '2024-12-01 10:00:00.000' }],- [- {- Id: 'fv-shared-1',- ItemId: 'item-1',- FieldKey: 'login.password',- Value: 'server-password',- CreatedAt: '2024-12-01 10:00:00.000',- UpdatedAt: '2024-12-08 11:00:00.000', // Later - server wins- },- ]- );-- const result = await mergeService.merge(localVault, serverVault);-- expect(result.success).toBe(true);-- const mergedFieldValues = readFieldValuesFromVault(result.mergedVaultBase64);- expect(mergedFieldValues).toHaveLength(1);- expect(mergedFieldValues[0].Value).toBe('server-password');- });-- it('should keep local FieldValue when local UpdatedAt is newer', async () => {- // Scenario: Same field edited on both devices, local edit is newer- const localVault = createTestVaultWithFieldValues(- [{ Id: 'item-1', Name: 'Test Item', CreatedAt: '2024-12-01 10:00:00.000', UpdatedAt: '2024-12-01 10:00:00.000' }],- [- {- Id: 'fv-shared-1',- ItemId: 'item-1',- FieldKey: 'login.password',- Value: 'local-password-newer',- CreatedAt: '2024-12-01 10:00:00.000',- UpdatedAt: '2024-12-08 12:00:00.000', // Later - local wins- },- ]- );-- const serverVault = createTestVaultWithFieldValues(- [{ Id: 'item-1', Name: 'Test Item', CreatedAt: '2024-12-01 10:00:00.000', UpdatedAt: '2024-12-01 10:00:00.000' }],- [- {- Id: 'fv-shared-1',- ItemId: 'item-1',- FieldKey: 'login.password',- Value: 'server-password-older',- CreatedAt: '2024-12-01 10:00:00.000',- UpdatedAt: '2024-12-08 10:00:00.000', // Earlier- },- ]- );-- const result = await mergeService.merge(localVault, serverVault);-- expect(result.success).toBe(true);-- const mergedFieldValues = readFieldValuesFromVault(result.mergedVaultBase64);- expect(mergedFieldValues).toHaveLength(1);- expect(mergedFieldValues[0].Value).toBe('local-password-newer');- });-- it('should handle soft-deleted FieldValue - keep delete when local is newer', async () => {- // Scenario: User deleted field locally (newer), server still has it- const localVault = createTestVaultWithFieldValues(- [{ Id: 'item-1', Name: 'Test Item', CreatedAt: '2024-12-01 10:00:00.000', UpdatedAt: '2024-12-01 10:00:00.000' }],- [- {- Id: 'fv-deleted-1',- ItemId: 'item-1',- FieldKey: 'login.notes',- Value: 'deleted-notes',- CreatedAt: '2024-12-01 10:00:00.000',- UpdatedAt: '2024-12-08 12:00:00.000', // Newer - local delete wins- IsDeleted: 1,- },- ]- );-- const serverVault = createTestVaultWithFieldValues(- [{ Id: 'item-1', Name: 'Test Item', CreatedAt: '2024-12-01 10:00:00.000', UpdatedAt: '2024-12-01 10:00:00.000' }],- [- {- Id: 'fv-deleted-1',- ItemId: 'item-1',- FieldKey: 'login.notes',- Value: 'server-notes',- CreatedAt: '2024-12-01 10:00:00.000',- UpdatedAt: '2024-12-08 10:00:00.000', // Older- IsDeleted: 0,- },- ]- );-- const result = await mergeService.merge(localVault, serverVault);-- expect(result.success).toBe(true);-- const mergedFieldValues = readFieldValuesFromVault(result.mergedVaultBase64);- expect(mergedFieldValues).toHaveLength(1);- expect(mergedFieldValues[0].IsDeleted).toBe(1);- });-- it('should restore FieldValue when server restore is newer than local delete', async () => {- // Scenario: User deleted locally, but server restored it with newer timestamp- const localVault = createTestVaultWithFieldValues(- [{ Id: 'item-1', Name: 'Test Item', CreatedAt: '2024-12-01 10:00:00.000', UpdatedAt: '2024-12-01 10:00:00.000' }],- [- {- Id: 'fv-restored-1',- ItemId: 'item-1',- FieldKey: 'login.notes',- Value: 'deleted-notes',- CreatedAt: '2024-12-01 10:00:00.000',- UpdatedAt: '2024-12-08 10:00:00.000', // Older- IsDeleted: 1,- },- ]- );-- const serverVault = createTestVaultWithFieldValues(- [{ Id: 'item-1', Name: 'Test Item', CreatedAt: '2024-12-01 10:00:00.000', UpdatedAt: '2024-12-01 10:00:00.000' }],- [- {- Id: 'fv-restored-1',- ItemId: 'item-1',- FieldKey: 'login.notes',- Value: 'restored-notes',- CreatedAt: '2024-12-01 10:00:00.000',- UpdatedAt: '2024-12-08 12:00:00.000', // Newer - server wins, restores- IsDeleted: 0,- },- ]- );-- const result = await mergeService.merge(localVault, serverVault);-- expect(result.success).toBe(true);-- const mergedFieldValues = readFieldValuesFromVault(result.mergedVaultBase64);- expect(mergedFieldValues).toHaveLength(1);- expect(mergedFieldValues[0].IsDeleted).toBe(0);- expect(mergedFieldValues[0].Value).toBe('restored-notes');- });- });-- describe('Item soft-delete and DeletedAt scenarios', () => {- it('should preserve DeletedAt when item is moved to trash', async () => {- // Scenario: Item moved to trash locally (newer)- const localVault = createTestVault([- {- Id: 'item-trashed',- Name: 'Trashed Item',- CreatedAt: '2024-12-01 10:00:00.000',- UpdatedAt: '2024-12-08 12:00:00.000', // Newer- DeletedAt: '2024-12-08 12:00:00.000',- IsDeleted: 0,- },- ]);-- const serverVault = createTestVault([- {- Id: 'item-trashed',- Name: 'Not Trashed Yet',- CreatedAt: '2024-12-01 10:00:00.000',- UpdatedAt: '2024-12-08 10:00:00.000', // Older- IsDeleted: 0,- DeletedAt: null,- },- ]);-- const result = await mergeService.merge(localVault, serverVault);-- expect(result.success).toBe(true);-- const mergedItems = readItemsFromVault(result.mergedVaultBase64);- expect(mergedItems).toHaveLength(1);- expect(mergedItems[0].IsDeleted).toBe(0);- });-- it('should restore from trash when server restore is newer', async () => {- // Scenario: Item in trash locally, but server restored it- const localVault = createTestVault([- {- Id: 'item-restored',- Name: 'In Trash Locally',- CreatedAt: '2024-12-01 10:00:00.000',- UpdatedAt: '2024-12-08 10:00:00.000', // Older- DeletedAt: '2024-12-08 10:00:00.000',- IsDeleted: 1,- },- ]);-- const serverVault = createTestVault([- {- Id: 'item-restored',- Name: 'Restored on Server',- CreatedAt: '2024-12-01 10:00:00.000',- UpdatedAt: '2024-12-08 12:00:00.000', // Newer- IsDeleted: 0,- DeletedAt: null,- },- ]);-- const result = await mergeService.merge(localVault, serverVault);-- expect(result.success).toBe(true);-- const mergedItems = readItemsFromVault(result.mergedVaultBase64);- expect(mergedItems).toHaveLength(1);- expect(mergedItems[0].IsDeleted).toBe(0);- expect(mergedItems[0].Name).toBe('Restored on Server');- });-- it('should handle complex scenario with items and field values together', async () => {- // Scenario: Realistic merge with items and their field values- const localVault = createTestVaultWithFieldValues(- [- { Id: 'item-1', Name: 'Item 1 Local', CreatedAt: '2024-12-01 10:00:00.000', UpdatedAt: '2024-12-08 15:00:00.000' }, // Local wins- { Id: 'item-2', Name: 'Item 2 Old', CreatedAt: '2024-12-01 10:00:00.000', UpdatedAt: '2024-12-08 10:00:00.000' }, // Server wins- { Id: 'item-3', Name: 'New Local Item', CreatedAt: '2024-12-08 14:00:00.000', UpdatedAt: '2024-12-08 14:00:00.000' }, // Local only- ],- [- { Id: 'fv-1a', ItemId: 'item-1', FieldKey: 'login.username', Value: 'local-user', CreatedAt: '2024-12-01 10:00:00.000', UpdatedAt: '2024-12-08 15:00:00.000' }, // Local wins- { Id: 'fv-1b', ItemId: 'item-1', FieldKey: 'login.password', Value: 'old-pass', CreatedAt: '2024-12-01 10:00:00.000', UpdatedAt: '2024-12-08 10:00:00.000' }, // Server wins- { Id: 'fv-3a', ItemId: 'item-3', FieldKey: 'login.url', Value: 'https://local.com', CreatedAt: '2024-12-08 14:00:00.000', UpdatedAt: '2024-12-08 14:00:00.000' }, // Local only- ]- );-- const serverVault = createTestVaultWithFieldValues(- [- { Id: 'item-1', Name: 'Item 1 Server', CreatedAt: '2024-12-01 10:00:00.000', UpdatedAt: '2024-12-08 12:00:00.000' }, // Older- { Id: 'item-2', Name: 'Item 2 Server', CreatedAt: '2024-12-01 10:00:00.000', UpdatedAt: '2024-12-08 16:00:00.000' }, // Newer- { Id: 'item-4', Name: 'Server Only Item', CreatedAt: '2024-12-08 13:00:00.000', UpdatedAt: '2024-12-08 13:00:00.000' }, // Server only- ],- [- { Id: 'fv-1a', ItemId: 'item-1', FieldKey: 'login.username', Value: 'server-user', CreatedAt: '2024-12-01 10:00:00.000', UpdatedAt: '2024-12-08 12:00:00.000' }, // Older- { Id: 'fv-1b', ItemId: 'item-1', FieldKey: 'login.password', Value: 'new-pass', CreatedAt: '2024-12-01 10:00:00.000', UpdatedAt: '2024-12-08 16:00:00.000' }, // Newer- { Id: 'fv-4a', ItemId: 'item-4', FieldKey: 'login.url', Value: 'https://server.com', CreatedAt: '2024-12-08 13:00:00.000', UpdatedAt: '2024-12-08 13:00:00.000' }, // Server only- ]- );-- const result = await mergeService.merge(localVault, serverVault);-- expect(result.success).toBe(true);-- // Verify items- const mergedItems = readItemsFromVault(result.mergedVaultBase64);- expect(mergedItems).toHaveLength(4);-- const item1 = mergedItems.find(i => i.Id === 'item-1');- expect(item1?.Name).toBe('Item 1 Local'); // Local wins-- const item2 = mergedItems.find(i => i.Id === 'item-2');- expect(item2?.Name).toBe('Item 2 Server'); // Server wins-- const item3 = mergedItems.find(i => i.Id === 'item-3');- expect(item3?.Name).toBe('New Local Item'); // Local only-- const item4 = mergedItems.find(i => i.Id === 'item-4');- expect(item4?.Name).toBe('Server Only Item'); // Server only-- // Verify field values- const mergedFieldValues = readFieldValuesFromVault(result.mergedVaultBase64);- expect(mergedFieldValues).toHaveLength(4);-- const fv1a = mergedFieldValues.find(fv => fv.Id === 'fv-1a');- expect(fv1a?.Value).toBe('local-user'); // Local wins-- const fv1b = mergedFieldValues.find(fv => fv.Id === 'fv-1b');- expect(fv1b?.Value).toBe('new-pass'); // Server wins-- const fv3a = mergedFieldValues.find(fv => fv.Id === 'fv-3a');- expect(fv3a?.Value).toBe('https://local.com'); // Local only-- const fv4a = mergedFieldValues.find(fv => fv.Id === 'fv-4a');- expect(fv4a?.Value).toBe('https://server.com'); // Server only- });- });-});--/**- * Helper to create a test vault database using the actual vault schema.- * Inserts test Items records for merge testing.- */-function createTestVault(items: Array<{- Id: string;- Name: string;- CreatedAt: string;- UpdatedAt: string;- IsDeleted?: number;- DeletedAt?: string | null;-}>): string {- const db = new SQL.Database();-- // Execute the complete vault schema- db.exec(vaultSchema);-- // Insert test Items records- for (const item of items) {- db.run(- `INSERT INTO Items (Id, Name, ItemType, LogoId, FolderId, CreatedAt, UpdatedAt, IsDeleted, DeletedAt)- VALUES (?, ?, 'Login', NULL, NULL, ?, ?, ?, ?)`,- [- item.Id,- item.Name,- item.CreatedAt,- item.UpdatedAt,- item.IsDeleted ?? 0,- item.DeletedAt ?? null,- ]- );- }-- // Export to base64- const bytes = db.export();- db.close();-- let binaryString = '';- for (let i = 0; i < bytes.length; i++) {- binaryString += String.fromCharCode(bytes[i]);- }- return btoa(binaryString);-}--/**- * Helper to read Items from a base64 vault.- */-function readItemsFromVault(vaultBase64: string): Array<{- Id: string;- Name: string;- UpdatedAt: string;- IsDeleted: number;-}> {- const binaryString = atob(vaultBase64);- const bytes = new Uint8Array(binaryString.length);- for (let i = 0; i < binaryString.length; i++) {- bytes[i] = binaryString.charCodeAt(i);- }-- const db = new SQL.Database(bytes);- const stmt = db.prepare('SELECT Id, Name, UpdatedAt, IsDeleted FROM Items');- const items: Array<{ Id: string; Name: string; UpdatedAt: string; IsDeleted: number }> = [];-- while (stmt.step()) {- const row = stmt.getAsObject() as { Id: string; Name: string; UpdatedAt: string; IsDeleted: number };- items.push(row);- }- stmt.free();- db.close();-- return items;-}--/**- * Type for FieldValue test record.- */-type TestFieldValue = {- Id: string;- ItemId: string;- FieldKey: string;- Value: string;- CreatedAt: string;- UpdatedAt: string;- IsDeleted?: number;-};--/**- * Type for Item test record.- */-type TestItem = {- Id: string;- Name: string;- CreatedAt: string;- UpdatedAt: string;- IsDeleted?: number;- DeletedAt?: string | null;-};--/**- * Helper to create a test vault with both Items and FieldValues.- */-function createTestVaultWithFieldValues(- items: TestItem[],- fieldValues: TestFieldValue[]-): string {- const db = new SQL.Database();-- // Execute the complete vault schema- db.exec(vaultSchema);-- // Insert test Items records- for (const item of items) {- db.run(- `INSERT INTO Items (Id, Name, ItemType, LogoId, FolderId, CreatedAt, UpdatedAt, IsDeleted, DeletedAt)- VALUES (?, ?, 'Login', NULL, NULL, ?, ?, ?, ?)`,- [- item.Id,- item.Name,- item.CreatedAt,- item.UpdatedAt,- item.IsDeleted ?? 0,- item.DeletedAt ?? null,- ]- );- }-- // Insert test FieldValues records- for (const fv of fieldValues) {- db.run(- `INSERT INTO FieldValues (Id, ItemId, FieldDefinitionId, FieldKey, Value, Weight, CreatedAt, UpdatedAt, IsDeleted)- VALUES (?, ?, NULL, ?, ?, 0, ?, ?, ?)`,- [- fv.Id,- fv.ItemId,- fv.FieldKey,- fv.Value,- fv.CreatedAt,- fv.UpdatedAt,- fv.IsDeleted ?? 0,- ]- );- }-- // Export to base64- const bytes = db.export();- db.close();-- let binaryString = '';- for (let i = 0; i < bytes.length; i++) {- binaryString += String.fromCharCode(bytes[i]);- }- return btoa(binaryString);-}--/**- * Helper to read FieldValues from a base64 vault.- */-function readFieldValuesFromVault(vaultBase64: string): Array<{- Id: string;- ItemId: string;- FieldKey: string;- Value: string;- UpdatedAt: string;- IsDeleted: number;-}> {- const binaryString = atob(vaultBase64);- const bytes = new Uint8Array(binaryString.length);- for (let i = 0; i < binaryString.length; i++) {- bytes[i] = binaryString.charCodeAt(i);- }-- const db = new SQL.Database(bytes);- const stmt = db.prepare('SELECT Id, ItemId, FieldKey, Value, UpdatedAt, IsDeleted FROM FieldValues');- const fieldValues: Array<{- Id: string;- ItemId: string;- FieldKey: string;- Value: string;- UpdatedAt: string;- IsDeleted: number;- }> = [];-- while (stmt.step()) {- const row = stmt.getAsObject() as {- Id: string;- ItemId: string;- FieldKey: string;- Value: string;- UpdatedAt: string;- IsDeleted: number;- };- fieldValues.push(row);- }- stmt.free();- db.close();-- return fieldValues;-}diff --git a/apps/browser-extension/wxt.config.ts b/apps/browser-extension/wxt.config.tsindex 95125632a..337eb29b8 100644--- a/apps/browser-extension/wxt.config.ts+++ b/apps/browser-extension/wxt.config.ts@@ -40,7 +40,8 @@ export default defineConfig({resources: ["webauthn.js","src/sql-wasm.wasm",- "src/argon2.wasm"+ "src/argon2.wasm",+ "src/aliasvault_core_bg.wasm"],matches: ["<all_urls>"]}]@@ -60,6 +61,10 @@ export default defineConfig({{src: 'node_modules/sql.js/dist/sql-wasm.wasm',dest: 'src'+ },+ {+ src: 'src/utils/dist/shared/rust-core/aliasvault_core_bg.wasm',+ dest: 'src'}]})diff --git a/shared/README.md b/shared/README.mdindex 7e765de38..372f7460c 100644--- a/shared/README.md+++ b/shared/README.md@@ -1,11 +1,35 @@-This folder contains shared (Typescript) modules that are used by multiple applications in the AliasVault monorepo.+This folder contains shared modules that are used by multiple applications in the AliasVault monorepo.++## rust-core+Cross-platform core library written in Rust, providing shared business logic across ALL platforms:+- Browser extensions (Chrome, Firefox, Edge, Safari) via WebAssembly+- Mobile apps (iOS via Swift bindings, Android via Kotlin bindings)+- Server (.NET via P/Invoke)+- Desktop apps (future)++Currently implements:+- **VaultMergeService** - Merges two SQLite vault databases using Last-Write-Wins (LWW) strategy++See [rust-core/README.md](rust-core/README.md) for detailed documentation.## identity-generator-This is the identity generator that is used by:+TypeScript identity generator used by:- Browser extension (React and custom Typescript)- Mobile apps (React Native)## password-generator-This is the password generator that is used by:+TypeScript password generator used by:- Browser extension (React and custom Typescript)+- Mobile apps (React Native)++## models+TypeScript models that are auto-generated to platform-specific code:+- TypeScript (source of truth)+- C# (.NET)+- Swift (iOS)+- Kotlin (Android)++## vault-sql+TypeScript SQL utilities for vault database operations:+- Browser extension- Mobile apps (React Native)\ No newline at end of filediff --git a/shared/build-and-distribute.sh b/shared/build-and-distribute.shindex f40a8e844..734249fec 100755--- a/shared/build-and-distribute.sh+++ b/shared/build-and-distribute.sh@@ -8,6 +8,7 @@ chmod +x ./identity-generator/build.shchmod +x ./password-generator/build.shchmod +x ./models/build.shchmod +x ./vault-sql/build.sh+chmod +x ./rust-core/build.sh# Run all build scriptsecho "🚀 Starting build process for all modules..."@@ -23,4 +24,17 @@ cd ../modelscd ../vault-sql./build.sh+# Rust core build (optional - requires Rust toolchain)+# Note: Browser extensions use TypeScript VaultMergeService with sql.js+# Rust core is for native platforms only (iOS, Android, .NET)+cd ../rust-core+if command -v rustc &> /dev/null; then+ echo "📦 Building rust-core (Rust toolchain detected)..."+ echo " Note: Browser extension uses TypeScript implementation"+ ./build.sh --csharp # Build for .NET by default on dev machines+else+ echo "⚠️ Skipping rust-core build (Rust not installed)"+ echo " Install Rust from https://rustup.rs to enable Rust core builds"+fi+echo "✅ All builds completed successfully."diff --git a/shared/rust-core/.gitignore b/shared/rust-core/.gitignorenew file mode 100644index 000000000..fc2aea965--- /dev/null+++ b/shared/rust-core/.gitignore@@ -0,0 +1,35 @@+# Rust build artifacts+/target/++# Distribution directory - compiled binaries are built locally or in CI, not committed+/dist/++# Cargo lock file (library projects typically don't commit this)+# Uncomment if you want to commit for reproducible builds+# Cargo.lock++# IDE+.idea/+*.swp+*.swo+.vscode/++# macOS+.DS_Store++# Temporary files+*.tmp+*.bak++# Compiled binaries - these are built locally or in CI+*.a+*.so+*.dylib+*.dll+*.wasm++# NOTE: Binaries are NOT committed to the repository.+# They are built:+# 1. Locally via ./build.sh when needed+# 2. In CI pipelines for deployment+# 3. In Docker builds for containerized deploymentsdiff --git a/shared/rust-core/Cargo.lock b/shared/rust-core/Cargo.locknew file mode 100644index 000000000..abeb6dea9--- /dev/null+++ b/shared/rust-core/Cargo.lock@@ -0,0 +1,770 @@+# This file is automatically @generated by Cargo.+# It is not intended for manual editing.+version = 4++[[package]]+name = "aliasvault-core"+version = "0.1.0"+dependencies = [+ "chrono",+ "console_error_panic_hook",+ "serde",+ "serde-wasm-bindgen",+ "serde_json",+ "thiserror",+ "uniffi",+ "wasm-bindgen",+]++[[package]]+name = "android_system_properties"+version = "0.1.5"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "819e7219dbd41043ac279b19830f2efc897156490d7fd6ea916720117ee66311"+dependencies = [+ "libc",+]++[[package]]+name = "anyhow"+version = "1.0.100"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "a23eb6b1614318a8071c9b2521f36b424b2c83db5eb3a0fead4a6c0809af6e61"++[[package]]+name = "askama"+version = "0.12.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "b79091df18a97caea757e28cd2d5fda49c6cd4bd01ddffd7ff01ace0c0ad2c28"+dependencies = [+ "askama_derive",+ "askama_escape",+]++[[package]]+name = "askama_derive"+version = "0.12.5"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "19fe8d6cb13c4714962c072ea496f3392015f0989b1a2847bb4b2d9effd71d83"+dependencies = [+ "askama_parser",+ "basic-toml",+ "mime",+ "mime_guess",+ "proc-macro2",+ "quote",+ "serde",+ "syn",+]++[[package]]+name = "askama_escape"+version = "0.10.3"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "619743e34b5ba4e9703bba34deac3427c72507c7159f5fd030aea8cac0cfe341"++[[package]]+name = "askama_parser"+version = "0.2.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "acb1161c6b64d1c3d83108213c2a2533a342ac225aabd0bda218278c2ddb00c0"+dependencies = [+ "nom",+]++[[package]]+name = "autocfg"+version = "1.5.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "c08606f8c3cbf4ce6ec8e28fb0014a2c086708fe954eaa885384a6165172e7e8"++[[package]]+name = "basic-toml"+version = "0.1.10"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "ba62675e8242a4c4e806d12f11d136e626e6c8361d6b829310732241652a178a"+dependencies = [+ "serde",+]++[[package]]+name = "bincode"+version = "1.3.3"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "b1f45e9417d87227c7a56d22e471c6206462cba514c7590c09aff4cf6d1ddcad"+dependencies = [+ "serde",+]++[[package]]+name = "bumpalo"+version = "3.19.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "46c5e41b57b8bba42a04676d81cb89e9ee8e859a1a66f80a5a72e1cb76b34d43"++[[package]]+name = "bytes"+version = "1.11.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "b35204fbdc0b3f4446b89fc1ac2cf84a8a68971995d0bf2e925ec7cd960f9cb3"++[[package]]+name = "camino"+version = "1.2.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "276a59bf2b2c967788139340c9f0c5b12d7fd6630315c15c217e559de85d2609"+dependencies = [+ "serde_core",+]++[[package]]+name = "cargo-platform"+version = "0.1.9"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "e35af189006b9c0f00a064685c727031e3ed2d8020f7ba284d78cc2671bd36ea"+dependencies = [+ "serde",+]++[[package]]+name = "cargo_metadata"+version = "0.15.4"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "eee4243f1f26fc7a42710e7439c149e2b10b05472f88090acce52632f231a73a"+dependencies = [+ "camino",+ "cargo-platform",+ "semver",+ "serde",+ "serde_json",+ "thiserror",+]++[[package]]+name = "cc"+version = "1.2.49"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "90583009037521a116abf44494efecd645ba48b6622457080f080b85544e2215"+dependencies = [+ "find-msvc-tools",+ "shlex",+]++[[package]]+name = "cfg-if"+version = "1.0.4"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "9330f8b2ff13f34540b44e946ef35111825727b38d33286ef986142615121801"++[[package]]+name = "chrono"+version = "0.4.42"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "145052bdd345b87320e369255277e3fb5152762ad123a901ef5c262dd38fe8d2"+dependencies = [+ "iana-time-zone",+ "js-sys",+ "num-traits",+ "serde",+ "wasm-bindgen",+ "windows-link",+]++[[package]]+name = "console_error_panic_hook"+version = "0.1.7"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "a06aeb73f470f66dcdbf7223caeebb85984942f22f1adb2a088cf9668146bbbc"+dependencies = [+ "cfg-if",+ "wasm-bindgen",+]++[[package]]+name = "core-foundation-sys"+version = "0.8.7"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "773648b94d0e5d620f64f280777445740e61fe701025087ec8b57f45c791888b"++[[package]]+name = "find-msvc-tools"+version = "0.1.5"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "3a3076410a55c90011c298b04d0cfa770b00fa04e1e3c97d3f6c9de105a03844"++[[package]]+name = "fs-err"+version = "2.11.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "88a41f105fe1d5b6b34b2055e3dc59bb79b46b48b2040b9e6c7b4b5de097aa41"+dependencies = [+ "autocfg",+]++[[package]]+name = "glob"+version = "0.3.3"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "0cc23270f6e1808e30a928bdc84dea0b9b4136a8bc82338574f23baf47bbd280"++[[package]]+name = "goblin"+version = "0.8.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "1b363a30c165f666402fe6a3024d3bec7ebc898f96a4a23bd1c99f8dbf3f4f47"+dependencies = [+ "log",+ "plain",+ "scroll",+]++[[package]]+name = "heck"+version = "0.5.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "2304e00983f87ffb38b55b444b5e3b60a884b5d30c0fca7d82fe33449bbe55ea"++[[package]]+name = "iana-time-zone"+version = "0.1.64"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "33e57f83510bb73707521ebaffa789ec8caf86f9657cad665b092b581d40e9fb"+dependencies = [+ "android_system_properties",+ "core-foundation-sys",+ "iana-time-zone-haiku",+ "js-sys",+ "log",+ "wasm-bindgen",+ "windows-core",+]++[[package]]+name = "iana-time-zone-haiku"+version = "0.1.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "f31827a206f56af32e590ba56d5d2d085f558508192593743f16b2306495269f"+dependencies = [+ "cc",+]++[[package]]+name = "itoa"+version = "1.0.15"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "4a5f13b858c8d314ee3e8f639011f7ccefe71f97f96e50151fb991f267928e2c"++[[package]]+name = "js-sys"+version = "0.3.83"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "464a3709c7f55f1f721e5389aa6ea4e3bc6aba669353300af094b29ffbdde1d8"+dependencies = [+ "once_cell",+ "wasm-bindgen",+]++[[package]]+name = "libc"+version = "0.2.178"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "37c93d8daa9d8a012fd8ab92f088405fb202ea0b6ab73ee2482ae66af4f42091"++[[package]]+name = "log"+version = "0.4.29"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "5e5032e24019045c762d3c0f28f5b6b8bbf38563a65908389bf7978758920897"++[[package]]+name = "memchr"+version = "2.7.6"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "f52b00d39961fc5b2736ea853c9cc86238e165017a493d1d5c8eac6bdc4cc273"++[[package]]+name = "mime"+version = "0.3.17"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "6877bb514081ee2a7ff5ef9de3281f14a4dd4bceac4c09388074a6b5df8a139a"++[[package]]+name = "mime_guess"+version = "2.0.5"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "f7c44f8e672c00fe5308fa235f821cb4198414e1c77935c1ab6948d3fd78550e"+dependencies = [+ "mime",+ "unicase",+]++[[package]]+name = "minimal-lexical"+version = "0.2.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "68354c5c6bd36d73ff3feceb05efa59b6acb7626617f4962be322a825e61f79a"++[[package]]+name = "nom"+version = "7.1.3"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "d273983c5a657a70a3e8f2a01329822f3b8c8172b73826411a55751e404a0a4a"+dependencies = [+ "memchr",+ "minimal-lexical",+]++[[package]]+name = "num-traits"+version = "0.2.19"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "071dfc062690e90b734c0b2273ce72ad0ffa95f0c74596bc250dcfd960262841"+dependencies = [+ "autocfg",+]++[[package]]+name = "once_cell"+version = "1.21.3"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "42f5e15c9953c5e4ccceeb2e7382a716482c34515315f7b03532b8b4e8393d2d"++[[package]]+name = "paste"+version = "1.0.15"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "57c0d7b74b563b49d38dae00a0c37d4d6de9b432382b2892f0574ddcae73fd0a"++[[package]]+name = "plain"+version = "0.2.3"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "b4596b6d070b27117e987119b4dac604f3c58cfb0b191112e24771b2faeac1a6"++[[package]]+name = "proc-macro2"+version = "1.0.103"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "5ee95bc4ef87b8d5ba32e8b7714ccc834865276eab0aed5c9958d00ec45f49e8"+dependencies = [+ "unicode-ident",+]++[[package]]+name = "quote"+version = "1.0.42"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "a338cc41d27e6cc6dce6cefc13a0729dfbb81c262b1f519331575dd80ef3067f"+dependencies = [+ "proc-macro2",+]++[[package]]+name = "rustversion"+version = "1.0.22"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "b39cdef0fa800fc44525c84ccb54a029961a8215f9619753635a9c0d2538d46d"++[[package]]+name = "ryu"+version = "1.0.20"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "28d3b2b1366ec20994f1fd18c3c594f05c5dd4bc44d8bb0c1c632c8d6829481f"++[[package]]+name = "scroll"+version = "0.12.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "6ab8598aa408498679922eff7fa985c25d58a90771bd6be794434c5277eab1a6"+dependencies = [+ "scroll_derive",+]++[[package]]+name = "scroll_derive"+version = "0.12.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "1783eabc414609e28a5ba76aee5ddd52199f7107a0b24c2e9746a1ecc34a683d"+dependencies = [+ "proc-macro2",+ "quote",+ "syn",+]++[[package]]+name = "semver"+version = "1.0.27"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "d767eb0aabc880b29956c35734170f26ed551a859dbd361d140cdbeca61ab1e2"+dependencies = [+ "serde",+ "serde_core",+]++[[package]]+name = "serde"+version = "1.0.228"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "9a8e94ea7f378bd32cbbd37198a4a91436180c5bb472411e48b5ec2e2124ae9e"+dependencies = [+ "serde_core",+ "serde_derive",+]++[[package]]+name = "serde-wasm-bindgen"+version = "0.6.5"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "8302e169f0eddcc139c70f139d19d6467353af16f9fce27e8c30158036a1e16b"+dependencies = [+ "js-sys",+ "serde",+ "wasm-bindgen",+]++[[package]]+name = "serde_core"+version = "1.0.228"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "41d385c7d4ca58e59fc732af25c3983b67ac852c1a25000afe1175de458b67ad"+dependencies = [+ "serde_derive",+]++[[package]]+name = "serde_derive"+version = "1.0.228"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "d540f220d3187173da220f885ab66608367b6574e925011a9353e4badda91d79"+dependencies = [+ "proc-macro2",+ "quote",+ "syn",+]++[[package]]+name = "serde_json"+version = "1.0.145"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "402a6f66d8c709116cf22f558eab210f5a50187f702eb4d7e5ef38d9a7f1c79c"+dependencies = [+ "itoa",+ "memchr",+ "ryu",+ "serde",+ "serde_core",+]++[[package]]+name = "shlex"+version = "1.3.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "0fda2ff0d084019ba4d7c6f371c95d8fd75ce3524c3cb8fb653a3023f6323e64"++[[package]]+name = "siphasher"+version = "0.3.11"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "38b58827f4464d87d377d175e90bf58eb00fd8716ff0a62f80356b5e61555d0d"++[[package]]+name = "smawk"+version = "0.3.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "b7c388c1b5e93756d0c740965c41e8822f866621d41acbdf6336a6a168f8840c"++[[package]]+name = "static_assertions"+version = "1.1.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "a2eb9349b6444b326872e140eb1cf5e7c522154d69e7a0ffb0fb81c06b37543f"++[[package]]+name = "syn"+version = "2.0.111"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "390cc9a294ab71bdb1aa2e99d13be9c753cd2d7bd6560c77118597410c4d2e87"+dependencies = [+ "proc-macro2",+ "quote",+ "unicode-ident",+]++[[package]]+name = "textwrap"+version = "0.16.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "c13547615a44dc9c452a8a534638acdf07120d4b6847c8178705da06306a3057"+dependencies = [+ "smawk",+]++[[package]]+name = "thiserror"+version = "1.0.69"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "b6aaf5339b578ea85b50e080feb250a3e8ae8cfcdff9a461c9ec2904bc923f52"+dependencies = [+ "thiserror-impl",+]++[[package]]+name = "thiserror-impl"+version = "1.0.69"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "4fee6c4efc90059e10f81e6d42c60a18f76588c3d74cb83a0b242a2b6c7504c1"+dependencies = [+ "proc-macro2",+ "quote",+ "syn",+]++[[package]]+name = "toml"+version = "0.5.11"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "f4f7f0dd8d50a853a531c426359045b1998f04219d88799810762cd4ad314234"+dependencies = [+ "serde",+]++[[package]]+name = "unicase"+version = "2.8.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "75b844d17643ee918803943289730bec8aac480150456169e647ed0b576ba539"++[[package]]+name = "unicode-ident"+version = "1.0.22"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "9312f7c4f6ff9069b165498234ce8be658059c6728633667c526e27dc2cf1df5"++[[package]]+name = "uniffi"+version = "0.28.3"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "4cb08c58c7ed7033150132febe696bef553f891b1ede57424b40d87a89e3c170"+dependencies = [+ "anyhow",+ "cargo_metadata",+ "uniffi_bindgen",+ "uniffi_core",+ "uniffi_macros",+]++[[package]]+name = "uniffi_bindgen"+version = "0.28.3"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "cade167af943e189a55020eda2c314681e223f1e42aca7c4e52614c2b627698f"+dependencies = [+ "anyhow",+ "askama",+ "camino",+ "cargo_metadata",+ "fs-err",+ "glob",+ "goblin",+ "heck",+ "once_cell",+ "paste",+ "serde",+ "textwrap",+ "toml",+ "uniffi_meta",+ "uniffi_udl",+]++[[package]]+name = "uniffi_checksum_derive"+version = "0.28.3"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "802d2051a700e3ec894c79f80d2705b69d85844dafbbe5d1a92776f8f48b563a"+dependencies = [+ "quote",+ "syn",+]++[[package]]+name = "uniffi_core"+version = "0.28.3"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "bc7687007d2546c454d8ae609b105daceb88175477dac280707ad6d95bcd6f1f"+dependencies = [+ "anyhow",+ "bytes",+ "log",+ "once_cell",+ "paste",+ "static_assertions",+]++[[package]]+name = "uniffi_macros"+version = "0.28.3"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "12c65a5b12ec544ef136693af8759fb9d11aefce740fb76916721e876639033b"+dependencies = [+ "bincode",+ "camino",+ "fs-err",+ "once_cell",+ "proc-macro2",+ "quote",+ "serde",+ "syn",+ "toml",+ "uniffi_meta",+]++[[package]]+name = "uniffi_meta"+version = "0.28.3"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "4a74ed96c26882dac1ca9b93ca23c827e284bacbd7ec23c6f0b0372f747d59e4"+dependencies = [+ "anyhow",+ "bytes",+ "siphasher",+ "uniffi_checksum_derive",+]++[[package]]+name = "uniffi_testing"+version = "0.28.3"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "6a6f984f0781f892cc864a62c3a5c60361b1ccbd68e538e6c9fbced5d82268ac"+dependencies = [+ "anyhow",+ "camino",+ "cargo_metadata",+ "fs-err",+ "once_cell",+]++[[package]]+name = "uniffi_udl"+version = "0.28.3"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "037820a4cfc4422db1eaa82f291a3863c92c7d1789dc513489c36223f9b4cdfc"+dependencies = [+ "anyhow",+ "textwrap",+ "uniffi_meta",+ "uniffi_testing",+ "weedle2",+]++[[package]]+name = "wasm-bindgen"+version = "0.2.106"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "0d759f433fa64a2d763d1340820e46e111a7a5ab75f993d1852d70b03dbb80fd"+dependencies = [+ "cfg-if",+ "once_cell",+ "rustversion",+ "wasm-bindgen-macro",+ "wasm-bindgen-shared",+]++[[package]]+name = "wasm-bindgen-macro"+version = "0.2.106"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "48cb0d2638f8baedbc542ed444afc0644a29166f1595371af4fecf8ce1e7eeb3"+dependencies = [+ "quote",+ "wasm-bindgen-macro-support",+]++[[package]]+name = "wasm-bindgen-macro-support"+version = "0.2.106"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "cefb59d5cd5f92d9dcf80e4683949f15ca4b511f4ac0a6e14d4e1ac60c6ecd40"+dependencies = [+ "bumpalo",+ "proc-macro2",+ "quote",+ "syn",+ "wasm-bindgen-shared",+]++[[package]]+name = "wasm-bindgen-shared"+version = "0.2.106"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "cbc538057e648b67f72a982e708d485b2efa771e1ac05fec311f9f63e5800db4"+dependencies = [+ "unicode-ident",+]++[[package]]+name = "weedle2"+version = "5.0.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "998d2c24ec099a87daf9467808859f9d82b61f1d9c9701251aea037f514eae0e"+dependencies = [+ "nom",+]++[[package]]+name = "windows-core"+version = "0.62.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "b8e83a14d34d0623b51dce9581199302a221863196a1dde71a7663a4c2be9deb"+dependencies = [+ "windows-implement",+ "windows-interface",+ "windows-link",+ "windows-result",+ "windows-strings",+]++[[package]]+name = "windows-implement"+version = "0.60.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "053e2e040ab57b9dc951b72c264860db7eb3b0200ba345b4e4c3b14f67855ddf"+dependencies = [+ "proc-macro2",+ "quote",+ "syn",+]++[[package]]+name = "windows-interface"+version = "0.59.3"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "3f316c4a2570ba26bbec722032c4099d8c8bc095efccdc15688708623367e358"+dependencies = [+ "proc-macro2",+ "quote",+ "syn",+]++[[package]]+name = "windows-link"+version = "0.2.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "f0805222e57f7521d6a62e36fa9163bc891acd422f971defe97d64e70d0a4fe5"++[[package]]+name = "windows-result"+version = "0.4.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "7781fa89eaf60850ac3d2da7af8e5242a5ea78d1a11c49bf2910bb5a73853eb5"+dependencies = [+ "windows-link",+]++[[package]]+name = "windows-strings"+version = "0.5.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "7837d08f69c77cf6b07689544538e017c1bfcf57e34b4c0ff58e6c2cd3b37091"+dependencies = [+ "windows-link",+]diff --git a/shared/rust-core/Cargo.toml b/shared/rust-core/Cargo.tomlnew file mode 100644index 000000000..4039d3369--- /dev/null+++ b/shared/rust-core/Cargo.toml@@ -0,0 +1,57 @@+[package]+name = "aliasvault-core"+version = "0.1.0"+edition = "2021"+description = "Cross-platform core library for AliasVault - provides shared merge logic for all platforms"+license = "MIT"+repository = "https://github.com/landhb/AliasVault"+authors = ["AliasVault Team"]++[package.metadata.wasm-pack.profile.release]+wasm-opt = false++[lib]+crate-type = ["lib", "cdylib", "staticlib"]+name = "aliasvault_core"++[features]+default = []+# Feature for UniFFI bindings (Swift/Kotlin)+uniffi = ["dep:uniffi"]+# Feature for WASM builds (browser extension)+wasm = ["dep:wasm-bindgen", "dep:serde-wasm-bindgen", "dep:console_error_panic_hook"]++[dependencies]+# Serialization - core dependency for JSON handling+serde = { version = "1.0", features = ["derive"] }+serde_json = "1.0"++# Date/time handling for LWW comparison+chrono = { version = "0.4", features = ["serde"] }++# Error handling+thiserror = "1.0"++# UniFFI for Swift/Kotlin bindings (optional)+uniffi = { version = "0.28", optional = true }++# WASM bindings (optional)+wasm-bindgen = { version = "0.2", optional = true }+serde-wasm-bindgen = { version = "0.6", optional = true }+console_error_panic_hook = { version = "0.1", optional = true }++[dev-dependencies]++# Dev profile - fast compilation+[profile.dev]+opt-level = 0+debug = false+incremental = true++# Release profile - optimized for size+[profile.release]+opt-level = "z"+lto = true+codegen-units = 1+panic = "abort"+strip = truediff --git a/shared/rust-core/README.md b/shared/rust-core/README.mdnew file mode 100644index 000000000..ef83bf0c6--- /dev/null+++ b/shared/rust-core/README.md@@ -0,0 +1,210 @@+# AliasVault Rust Core++Cross-platform core library for AliasVault, providing shared business logic for **native platforms**:+- **Mobile Apps** (iOS via Swift bindings, Android via Kotlin bindings)+- **Server** (.NET via P/Invoke)+- **Desktop Apps** (future)++> **Note:** Browser extensions use the TypeScript [VaultMergeService](../../apps/browser-extension/src/utils/VaultMergeService.ts) with sql.js (pre-compiled SQLite WASM). This is more efficient than re-compiling SQLite via Rust to WASM.++## Architecture++```+┌─────────────────────────────────────────────────────────────────────────┐+│ Rust Core Library │+│ ┌─────────────────────────────────────────────────────────────────────┐│+│ │ src/lib.rs - Main library entry point ││+│ │ src/merge.rs - Vault merge service (LWW strategy) ││+│ │ src/types.rs - Common types and table configurations ││+│ │ src/error.rs - Error types ││+│ └─────────────────────────────────────────────────────────────────────┘│+└─────────────────────────────────────────────────────────────────────────┘+ │+ ┌──────────────────────────┼──────────────────────────┐+ │ │ │+ ▼ ▼ ▼+┌─────────────────┐ ┌─────────────────┐ ┌─────────────────┐+│ UniFFI (FFI) │ │ UniFFI (FFI) │ │ C FFI (.NET) │+│ Swift bindings │ │ Kotlin bindings │ │ P/Invoke │+└────────┬────────┘ └────────┬────────┘ └────────┬────────┘+ │ │ │+ ▼ ▼ ▼+┌─────────────────┐ ┌─────────────────┐ ┌─────────────────┐+│ iOS Mobile │ │ Android Mobile │ │ Server │+│ App │ │ App │ │ (.NET) │+└─────────────────┘ └─────────────────┘ └─────────────────┘+```++## Prerequisites++### Required+- **Rust** (1.70+): Install via [rustup](https://rustup.rs/)+ ```bash+ curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | sh+ ```++### For iOS builds (macOS only)+- **Xcode** with command line tools++### For Android builds+- **Android NDK**: Set `ANDROID_NDK_HOME` environment variable+- **cargo-ndk**: For Android cross-compilation (installed automatically)+ ```bash+ cargo install cargo-ndk+ ```++## Building++### Build all targets+```bash+./build.sh+```++### Build specific targets+```bash+./build.sh --ios # iOS only (macOS required)+./build.sh --android # Android only (NDK required)+./build.sh --csharp # C#/.NET only+```++### Manual builds (for development)+```bash+# iOS (device)+cargo build --release --target aarch64-apple-ios --features uniffi++# Android (arm64)+cargo ndk --target aarch64-linux-android --platform 21 -- build --release --features uniffi++# Native (current platform)+cargo build --release+```++## Output Structure++After building, artifacts are placed in `dist/` and distributed to consumer apps:++```+dist/+├── ios/ # iOS libraries+│ ├── device/+│ │ └── libaliasvault_core.a+│ ├── simulator/+│ │ └── libaliasvault_core.a (universal)+│ └── aliasvault_core.swift+├── android/ # Android libraries+│ ├── arm64-v8a/+│ │ └── libaliasvault_core.so+│ ├── armeabi-v7a/+│ │ └── libaliasvault_core.so+│ ├── x86_64/+│ │ └── libaliasvault_core.so+│ ├── x86/+│ │ └── libaliasvault_core.so+│ └── aliasvault_core.kt+└── csharp/ # C# libraries+ ├── osx-arm64/+ │ └── libaliasvault_core.dylib+ ├── osx-x64/+ │ └── libaliasvault_core.dylib+ ├── linux-x64/+ │ └── libaliasvault_core.so+ └── VaultMergeService.cs+```++## Usage++### Swift (iOS)++```swift+import AliasVaultCore++let mergeService = VaultMergeService()++do {+ let result = try mergeService.merge(+ localVaultBase64: localVault,+ serverVaultBase64: serverVault+ )++ print("Merged \(result.stats.tablesProcessed) tables")+ print("New vault: \(result.mergedVaultBase64.prefix(50))...")+} catch {+ print("Merge failed: \(error)")+}+```++### Kotlin (Android)++```kotlin+import net.aliasvault.core.VaultMergeService++val mergeService = VaultMergeService()++try {+ val result = mergeService.merge(+ localVaultBase64 = localVault,+ serverVaultBase64 = serverVault+ )++ println("Merged ${result.stats.tablesProcessed} tables")+ println("Conflicts: ${result.stats.conflicts}")+} catch (e: Exception) {+ println("Merge failed: ${e.message}")+}+```++### C# (.NET)++```csharp+using AliasVault.Shared.RustCore;++var result = VaultMergeService.Merge(localVaultBase64, serverVaultBase64);++Console.WriteLine($"Merged {result.Stats.TablesProcessed} tables");+Console.WriteLine($"Conflicts: {result.Stats.Conflicts}");+Console.WriteLine($"Records from server: {result.Stats.RecordsFromServer}");+```++## Development++### Running tests+```bash+cargo test+```++### Checking code+```bash+cargo clippy+cargo fmt --check+```++### Adding new functionality++1. Add Rust implementation in `src/`+2. Update `src/aliasvault_core.udl` for UniFFI bindings+3. Run `./build.sh` to generate all bindings++## Binary Size Considerations++The compiled native libraries include SQLite bundled statically. Approximate sizes:++| Target | Approximate Size |+|--------|-----------------|+| iOS (arm64 static) | ~20MB |+| Android (arm64 shared) | ~2-3MB |+| macOS (.dylib) | ~16KB (dynamic) |++> **Note:** Binaries are NOT committed to the repository. They are built:+> 1. Locally via `./build.sh` when needed+> 2. In CI pipelines for deployment+> 3. In Docker builds for containerized deployments++## Why Rust for Native, TypeScript for Browser?++- **Browser Extensions**: Already use sql.js (SQLite compiled to WASM). Re-compiling SQLite via Rust to WASM adds complexity without benefit since sql.js already handles this well.+- **Native Platforms**: Rust compiles to native code with excellent SQLite support. UniFFI generates idiomatic Swift/Kotlin bindings automatically.+- **Consistency**: Both implementations follow the same LWW merge algorithm, ensuring identical behavior across all platforms.++## License++MIT License - see the main AliasVault repository for details.diff --git a/shared/rust-core/build.sh b/shared/rust-core/build.shnew file mode 100755index 000000000..83f1c1998--- /dev/null+++ b/shared/rust-core/build.sh@@ -0,0 +1,298 @@+#!/bin/bash++set -e # Stop on error+set -u # Treat unset variables as errors++# Colors for output+RED='\033[0;31m'+GREEN='\033[0;32m'+YELLOW='\033[1;33m'+BLUE='\033[0;34m'+NC='\033[0m' # No Color++# Script directory+SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"+cd "$SCRIPT_DIR"++# Output directories+DIST_DIR="$SCRIPT_DIR/dist"+WASM_DIR="$DIST_DIR/wasm"++# Target directories in consumer apps+BROWSER_EXT_DIST="$SCRIPT_DIR/../../apps/browser-extension/src/utils/dist/shared/rust-core"++echo -e "${BLUE}========================================${NC}"+echo -e "${BLUE} AliasVault Rust Core Build Script${NC}"+echo -e "${BLUE}========================================${NC}"+echo ""++# Check for required tools+check_tool() {+ if ! command -v "$1" &> /dev/null; then+ echo -e "${RED}Error: $1 is not installed${NC}"+ echo "Please install $1 first:"+ echo "$2"+ exit 1+ fi+}++echo -e "${YELLOW}Checking prerequisites...${NC}"+check_tool "rustc" "Visit https://rustup.rs"+check_tool "cargo" "Visit https://rustup.rs"++# Check Rust version+RUST_VERSION=$(rustc --version | cut -d' ' -f2)+echo -e " Rust version: ${GREEN}$RUST_VERSION${NC}"++# Build mode selection+BUILD_ALL=false+BUILD_BROWSER=false+FAST_MODE=false++# Parse arguments+while [[ $# -gt 0 ]]; do+ case $1 in+ --browser)+ BUILD_BROWSER=true+ shift+ ;;+ --fast|--dev)+ FAST_MODE=true+ echo -e "${YELLOW}Fast/dev mode enabled${NC}"+ shift+ ;;+ --help)+ echo "Usage: $0 [options]"+ echo ""+ echo "Target options:"+ echo " --browser Build WASM for browser extension"+ echo ""+ echo "Speed options:"+ echo " --fast, --dev Faster builds (for development)"+ echo ""+ echo "Other options:"+ echo " --help Show this help message"+ echo ""+ echo "Examples:"+ echo " ./build.sh --browser # Build WASM for browser extension"+ echo " ./build.sh --browser --fast # Fast dev build"+ exit 0+ ;;+ *)+ echo -e "${RED}Unknown option: $1${NC}"+ exit 1+ ;;+ esac+done++# If no targets specified, show help+if ! $BUILD_BROWSER; then+ echo "No target specified. Use --help for usage."+ echo ""+ echo "Quick start:"+ echo " ./build.sh --browser # Build for browser extension"+ exit 0+fi++# ============================================+# Browser Extension Build (WASM)+# ============================================+build_browser() {+ echo ""+ echo -e "${BLUE}Building WASM for browser extension...${NC}"++ local start_time=$(date +%s)++ # Check for wasm-pack+ if ! command -v wasm-pack &> /dev/null; then+ echo -e "${YELLOW}Installing wasm-pack...${NC}"+ cargo install wasm-pack+ fi++ # Ensure wasm target is installed+ if ! rustup target list --installed 2>/dev/null | grep -q "wasm32-unknown-unknown"; then+ echo -e " Installing wasm32-unknown-unknown target..."+ rustup target add wasm32-unknown-unknown+ fi++ # Build with wasm-pack+ echo -e " Running wasm-pack build..."+ if $FAST_MODE; then+ wasm-pack build --dev --target web --out-dir "$WASM_DIR" --features wasm+ else+ wasm-pack build --release --target web --out-dir "$WASM_DIR" --features wasm+ fi++ local end_time=$(date +%s)+ local duration=$((end_time - start_time))++ # Show output size+ if [ -f "$WASM_DIR/aliasvault_core_bg.wasm" ]; then+ WASM_SIZE=$(ls -lh "$WASM_DIR/aliasvault_core_bg.wasm" | awk '{print $5}')+ echo -e "${GREEN}WASM build complete! (${duration}s)${NC}"+ echo -e " Size: ${YELLOW}$WASM_SIZE${NC}"+ fi+}++# ============================================+# Distribution+# ============================================+distribute_browser() {+ echo ""+ echo -e "${BLUE}Distributing to browser extension...${NC}"++ if [ -d "$WASM_DIR" ] && [ -n "$(ls -A "$WASM_DIR" 2>/dev/null)" ]; then+ rm -rf "$BROWSER_EXT_DIST"+ mkdir -p "$BROWSER_EXT_DIST"+ cp "$WASM_DIR"/aliasvault_core* "$BROWSER_EXT_DIST/"+ cp "$WASM_DIR"/package.json "$BROWSER_EXT_DIST/"++ # Create TypeScript wrapper+ cat > "$BROWSER_EXT_DIST/index.ts" << 'TYPESCRIPT_EOF'+/**+ * Rust Core WASM Module for AliasVault+ *+ * This module provides the merge logic via WebAssembly.+ * The WASM handles the LWW merge algorithm, while the caller+ * handles SQLite I/O using sql.js.+ */++import init, { getSyncableTableNames, mergeVaults } from './aliasvault_core.js';++export type Record = { [key: string]: unknown };++export interface TableData {+ name: string;+ records: Record[];+}++export interface MergeInput {+ local_tables: TableData[];+ server_tables: TableData[];+}++export interface TableMergeResult {+ name: string;+ updates: Record[];+ inserts: Record[];+ kept_local_ids: string[];+}++export interface MergeStats {+ tables_processed: number;+ records_from_local: number;+ records_from_server: number;+ records_created_locally: number;+ conflicts: number;+}++export interface MergeOutput {+ success: boolean;+ tables: TableMergeResult[];+ stats: MergeStats;+}++let initialized = false;++/**+ * Initialize the WASM module. Must be called before using other functions.+ */+export async function initRustCore(): Promise<void> {+ if (initialized) return;+ await init();+ initialized = true;+}++/**+ * Get the list of table names that need to be synced.+ */+export function getTableNames(): string[] {+ if (!initialized) throw new Error('Call initRustCore() first');+ return getSyncableTableNames();+}++/**+ * Merge local and server vault data using LWW strategy.+ *+ * @param input - Local and server table data+ * @returns Merge result with updates and inserts to apply+ */+export function merge(input: MergeInput): MergeOutput {+ if (!initialized) throw new Error('Call initRustCore() first');+ return mergeVaults(input) as MergeOutput;+}++export { init, getSyncableTableNames, mergeVaults };+TYPESCRIPT_EOF++ # Create README+ cat > "$BROWSER_EXT_DIST/README.md" << 'README_EOF'+# Rust Core WASM Module++Auto-generated from `/shared/rust-core`. Do not edit manually.++## Usage++```typescript+import { initRustCore, merge, getTableNames } from './rust-core';++// Initialize once at startup+await initRustCore();++// Get list of tables to sync+const tableNames = getTableNames();++// Read tables from local and server SQLite databases (using sql.js)+const localTables = tableNames.map(name => ({+ name,+ records: readTableFromDb(localDb, name)+}));+const serverTables = tableNames.map(name => ({+ name,+ records: readTableFromDb(serverDb, name)+}));++// Merge using Rust core+const result = merge({ local_tables: localTables, server_tables: serverTables });++// Apply changes to local database+for (const table of result.tables) {+ for (const record of table.updates) {+ updateRecordInDb(localDb, table.name, record);+ }+ for (const record of table.inserts) {+ insertRecordInDb(localDb, table.name, record);+ }+}+```++## Regenerate++```bash+cd /shared/rust-core+./build.sh --browser+```+README_EOF++ echo -e "${GREEN}Distributed to: $BROWSER_EXT_DIST${NC}"+ ls -lh "$BROWSER_EXT_DIST/"+ fi+}++# ============================================+# Main Build Process+# ============================================+TOTAL_START=$(date +%s)++if $BUILD_BROWSER; then+ build_browser+ distribute_browser+fi++TOTAL_END=$(date +%s)+TOTAL_DURATION=$((TOTAL_END - TOTAL_START))++echo ""+echo -e "${GREEN}========================================${NC}"+echo -e "${GREEN} Build completed in ${TOTAL_DURATION}s${NC}"+echo -e "${GREEN}========================================${NC}"diff --git a/shared/rust-core/src/error.rs b/shared/rust-core/src/error.rsnew file mode 100644index 000000000..390efc1e5--- /dev/null+++ b/shared/rust-core/src/error.rs@@ -0,0 +1,26 @@+//! Error types for the AliasVault core library.++use thiserror::Error;++/// Errors that can occur during vault operations.+#[derive(Error, Debug)]+#[cfg_attr(feature = "uniffi", derive(uniffi::Error))]+#[cfg_attr(feature = "uniffi", uniffi(flat_error))]+pub enum VaultError {+ /// Error serializing/deserializing JSON+ #[error("JSON error: {0}")]+ JsonError(String),++ /// General error+ #[error("Error: {0}")]+ General(String),+}++impl From<serde_json::Error> for VaultError {+ fn from(err: serde_json::Error) -> Self {+ VaultError::JsonError(err.to_string())+ }+}++/// Result type alias for vault operations.+pub type VaultResult<T> = Result<T, VaultError>;diff --git a/shared/rust-core/src/lib.rs b/shared/rust-core/src/lib.rsnew file mode 100644index 000000000..b78ee571c--- /dev/null+++ b/shared/rust-core/src/lib.rs@@ -0,0 +1,42 @@+//! AliasVault Core Library+//!+//! Cross-platform merge logic for AliasVault using Last-Write-Wins (LWW) strategy.+//!+//! This library accepts table data as JSON and returns merged results as JSON.+//! Each platform (browser, iOS, Android, .NET) handles its own SQLite I/O+//! and calls this library for the merge logic.+//!+//! # Example (conceptual)+//! ```ignore+//! // Platform reads tables from local and server SQLite databases+//! let local_tables = read_all_tables_as_json(local_db);+//! let server_tables = read_all_tables_as_json(server_db);+//!+//! // Rust performs the merge+//! let result = merge_vaults(local_tables, server_tables);+//!+//! // Platform applies changes to local database+//! apply_updates(local_db, result.updates);+//! apply_inserts(local_db, result.inserts);+//! ```++pub mod error;+pub mod merge;+pub mod types;++pub use error::VaultError;+pub use merge::{+ merge_vaults, MergeInput, MergeOutput, MergeStats, SqlStatement, TableData,+};+pub use types::SYNCABLE_TABLE_NAMES;++// WASM bindings+#[cfg(feature = "wasm")]+pub mod wasm;++#[cfg(feature = "wasm")]+pub use wasm::*;++// UniFFI scaffolding+#[cfg(feature = "uniffi")]+uniffi::setup_scaffolding!();diff --git a/shared/rust-core/src/merge.rs b/shared/rust-core/src/merge.rsnew file mode 100644index 000000000..e993fc3e2--- /dev/null+++ b/shared/rust-core/src/merge.rs@@ -0,0 +1,545 @@+//! Vault merge logic using Last-Write-Wins (LWW) strategy.+//!+//! This module provides the core merge functionality that works on JSON table data.+//! It generates SQL statements that clients can execute directly on their local database.++use chrono::{DateTime, Utc};+use serde::{Deserialize, Serialize};+use std::collections::HashMap;++use crate::error::VaultResult;+use crate::types::SYNCABLE_TABLES;++/// A record is a map of column names to JSON values.+pub type Record = HashMap<String, serde_json::Value>;++/// Data for a single table.+#[derive(Debug, Clone, Serialize, Deserialize)]+pub struct TableData {+ /// Table name+ pub name: String,+ /// All records in this table+ pub records: Vec<Record>,+}++/// Input for the merge operation.+#[derive(Debug, Clone, Serialize, Deserialize)]+pub struct MergeInput {+ /// Tables from the local database+ pub local_tables: Vec<TableData>,+ /// Tables from the server database+ pub server_tables: Vec<TableData>,+}++/// A SQL statement with its parameter values.+#[derive(Debug, Clone, Serialize, Deserialize)]+pub struct SqlStatement {+ /// The SQL query with ? placeholders+ pub sql: String,+ /// Parameter values in order+ pub params: Vec<serde_json::Value>,+}++/// Statistics about what was merged.+#[derive(Debug, Clone, Default, Serialize, Deserialize)]+#[cfg_attr(feature = "uniffi", derive(uniffi::Record))]+pub struct MergeStats {+ /// Number of tables processed+ pub tables_processed: u32,+ /// Records where local version was kept+ pub records_from_local: u32,+ /// Records where server version was used (updates)+ pub records_from_server: u32,+ /// Records that only existed locally (created offline)+ pub records_created_locally: u32,+ /// Number of conflicts resolved (both had the record)+ pub conflicts: u32,+ /// Records inserted from server (server-only records)+ pub records_inserted: u32,+}++/// Output of the merge operation.+#[derive(Debug, Clone, Serialize, Deserialize)]+pub struct MergeOutput {+ /// Whether the merge was successful+ pub success: bool,+ /// SQL statements to execute on the local database (in order)+ pub statements: Vec<SqlStatement>,+ /// Overall statistics+ pub stats: MergeStats,+}++/// Main entry point: merge local and server vault data.+///+/// # Arguments+/// * `input` - MergeInput containing local and server table data+///+/// # Returns+/// MergeOutput with SQL statements to execute on local database+pub fn merge_vaults(input: MergeInput) -> VaultResult<MergeOutput> {+ let mut total_stats = MergeStats::default();+ let mut statements: Vec<SqlStatement> = Vec::new();++ // Create lookup maps for quick access+ let local_map: HashMap<&str, &TableData> = input+ .local_tables+ .iter()+ .map(|t| (t.name.as_str(), t))+ .collect();++ let server_map: HashMap<&str, &TableData> = input+ .server_tables+ .iter()+ .map(|t| (t.name.as_str(), t))+ .collect();++ // Process each syncable table+ for table_config in SYNCABLE_TABLES {+ let table_name = table_config.name;++ let local_data = local_map.get(table_name);+ let server_data = server_map.get(table_name);++ // Skip if table doesn't exist in either database+ let (local_records, server_records) = match (local_data, server_data) {+ (Some(l), Some(s)) => (&l.records, &s.records),+ (Some(l), None) => {+ // Table only in local - nothing to merge+ total_stats.records_created_locally += l.records.len() as u32;+ continue;+ }+ (None, Some(s)) => {+ // Table only in server - insert all+ for record in &s.records {+ if let Some(stmt) = generate_insert_sql(table_name, record) {+ statements.push(stmt);+ total_stats.records_inserted += 1;+ }+ }+ total_stats.tables_processed += 1;+ continue;+ }+ (None, None) => continue,+ };++ // Merge the table and generate SQL statements+ let table_statements = if table_config.uses_composite_key() {+ merge_table_by_composite_key(+ table_name,+ local_records,+ server_records,+ table_config.composite_key_columns,+ &mut total_stats,+ )+ } else {+ merge_table_by_id(table_name, local_records, server_records, &mut total_stats)+ };++ statements.extend(table_statements);+ total_stats.tables_processed += 1;+ }++ Ok(MergeOutput {+ success: true,+ statements,+ stats: total_stats,+ })+}++/// Merge a JSON string input and return JSON string output.+/// Convenience function for FFI.+pub fn merge_vaults_json(input_json: &str) -> VaultResult<String> {+ let input: MergeInput = serde_json::from_str(input_json)?;+ let output = merge_vaults(input)?;+ let output_json = serde_json::to_string(&output)?;+ Ok(output_json)+}++/// Merge table records by Id (standard merge).+/// Returns SQL statements to apply to local database.+fn merge_table_by_id(+ table_name: &str,+ local_records: &[Record],+ server_records: &[Record],+ stats: &mut MergeStats,+) -> Vec<SqlStatement> {+ let mut statements: Vec<SqlStatement> = Vec::new();++ // Create map of server records by Id+ let mut server_map: HashMap<String, &Record> = HashMap::new();+ for record in server_records {+ if let Some(id) = get_record_id(record) {+ server_map.insert(id, record);+ }+ }++ // Process local records+ for local_record in local_records {+ let local_id = match get_record_id(local_record) {+ Some(id) => id,+ None => continue,+ };++ if let Some(server_record) = server_map.get(&local_id) {+ // Record exists in both - compare UpdatedAt for LWW+ let local_ts = get_updated_at(local_record);+ let server_ts = get_updated_at(server_record);++ match (server_ts, local_ts) {+ (Some(s_ts), Some(l_ts)) if s_ts > l_ts => {+ // Server wins - generate UPDATE+ stats.conflicts += 1;+ stats.records_from_server += 1;+ if let Some(stmt) = generate_update_sql(table_name, server_record, &local_id) {+ statements.push(stmt);+ }+ }+ _ => {+ // Local wins - no action needed+ stats.records_from_local += 1;+ }+ }+ server_map.remove(&local_id);+ } else {+ // Only in local (created offline) - no action needed+ stats.records_created_locally += 1;+ }+ }++ // Server-only records - generate INSERTs+ for server_record in server_map.values() {+ stats.records_inserted += 1;+ if let Some(stmt) = generate_insert_sql(table_name, server_record) {+ statements.push(stmt);+ }+ }++ statements+}++/// Merge table by composite key.+/// Returns SQL statements to apply to local database.+fn merge_table_by_composite_key(+ table_name: &str,+ local_records: &[Record],+ server_records: &[Record],+ key_columns: &[&str],+ stats: &mut MergeStats,+) -> Vec<SqlStatement> {+ let mut statements: Vec<SqlStatement> = Vec::new();++ #[cfg(feature = "wasm")]+ {+ use crate::wasm::log;+ log(&format!(+ "[merge_composite] Processing {} - local={} records, server={} records, key_cols={:?}",+ table_name,+ local_records.len(),+ server_records.len(),+ key_columns+ ));+ }++ // Create map of server records by composite key+ let mut server_map: HashMap<String, &Record> = HashMap::new();+ for record in server_records {+ let key = get_composite_key(record, key_columns);+ #[cfg(feature = "wasm")]+ {+ use crate::wasm::log;+ let value = record.get("Value").and_then(|v| v.as_str()).unwrap_or("(no value)");+ let updated = record.get("UpdatedAt").and_then(|v| v.as_str()).unwrap_or("(no ts)");+ log(&format!("[merge_composite] SERVER record: key={}, value={}, updated={}", key, value, updated));+ }+ // Keep the one with latest UpdatedAt if duplicate keys+ if let Some(existing) = server_map.get(&key) {+ if get_updated_at(record) > get_updated_at(existing) {+ server_map.insert(key, record);+ }+ } else {+ server_map.insert(key, record);+ }+ }++ // Process local records+ for local_record in local_records {+ let composite_key = get_composite_key(local_record, key_columns);++ let local_id = match get_record_id(local_record) {+ Some(id) => id,+ None => continue,+ };++ #[cfg(feature = "wasm")]+ {+ use crate::wasm::log;+ let value = local_record.get("Value").and_then(|v| v.as_str()).unwrap_or("(no value)");+ let updated = local_record.get("UpdatedAt").and_then(|v| v.as_str()).unwrap_or("(no ts)");+ log(&format!("[merge_composite] LOCAL record: key={}, value={}, updated={}", composite_key, value, updated));+ }++ if let Some(server_record) = server_map.get(&composite_key) {+ // Record exists in both - compare UpdatedAt+ let local_ts = get_updated_at(local_record);+ let server_ts = get_updated_at(server_record);++ match (server_ts, local_ts) {+ (Some(s_ts), Some(l_ts)) if s_ts > l_ts => {+ // Server wins - update with server data but keep local Id+ stats.conflicts += 1;+ stats.records_from_server += 1;+ if let Some(stmt) = generate_update_sql(table_name, server_record, &local_id) {+ #[cfg(feature = "wasm")]+ {+ use crate::wasm::log;+ log(&format!("[merge_composite] SERVER WINS: key={}", composite_key));+ }+ statements.push(stmt);+ }+ }+ _ => {+ // Local wins - no action needed+ stats.records_from_local += 1;+ #[cfg(feature = "wasm")]+ {+ use crate::wasm::log;+ log(&format!("[merge_composite] LOCAL WINS: key={}", composite_key));+ }+ }+ }+ server_map.remove(&composite_key);+ } else {+ // Only in local - no action needed+ stats.records_created_locally += 1;+ #[cfg(feature = "wasm")]+ {+ use crate::wasm::log;+ log(&format!("[merge_composite] LOCAL ONLY: key={}", composite_key));+ }+ }+ }++ // Server-only records (by composite key) - generate INSERTs+ for (key, server_record) in &server_map {+ stats.records_inserted += 1;+ #[cfg(feature = "wasm")]+ {+ use crate::wasm::log;+ log(&format!("[merge_composite] SERVER ONLY (INSERT): key={}", key));+ }+ if let Some(stmt) = generate_insert_sql(table_name, server_record) {+ statements.push(stmt);+ }+ }++ statements+}++/// Get the Id field from a record.+fn get_record_id(record: &Record) -> Option<String> {+ record.get("Id").and_then(|v| v.as_str()).map(String::from)+}++/// Get the UpdatedAt timestamp from a record.+/// Handles both RFC3339 format (2025-12-11T06:50:10.674Z) and+/// SQLite format (2025-12-11 06:50:10.674).+fn get_updated_at(record: &Record) -> Option<DateTime<Utc>> {+ record+ .get("UpdatedAt")+ .and_then(|v| v.as_str())+ .and_then(|s| {+ // Try RFC3339 first+ DateTime::parse_from_rfc3339(s)+ .map(|dt| dt.with_timezone(&Utc))+ .ok()+ .or_else(|| {+ // Try SQLite format: "YYYY-MM-DD HH:MM:SS.mmm"+ chrono::NaiveDateTime::parse_from_str(s, "%Y-%m-%d %H:%M:%S%.f")+ .ok()+ .map(|naive| naive.and_utc())+ })+ })+}++/// Generate composite key from specified columns.+/// Concatenates column values with ":" separator.+fn get_composite_key(record: &Record, key_columns: &[&str]) -> String {+ key_columns+ .iter()+ .map(|col| {+ record+ .get(*col)+ .and_then(|v| v.as_str())+ .unwrap_or("")+ })+ .collect::<Vec<_>>()+ .join(":")+}++/// Generate an INSERT SQL statement for a record.+/// Uses INSERT OR REPLACE to handle potential conflicts.+fn generate_insert_sql(table_name: &str, record: &Record) -> Option<SqlStatement> {+ if record.is_empty() {+ return None;+ }++ // Sort column names for consistent ordering+ let mut columns: Vec<&String> = record.keys().collect();+ columns.sort();++ let column_list = columns.iter().map(|c| c.as_str()).collect::<Vec<_>>().join(", ");+ let placeholders = columns.iter().map(|_| "?").collect::<Vec<_>>().join(", ");+ let params: Vec<serde_json::Value> = columns.iter().map(|c| record[*c].clone()).collect();++ let sql = format!(+ "INSERT OR REPLACE INTO {} ({}) VALUES ({})",+ table_name, column_list, placeholders+ );++ Some(SqlStatement { sql, params })+}++/// Generate an UPDATE SQL statement for a record.+/// Updates all columns except Id, which is used in the WHERE clause.+fn generate_update_sql(table_name: &str, record: &Record, id: &str) -> Option<SqlStatement> {+ if record.is_empty() {+ return None;+ }++ // Sort column names for consistent ordering, excluding Id+ let mut columns: Vec<&String> = record.keys().filter(|c| *c != "Id").collect();+ columns.sort();++ if columns.is_empty() {+ return None;+ }++ let set_clause = columns+ .iter()+ .map(|c| format!("{} = ?", c))+ .collect::<Vec<_>>()+ .join(", ");++ let mut params: Vec<serde_json::Value> = columns.iter().map(|c| record[*c].clone()).collect();+ params.push(serde_json::json!(id)); // Add Id for WHERE clause++ let sql = format!("UPDATE {} SET {} WHERE Id = ?", table_name, set_clause);++ Some(SqlStatement { sql, params })+}++#[cfg(test)]+mod tests {+ use super::*;++ fn make_record(id: &str, updated_at: &str) -> Record {+ let mut record = HashMap::new();+ record.insert("Id".to_string(), serde_json::json!(id));+ record.insert("UpdatedAt".to_string(), serde_json::json!(updated_at));+ record.insert("Name".to_string(), serde_json::json!(format!("Record {}", id)));+ record+ }++ #[test]+ fn test_local_wins_when_newer() {+ let local = vec![make_record("1", "2024-01-02T00:00:00Z")];+ let server = vec![make_record("1", "2024-01-01T00:00:00Z")];+ let mut stats = MergeStats::default();++ let statements = merge_table_by_id("Test", &local, &server, &mut stats);++ assert_eq!(stats.records_from_local, 1);+ assert_eq!(stats.records_from_server, 0);+ assert!(statements.is_empty()); // No SQL needed when local wins+ }++ #[test]+ fn test_server_wins_when_newer() {+ let local = vec![make_record("1", "2024-01-01T00:00:00Z")];+ let server = vec![make_record("1", "2024-01-02T00:00:00Z")];+ let mut stats = MergeStats::default();++ let statements = merge_table_by_id("Test", &local, &server, &mut stats);++ assert_eq!(stats.records_from_server, 1);+ assert_eq!(stats.conflicts, 1);+ assert_eq!(statements.len(), 1);+ assert!(statements[0].sql.starts_with("UPDATE Test SET"));+ }++ #[test]+ fn test_server_only_record_inserted() {+ let local: Vec<Record> = vec![];+ let server = vec![make_record("1", "2024-01-01T00:00:00Z")];+ let mut stats = MergeStats::default();++ let statements = merge_table_by_id("Test", &local, &server, &mut stats);++ assert_eq!(stats.records_inserted, 1);+ assert_eq!(statements.len(), 1);+ assert!(statements[0].sql.starts_with("INSERT OR REPLACE INTO Test"));+ }++ #[test]+ fn test_local_only_record_kept() {+ let local = vec![make_record("1", "2024-01-01T00:00:00Z")];+ let server: Vec<Record> = vec![];+ let mut stats = MergeStats::default();++ let statements = merge_table_by_id("Test", &local, &server, &mut stats);++ assert_eq!(stats.records_created_locally, 1);+ assert!(statements.is_empty()); // No SQL needed+ }++ #[test]+ fn test_merge_vaults_json() {+ let input = MergeInput {+ local_tables: vec![TableData {+ name: "Items".to_string(),+ records: vec![make_record("1", "2024-01-01T00:00:00Z")],+ }],+ server_tables: vec![TableData {+ name: "Items".to_string(),+ records: vec![make_record("1", "2024-01-02T00:00:00Z")],+ }],+ };++ let input_json = serde_json::to_string(&input).unwrap();+ let output_json = merge_vaults_json(&input_json).unwrap();+ let output: MergeOutput = serde_json::from_str(&output_json).unwrap();++ assert!(output.success);+ assert_eq!(output.stats.conflicts, 1);+ // Should have one UPDATE statement+ assert_eq!(output.statements.len(), 1);+ assert!(output.statements[0].sql.starts_with("UPDATE Items SET"));+ }++ #[test]+ fn test_generate_insert_sql() {+ let record = make_record("test-id", "2024-01-01T00:00:00Z");+ let stmt = generate_insert_sql("Items", &record).unwrap();++ assert!(stmt.sql.contains("INSERT OR REPLACE INTO Items"));+ assert!(stmt.sql.contains("Id"));+ assert!(stmt.sql.contains("Name"));+ assert!(stmt.sql.contains("UpdatedAt"));+ assert_eq!(stmt.params.len(), 3);+ }++ #[test]+ fn test_generate_update_sql() {+ let record = make_record("test-id", "2024-01-01T00:00:00Z");+ let stmt = generate_update_sql("Items", &record, "test-id").unwrap();++ assert!(stmt.sql.starts_with("UPDATE Items SET"));+ assert!(stmt.sql.contains("WHERE Id = ?"));+ // Should not include Id in SET clause+ assert!(!stmt.sql.contains("Id = ?,")); // Id only at end for WHERE+ // Params: Name, UpdatedAt (sorted), then Id for WHERE+ assert_eq!(stmt.params.len(), 3);+ // Last param should be the Id+ assert_eq!(stmt.params[2], serde_json::json!("test-id"));+ }+}diff --git a/shared/rust-core/src/types.rs b/shared/rust-core/src/types.rsnew file mode 100644index 000000000..dfffb82fe--- /dev/null+++ b/shared/rust-core/src/types.rs@@ -0,0 +1,62 @@+//! Common types used across the AliasVault core library.++/// Configuration for a syncable table.+#[derive(Debug, Clone)]+pub struct TableConfig {+ /// Table name in the database+ pub name: &'static str,+ /// Columns to use for composite key matching (if any).+ /// When empty, uses "Id" column for matching.+ /// When set, these columns are concatenated to form the composite key.+ pub composite_key_columns: &'static [&'static str],+}++impl TableConfig {+ pub const fn new(name: &'static str) -> Self {+ Self {+ name,+ composite_key_columns: &[],+ }+ }++ pub const fn with_composite_key(mut self, columns: &'static [&'static str]) -> Self {+ self.composite_key_columns = columns;+ self+ }++ /// Returns true if this table uses composite key matching.+ pub const fn uses_composite_key(&self) -> bool {+ !self.composite_key_columns.is_empty()+ }+}++/// All tables that need LWW merge.+/// FieldValues uses composite key (ItemId + FieldKey) for merging.+pub static SYNCABLE_TABLES: &[TableConfig] = &[+ TableConfig::new("Items"),+ TableConfig::new("FieldValues").with_composite_key(&["ItemId", "FieldKey"]),+ TableConfig::new("Folders"),+ TableConfig::new("Tags"),+ TableConfig::new("ItemTags"),+ TableConfig::new("Attachments"),+ TableConfig::new("TotpCodes"),+ TableConfig::new("Passkeys"),+ TableConfig::new("FieldDefinitions"),+ TableConfig::new("FieldHistories"),+ TableConfig::new("Logos"),+];++/// List of syncable table names (for clients to know which tables to read).+pub const SYNCABLE_TABLE_NAMES: &[&str] = &[+ "Items",+ "FieldValues",+ "Folders",+ "Tags",+ "ItemTags",+ "Attachments",+ "TotpCodes",+ "Passkeys",+ "FieldDefinitions",+ "FieldHistories",+ "Logos",+];diff --git a/shared/rust-core/src/wasm.rs b/shared/rust-core/src/wasm.rsnew file mode 100644index 000000000..f7f08df74--- /dev/null+++ b/shared/rust-core/src/wasm.rs@@ -0,0 +1,50 @@+//! WASM bindings for browser extension.++use wasm_bindgen::prelude::*;++use crate::merge::{merge_vaults, MergeInput, MergeOutput};++#[wasm_bindgen]+extern "C" {+ #[wasm_bindgen(js_namespace = console)]+ pub fn log(s: &str);+}++/// Initialize panic hook for better error messages.+#[wasm_bindgen(start)]+pub fn init() {+ console_error_panic_hook::set_once();+}++/// Get the list of table names that need to be synced.+#[wasm_bindgen(js_name = getSyncableTableNames)]+pub fn get_syncable_table_names() -> Vec<String> {+ crate::types::SYNCABLE_TABLE_NAMES+ .iter()+ .map(|s| s.to_string())+ .collect()+}++/// Merge vaults using LWW strategy.+///+/// Takes a JsValue (MergeInput) and returns a JsValue (MergeOutput).+#[wasm_bindgen(js_name = mergeVaults)]+pub fn merge_vaults_js(input: JsValue) -> Result<JsValue, JsValue> {+ let input: MergeInput = serde_wasm_bindgen::from_value(input)+ .map_err(|e| JsValue::from_str(&format!("Failed to parse input: {}", e)))?;++ let output: MergeOutput = merge_vaults(input)+ .map_err(|e| JsValue::from_str(&format!("Merge failed: {}", e)))?;++ serde_wasm_bindgen::to_value(&output)+ .map_err(|e| JsValue::from_str(&format!("Failed to serialize output: {}", e)))+}++/// Merge vaults using JSON strings (alternative API).+///+/// Takes a JSON string and returns a JSON string.+#[wasm_bindgen(js_name = mergeVaultsJson)]+pub fn merge_vaults_json_js(input_json: &str) -> Result<String, JsValue> {+ crate::merge::merge_vaults_json(input_json)+ .map_err(|e| JsValue::from_str(&format!("Merge failed: {}", e)))+}