Privacy-first password manager with built-in email aliasing. Fully encrypted and self-hostable.
Remove unused mobile app native test code which does not work anymore against API v2 (#2469)
Leendert de Borstfd774073eb08
diff --git a/.github/workflows/e2e-tests-android.yml b/.github/workflows/e2e-tests-android.ymldeleted file mode 100644index 8c929ddc0..000000000--- a/.github/workflows/e2e-tests-android.yml+++ /dev/null@@ -1,197 +0,0 @@-# Android native E2E tests-name: E2E Tests - Android--on:- push:- branches: [ "main" ]- paths:- - 'apps/mobile-app/**'- - 'core/**'- - '.github/workflows/e2e-tests-android.yml'- - '.github/actions/build-core-libraries/**'- - '.github/actions/start-api-server/**'- pull_request:- branches: [ "main" ]- paths:- - 'apps/mobile-app/**'- - 'core/**'- - '.github/workflows/e2e-tests-android.yml'- - '.github/actions/build-core-libraries/**'- - '.github/actions/start-api-server/**'- workflow_dispatch:--concurrency:- group: ${{ github.workflow }}-${{ github.ref }}- cancel-in-progress: true--jobs:- android-e2e-tests:- if: false # Temporarily disabled - will re-test in separate PR- timeout-minutes: 60- runs-on: ubuntu-latest- defaults:- run:- working-directory: apps/mobile-app-- steps:- - name: Free disk space- uses: jlumbroso/[email protected]- with:- tool-cache: false- android: false # Keep Android SDK- dotnet: false # Keep .NET (we need it)- haskell: true- large-packages: true- docker-images: true- swap-storage: true-- - name: Checkout repository- uses: actions/checkout@v6-- - name: Setup Java- uses: actions/setup-java@v5- with:- distribution: 'temurin'- java-version: '17'-- - name: Setup Node.js- uses: actions/setup-node@v6- with:- node-version: '24'- cache: 'npm'- cache-dependency-path: apps/mobile-app/package-lock.json-- - name: Setup Android SDK- uses: android-actions/setup-android@v4- with:- packages: platform-tools-- - name: Accept Android licenses- run: yes | sdkmanager --licenses || true-- - name: Install Android NDK- run: sdkmanager --install "ndk;26.1.10909125"-- - name: Build core libraries- uses: ./.github/actions/build-core-libraries- with:- target: android-- - name: Install mobile app dependencies- run: npm ci-- - name: Start PostgreSQL- run: |- sudo systemctl start postgresql- sudo -u postgres createuser -s aliasvault || true- sudo -u postgres psql -c "ALTER USER aliasvault WITH PASSWORD 'password';" || true- sudo -u postgres createdb -O aliasvault aliasdb_e2e_android || true-- - name: Start API server- uses: ./.github/actions/start-api-server- with:- database: aliasdb_e2e_android- db-port: "5432"-- - name: Enable KVM- run: |- echo 'KERNEL=="kvm", GROUP="kvm", MODE="0666", OPTIONS+="static_node=kvm"' | sudo tee /etc/udev/rules.d/99-kvm4all.rules- sudo udevadm control --reload-rules- sudo udevadm trigger --name-match=kvm-- - name: Cache AVD- uses: actions/cache@v5- id: avd-cache- with:- path: |- ~/.android/avd/*- ~/.android/adb*- key: avd-api-34-x86_64-${{ runner.os }}-- - name: Create AVD and generate snapshot for caching- if: steps.avd-cache.outputs.cache-hit != 'true'- uses: reactivecircus/android-emulator-runner@v2- with:- api-level: 34- arch: x86_64- target: google_apis- force-avd-creation: false- emulator-options: -no-window -gpu swiftshader_indirect -noaudio -no-boot-anim -camera-back none- disable-animations: true- script: echo "Generated AVD snapshot for caching."-- - name: Start Metro bundler- run: |- # Start Metro bundler in background (non-interactive mode for CI)- npx expo start --offline > /tmp/metro.log 2>&1 &- METRO_PID=$!- echo $METRO_PID > /tmp/metro.pid-- # Wait for Metro to be ready- echo "Waiting for Metro bundler to start..."- for i in {1..30}; do- if curl -s http://localhost:8081/status 2>/dev/null | grep -q "packager-status:running"; then- echo "Metro bundler is ready!"- break- fi- echo "Attempt $i: Metro not ready yet..."- # Show recent log for debugging- tail -3 /tmp/metro.log 2>/dev/null || true- sleep 2- done-- - name: Build and Run Android E2E Tests- uses: reactivecircus/android-emulator-runner@v2- with:- api-level: 34- arch: x86_64- target: google_apis- force-avd-creation: false- emulator-options: -no-snapshot-save -no-window -gpu swiftshader_indirect -noaudio -no-boot-anim -camera-back none- disable-animations: true- working-directory: apps/mobile-app/android- script: |- # Wait for emulator to be fully booted- adb wait-for-device- adb shell input keyevent 82 # Unlock screen-- # Set up port forwarding so emulator can reach host's API server and Metro bundler- adb reverse tcp:5100 tcp:5100 # API server- adb reverse tcp:8081 tcp:8081 # Metro bundler-- # Build and install the debug APK- ./gradlew :app:assembleDebug- adb install -r app/build/outputs/apk/debug/app-debug.apk-- # Run the instrumented tests- ./gradlew :app:connectedDebugAndroidTest -Pandroid.testInstrumentationRunnerArguments.API_URL=http://10.0.2.2:5100 --stacktrace- env:- API_URL: "http://10.0.2.2:5100"- ANDROID_NDK_HOME: ${{ env.ANDROID_SDK_ROOT }}/ndk/26.1.10909125-- - name: Upload test results- if: always()- uses: actions/upload-artifact@v7- with:- name: android-e2e-test-results- path: apps/mobile-app/android/app/build/reports/androidTests/- retention-days: 14-- - name: Upload test outputs- if: always()- uses: actions/upload-artifact@v7- with:- name: android-e2e-test-outputs- path: apps/mobile-app/android/app/build/outputs/androidTest-results/- retention-days: 14-- - name: Upload logs on failure- if: failure()- uses: actions/upload-artifact@v7- with:- name: android-e2e-test-logs- path: |- /tmp/api-server.log- /tmp/metro.log- retention-days: 14- if-no-files-found: ignorediff --git a/.github/workflows/e2e-tests-ios.yml b/.github/workflows/e2e-tests-ios.ymldeleted file mode 100644index 500d480d4..000000000--- a/.github/workflows/e2e-tests-ios.yml+++ /dev/null@@ -1,239 +0,0 @@-# iOS native E2E tests-name: E2E Tests - iOS--on:- push:- branches: [ "main" ]- paths:- - 'apps/mobile-app/**'- - 'core/**'- - '.github/workflows/e2e-tests-ios.yml'- - '.github/actions/build-core-libraries/**'- - '.github/actions/start-api-server/**'- pull_request:- branches: [ "main" ]- paths:- - 'apps/mobile-app/**'- - 'core/**'- - '.github/workflows/e2e-tests-ios.yml'- - '.github/actions/build-core-libraries/**'- - '.github/actions/start-api-server/**'- workflow_dispatch:--concurrency:- group: ${{ github.workflow }}-${{ github.ref }}- cancel-in-progress: true--jobs:- ios-e2e-tests:- if: false # Temporarily disabled - will re-test in separate PR- timeout-minutes: 60- runs-on: macos-15- defaults:- run:- working-directory: apps/mobile-app-- steps:- - name: Checkout repository- uses: actions/checkout@v6-- - name: Setup Xcode- uses: maxim-lobanov/setup-xcode@v1- with:- xcode-version: latest-stable-- - name: Setup Node.js- uses: actions/setup-node@v6- with:- node-version: '24'- cache: 'npm'- cache-dependency-path: apps/mobile-app/package-lock.json-- - name: Setup Ruby- uses: ruby/setup-ruby@v1- with:- ruby-version: '3.2'- bundler-cache: true-- - name: Install CocoaPods- run: sudo gem install cocoapods-- - name: Build core libraries- uses: ./.github/actions/build-core-libraries- with:- target: ios-- - name: Install mobile app dependencies- run: npm ci-- - name: Install CocoaPods dependencies- run: |- cd ios- pod install-- - name: Start PostgreSQL- run: |- # Install and start PostgreSQL- brew install postgresql@17- brew services start postgresql@17-- # Add PostgreSQL to PATH- echo "/opt/homebrew/opt/postgresql@17/bin" >> $GITHUB_PATH- export PATH="/opt/homebrew/opt/postgresql@17/bin:$PATH"-- # Wait for PostgreSQL to be ready- for i in {1..15}; do- if /opt/homebrew/opt/postgresql@17/bin/pg_isready -h localhost; then- echo "PostgreSQL is ready!"- break- fi- echo "Waiting for PostgreSQL... attempt $i"- sleep 1- done-- # Create database and user- /opt/homebrew/opt/postgresql@17/bin/createuser -s aliasvault || true- /opt/homebrew/opt/postgresql@17/bin/psql postgres -c "ALTER USER aliasvault WITH PASSWORD 'password';" || true- /opt/homebrew/opt/postgresql@17/bin/createdb -O aliasvault aliasdb_e2e_ios || true-- - name: Start API server- uses: ./.github/actions/start-api-server- with:- database: aliasdb_e2e_ios- db-port: "5432"-- - name: Boot iOS Simulator- run: |- # List available simulators- xcrun simctl list devices available-- # Find and boot iPhone 16 Pro simulator (or fallback to any iPhone)- SIMULATOR_ID=$(xcrun simctl list devices available | grep "iPhone 16 Pro" | head -1 | grep -oE '[A-F0-9-]{36}')-- if [ -z "$SIMULATOR_ID" ]; then- # Fallback to iPhone 15 Pro- SIMULATOR_ID=$(xcrun simctl list devices available | grep "iPhone 15 Pro" | head -1 | grep -oE '[A-F0-9-]{36}')- fi-- if [ -z "$SIMULATOR_ID" ]; then- # Fallback to any iPhone- SIMULATOR_ID=$(xcrun simctl list devices available | grep "iPhone" | head -1 | grep -oE '[A-F0-9-]{36}')- fi-- if [ -z "$SIMULATOR_ID" ]; then- echo "No iPhone simulator found!"- exit 1- fi-- echo "Booting simulator: $SIMULATOR_ID"- xcrun simctl boot "$SIMULATOR_ID" || true-- # Wait for simulator to be fully booted- echo "Waiting for simulator to be ready..."- xcrun simctl bootstatus "$SIMULATOR_ID" -b-- # Disable AutoFill to prevent "Save Password" prompts during tests- echo "Disabling AutoFill in simulator..."- xcrun simctl spawn "$SIMULATOR_ID" defaults write com.apple.Preferences AutoFillPasswords -bool NO- xcrun simctl spawn "$SIMULATOR_ID" defaults write -g AutoFillPasswords -bool NO-- echo "SIMULATOR_ID=$SIMULATOR_ID" >> $GITHUB_ENV-- - name: Start Metro bundler- run: |- # Start Metro bundler in background (non-interactive mode for CI)- npx expo start --offline > /tmp/metro.log 2>&1 &- METRO_PID=$!- echo $METRO_PID > /tmp/metro.pid-- # Wait for Metro to be ready- echo "Waiting for Metro bundler to start..."- for i in {1..30}; do- if curl -s http://localhost:8081/status 2>/dev/null | grep -q "packager-status:running"; then- echo "Metro bundler is ready!"- break- fi- echo "Attempt $i: Metro not ready yet..."- # Show recent log for debugging- tail -3 /tmp/metro.log 2>/dev/null || true- sleep 2- done-- - name: Build iOS app for testing- run: |- cd ios- xcodebuild build-for-testing \- -workspace AliasVault.xcworkspace \- -scheme AliasVault \- -sdk iphonesimulator \- -destination "id=${{ env.SIMULATOR_ID }}" \- -derivedDataPath build \- CODE_SIGNING_ALLOWED=NO \- CODE_SIGN_IDENTITY="-" \- DEVELOPMENT_TEAM="" \- IDEFileSystemSynchronizedGroupsAreEnabled=NO- env:- IDEFileSystemSynchronizedGroupsAreEnabled: NO-- - name: Run iOS E2E Tests- run: |- cd ios- xcodebuild test-without-building \- -workspace AliasVault.xcworkspace \- -scheme AliasVault \- -sdk iphonesimulator \- -destination "id=${{ env.SIMULATOR_ID }}" \- -derivedDataPath build \- -only-testing:AliasVaultUITests \- -resultBundlePath TestResults.xcresult \- -parallel-testing-enabled NO \- -maximum-concurrent-test-simulator-destinations 1 \- CODE_SIGNING_ALLOWED=NO \- CODE_SIGN_IDENTITY="-" \- DEVELOPMENT_TEAM="" \- IDEFileSystemSynchronizedGroupsAreEnabled=NO- env:- API_URL: "http://localhost:5100"- IDEFileSystemSynchronizedGroupsAreEnabled: NO-- - name: Extract attachments from xcresult- if: always()- run: |- mkdir -p /tmp/test-attachments- # Extract all attachments from the xcresult bundle- if [ -d "ios/TestResults.xcresult" ]; then- xcrun xcresulttool get --path ios/TestResults.xcresult --format json > /tmp/test-attachments/results.json 2>/dev/null || true- # Export attachments- xcrun xcresulttool export --path ios/TestResults.xcresult --output-path /tmp/test-attachments --type file 2>/dev/null || true- # List what we found- echo "Attachments found:"- ls -la /tmp/test-attachments/ || true- fi-- - name: Upload test results- if: always()- uses: actions/upload-artifact@v7- with:- name: ios-e2e-test-results- path: apps/mobile-app/ios/TestResults.xcresult- retention-days: 14-- - name: Upload extracted attachments- if: always()- uses: actions/upload-artifact@v7- with:- name: ios-e2e-test-attachments- path: /tmp/test-attachments/- retention-days: 14- if-no-files-found: ignore-- - name: Upload logs on failure- if: failure()- uses: actions/upload-artifact@v7- with:- name: ios-e2e-test-logs- path: |- /tmp/api-server.log- /tmp/metro.log- retention-days: 14- if-no-files-found: ignorediff --git a/apps/mobile-app/android/app/build.gradle b/apps/mobile-app/android/app/build.gradleindex 090a1b99e..6423b97fa 100644--- a/apps/mobile-app/android/app/build.gradle+++ b/apps/mobile-app/android/app/build.gradle@@ -95,9 +95,6 @@ android {versionCode 3100100versionName "0.31.0-alpha"- // Instrumented test configuration- testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"-buildConfigField "String", "REACT_NATIVE_RELEASE_LEVEL", "\"${findProperty('reactNativeReleaseLevel') ?: 'stable'}\""}signingConfigs {@@ -234,14 +231,6 @@ dependencies {testImplementation 'org.junit.jupiter:junit-jupiter-api:5.9.2'testImplementation 'org.junit.vintage:junit-vintage-engine:5.9.2'- // Instrumented test dependencies (androidTest)- androidTestImplementation 'androidx.test:core:1.5.0'- androidTestImplementation 'androidx.test:runner:1.5.2'- androidTestImplementation 'androidx.test:rules:1.5.0'- androidTestImplementation 'androidx.test.ext:junit:1.1.5'- androidTestImplementation 'androidx.test.uiautomator:uiautomator:2.2.0'- androidTestImplementation 'org.jetbrains.kotlinx:kotlinx-coroutines-test:1.7.3'-def isGifEnabled = (findProperty('expo.gif.enabled') ?: "") == "true";def isWebpEnabled = (findProperty('expo.webp.enabled') ?: "") == "true";def isWebpAnimatedEnabled = (findProperty('expo.webp.animated') ?: "") == "true";diff --git a/apps/mobile-app/android/app/src/androidTest/java/net/aliasvault/app/AliasVaultUITests.kt b/apps/mobile-app/android/app/src/androidTest/java/net/aliasvault/app/AliasVaultUITests.ktdeleted file mode 100644index fa733c28c..000000000--- a/apps/mobile-app/android/app/src/androidTest/java/net/aliasvault/app/AliasVaultUITests.kt+++ /dev/null@@ -1,724 +0,0 @@-package net.aliasvault.app--import android.content.Intent-import android.net.Uri-import androidx.test.ext.junit.runners.AndroidJUnit4-import androidx.test.platform.app.InstrumentationRegistry-import androidx.test.uiautomator.UiDevice-import kotlinx.coroutines.runBlocking-import net.aliasvault.app.UITestHelpers.assertTestIdExists-import net.aliasvault.app.UITestHelpers.existsByTestId-import net.aliasvault.app.UITestHelpers.findByTestId-import net.aliasvault.app.UITestHelpers.findByText-import net.aliasvault.app.UITestHelpers.hideKeyboard-import net.aliasvault.app.UITestHelpers.longSleep-import net.aliasvault.app.UITestHelpers.scrollToTestId-import net.aliasvault.app.UITestHelpers.scrollToText-import net.aliasvault.app.UITestHelpers.tapTestId-import net.aliasvault.app.UITestHelpers.typeIntoTestId-import net.aliasvault.app.UITestHelpers.waitForTestId-import net.aliasvault.app.UITestHelpers.waitForText-import net.aliasvault.app.UITestHelpers.waitForTextContains-import org.junit.After-import org.junit.Assert.assertNotNull-import org.junit.Assert.assertTrue-import org.junit.Assume.assumeTrue-import org.junit.Before-import org.junit.FixMethodOrder-import org.junit.Test-import org.junit.runner.RunWith-import org.junit.runners.MethodSorters--/**- * E2E UI Tests for AliasVault Android app.- *- * These tests use dynamically created test users via the API, so no pre-configured- * credentials are needed. Each test creates its own isolated test user to ensure- * tests can run independently (in isolation or in sequence) with a known state.- *- * Prerequisites:- * - Local API server running at the URL specified in TestConfiguration.apiUrl- * - Android Emulator with the app installed- *- * Note: Tests use UI Automator for interacting with React Native views via accessibility- * labels (testID in React Native maps to contentDescription in Android).- */-@RunWith(AndroidJUnit4::class)-@FixMethodOrder(MethodSorters.NAME_ASCENDING)-class AliasVaultUITests {- private lateinit var device: UiDevice- private val packageName = "net.aliasvault.app"-- @Before- fun setUp() {- device = UiDevice.getInstance(InstrumentationRegistry.getInstrumentation())-- // Wake up device if sleeping- device.wakeUp()- }-- @After- fun tearDown() {- // Take screenshot on failure would go here if needed- }-- // region Test Setup-- /**- * Creates a new test user for this test.- * Each test gets its own isolated user to ensure tests can run independently.- */- private fun createTestUser(): TestUser = runBlocking {- // Check if API is available- val apiAvailable = TestUserRegistration.isApiAvailable()- assumeTrue("API not available at ${TestConfiguration.apiUrl}. Start the local server first.", apiAvailable)-- // Create a new test user for this specific test- val user = TestUserRegistration.createTestUser()- println("[Setup] Created test user: ${user.username}")- user- }-- /**- * Launch the app fresh.- * Note: For UI tests, the app uses a pre-bundled JS bundle (no Metro needed).- */- private fun launchApp() {- val context = InstrumentationRegistry.getInstrumentation().targetContext- val intent = context.packageManager.getLaunchIntentForPackage(packageName)- intent?.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK)- context.startActivity(intent)-- // Wait for app to start and JS bundle to load- Thread.sleep(5000)-- // Wait for one of the expected screens (check all simultaneously with polling)- val startTime = System.currentTimeMillis()- val timeout = TestConfiguration.EXTENDED_TIMEOUT_MS- while (System.currentTimeMillis() - startTime < timeout) {- if (device.findByTestId("login-screen") != null ||- device.findByTestId("unlock-screen") != null ||- device.findByTestId("items-screen") != null- ) {- return- }- Thread.sleep(200)- }- }-- /**- * Open a deep link in the app.- */- private fun openDeepLink(url: String) {- val context = InstrumentationRegistry.getInstrumentation().targetContext- val intent = Intent(Intent.ACTION_VIEW, Uri.parse(url)).apply {- addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)- setPackage(packageName)- }- context.startActivity(intent)- longSleep()- }-- /**- * Pull to refresh gesture.- */- private fun pullToRefresh() {- device.swipe(- device.displayWidth / 2,- device.displayHeight / 4,- device.displayWidth / 2,- device.displayHeight * 3 / 4,- 10,- )- longSleep()- }-- // endregion-- // region Test 01: Create New Item-- /**- * Verifies item creation flow: opens add form, fills in details, saves, and verifies- * the item appears in the list. Creates its own isolated test user.- */- @Test- fun test01CreateItem() {- val testUser = createTestUser()- val uniqueName = TestConfiguration.generateUniqueName("E2E Test")- println("[Test01] Creating item with name: $uniqueName")-- launchApp()- loginWithTestUser(testUser)-- // Verify items screen is displayed- println("[Test01] Verifying items screen is displayed")- device.assertTestIdExists("items-screen", TestConfiguration.EXTENDED_TIMEOUT_MS)-- // Create item- val itemParams = CreateItemParams(- name = uniqueName,- serviceUrl = "https://example.com",- email = "[email protected]",- username = "e2euser",- )-- assertTrue("Should create item", createItem(itemParams))-- // Verify item exists in list- assertTrue("Should find item in list", verifyItemExistsInList(uniqueName))-- // Open and verify item details- assertTrue("Should verify item details", openAndVerifyItem(uniqueName, "[email protected]"))-- println("[Test01] Item creation and verification successful")- }-- // endregion-- // region Test 02: Offline Mode and Sync-- /**- * Verifies offline mode and sync recovery:- * 1. Goes offline by setting API URL to invalid (simulates network failure)- * 2. Creates a credential while offline (stored locally)- * 3. Goes back online and triggers sync- * 4. Verifies the credential persists after sync- */- @Test- fun test02OfflineModeAndSync() {- val testUser = createTestUser()- val originalApiUrl = TestConfiguration.apiUrl- val invalidApiUrl = "http://offline.invalid.localhost:9999"- val uniqueName = TestConfiguration.generateUniqueName("Offline Test")- println("[Test02] Creating offline item with name: $uniqueName")-- launchApp()- loginWithTestUser(testUser)-- // Step 1: Verify online state- println("[Test02] Step 1: Verify online state")- device.assertTestIdExists("items-screen", TestConfiguration.EXTENDED_TIMEOUT_MS)-- // Step 2: Enable offline mode via deep link- println("[Test02] Step 2: Enable offline mode via deep link")- val encodedInvalidUrl = Uri.encode(invalidApiUrl)- println("[Test02] Setting API URL to invalid: $invalidApiUrl")- openDeepLink("aliasvault://open/__debug__/set-api-url/$encodedInvalidUrl")-- unlockVaultIfNeeded(testUser)- device.assertTestIdExists("items-screen", TestConfiguration.DEFAULT_TIMEOUT_MS)-- // Trigger sync to detect offline state- pullToRefresh()- Thread.sleep(3000)-- device.assertTestIdExists("sync-indicator-offline", TestConfiguration.DEFAULT_TIMEOUT_MS)- println("[Test02] Offline mode enabled successfully")-- // Step 3: Create item while offline- println("[Test02] Step 3: Create item while offline")- val offlineItemParams = CreateItemParams(- name = uniqueName,- serviceUrl = "https://offline-test.example.com",- email = "[email protected]",- )-- assertTrue("Should create item while offline", createItem(offlineItemParams))- assertTrue("Should find item in list", verifyItemExistsInList(uniqueName))-- println("[Test02] Item created while offline and appears in list")-- // Step 4: Go back online and sync- println("[Test02] Step 4: Go back online and sync")- val encodedValidUrl = Uri.encode(originalApiUrl)- println("[Test02] Restoring API URL to: $originalApiUrl")- openDeepLink("aliasvault://open/__debug__/set-api-url/$encodedValidUrl")-- unlockVaultIfNeeded(testUser)- device.assertTestIdExists("items-screen", TestConfiguration.DEFAULT_TIMEOUT_MS)-- Thread.sleep(2000)- pullToRefresh()- Thread.sleep(5000)-- // Verify offline indicator is gone- assertTrue(- "Offline indicator should be gone after sync",- !device.existsByTestId("sync-indicator-offline"),- )-- println("[Test02] Back online and synced successfully")-- // Step 5: Verify item persists after sync- println("[Test02] Step 5: Verify item persists after sync")- assertTrue(- "Should verify item after sync",- openAndVerifyItem(uniqueName, "[email protected]"),- )-- println("[Test02] Offline item verified after sync - test passed")- }-- // endregion-- // region Test 03: RPO Recovery-- /**- * Verifies RPO (Recovery Point Objective) recovery scenario:- * When the client detects that its local server revision is higher than the actual server revision- * (simulating server data loss/rollback), it should upload its vault to recover the server state.- */- @Test- fun test03RPORecovery() = runBlocking {- val testUser = createTestUser()- val uniqueName = TestConfiguration.generateUniqueName("RPO Test")- println("[Test03] Testing RPO recovery with item: $uniqueName")-- launchApp()- loginWithTestUser(testUser)-- // Step 1: Verify initial state and get server revision- println("[Test03] Step 1: Verify initial state")- device.assertTestIdExists("items-screen", TestConfiguration.EXTENDED_TIMEOUT_MS)-- val initialRevisions = TestUserRegistration.getVaultRevisionsByUsername(testUser.username)- val initialRevision = initialRevisions.second- println("[Test03] Initial server revision: $initialRevision")-- // Step 2: Create credential while online- println("[Test03] Step 2: Create credential while online")- val rpoItemParams = CreateItemParams(- name = uniqueName,- serviceUrl = "https://rpo-test.example.com",- email = "[email protected]",- )-- assertTrue("Should create item", createItem(rpoItemParams))- Thread.sleep(1000) // Wait for sync-- println("[Test03] Credential created and synced to server")-- val afterCreateRevisions = TestUserRegistration.getVaultRevisionsByUsername(testUser.username)- val revisionAfterCreate = afterCreateRevisions.second- println("[Test03] Server revision after create: $revisionAfterCreate")-- assertTrue(- "Server revision should increase after creating credential",- revisionAfterCreate > initialRevision,- )-- // Step 3: Simulate server data loss- println("[Test03] Step 3: Simulate server data loss")- val deletedCount = TestUserRegistration.deleteVaultRevisionsByUsername(testUser.username, 1)- println("[Test03] Deleted $deletedCount vault revision(s) from server to simulate data loss")-- val afterDeleteRevisions = TestUserRegistration.getVaultRevisionsByUsername(testUser.username)- val revisionAfterDelete = afterDeleteRevisions.second- println("[Test03] Server revision after delete: $revisionAfterDelete")-- assertTrue(- "Server revision should decrease after deleting vault revision",- revisionAfterDelete < revisionAfterCreate,- )-- // Step 4: Trigger sync for RPO recovery- println("[Test03] Step 4: Trigger sync for RPO recovery")- println("[Test03] Triggering sync - client should detect RPO scenario and upload vault")- pullToRefresh()- Thread.sleep(5000)-- // Step 5: Verify credential persists after RPO recovery- println("[Test03] Step 5: Verify credential persists after RPO recovery")- assertTrue(- "Credential should still exist after RPO recovery",- openAndVerifyItem(uniqueName, "[email protected]"),- )-- // Verify server revision restored- val finalRevisions = TestUserRegistration.getVaultRevisionsByUsername(testUser.username)- val finalRevision = finalRevisions.second- println("[Test03] Final server revision: $finalRevision")-- assertTrue(- "Server revision should be restored after RPO recovery",- finalRevision >= revisionAfterCreate,- )-- println(- "[Test03] SUCCESS - Revision flow: $initialRevision → $revisionAfterCreate " +- "(create) → $revisionAfterDelete (rollback) → $finalRevision (recovered)",- )- }-- // endregion-- // region Test 04: Forced Logout Recovery-- /**- * Verifies forced logout recovery mechanism:- * When a forced logout occurs (e.g., 401 unauthorized due to token invalidation),- * the client should preserve the encrypted vault locally. On next login with the same- * credentials, the client should detect the preserved vault and recover by uploading- * it to the server.- */- @Test- fun test04ForcedLogoutRecovery() = runBlocking {- val testUser = createTestUser()- val uniqueName = TestConfiguration.generateUniqueName("Forced Logout Test")- println("[Test04] Testing forced logout recovery with item: $uniqueName")-- launchApp()- loginWithTestUser(testUser)-- // Step 1: Verify initial state- println("[Test04] Step 1: Verify initial state")- device.assertTestIdExists("items-screen", TestConfiguration.EXTENDED_TIMEOUT_MS)-- // Step 2: Create credential while online- println("[Test04] Step 2: Create credential while online")- val forcedLogoutItemParams = CreateItemParams(- name = uniqueName,- serviceUrl = "https://forced-logout-test.example.com",- email = "[email protected]",- )-- assertTrue("Should create item", createItem(forcedLogoutItemParams))- Thread.sleep(1000) // Wait for sync-- println("[Test04] Credential created and synced to server")-- val beforeLogoutRevisions = TestUserRegistration.getVaultRevisionsByUsername(testUser.username)- val revisionBeforeLogout = beforeLogoutRevisions.second- println("[Test04] Server revision before forced logout: $revisionBeforeLogout")-- // Simulate server data loss- val deletedCount = TestUserRegistration.deleteVaultRevisionsByUsername(testUser.username, 1)- println("[Test04] Deleted $deletedCount vault revision(s) to simulate server data loss")-- val afterRollbackRevisions = TestUserRegistration.getVaultRevisionsByUsername(testUser.username)- val revisionAfterRollback = afterRollbackRevisions.second- println("[Test04] Server revision after rollback: $revisionAfterRollback")-- // Step 3: Block user to trigger forced logout- println("[Test04] Step 3: Block user to trigger forced logout")- TestUserRegistration.blockUserByUsername(testUser.username)- println("[Test04] User blocked")-- // Step 4: Trigger sync to cause forced logout- println("[Test04] Step 4: Trigger sync to cause forced logout")- pullToRefresh()-- // Wait for session expired dialog and dismiss it- val okButton = device.waitForText("OK", TestConfiguration.DEFAULT_TIMEOUT_MS)- if (okButton != null) {- println("[Test04] Session expired modal detected, dismissing...")- okButton.click()- Thread.sleep(1000)- } else {- println("[Test04] No session expired modal detected, continuing...")- }-- // Step 5: Verify login screen- println("[Test04] Step 5: Verify login screen after forced logout")- device.assertTestIdExists("login-screen", TestConfiguration.EXTENDED_TIMEOUT_MS)-- // Verify username is prefilled (orphan vault preservation)- val usernameInput = device.findByTestId("username-input")- assertNotNull("Username input should be visible", usernameInput)-- val usernameValue = usernameInput?.text ?: ""- println("[Test04] Username field value: '$usernameValue'")-- println("[Test04] Forced logout confirmed - on login screen")-- // Unblock user so they can log in again- TestUserRegistration.unblockUserByUsername(testUser.username)- println("[Test04] User unblocked")-- // Step 6: Re-login with same credentials- println("[Test04] Step 6: Re-login with same credentials")- assertTrue("Should type username", device.typeIntoTestId("username-input", testUser.username))- assertTrue("Should tap password input", device.tapTestId("password-input"))- assertTrue("Should type password", device.typeIntoTestId("password-input", testUser.password))-- device.hideKeyboard()- assertTrue("Should tap login button", device.tapTestId("login-button"))-- // Wait for login to complete- device.assertTestIdExists("items-screen", TestConfiguration.EXTENDED_TIMEOUT_MS)- Thread.sleep(5000) // Wait for sync-- println("[Test04] Re-login successful")-- // Step 7: Verify credential still exists- println("[Test04] Step 7: Verify credential still exists")- assertTrue(- "Credential should still exist after forced logout recovery",- openAndVerifyItem(uniqueName, "[email protected]"),- )-- // Verify server revision is restored- val finalRevisions = TestUserRegistration.getVaultRevisionsByUsername(testUser.username)- val finalRevision = finalRevisions.second- println("[Test04] Final server revision: $finalRevision")-- assertTrue(- "Server revision should be restored after forced logout recovery",- finalRevision >= revisionBeforeLogout,- )-- println("[Test04] SUCCESS - Forced logout recovery verified!")- println("[Test04] Revision flow: $revisionBeforeLogout (before) → $revisionAfterRollback (rollback) → $finalRevision (recovered)")- }-- // endregion-- // region Helper Methods-- /**- * Logs in with test user at the beginning of a test.- * Always logs out first if already logged in to ensure we're using the correct test user.- */- private fun loginWithTestUser(testUser: TestUser) {- // Wait for app to settle - poll for any expected screen- val startTime = System.currentTimeMillis()- val maxWaitTime = 15000L-- while (System.currentTimeMillis() - startTime < maxWaitTime) {- if (device.findByTestId("unlock-screen") != null ||- device.findByTestId("login-screen") != null ||- device.findByTestId("items-screen") != null- ) {- break- }- Thread.sleep(200)- }-- // Handle unlock screen - logout to start fresh- if (device.existsByTestId("unlock-screen")) {- println("[Helper] Unlock screen detected - logging out to login fresh with test user")-- if (device.tapTestId("logout-button")) {- // Handle logout confirmation- val confirmButton = device.waitForText("Logout", TestConfiguration.SHORT_TIMEOUT_MS)- confirmButton?.click()- }-- device.waitForTestId("login-screen", TestConfiguration.DEFAULT_TIMEOUT_MS)- }-- // Check if we're on login screen- if (device.existsByTestId("login-screen")) {- performLogin(testUser)- return- }-- // Check if already on items screen- if (device.existsByTestId("items-screen")) {- println("[Helper] Already on items screen, assuming correct user is logged in")- return- }-- println("[Helper] Unknown app state after waiting, test may fail")- }-- /**- * Unlocks the vault if the unlock screen is displayed.- */- private fun unlockVaultIfNeeded(testUser: TestUser) {- val unlockScreen = device.waitForTestId("unlock-screen", TestConfiguration.SHORT_TIMEOUT_MS)- if (unlockScreen == null) {- if (device.existsByTestId("items-screen")) {- println("[Helper] Already on items screen, no unlock needed")- } else {- println("[Helper] Not on unlock or items screen, proceeding anyway")- }- return- }-- println("[Helper] Unlock screen detected - entering password to unlock")-- device.tapTestId("unlock-password-input")- device.typeIntoTestId("unlock-password-input", testUser.password)- device.hideKeyboard()- device.tapTestId("unlock-button")-- device.waitForTestId("items-screen", TestConfiguration.EXTENDED_TIMEOUT_MS)- }-- /**- * Performs login with the given test user credentials.- */- private fun performLogin(testUser: TestUser) {- // Check if API URL is already configured to localhost- val serverUrlLink = device.findByTestId("server-url-link")- var needsApiConfig = true-- if (serverUrlLink != null) {- val urlText = serverUrlLink.text ?: ""- if (urlText.contains("localhost")) {- println("[Helper] API URL already configured to localhost, skipping API configuration")- needsApiConfig = false- } else {- println("[Helper] API URL shows '$urlText', need to configure to localhost")- }- }-- if (needsApiConfig) {- if (device.tapTestId("server-url-link-button")) {- if (device.waitForTestId("api-option-custom", TestConfiguration.DEFAULT_TIMEOUT_MS) != null) {- device.tapTestId("api-option-custom")-- if (device.waitForTestId("custom-api-url-input") != null) {- device.tapTestId("custom-api-url-input")- device.typeIntoTestId("custom-api-url-input", TestConfiguration.apiUrl)- println("[Helper] Configured API URL: ${TestConfiguration.apiUrl}")- }-- device.hideKeyboard()- device.tapTestId("back-button")- }- }- }-- // Wait for login screen- device.waitForTestId("login-screen")-- // Enter credentials- device.typeIntoTestId("username-input", testUser.username)- device.tapTestId("password-input")- device.typeIntoTestId("password-input", testUser.password)- device.hideKeyboard()- device.tapTestId("login-button")-- // Wait for items screen- device.waitForTestId("items-screen", TestConfiguration.EXTENDED_TIMEOUT_MS)- }-- /**- * Parameters for creating a new item.- */- data class CreateItemParams(- val name: String,- val serviceUrl: String = "https://example.com",- val email: String = "[email protected]",- val username: String? = null,- )-- /**- * Creates a new item with the given parameters.- */- private fun createItem(params: CreateItemParams): Boolean {- println("[Helper] Creating item: ${params.name}")-- // Tap add button- if (!device.tapTestId("add-item-button")) {- println("[Helper] Failed to tap add button")- return false- }-- if (device.waitForTestId("add-edit-screen", TestConfiguration.DEFAULT_TIMEOUT_MS) == null) {- println("[Helper] Add/edit screen did not appear")- return false- }-- // Fill item name- device.scrollToTestId("item-name-input")- device.tapTestId("item-name-input")- device.typeIntoTestId("item-name-input", params.name)-- // Fill service URL- device.scrollToTestId("service-url-input")- device.tapTestId("service-url-input")- device.typeIntoTestId("service-url-input", params.serviceUrl)-- // Add email- device.scrollToTestId("add-email-button")- device.tapTestId("add-email-button")-- device.scrollToTestId("login-email-input")- device.tapTestId("login-email-input")- device.typeIntoTestId("login-email-input", params.email)-- // Optionally add username- if (params.username != null) {- device.scrollToTestId("login-username-input")- if (device.existsByTestId("login-username-input")) {- device.tapTestId("login-username-input")- device.typeIntoTestId("login-username-input", params.username)- }- }-- device.hideKeyboard()-- // Save item- device.tapTestId("save-button")-- if (device.waitForText("Login credentials", TestConfiguration.DEFAULT_TIMEOUT_MS) == null) {- println("[Helper] Item detail screen did not appear after save")- return false- }-- // Return to items list- Thread.sleep(1000)- device.tapTestId("back-button")-- if (device.waitForTestId("items-screen", TestConfiguration.DEFAULT_TIMEOUT_MS) == null) {- println("[Helper] Did not return to items screen")- return false- }-- // Wait for list to populate- Thread.sleep(2000)-- println("[Helper] Item '${params.name}' created successfully")- return true- }-- /**- * Verifies that an item with the given name exists in the items list.- */- private fun verifyItemExistsInList(name: String): Boolean {- val itemFound = device.scrollToText(name) != null ||- device.waitForText(name, TestConfiguration.DEFAULT_TIMEOUT_MS) != null-- if (!itemFound) {- println("[Helper] Item '$name' not found in list")- return false- }-- println("[Helper] Item '$name' found in list")- return true- }-- /**- * Opens an item from the list and verifies its details.- */- private fun openAndVerifyItem(name: String, expectedEmail: String? = null): Boolean {- val itemCard = device.scrollToText(name) ?: device.findByText(name)-- if (itemCard == null) {- println("[Helper] Item '$name' not found in list")- return false- }-- itemCard.click()-- if (device.waitForText("Login credentials", TestConfiguration.DEFAULT_TIMEOUT_MS) == null) {- println("[Helper] Item detail screen did not appear")- return false- }-- if (expectedEmail != null) {- if (device.waitForTextContains(expectedEmail) == null) {- println("[Helper] Expected email '$expectedEmail' not found")- return false- }- }-- println("[Helper] Item '$name' verified successfully")- return true- }-- // endregion-}diff --git a/apps/mobile-app/android/app/src/androidTest/java/net/aliasvault/app/TestConfiguration.kt b/apps/mobile-app/android/app/src/androidTest/java/net/aliasvault/app/TestConfiguration.ktdeleted file mode 100644index 48d4cb954..000000000--- a/apps/mobile-app/android/app/src/androidTest/java/net/aliasvault/app/TestConfiguration.kt+++ /dev/null@@ -1,49 +0,0 @@-package net.aliasvault.app--/**- * Configuration for E2E UI tests.- */-object TestConfiguration {- /**- * API URL for testing (defaults to local development server).- * Can be overridden by setting the API_URL instrumentation argument.- */- val apiUrl: String- get() = System.getProperty("API_URL") ?: "http://10.0.2.2:5100"-- /**- * Generate a unique name for test items.- */- fun generateUniqueName(prefix: String = "E2E Test"): String {- val timestamp = System.currentTimeMillis()- return "$prefix $timestamp"- }-- /**- * Default timeout for element waiting (milliseconds).- */- const val DEFAULT_TIMEOUT_MS = 10_000L-- /**- * Extended timeout for operations that may take longer (like login with network).- */- const val EXTENDED_TIMEOUT_MS = 30_000L-- /**- * Short timeout for quick checks (milliseconds).- */- const val SHORT_TIMEOUT_MS = 2_000L-- /**- * Default Argon2Id encryption settings matching server defaults.- */- object EncryptionDefaults {- const val TYPE = "Argon2Id"- const val ITERATIONS = 5- const val MEMORY_SIZE = 65536- const val PARALLELISM = 1-- val settingsJson: String- get() = """{"DegreeOfParallelism":$PARALLELISM,"MemorySize":$MEMORY_SIZE,"Iterations":$ITERATIONS}"""- }-}diff --git a/apps/mobile-app/android/app/src/androidTest/java/net/aliasvault/app/TestUserRegistration.kt b/apps/mobile-app/android/app/src/androidTest/java/net/aliasvault/app/TestUserRegistration.ktdeleted file mode 100644index 4d5d61848..000000000--- a/apps/mobile-app/android/app/src/androidTest/java/net/aliasvault/app/TestUserRegistration.kt+++ /dev/null@@ -1,544 +0,0 @@-package net.aliasvault.app--import android.database.sqlite.SQLiteDatabase-import android.util.Base64-import android.util.Log-import kotlinx.coroutines.Dispatchers-import kotlinx.coroutines.withContext-import net.aliasvault.app.vaultstore.models.VaultSql-import net.aliasvault.app.vaultstore.models.VaultVersions-import org.json.JSONArray-import org.json.JSONObject-import uniffi.aliasvault_core.argon2DeriveKey-import uniffi.aliasvault_core.srpDerivePrivateKey-import uniffi.aliasvault_core.srpDeriveVerifier-import uniffi.aliasvault_core.srpGenerateSalt-import java.io.File-import java.net.HttpURLConnection-import java.net.URL-import java.nio.charset.StandardCharsets-import java.security.KeyPairGenerator-import java.security.SecureRandom-import javax.crypto.Cipher-import javax.crypto.spec.GCMParameterSpec-import javax.crypto.spec.SecretKeySpec--/**- * Test user credentials and token.- */-data class TestUser(- val username: String,- val password: String,- val token: String,- val refreshToken: String,-)--/**- * Token response from the API.- */-data class TokenResponse(- val token: String,- val refreshToken: String,-)--/**- * Test user registration helper using SRP protocol.- * Uses the Rust core library for SRP operations via UniFFI bindings.- */-object TestUserRegistration {- private const val TAG = "TestUserRegistration"-- /**- * API URL for testing.- */- val apiUrl: String- get() = TestConfiguration.apiUrl-- // region Username/Password Generation-- /**- * Generate a random test username.- */- fun generateTestUsername(): String {- val chars = "abcdefghijklmnopqrstuvwxyz0123456789"- val randomPart = (1..10)- .map { chars.random() }- .joinToString("")- return "[email protected]"- }-- /**- * Generate a test password.- * Uses a static password for easier debugging and test reproducibility.- */- fun generateTestPassword(): String = "password"-- /**- * Normalize username by converting to lowercase and trimming whitespace.- */- fun normalizeUsername(username: String): String =- username.lowercase().trim()-- // endregion-- // region Hex Conversion-- /**- * Convert ByteArray to uppercase hex string.- */- fun bytesToHex(data: ByteArray): String =- data.joinToString("") { "%02X".format(it) }-- // endregion-- // region Registration-- /**- * Register a new test user via the API using SRP protocol.- * Uses Rust core for all SRP operations.- */- suspend fun registerTestUser(- apiBaseUrl: String,- username: String,- password: String,- ): TokenResponse = withContext(Dispatchers.IO) {- val baseUrl = apiBaseUrl.trimEnd('/') + "/v1/"- val normalizedUsername = normalizeUsername(username)-- // Generate salt using Rust core- val salt = srpGenerateSalt()-- // Derive key from password using Rust core Argon2, against the parameters the request declares- val encryptionKey = argon2DeriveKey(password, salt, TestConfiguration.EncryptionDefaults.settingsJson)- val passwordHashHex = bytesToHex(encryptionKey)-- // Derive SRP private key and verifier using Rust core- val privateKey = srpDerivePrivateKey(salt, normalizedUsername, passwordHashHex)- val verifier = srpDeriveVerifier(privateKey)-- // Build registration request- val registerRequest = JSONObject().apply {- put("username", normalizedUsername)- put("salt", salt)- put("verifier", verifier)- put("encryptionType", TestConfiguration.EncryptionDefaults.TYPE)- put("encryptionSettings", TestConfiguration.EncryptionDefaults.settingsJson)- }-- // Send registration request- val connection = URL("${baseUrl}Auth/register").openConnection() as HttpURLConnection- try {- connection.requestMethod = "POST"- connection.setRequestProperty("Content-Type", "application/json")- connection.doOutput = true-- connection.outputStream.bufferedWriter().use {- it.write(registerRequest.toString())- }-- if (connection.responseCode != 200) {- val errorBody = try {- connection.errorStream?.bufferedReader()?.readText() ?: "Unknown error"- } catch (e: Exception) {- "HTTP ${connection.responseCode}"- }- throw Exception("Registration failed: $errorBody")- }-- val responseBody = connection.inputStream.bufferedReader().readText()- val json = JSONObject(responseBody)-- val tokenResponse = TokenResponse(- token = json.getString("token"),- refreshToken = json.getString("refreshToken"),- )-- // Upload initial empty vault- uploadInitialVault(- apiBaseUrl = apiBaseUrl,- token = tokenResponse.token,- username = normalizedUsername,- encryptionKey = encryptionKey,- )-- tokenResponse- } finally {- connection.disconnect()- }- }-- // endregion-- // region Vault Upload-- /**- * Upload an initial empty vault to the server.- */- private suspend fun uploadInitialVault(- apiBaseUrl: String,- token: String,- username: String,- encryptionKey: ByteArray,- ) = withContext(Dispatchers.IO) {- val baseUrl = apiBaseUrl.trimEnd('/') + "/v1/"-- // Create empty vault database- val vaultBase64 = createEmptyVaultDatabase()-- // Encrypt the vault using AES-GCM- val encryptedVault = symmetricEncrypt(vaultBase64, encryptionKey)-- // Generate RSA key pair for the vault- val rsaKeyPair = generateRsaKeyPair()-- // Get current timestamp in ISO8601 format- val now = java.text.SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'", java.util.Locale.US)- .apply { timeZone = java.util.TimeZone.getTimeZone("UTC") }- .format(java.util.Date())-- // Build vault upload request- val vaultRequest = JSONObject().apply {- put("username", normalizeUsername(username))- put("blob", encryptedVault)- put("version", VaultVersions.latestVersion)- put("currentRevisionNumber", VaultVersions.latestRevision)- put("encryptionPublicKey", rsaKeyPair.first)- put("credentialsCount", 0)- put("emailAddressList", JSONArray())- put("privateEmailDomainList", JSONArray())- put("hiddenPrivateEmailDomainList", JSONArray())- put("publicEmailDomainList", JSONArray())- put("createdAt", now)- put("updatedAt", now)- }-- val connection = URL("${baseUrl}Vault").openConnection() as HttpURLConnection- try {- connection.requestMethod = "POST"- connection.setRequestProperty("Content-Type", "application/json")- connection.setRequestProperty("Authorization", "Bearer $token")- connection.doOutput = true-- connection.outputStream.bufferedWriter().use {- it.write(vaultRequest.toString())- }-- if (connection.responseCode != 200) {- val errorBody = try {- connection.errorStream?.bufferedReader()?.readText() ?: "Unknown error"- } catch (e: Exception) {- "HTTP ${connection.responseCode}"- }- throw Exception("Failed to upload vault: $errorBody")- }- } finally {- connection.disconnect()- }- }-- // endregion-- // region Encryption Helpers-- /**- * Encrypt data using AES-GCM.- */- private fun symmetricEncrypt(plaintext: String, key: ByteArray): String {- val iv = ByteArray(12)- SecureRandom().nextBytes(iv)-- val cipher = Cipher.getInstance("AES/GCM/NoPadding")- val keySpec = SecretKeySpec(key, "AES")- val gcmSpec = GCMParameterSpec(128, iv)-- cipher.init(Cipher.ENCRYPT_MODE, keySpec, gcmSpec)- val encrypted = cipher.doFinal(plaintext.toByteArray(StandardCharsets.UTF_8))-- // Combined format: nonce + ciphertext + tag- val combined = ByteArray(iv.size + encrypted.size)- System.arraycopy(iv, 0, combined, 0, iv.size)- System.arraycopy(encrypted, 0, combined, iv.size, encrypted.size)-- return Base64.encodeToString(combined, Base64.NO_WRAP)- }-- /**- * Generate RSA key pair for vault encryption.- */- private fun generateRsaKeyPair(): Pair<String, String> {- val keyPairGenerator = KeyPairGenerator.getInstance("RSA")- keyPairGenerator.initialize(2048)- val keyPair = keyPairGenerator.generateKeyPair()-- val publicKey = keyPair.public as java.security.interfaces.RSAPublicKey- val privateKey = keyPair.private as java.security.interfaces.RSAPrivateKey-- // Export as simple JWK format- val publicKeyJwk = JSONObject().apply {- put("kty", "RSA")- put("key_ops", JSONArray().put("encrypt"))- put("ext", true)- put(- "n",- Base64.encodeToString(- publicKey.modulus.toByteArray(),- Base64.URL_SAFE or Base64.NO_PADDING or Base64.NO_WRAP,- ),- )- put(- "e",- Base64.encodeToString(- publicKey.publicExponent.toByteArray(),- Base64.URL_SAFE or Base64.NO_PADDING or Base64.NO_WRAP,- ),- )- }-- val privateKeyJwk = JSONObject().apply {- put("kty", "RSA")- put("key_ops", JSONArray().put("decrypt"))- put("ext", true)- put(- "n",- Base64.encodeToString(- privateKey.modulus.toByteArray(),- Base64.URL_SAFE or Base64.NO_PADDING or Base64.NO_WRAP,- ),- )- }-- return Pair(publicKeyJwk.toString(), privateKeyJwk.toString())- }-- // endregion-- // region Empty Vault Creation-- /**- * Split a SQL script into the individual statements execSQL accepts, one at a time.- *- * A CREATE TRIGGER carries its own semicolons inside its BEGIN ... END body, so splitting the script- * on ";" alone would cut the trigger into fragments that are not valid SQL on their own. A trigger- * therefore runs until its terminating END instead.- */- private fun splitSqlStatements(sql: String): List<String> {- val statements = mutableListOf<String>()- val current = StringBuilder()- var inTriggerBody = false-- for (line in sql.lines()) {- val trimmed = line.trim()- if (trimmed.isEmpty()) {- continue- }-- current.appendLine(line)- val upper = trimmed.uppercase()-- if (!inTriggerBody && upper.startsWith("CREATE TRIGGER")) {- inTriggerBody = true- continue- }-- val statementEnded = if (inTriggerBody) upper == "END;" else trimmed.endsWith(";")- if (statementEnded) {- statements.add(current.toString().trim().trimEnd(';'))- current.setLength(0)- inTriggerBody = false- }- }-- return statements.filter { it.isNotEmpty() }- }-- /**- * Create an empty vault database as base64 string.- */- private fun createEmptyVaultDatabase(): String {- val tempFile = File.createTempFile("vault", ".db")- try {- val db = SQLiteDatabase.openOrCreateDatabase(tempFile, null)- try {- // Execute the complete schema SQL- for (statement in splitSqlStatements(VaultSql.completeSchema)) {- db.execSQL("$statement;")- }- } finally {- db.close()- }-- // Read the database file and encode as base64- val dbBytes = tempFile.readBytes()- return Base64.encodeToString(dbBytes, Base64.NO_WRAP)- } finally {- tempFile.delete()- }- }-- // endregion-- // region Public API-- /**- * Create a test user with random credentials.- */- suspend fun createTestUser(apiBaseUrl: String? = null): TestUser {- val url = apiBaseUrl ?: apiUrl- val username = generateTestUsername()- val password = generateTestPassword()-- val tokenResponse = registerTestUser(- apiBaseUrl = url,- username = username,- password = password,- )-- return TestUser(- username = username,- password = password,- token = tokenResponse.token,- refreshToken = tokenResponse.refreshToken,- )- }-- /**- * Check if the API is available.- */- suspend fun isApiAvailable(apiBaseUrl: String? = null): Boolean = withContext(Dispatchers.IO) {- val url = (apiBaseUrl ?: apiUrl).trimEnd('/') + "/v1/"-- try {- val connection = URL("${url}Auth/status").openConnection() as HttpURLConnection- connection.requestMethod = "GET"- connection.setRequestProperty("Content-Type", "application/json")- connection.connectTimeout = 5000- connection.readTimeout = 5000-- val responseCode = connection.responseCode- connection.disconnect()-- // Status endpoint returns 401 when not authenticated, but that means API is running- responseCode == 401 || responseCode == 200- } catch (e: Exception) {- Log.e(TAG, "API not available", e)- false- }- }-- // endregion-- // region Test Helpers (DEV API Endpoints)-- /**- * Get vault revision information for a user by username.- * This is an anonymous endpoint that doesn't require authentication.- */- suspend fun getVaultRevisionsByUsername(- username: String,- apiBaseUrl: String? = null,- ): Pair<Int, Int> = withContext(Dispatchers.IO) {- val url = (apiBaseUrl ?: apiUrl).trimEnd('/') + "/v1/"- val encodedUsername = java.net.URLEncoder.encode(username, "UTF-8")-- val connection =- URL("${url}Test/vault-revisions/by-username/$encodedUsername").openConnection() as HttpURLConnection- try {- connection.requestMethod = "GET"- connection.setRequestProperty("Content-Type", "application/json")-- if (connection.responseCode != 200) {- throw Exception("Failed to get vault revisions: HTTP ${connection.responseCode}")- }-- val responseBody = connection.inputStream.bufferedReader().readText()- val json = JSONObject(responseBody)-- Pair(- json.optInt("count", 0),- json.optInt("currentRevision", 0),- )- } finally {- connection.disconnect()- }- }-- /**- * Delete the newest vault revisions for a user by username.- */- suspend fun deleteVaultRevisionsByUsername(- username: String,- count: Int,- apiBaseUrl: String? = null,- ): Int = withContext(Dispatchers.IO) {- val url = (apiBaseUrl ?: apiUrl).trimEnd('/') + "/v1/"- val encodedUsername = java.net.URLEncoder.encode(username, "UTF-8")-- val connection =- URL("${url}Test/vault-revisions/by-username/$encodedUsername/$count").openConnection() as HttpURLConnection- try {- connection.requestMethod = "DELETE"- connection.setRequestProperty("Content-Type", "application/json")-- if (connection.responseCode != 200) {- throw Exception("Failed to delete vault revisions: HTTP ${connection.responseCode}")- }-- val responseBody = connection.inputStream.bufferedReader().readText()- val json = JSONObject(responseBody)-- json.optInt("deleted", 0)- } finally {- connection.disconnect()- }- }-- /**- * Block a user's account by username.- */- suspend fun blockUserByUsername(- username: String,- apiBaseUrl: String? = null,- ) = withContext(Dispatchers.IO) {- val url = (apiBaseUrl ?: apiUrl).trimEnd('/') + "/v1/"- val encodedUsername = java.net.URLEncoder.encode(username, "UTF-8")-- val connection =- URL("${url}Test/block-user/by-username/$encodedUsername").openConnection() as HttpURLConnection- try {- connection.requestMethod = "POST"- connection.setRequestProperty("Content-Type", "application/json")-- if (connection.responseCode != 200) {- throw Exception("Failed to block user: HTTP ${connection.responseCode}")- }- } finally {- connection.disconnect()- }- }-- /**- * Unblock a user's account by username.- */- suspend fun unblockUserByUsername(- username: String,- apiBaseUrl: String? = null,- ) = withContext(Dispatchers.IO) {- val url = (apiBaseUrl ?: apiUrl).trimEnd('/') + "/v1/"- val encodedUsername = java.net.URLEncoder.encode(username, "UTF-8")-- val connection =- URL("${url}Test/unblock-user/by-username/$encodedUsername").openConnection() as HttpURLConnection- try {- connection.requestMethod = "POST"- connection.setRequestProperty("Content-Type", "application/json")-- if (connection.responseCode != 200) {- throw Exception("Failed to unblock user: HTTP ${connection.responseCode}")- }- } finally {- connection.disconnect()- }- }-- // endregion-}diff --git a/apps/mobile-app/android/app/src/androidTest/java/net/aliasvault/app/UITestHelpers.kt b/apps/mobile-app/android/app/src/androidTest/java/net/aliasvault/app/UITestHelpers.ktdeleted file mode 100644index 0ef30571a..000000000--- a/apps/mobile-app/android/app/src/androidTest/java/net/aliasvault/app/UITestHelpers.kt+++ /dev/null@@ -1,390 +0,0 @@-package net.aliasvault.app--import android.util.Log-import androidx.test.uiautomator.By-import androidx.test.uiautomator.UiDevice-import androidx.test.uiautomator.UiObject2-import androidx.test.uiautomator.Until--/**- * UI test helper functions for Android instrumented tests.- * Provides utilities for interacting with React Native views via UI Automator.- */-object UITestHelpers {- private const val TAG = "UITestHelpers"-- // region Element Finding-- /**- * Find an element by its testID.- * React Native on Android exposes testID via resource-id (without package prefix).- */- fun UiDevice.findByTestId(testId: String): UiObject2? {- // Primary: resource-id without package prefix - this is where RN maps testID- return findObject(By.res(testId))- }-- /**- * Find an element by text content.- */- fun UiDevice.findByText(text: String): UiObject2? {- return findObject(By.text(text))- }-- /**- * Find an element by text containing a substring.- */- fun UiDevice.findByTextContains(text: String): UiObject2? {- return findObject(By.textContains(text))- }-- // endregion-- // region Waiting-- /**- * Wait for an element with testID to exist.- * Uses resource-id without package prefix (By.res) which is where React Native maps testID.- */- fun UiDevice.waitForTestId(- testId: String,- timeout: Long = TestConfiguration.DEFAULT_TIMEOUT_MS,- ): UiObject2? {- // Primary: resource-id without package prefix - this is where RN maps testID- val result = wait(Until.findObject(By.res(testId)), timeout)- if (result == null) {- Log.w(TAG, "Timeout waiting for testId: $testId")- }- return result- }-- /**- * Wait for an element with text to exist.- */- fun UiDevice.waitForText(- text: String,- timeout: Long = TestConfiguration.SHORT_TIMEOUT_MS,- ): UiObject2? {- val result = wait(Until.findObject(By.text(text)), timeout)- if (result == null) {- Log.w(TAG, "Timeout waiting for text: $text")- }- return result- }-- /**- * Wait for an element with text containing substring to exist.- */- fun UiDevice.waitForTextContains(- text: String,- timeout: Long = TestConfiguration.SHORT_TIMEOUT_MS,- ): UiObject2? {- val result = wait(Until.findObject(By.textContains(text)), timeout)- if (result == null) {- Log.w(TAG, "Timeout waiting for text containing: $text")- }- return result- }-- /**- * Wait for an element to be gone.- */- fun UiDevice.waitForTestIdGone(- testId: String,- timeout: Long = TestConfiguration.SHORT_TIMEOUT_MS,- ): Boolean {- // Primary: resource-id without package prefix - this is where RN maps testID- return wait(Until.gone(By.res(testId)), timeout) ?: true- }-- /**- * Wait for text to be gone.- */- fun UiDevice.waitForTextGone(- text: String,- timeout: Long = TestConfiguration.SHORT_TIMEOUT_MS,- ): Boolean {- return wait(Until.gone(By.text(text)), timeout) ?: false- }-- // endregion-- // region Existence Checks-- /**- * Check if an element with testID exists.- */- fun UiDevice.existsByTestId(testId: String): Boolean {- return findByTestId(testId) != null- }-- /**- * Check if an element with text exists.- */- fun UiDevice.existsByText(text: String): Boolean {- return findByText(text) != null- }-- /**- * Check if an element with text containing substring exists.- */- fun UiDevice.existsByTextContains(text: String): Boolean {- return findByTextContains(text) != null- }-- // endregion-- // region Actions-- /**- * Tap on an element with testID.- */- fun UiDevice.tapTestId(testId: String): Boolean {- // Try immediate find first (no waiting)- val element = findByTestId(testId)- return if (element != null) {- element.click()- true- } else {- Log.e(TAG, "Failed to tap testId: $testId - element not found")- false- }- }-- /**- * Tap on an element with text.- */- fun UiDevice.tapText(text: String): Boolean {- // Try immediate find first (no waiting)- val element = findByText(text)- return if (element != null) {- element.click()- true- } else {- Log.e(TAG, "Failed to tap text: $text - element not found")- false- }- }-- /**- * Type text into an element with testID.- */- fun UiDevice.typeIntoTestId(testId: String, text: String): Boolean {- // Try immediate find first (no waiting)- val element = findByTestId(testId)- return if (element != null) {- element.click()- Thread.sleep(100) // Small delay for focus- element.text = text- true- } else {- Log.e(TAG, "Failed to type into testId: $testId - element not found")- false- }- }-- /**- * Clear text in an element with testID.- */- fun UiDevice.clearTestId(testId: String): Boolean {- // Try immediate find first (no waiting)- val element = findByTestId(testId)- return if (element != null) {- element.click()- Thread.sleep(100) // Small delay for focus- element.clear()- true- } else {- Log.e(TAG, "Failed to clear testId: $testId - element not found")- false- }- }-- // endregion-- // region Scrolling-- /**- * Scroll down to find an element with testID.- */- fun UiDevice.scrollToTestId(- testId: String,- maxScrolls: Int = 5,- ): UiObject2? {- repeat(maxScrolls) {- findByTestId(testId)?.let { return it }- swipe(- displayWidth / 2,- displayHeight * 3 / 4,- displayWidth / 2,- displayHeight / 4,- 10,- )- Thread.sleep(300) // Wait for scroll to settle- }- return findByTestId(testId)- }-- /**- * Scroll down to find an element with text.- */- fun UiDevice.scrollToText(- text: String,- maxScrolls: Int = 5,- ): UiObject2? {- repeat(maxScrolls) {- findByText(text)?.let { return it }- swipe(- displayWidth / 2,- displayHeight * 3 / 4,- displayWidth / 2,- displayHeight / 4,- 10,- )- Thread.sleep(300) // Wait for scroll to settle- }- return findByText(text)- }-- // endregion-- // region Navigation-- /**- * Navigate back using the device back button.- */- fun UiDevice.navigateBack() {- pressBack()- Thread.sleep(500) // Wait for navigation animation- }-- /**- * Navigate home using the device home button.- */- fun UiDevice.navigateHome() {- pressHome()- Thread.sleep(500) // Wait for navigation animation- }-- // endregion-- // region Assert Helpers-- /**- * Assert that an element with testID exists.- */- fun UiDevice.assertTestIdExists(- testId: String,- timeout: Long = TestConfiguration.DEFAULT_TIMEOUT_MS,- ) {- val element = waitForTestId(testId, timeout)- if (element == null) {- throw AssertionError("Expected element with testId '$testId' to exist, but it was not found")- }- }-- /**- * Assert that an element with text exists.- */- fun UiDevice.assertTextExists(- text: String,- timeout: Long = TestConfiguration.DEFAULT_TIMEOUT_MS,- ) {- val element = waitForText(text, timeout)- if (element == null) {- throw AssertionError("Expected element with text '$text' to exist, but it was not found")- }- }-- /**- * Assert that an element with text containing substring exists.- */- fun UiDevice.assertTextContains(- text: String,- timeout: Long = TestConfiguration.DEFAULT_TIMEOUT_MS,- ) {- val element = waitForTextContains(text, timeout)- if (element == null) {- throw AssertionError(- "Expected element containing text '$text' to exist, but it was not found",- )- }- }-- /**- * Assert that an element with testID does not exist.- */- fun UiDevice.assertTestIdNotExists(testId: String) {- val element = findByTestId(testId)- if (element != null) {- throw AssertionError("Expected element with testId '$testId' to NOT exist, but it was found")- }- }-- /**- * Assert that an element with text does not exist.- */- fun UiDevice.assertTextNotExists(text: String) {- val element = findByText(text)- if (element != null) {- throw AssertionError("Expected element with text '$text' to NOT exist, but it was found")- }- }-- // endregion-- // region Text Field Helpers-- /**- * Get the text value from an element with testID.- */- fun UiDevice.getTextFromTestId(testId: String): String? {- return findByTestId(testId)?.text- }-- /**- * Check if a text field with testID has specific text.- */- fun UiDevice.testIdHasText(testId: String, expectedText: String): Boolean {- return findByTestId(testId)?.text == expectedText- }-- // endregion-- // region Keyboard-- /**- * Hide the keyboard if visible.- */- fun UiDevice.hideKeyboard() {- pressBack()- Thread.sleep(200)- }-- // endregion-- // region Sleep Helpers-- /**- * Short sleep for UI to update.- */- fun shortSleep() {- Thread.sleep(500)- }-- /**- * Medium sleep for animations.- */- fun mediumSleep() {- Thread.sleep(1000)- }-- /**- * Long sleep for network operations.- */- fun longSleep() {- Thread.sleep(2000)- }-- // endregion-}diff --git a/apps/mobile-app/ios/AliasVault.xcodeproj/project.pbxproj b/apps/mobile-app/ios/AliasVault.xcodeproj/project.pbxprojindex 5124988b8..b9d4ee377 100644--- a/apps/mobile-app/ios/AliasVault.xcodeproj/project.pbxproj+++ b/apps/mobile-app/ios/AliasVault.xcodeproj/project.pbxproj@@ -8,8 +8,6 @@/* Begin PBXBuildFile section */07A10A71081ED4937FFAA625 /* RustCoreFramework.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 61BC8C49EE3C1989FFB6DB3B /* RustCoreFramework.framework */; };- 07A10A71081ED4937FFAA626 /* RustCoreFramework.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 61BC8C49EE3C1989FFB6DB3B /* RustCoreFramework.framework */; };- 07A10A71081ED4937FFAA627 /* VaultModels.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = CEE482AA2DBE8EFE00F4A367 /* VaultModels.framework */; };1381C2F6D317F2404928BA59 /* libPods-VaultUI.a in Frameworks */ = {isa = PBXBuildFile; fileRef = C32D89DCBA51D7C8CDE51DD2 /* libPods-VaultUI.a */; };13B07FBF1A68108700A75B9A /* Images.xcassets in Resources */ = {isa = PBXBuildFile; fileRef = 13B07FB51A68108700A75B9A /* Images.xcassets */; };3D1B0279B0714C8FF732D2D3 /* libPods-AliasVault.a in Frameworks */ = {isa = PBXBuildFile; fileRef = 0E23F2188770B15FCBFEBC57 /* libPods-AliasVault.a */; };@@ -80,20 +78,6 @@remoteGlobalIDString = CEE481692DBE8AC800F4A367;remoteInfo = VaultUI;};- CE59C7642E4F47FE0024A246 /* PBXContainerItemProxy */ = {- isa = PBXContainerItemProxy;- containerPortal = 83CBB9F71A601CBA00E9B192 /* Project object */;- proxyType = 1;- remoteGlobalIDString = 13B07F861A680F5B00A75B9A;- remoteInfo = AliasVault;- };- CE59C7662E4F47FE0024A247 /* PBXContainerItemProxy */ = {- isa = PBXContainerItemProxy;- containerPortal = 83CBB9F71A601CBA00E9B192 /* Project object */;- proxyType = 1;- remoteGlobalIDString = CEE482A92DBE8EFE00F4A367;- remoteInfo = VaultModels;- };CE7782612EA1822400A75E6F /* PBXContainerItemProxy */ = {isa = PBXContainerItemProxy;containerPortal = 83CBB9F71A601CBA00E9B192 /* Project object */;@@ -206,8 +190,6 @@/* End PBXCopyFilesBuildPhase section *//* Begin PBXFileReference section */- 017AFF1289CCDC7514CC84DA /* Pods-AliasVaultUITests.release.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; name = "Pods-AliasVaultUITests.release.xcconfig"; path = "Target Support Files/Pods-AliasVaultUITests/Pods-AliasVaultUITests.release.xcconfig"; sourceTree = "<group>"; };- 0185B497D6794232013782D4 /* Pods-AliasVaultUITests.debug.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; name = "Pods-AliasVaultUITests.debug.xcconfig"; path = "Target Support Files/Pods-AliasVaultUITests/Pods-AliasVaultUITests.debug.xcconfig"; sourceTree = "<group>"; };09DFCC3CBA13D19073CBCC7F /* Pods-VaultStoreKit.debug.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; name = "Pods-VaultStoreKit.debug.xcconfig"; path = "Target Support Files/Pods-VaultStoreKit/Pods-VaultStoreKit.debug.xcconfig"; sourceTree = "<group>"; };0E23F2188770B15FCBFEBC57 /* libPods-AliasVault.a */ = {isa = PBXFileReference; explicitFileType = archive.ar; includeInIndex = 0; path = "libPods-AliasVault.a"; sourceTree = BUILT_PRODUCTS_DIR; };13B07F961A680F5B00A75B9A /* AliasVault.app */ = {isa = PBXFileReference; explicitFileType = wrapper.application; includeInIndex = 0; path = AliasVault.app; sourceTree = BUILT_PRODUCTS_DIR; };@@ -234,7 +216,6 @@962DE0FB93C9458BAFEEED60 /* AliasVault-Bridging-Header.h */ = {isa = PBXFileReference; explicitFileType = undefined; fileEncoding = 4; includeInIndex = 0; lastKnownFileType = sourcecode.c.h; name = "AliasVault-Bridging-Header.h"; path = "AliasVault/AliasVault-Bridging-Header.h"; sourceTree = "<group>"; };9668BBEEC62508A81A7214E2 /* Pods-PreviewHost.release.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; name = "Pods-PreviewHost.release.xcconfig"; path = "Target Support Files/Pods-PreviewHost/Pods-PreviewHost.release.xcconfig"; sourceTree = "<group>"; };9996E7A841D488251B139CFC /* aliasvault_core.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = aliasvault_core.swift; path = RustCoreFramework/RustCore/Generated/aliasvault_core.swift; sourceTree = "<group>"; };- 9A795EF04BF70F714FA4B0E5 /* libPods-AliasVaultUITests.a */ = {isa = PBXFileReference; explicitFileType = archive.ar; includeInIndex = 0; path = "libPods-AliasVaultUITests.a"; sourceTree = BUILT_PRODUCTS_DIR; };9E9AD944E3A0F270C797F5DD /* libPods-VaultStoreKitTests.a */ = {isa = PBXFileReference; explicitFileType = archive.ar; includeInIndex = 0; path = "libPods-VaultStoreKitTests.a"; sourceTree = BUILT_PRODUCTS_DIR; };A9E70CCF7AAA4E05B57CCCC4 /* Pods-VaultStoreKitTests.debug.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; name = "Pods-VaultStoreKitTests.debug.xcconfig"; path = "Target Support Files/Pods-VaultStoreKitTests/Pods-VaultStoreKitTests.debug.xcconfig"; sourceTree = "<group>"; };AA286B85B6C04FC6940260E9 /* SplashScreen.storyboard */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = file.storyboard; name = SplashScreen.storyboard; path = AliasVault/SplashScreen.storyboard; sourceTree = "<group>"; };@@ -249,7 +230,6 @@C9F10947D429671B08FE934C /* Info.plist */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.plist.xml; path = Info.plist; sourceTree = "<group>"; };CE26D68C2DA7FCD2006DC04D /* VaultManager.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = VaultManager.swift; sourceTree = "<group>"; };CE3AE2B02DC7ACD700E7745E /* .swiftlint.yml */ = {isa = PBXFileReference; lastKnownFileType = text.yaml; path = .swiftlint.yml; sourceTree = "<group>"; };- CE59C75F2E4F47FD0024A246 /* AliasVaultUITests.xctest */ = {isa = PBXFileReference; explicitFileType = wrapper.cfbundle; includeInIndex = 0; path = AliasVaultUITests.xctest; sourceTree = BUILT_PRODUCTS_DIR; };CE73B39F2DFC8A0C0081B6CB /* AliasVault.icon */ = {isa = PBXFileReference; lastKnownFileType = folder.iconcomposer.icon; path = AliasVault.icon; sourceTree = "<group>"; };CE77825D2EA1822400A75E6F /* VaultUtils.framework */ = {isa = PBXFileReference; explicitFileType = wrapper.framework; includeInIndex = 0; path = VaultUtils.framework; sourceTree = BUILT_PRODUCTS_DIR; };CE9A58FA2DBA982100CB0A4C /* RCTNativeVaultManager.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = RCTNativeVaultManager.h; sourceTree = "<group>"; };@@ -284,7 +264,6 @@/* End PBXFileSystemSynchronizedBuildFileExceptionSet section *//* Begin PBXFileSystemSynchronizedRootGroup section */- CE59C7602E4F47FD0024A246 /* AliasVaultUITests */ = {isa = PBXFileSystemSynchronizedRootGroup; explicitFileTypes = {}; explicitFolders = (); path = AliasVaultUITests; sourceTree = "<group>"; };CE77825E2EA1822400A75E6F /* VaultUtils */ = {isa = PBXFileSystemSynchronizedRootGroup; explicitFileTypes = {}; explicitFolders = (); path = VaultUtils; sourceTree = "<group>"; };CEE480882DBE86DC00F4A367 /* VaultStoreKit */ = {isa = PBXFileSystemSynchronizedRootGroup; explicitFileTypes = {}; explicitFolders = (); path = VaultStoreKit; sourceTree = "<group>"; };CEE480972DBE86DD00F4A367 /* VaultStoreKitTests */ = {isa = PBXFileSystemSynchronizedRootGroup; explicitFileTypes = {}; explicitFolders = (); path = VaultStoreKitTests; sourceTree = "<group>"; };@@ -315,15 +294,6 @@);runOnlyForDeploymentPostprocessing = 0;};- CE59C75C2E4F47FD0024A246 /* Frameworks */ = {- isa = PBXFrameworksBuildPhase;- buildActionMask = 2147483647;- files = (- 07A10A71081ED4937FFAA626 /* RustCoreFramework.framework in Frameworks */,- 07A10A71081ED4937FFAA627 /* VaultModels.framework in Frameworks */,- );- runOnlyForDeploymentPostprocessing = 0;- };CE77825A2EA1822400A75E6F /* Frameworks */ = {isa = PBXFrameworksBuildPhase;buildActionMask = 2147483647;@@ -424,7 +394,6 @@456ACD01FF420AE789429A59 /* libPods-VaultStoreTests.a */,C32D89DCBA51D7C8CDE51DD2 /* libPods-VaultUI.a */,9E9AD944E3A0F270C797F5DD /* libPods-VaultStoreKitTests.a */,- 9A795EF04BF70F714FA4B0E5 /* libPods-AliasVaultUITests.a */,DC967BC4C05235EC23436A20 /* iOS */,);name = Frameworks;@@ -481,7 +450,6 @@CEE480882DBE86DC00F4A367 /* VaultStoreKit */,CEE480972DBE86DD00F4A367 /* VaultStoreKitTests */,CEE4816B2DBE8AC800F4A367 /* VaultUI */,- CE59C7602E4F47FD0024A246 /* AliasVaultUITests */,CE77825E2EA1822400A75E6F /* VaultUtils */,2D16E6871FA4F8E400B85C8A /* Frameworks */,832341AE1AAA6A7D00B99B32 /* Libraries */,@@ -505,7 +473,6 @@CEE480912DBE86DD00F4A367 /* VaultStoreKitTests.xctest */,CEE4816A2DBE8AC800F4A367 /* VaultUI.framework */,CEE482AA2DBE8EFE00F4A367 /* VaultModels.framework */,- CE59C75F2E4F47FD0024A246 /* AliasVaultUITests.xctest */,CE77825D2EA1822400A75E6F /* VaultUtils.framework */,61BC8C49EE3C1989FFB6DB3B /* RustCoreFramework.framework */,);@@ -582,8 +549,6 @@1A927300CBD3BFE2B7A3CA37 /* Pods-VaultUI.release.xcconfig */,A9E70CCF7AAA4E05B57CCCC4 /* Pods-VaultStoreKitTests.debug.xcconfig */,B18F3A7E310165C29C8C6DFE /* Pods-VaultStoreKitTests.release.xcconfig */,- 0185B497D6794232013782D4 /* Pods-AliasVaultUITests.debug.xcconfig */,- 017AFF1289CCDC7514CC84DA /* Pods-AliasVaultUITests.release.xcconfig */,);path = Pods;sourceTree = "<group>";@@ -705,28 +670,6 @@productReference = 61BC8C49EE3C1989FFB6DB3B /* RustCoreFramework.framework */;productType = "com.apple.product-type.framework";};- CE59C75E2E4F47FD0024A246 /* AliasVaultUITests */ = {- isa = PBXNativeTarget;- buildConfigurationList = CE59C7682E4F47FE0024A246 /* Build configuration list for PBXNativeTarget "AliasVaultUITests" */;- buildPhases = (- CE59C75B2E4F47FD0024A246 /* Sources */,- CE59C75C2E4F47FD0024A246 /* Frameworks */,- CE59C75D2E4F47FD0024A246 /* Resources */,- );- buildRules = (- );- dependencies = (- CE59C7652E4F47FE0024A246 /* PBXTargetDependency */,- CE59C7672E4F47FE0024A247 /* PBXTargetDependency */,- );- fileSystemSynchronizedGroups = (- CE59C7602E4F47FD0024A246 /* AliasVaultUITests */,- );- name = AliasVaultUITests;- productName = AliasVaultUITests;- productReference = CE59C75F2E4F47FD0024A246 /* AliasVaultUITests.xctest */;- productType = "com.apple.product-type.bundle.ui-testing";- };CE77825C2EA1822400A75E6F /* VaultUtils */ = {isa = PBXNativeTarget;buildConfigurationList = CE7782652EA1822400A75E6F /* Build configuration list for PBXNativeTarget "VaultUtils" */;@@ -876,9 +819,6 @@13B07F861A680F5B00A75B9A = {LastSwiftMigration = 1250;};- CE59C75E2E4F47FD0024A246 = {- CreatedOnToolsVersion = 16.4;- };CE77825C2EA1822400A75E6F = {CreatedOnToolsVersion = 26.0.1;};@@ -946,7 +886,6 @@CEE480862DBE86DC00F4A367 /* VaultStoreKit */,CEE480902DBE86DD00F4A367 /* VaultStoreKitTests */,CEE481692DBE8AC800F4A367 /* VaultUI */,- CE59C75E2E4F47FD0024A246 /* AliasVaultUITests */,CEE482A92DBE8EFE00F4A367 /* VaultModels */,CE77825C2EA1822400A75E6F /* VaultUtils */,55118F9387BE1BFE21365CB8 /* RustCoreFramework */,@@ -974,13 +913,6 @@);runOnlyForDeploymentPostprocessing = 0;};- CE59C75D2E4F47FD0024A246 /* Resources */ = {- isa = PBXResourcesBuildPhase;- buildActionMask = 2147483647;- files = (- );- runOnlyForDeploymentPostprocessing = 0;- };CE77825B2EA1822400A75E6F /* Resources */ = {isa = PBXResourcesBuildPhase;buildActionMask = 2147483647;@@ -1323,13 +1255,6 @@);runOnlyForDeploymentPostprocessing = 0;};- CE59C75B2E4F47FD0024A246 /* Sources */ = {- isa = PBXSourcesBuildPhase;- buildActionMask = 2147483647;- files = (- );- runOnlyForDeploymentPostprocessing = 0;- };CE7782592EA1822400A75E6F /* Sources */ = {isa = PBXSourcesBuildPhase;buildActionMask = 2147483647;@@ -1401,16 +1326,6 @@target = CEE481692DBE8AC800F4A367 /* VaultUI */;targetProxy = CE48FD652DBEA3B800E5E3D6 /* PBXContainerItemProxy */;};- CE59C7652E4F47FE0024A246 /* PBXTargetDependency */ = {- isa = PBXTargetDependency;- target = 13B07F861A680F5B00A75B9A /* AliasVault */;- targetProxy = CE59C7642E4F47FE0024A246 /* PBXContainerItemProxy */;- };- CE59C7672E4F47FE0024A247 /* PBXTargetDependency */ = {- isa = PBXTargetDependency;- target = CEE482A92DBE8EFE00F4A367 /* VaultModels */;- targetProxy = CE59C7662E4F47FE0024A247 /* PBXContainerItemProxy */;- };CE7782622EA1822400A75E6F /* PBXTargetDependency */ = {isa = PBXTargetDependency;target = CE77825C2EA1822400A75E6F /* VaultUtils */;@@ -1791,75 +1706,6 @@};name = Debug;};- CE59C7662E4F47FE0024A246 /* Debug */ = {- isa = XCBuildConfiguration;- buildSettings = {- ASSETCATALOG_COMPILER_GENERATE_SWIFT_ASSET_SYMBOL_EXTENSIONS = YES;- CLANG_ANALYZER_NONNULL = YES;- CLANG_ANALYZER_NUMBER_OBJECT_CONVERSION = YES_AGGRESSIVE;- CLANG_CXX_LANGUAGE_STANDARD = "gnu++20";- CLANG_ENABLE_OBJC_WEAK = YES;- CLANG_WARN_DOCUMENTATION_COMMENTS = YES;- CLANG_WARN_QUOTED_INCLUDE_IN_FRAMEWORK_HEADER = YES;- CLANG_WARN_UNGUARDED_AVAILABILITY = YES_AGGRESSIVE;- CODE_SIGN_STYLE = Automatic;- CURRENT_PROJECT_VERSION = 3100100;- DEBUG_INFORMATION_FORMAT = dwarf;- DEVELOPMENT_TEAM = 8PHW4HN3F7;- ENABLE_USER_SCRIPT_SANDBOXING = YES;- GCC_C_LANGUAGE_STANDARD = gnu17;- GENERATE_INFOPLIST_FILE = YES;- IPHONEOS_DEPLOYMENT_TARGET = 17.0;- LOCALIZATION_PREFERS_STRING_CATALOGS = YES;- MARKETING_VERSION = 1.0;- MTL_ENABLE_DEBUG_INFO = INCLUDE_SOURCE;- MTL_FAST_MATH = YES;- OTHER_SWIFT_FLAGS = "$(inherited) -D EXPO_CONFIGURATION_DEBUG";- PRODUCT_BUNDLE_IDENTIFIER = net.aliasvault.app.AliasVaultUITests;- PRODUCT_NAME = "$(TARGET_NAME)";- SWIFT_ACTIVE_COMPILATION_CONDITIONS = "DEBUG $(inherited)";- SWIFT_EMIT_LOC_STRINGS = NO;- SWIFT_OPTIMIZATION_LEVEL = "-Onone";- SWIFT_VERSION = 5.0;- TARGETED_DEVICE_FAMILY = "1,2";- TEST_TARGET_NAME = AliasVault;- };- name = Debug;- };- CE59C7672E4F47FE0024A246 /* Release */ = {- isa = XCBuildConfiguration;- buildSettings = {- ASSETCATALOG_COMPILER_GENERATE_SWIFT_ASSET_SYMBOL_EXTENSIONS = YES;- CLANG_ANALYZER_NONNULL = YES;- CLANG_ANALYZER_NUMBER_OBJECT_CONVERSION = YES_AGGRESSIVE;- CLANG_CXX_LANGUAGE_STANDARD = "gnu++20";- CLANG_ENABLE_OBJC_WEAK = YES;- CLANG_WARN_DOCUMENTATION_COMMENTS = YES;- CLANG_WARN_QUOTED_INCLUDE_IN_FRAMEWORK_HEADER = YES;- CLANG_WARN_UNGUARDED_AVAILABILITY = YES_AGGRESSIVE;- CODE_SIGN_STYLE = Automatic;- COPY_PHASE_STRIP = NO;- CURRENT_PROJECT_VERSION = 3100100;- DEBUG_INFORMATION_FORMAT = "dwarf-with-dsym";- DEVELOPMENT_TEAM = 8PHW4HN3F7;- ENABLE_USER_SCRIPT_SANDBOXING = YES;- GCC_C_LANGUAGE_STANDARD = gnu17;- GENERATE_INFOPLIST_FILE = YES;- IPHONEOS_DEPLOYMENT_TARGET = 17.0;- LOCALIZATION_PREFERS_STRING_CATALOGS = YES;- MARKETING_VERSION = 1.0;- MTL_FAST_MATH = YES;- OTHER_SWIFT_FLAGS = "$(inherited) -D EXPO_CONFIGURATION_RELEASE";- PRODUCT_BUNDLE_IDENTIFIER = net.aliasvault.app.AliasVaultUITests;- PRODUCT_NAME = "$(TARGET_NAME)";- SWIFT_COMPILATION_MODE = wholemodule;- SWIFT_EMIT_LOC_STRINGS = NO;- SWIFT_VERSION = 5.0;- TARGETED_DEVICE_FAMILY = "1,2";- TEST_TARGET_NAME = AliasVault;- };- name = Release;- };CE7782662EA1822400A75E6F /* Debug */ = {isa = XCBuildConfiguration;buildSettings = {@@ -2511,15 +2357,6 @@defaultConfigurationIsVisible = 0;defaultConfigurationName = Release;};- CE59C7682E4F47FE0024A246 /* Build configuration list for PBXNativeTarget "AliasVaultUITests" */ = {- isa = XCConfigurationList;- buildConfigurations = (- CE59C7662E4F47FE0024A246 /* Debug */,- CE59C7672E4F47FE0024A246 /* Release */,- );- defaultConfigurationIsVisible = 0;- defaultConfigurationName = Release;- };CE7782652EA1822400A75E6F /* Build configuration list for PBXNativeTarget "VaultUtils" */ = {isa = XCConfigurationList;buildConfigurations = (diff --git a/apps/mobile-app/ios/AliasVault.xcodeproj/xcshareddata/xcschemes/AliasVault.xcscheme b/apps/mobile-app/ios/AliasVault.xcodeproj/xcshareddata/xcschemes/AliasVault.xcschemeindex 4bcc7ffe4..c3352f446 100644--- a/apps/mobile-app/ios/AliasVault.xcodeproj/xcshareddata/xcschemes/AliasVault.xcscheme+++ b/apps/mobile-app/ios/AliasVault.xcodeproj/xcshareddata/xcschemes/AliasVault.xcscheme@@ -39,17 +39,6 @@ReferencedContainer = "container:AliasVault.xcodeproj"></BuildableReference></TestableReference>- <TestableReference- skipped = "NO"- parallelizable = "YES">- <BuildableReference- BuildableIdentifier = "primary"- BlueprintIdentifier = "CE59C75E2E4F47FD0024A246"- BuildableName = "AliasVaultUITests.xctest"- BlueprintName = "AliasVaultUITests"- ReferencedContainer = "container:AliasVault.xcodeproj">- </BuildableReference>- </TestableReference></Testables></TestAction><LaunchActiondiff --git a/apps/mobile-app/ios/AliasVault.xcodeproj/xcshareddata/xcschemes/AliasVaultUITests.xcscheme b/apps/mobile-app/ios/AliasVault.xcodeproj/xcshareddata/xcschemes/AliasVaultUITests.xcschemedeleted file mode 100644index 6047f147f..000000000--- a/apps/mobile-app/ios/AliasVault.xcodeproj/xcshareddata/xcschemes/AliasVaultUITests.xcscheme+++ /dev/null@@ -1,108 +0,0 @@-<?xml version="1.0" encoding="UTF-8"?>-<Scheme- LastUpgradeVersion = "1620"- version = "1.7">- <BuildAction- parallelizeBuildables = "YES"- buildImplicitDependencies = "YES"- buildArchitectures = "Automatic">- <BuildActionEntries>- <BuildActionEntry- buildForTesting = "YES"- buildForRunning = "YES"- buildForProfiling = "NO"- buildForArchiving = "NO"- buildForAnalyzing = "NO">- <BuildableReference- BuildableIdentifier = "primary"- BlueprintIdentifier = "CE59C75E2E4F47FD0024A246"- BuildableName = "AliasVaultUITests.xctest"- BlueprintName = "AliasVaultUITests"- ReferencedContainer = "container:AliasVault.xcodeproj">- </BuildableReference>- </BuildActionEntry>- <BuildActionEntry- buildForTesting = "YES"- buildForRunning = "YES"- buildForProfiling = "YES"- buildForArchiving = "YES"- buildForAnalyzing = "YES">- <BuildableReference- BuildableIdentifier = "primary"- BlueprintIdentifier = "13B07F861A680F5B00A75B9A"- BuildableName = "AliasVault.app"- BlueprintName = "AliasVault"- ReferencedContainer = "container:AliasVault.xcodeproj">- </BuildableReference>- </BuildActionEntry>- </BuildActionEntries>- </BuildAction>- <TestAction- buildConfiguration = "Debug"- selectedDebuggerIdentifier = "Xcode.DebuggerFoundation.Debugger.LLDB"- selectedLauncherIdentifier = "Xcode.DebuggerFoundation.Launcher.LLDB"- shouldUseLaunchSchemeArgsEnv = "YES">- <TestPlans>- <TestPlanReference- reference = "container:AliasVaultUITests.xctestplan"- default = "YES">- </TestPlanReference>- </TestPlans>- <Testables>- <TestableReference- skipped = "NO"- parallelizable = "YES">- <BuildableReference- BuildableIdentifier = "primary"- BlueprintIdentifier = "CE59C75E2E4F47FD0024A246"- BuildableName = "AliasVaultUITests.xctest"- BlueprintName = "AliasVaultUITests"- ReferencedContainer = "container:AliasVault.xcodeproj">- </BuildableReference>- </TestableReference>- </Testables>- </TestAction>- <LaunchAction- buildConfiguration = "Debug"- selectedDebuggerIdentifier = "Xcode.DebuggerFoundation.Debugger.LLDB"- selectedLauncherIdentifier = "Xcode.DebuggerFoundation.Launcher.LLDB"- launchStyle = "0"- useCustomWorkingDirectory = "NO"- ignoresPersistentStateOnLaunch = "NO"- debugDocumentVersioning = "YES"- debugServiceExtension = "internal"- allowLocationSimulation = "YES">- <MacroExpansion>- <BuildableReference- BuildableIdentifier = "primary"- BlueprintIdentifier = "13B07F861A680F5B00A75B9A"- BuildableName = "AliasVault.app"- BlueprintName = "AliasVault"- ReferencedContainer = "container:AliasVault.xcodeproj">- </BuildableReference>- </MacroExpansion>- </LaunchAction>- <ProfileAction- buildConfiguration = "Release"- shouldUseLaunchSchemeArgsEnv = "YES"- savedToolIdentifier = ""- useCustomWorkingDirectory = "NO"- debugDocumentVersioning = "YES">- <MacroExpansion>- <BuildableReference- BuildableIdentifier = "primary"- BlueprintIdentifier = "13B07F861A680F5B00A75B9A"- BuildableName = "AliasVault.app"- BlueprintName = "AliasVault"- ReferencedContainer = "container:AliasVault.xcodeproj">- </BuildableReference>- </MacroExpansion>- </ProfileAction>- <AnalyzeAction- buildConfiguration = "Debug">- </AnalyzeAction>- <ArchiveAction- buildConfiguration = "Release"- revealArchiveInOrganizer = "YES">- </ArchiveAction>-</Scheme>diff --git a/apps/mobile-app/ios/AliasVault.xcworkspace/contents.xcworkspacedata b/apps/mobile-app/ios/AliasVault.xcworkspace/contents.xcworkspacedataindex 2bf6abb39..ea2fde653 100644--- a/apps/mobile-app/ios/AliasVault.xcworkspace/contents.xcworkspacedata+++ b/apps/mobile-app/ios/AliasVault.xcworkspace/contents.xcworkspacedata@@ -7,7 +7,4 @@<FileReflocation = "group:Pods/Pods.xcodeproj"></FileRef>- <FileRef- location = "group:AliasVaultUITests.xctestplan">- </FileRef></Workspace>diff --git a/apps/mobile-app/ios/AliasVaultUITests.xctestplan b/apps/mobile-app/ios/AliasVaultUITests.xctestplandeleted file mode 100644index f678b283e..000000000--- a/apps/mobile-app/ios/AliasVaultUITests.xctestplan+++ /dev/null@@ -1,30 +0,0 @@-{- "configurations" : [- {- "id" : "951DE877-ECA8-4F41-8726-D1278DCCDFA0",- "name" : "Test Scheme Action",- "options" : {-- }- }- ],- "defaultOptions" : {- "performanceAntipatternCheckerEnabled" : true,- "targetForVariableExpansion" : {- "containerPath" : "container:AliasVault.xcodeproj",- "identifier" : "13B07F861A680F5B00A75B9A",- "name" : "AliasVault"- }- },- "testTargets" : [- {- "parallelizable" : true,- "target" : {- "containerPath" : "container:AliasVault.xcodeproj",- "identifier" : "CE59C75E2E4F47FD0024A246",- "name" : "AliasVaultUITests"- }- }- ],- "version" : 1-}diff --git a/apps/mobile-app/ios/AliasVaultUITests/AliasVaultUITests.swift b/apps/mobile-app/ios/AliasVaultUITests/AliasVaultUITests.swiftdeleted file mode 100644index 8c1c76de8..000000000--- a/apps/mobile-app/ios/AliasVaultUITests/AliasVaultUITests.swift+++ /dev/null@@ -1,1111 +0,0 @@-import XCTest--/// E2E UI Tests for AliasVault iOS app.-///-/// These tests use dynamically created test users via the API, so no pre-configured-/// credentials are needed. Each test creates its own isolated test user to ensure-/// tests can run independently (in isolation or in sequence) with a known state.-///-/// Prerequisites:-/// - Local API server running at the URL specified in TestConfiguration.apiUrl-/// - iOS Simulator with the app installed-///-/// Note: All UI interactions use `NoIdle` variants (e.g., `waitForExistenceNoIdle`,-/// `tapNoIdle`) to avoid XCTest hanging on React Native's continuous timers/animations.-final class AliasVaultUITests: XCTestCase {- var app: XCUIApplication!-- override func setUp() {- super.setUp()- continueAfterFailure = false- app = XCUIApplication()- app.launchArguments.append("--uitest")- }-- override func tearDown() {- app = nil- super.tearDown()- }-- // MARK: - Test Setup-- /// Creates a new test user for this test.- /// Each test gets its own isolated user to ensure tests can run independently.- private func createTestUser() async throws -> TestUser {- // Check if API is available- let apiAvailable = await TestUserRegistration.isApiAvailable()- guard apiAvailable else {- throw XCTSkip("API not available at \(TestConfiguration.apiUrl). Start the local server first.")- }-- // Create a new test user for this specific test- let user = try await TestUserRegistration.createTestUser()- print("[Setup] Created test user: \(user.username)")- return user- }-- // MARK: - Error Reporting Helpers-- /// Captures a failure screenshot with descriptive name and attaches it to the test.- /// Call this in assertion failure handlers or catch blocks.- @MainActor- private func captureFailureState(context: String) {- let screenshot = XCUIScreen.main.screenshot()- let attachment = XCTAttachment(screenshot: screenshot)- attachment.name = "FAILURE-\(context)"- attachment.lifetime = .keepAlways- add(attachment)-- // Also log the current app hierarchy for debugging- let hierarchyAttachment = XCTAttachment(string: app.debugDescription)- hierarchyAttachment.name = "FAILURE-hierarchy-\(context)"- hierarchyAttachment.lifetime = .keepAlways- add(hierarchyAttachment)- }-- /// Asserts an element exists with enhanced error reporting.- /// On failure, captures screenshot and app hierarchy for CI debugging.- /// Returns true if element exists, false otherwise. Use for early returns.- @discardableResult- @MainActor- private func assertElementExists(- _ element: XCUIElement,- timeout: TimeInterval = TestConfiguration.defaultTimeout,- message: String,- context: String- ) -> Bool {- let exists = element.waitForExistenceNoIdle(timeout: timeout)- if !exists {- captureFailureState(context: context)- XCTFail("\(message). Element identifier: '\(element.identifier)', exists: \(element.exists), isHittable: \(element.isHittable)")- return false- }- return true- }-- /// Asserts text appears on screen with enhanced error reporting.- /// Returns true if text appears, false otherwise. Use for early returns.- @discardableResult- @MainActor- private func assertTextAppears(- _ text: String,- timeout: TimeInterval = TestConfiguration.defaultTimeout,- message: String,- context: String- ) -> Bool {- let appeared = app.waitForText(text, timeout: timeout)- if !appeared {- captureFailureState(context: context)- XCTFail("\(message). Expected text: '\(text)'")- return false- }- return true- }-- /// Asserts text containing substring appears with enhanced error reporting.- /// Returns true if text appears, false otherwise. Use for early returns.- @discardableResult- @MainActor- private func assertTextContaining(- _ substring: String,- timeout: TimeInterval = TestConfiguration.defaultTimeout,- message: String,- context: String- ) -> Bool {- let appeared = app.waitForTextContaining(substring, timeout: timeout)- if !appeared {- captureFailureState(context: context)- XCTFail("\(message). Expected text containing: '\(substring)'")- return false- }- return true- }-- // MARK: - Test 01: Create New Item-- /// Verifies item creation flow: opens add form, fills in details, saves, and verifies- /// the item appears in the list. Creates its own isolated test user.- @MainActor- func test01CreateItem() async throws {- let testUser = try await createTestUser()- let uniqueName = TestConfiguration.generateUniqueName(prefix: "E2E Test")- print("[Test01] Creating item with name: \(uniqueName)")-- app.launch()- loginWithTestUser(testUser)-- // Verify items screen is displayed- print("[Test01] Verifying items screen is displayed")- let itemsScreen = app.findElement(testID: "items-screen")- guard assertElementExists(- itemsScreen,- timeout: TestConfiguration.extendedTimeout,- message: "Should be on items screen after launch/unlock",- context: "01-items-screen"- ) else {- return- }-- // Create item using helper- let itemParams = CreateItemParams(- name: uniqueName,- serviceUrl: "https://example.com",- email: "[email protected]",- username: "e2euser"- )-- guard createItem(params: itemParams, contextPrefix: "01") else {- return- }-- // Verify item exists in list- guard verifyItemExistsInList(name: uniqueName, contextPrefix: "01") else {- return- }-- // Open and verify item details- guard openAndVerifyItem(name: uniqueName, expectedEmail: "[email protected]", contextPrefix: "01") else {- return- }-- let itemVerifiedScreenshot = XCUIScreen.main.screenshot()- let attachment = XCTAttachment(screenshot: itemVerifiedScreenshot)- attachment.name = "01-item-verified"- attachment.lifetime = .keepAlways- add(attachment)-- print("[Test01] Item creation and verification successful")- }-- // MARK: - Test 02: Offline Mode and Sync-- /// Verifies offline mode and sync recovery:- /// 1. Goes offline by setting API URL to invalid (simulates network failure)- /// 2. Creates a credential while offline (stored locally)- /// 3. Goes back online and triggers sync- /// 4. Verifies the credential persists after sync- ///- /// Uses debug deep links (`__debug__/set-api-url`) to toggle offline mode.- /// These only work in development builds.- @MainActor- func test02OfflineModeAndSync() async throws {- let testUser = try await createTestUser()-- app.launch()- loginWithTestUser(testUser)-- let originalApiUrl = TestConfiguration.apiUrl- let invalidApiUrl = "http://offline.invalid.localhost:9999"- let uniqueName = TestConfiguration.generateUniqueName(prefix: "Offline Test")- print("[Test02] Creating offline item with name: \(uniqueName)")-- let itemsScreen = app.findElement(testID: "items-screen")- let offlineIndicator = app.findElement(testID: "sync-indicator-offline")-- // Step 1: Verify online state- print("[Test02] Step 1: Verify online state")- guard assertElementExists(- itemsScreen,- timeout: TestConfiguration.extendedTimeout,- message: "Should be on items screen",- context: "02-items-screen"- ) else {- return- }-- let initialStateScreenshot = XCUIScreen.main.screenshot()- let attachment1 = XCTAttachment(screenshot: initialStateScreenshot)- attachment1.name = "02-1-initial-state-online"- attachment1.lifetime = .keepAlways- add(attachment1)-- // Step 2: Enable offline mode via deep link- print("[Test02] Step 2: Enable offline mode via deep link")- let encodedInvalidUrl = invalidApiUrl.addingPercentEncoding(withAllowedCharacters: .urlPathAllowed) ?? invalidApiUrl- print("[Test02] Setting API URL to invalid: \(invalidApiUrl)")- app.openDeepLink("aliasvault://open/__debug__/set-api-url/\(encodedInvalidUrl)")-- unlockVaultIfNeeded(with: testUser)-- guard assertElementExists(- itemsScreen,- timeout: 10,- message: "Should return to items screen after deep link",- context: "02-after-offline-deeplink"- ) else {- return- }-- // Trigger a sync attempt to detect offline state- app.pullToRefresh()- sleep(3)-- guard assertElementExists(- offlineIndicator,- timeout: 10,- message: "Offline indicator should appear after API URL change",- context: "02-offline-indicator"- ) else {- return- }-- let offlineModeScreenshot = XCUIScreen.main.screenshot()- let attachment2 = XCTAttachment(screenshot: offlineModeScreenshot)- attachment2.name = "02-2-offline-mode-enabled"- attachment2.lifetime = .keepAlways- add(attachment2)-- print("[Test02] Offline mode enabled successfully")-- // Step 3: Create item while offline using helper- print("[Test02] Step 3: Create item while offline")- let offlineItemParams = CreateItemParams(- name: uniqueName,- serviceUrl: "https://offline-test.example.com",- email: "[email protected]"- )-- guard createItem(params: offlineItemParams, contextPrefix: "02") else {- return- }-- // Verify item exists in list- guard verifyItemExistsInList(name: uniqueName, contextPrefix: "02") else {- return- }-- let itemInListOfflineScreenshot = XCUIScreen.main.screenshot()- let attachment3 = XCTAttachment(screenshot: itemInListOfflineScreenshot)- attachment3.name = "02-3-item-in-list-offline"- attachment3.lifetime = .keepAlways- add(attachment3)-- print("[Test02] Item created while offline and appears in list")-- // Step 4: Go back online and sync- print("[Test02] Step 4: Go back online and sync")- let encodedValidUrl = originalApiUrl.addingPercentEncoding(withAllowedCharacters: .urlPathAllowed) ?? originalApiUrl- print("[Test02] Restoring API URL to: \(originalApiUrl)")- app.openDeepLink("aliasvault://open/__debug__/set-api-url/\(encodedValidUrl)")-- unlockVaultIfNeeded(with: testUser)-- guard assertElementExists(- itemsScreen,- timeout: 10,- message: "Should return to items screen after restoring API URL",- context: "02-after-online-deeplink"- ) else {- return- }-- sleep(2)-- let backOnlineScreenshot = XCUIScreen.main.screenshot()- let attachment9 = XCTAttachment(screenshot: backOnlineScreenshot)- attachment9.name = "02-9-back-online"- attachment9.lifetime = .keepAlways- add(attachment9)-- app.pullToRefresh()- sleep(5)-- // Verify offline indicator is gone- if offlineIndicator.exists {- captureFailureState(context: "02-offline-indicator-still-present")- XCTFail("Offline indicator should be gone after sync")- }-- let syncedScreenshot = XCUIScreen.main.screenshot()- let attachment10 = XCTAttachment(screenshot: syncedScreenshot)- attachment10.name = "02-10-synced-successfully"- attachment10.lifetime = .keepAlways- add(attachment10)-- print("[Test02] Back online and synced successfully")-- // Step 5: Verify item persists after sync using helper- print("[Test02] Step 5: Verify item persists after sync")- guard openAndVerifyItem(name: uniqueName, expectedEmail: "[email protected]", contextPrefix: "02-after-sync") else {- return- }-- let itemVerifiedAfterSyncScreenshot = XCUIScreen.main.screenshot()- let attachment11 = XCTAttachment(screenshot: itemVerifiedAfterSyncScreenshot)- attachment11.name = "02-11-item-verified-after-sync"- attachment11.lifetime = .keepAlways- add(attachment11)-- print("[Test02] Offline item verified after sync - test passed")- }-- // MARK: - Test 03: RPO Recovery-- /// Verifies RPO (Recovery Point Objective) recovery scenario:- /// When the client detects that its local server revision is higher than the actual server revision- /// (simulating server data loss/rollback), it should upload its vault to recover the server state.- ///- /// This test simulates the scenario where:- /// - Client creates credentials → server has vault at revision N with the credential- /// - Server data loss occurs → we delete the latest vault revision via API- /// - Server now at revision N-1 (without the credential)- /// - Client still has the credential locally and thinks server is at revision N- /// - On next sync, client detects: "server says revision N-1, but I synced at N"- /// - Client uploads its vault to "recover" the server (RPO behavior)- /// - Credential should still exist after sync (proving upload happened, not download)- ///- /// Test flow:- /// 1. Create a credential while online (syncs to server, revision = N)- /// 2. Wait for sync to complete- /// 3. Delete the latest vault revision on server via API (simulates server data loss)- /// 4. Trigger sync - client detects server is "behind" and uploads- /// 5. Verify credential still exists (client data was uploaded, not downloaded from server)- /// 6. Verify server revision is restored via API- @MainActor- func test03RPORecovery() async throws {- let testUser = try await createTestUser()- let uniqueName = TestConfiguration.generateUniqueName(prefix: "RPO Test")- print("[Test03] Testing RPO recovery with item: \(uniqueName)")-- app.launch()- loginWithTestUser(testUser)-- let itemsScreen = app.findElement(testID: "items-screen")- var initialRevision = 0- var revisionAfterCreate = 0- var revisionAfterDelete = 0-- // Step 1: Verify initial state and get server revision- print("[Test03] Step 1: Verify initial state")- guard assertElementExists(- itemsScreen,- timeout: TestConfiguration.extendedTimeout,- message: "Should be on items screen after launch/unlock",- context: "03-items-screen"- ) else {- return- }-- let initialStateScreenshot = XCUIScreen.main.screenshot()- let attachment1 = XCTAttachment(screenshot: initialStateScreenshot)- attachment1.name = "03-1-initial-state"- attachment1.lifetime = .keepAlways- add(attachment1)-- // Get initial revision using username-based API (no auth token needed)- let initialRevisions = try await TestUserRegistration.getVaultRevisionsByUsername(username: testUser.username)- initialRevision = initialRevisions.currentRevision- print("[Test03] Initial server revision: \(initialRevision)")-- // Step 2: Create credential while online using helper- print("[Test03] Step 2: Create credential while online")- let rpoItemParams = CreateItemParams(- name: uniqueName,- serviceUrl: "https://rpo-test.example.com",- email: "[email protected]"- )-- guard createItem(params: rpoItemParams, contextPrefix: "03") else {- return- }-- sleep(1) // Wait for sync-- print("[Test03] Credential created and synced to server")-- // Verify revision increased (async)- let afterCreateRevisions = try await TestUserRegistration.getVaultRevisionsByUsername(username: testUser.username)- revisionAfterCreate = afterCreateRevisions.currentRevision- print("[Test03] Server revision after create: \(revisionAfterCreate)")-- XCTAssertGreaterThan(- revisionAfterCreate, initialRevision,- "Server revision should increase after creating credential (was \(initialRevision), now \(revisionAfterCreate))"- )-- // Step 3: Simulate server data loss- print("[Test03] Step 3: Simulate server data loss")- let afterSyncScreenshot = XCUIScreen.main.screenshot()- let attachment3 = XCTAttachment(screenshot: afterSyncScreenshot)- attachment3.name = "03-3-after-initial-sync"- attachment3.lifetime = .keepAlways- add(attachment3)-- // Delete vault revision to simulate data loss (async)- let deletedCount = try await TestUserRegistration.deleteVaultRevisionsByUsername(- username: testUser.username,- count: 1- )- print("[Test03] Deleted \(deletedCount) vault revision(s) from server to simulate data loss")-- let afterDeleteRevisions = try await TestUserRegistration.getVaultRevisionsByUsername(username: testUser.username)- revisionAfterDelete = afterDeleteRevisions.currentRevision- print("[Test03] Server revision after delete: \(revisionAfterDelete)")-- XCTAssertLessThan(- revisionAfterDelete, revisionAfterCreate,- "Server revision should decrease after deleting vault revision (was \(revisionAfterCreate), now \(revisionAfterDelete))"- )-- // Step 4: Trigger sync for RPO recovery- print("[Test03] Step 4: Trigger sync for RPO recovery")- let afterServerRollbackScreenshot = XCUIScreen.main.screenshot()- let attachment4 = XCTAttachment(screenshot: afterServerRollbackScreenshot)- attachment4.name = "03-4-after-server-rollback"- attachment4.lifetime = .keepAlways- add(attachment4)-- print("[Test03] Triggering sync - client should detect RPO scenario and upload vault")- app.pullToRefresh()- sleep(5)-- let afterRpoSyncScreenshot = XCUIScreen.main.screenshot()- let attachment5 = XCTAttachment(screenshot: afterRpoSyncScreenshot)- attachment5.name = "03-5-after-rpo-sync"- attachment5.lifetime = .keepAlways- add(attachment5)-- // Step 5: Verify credential persists after RPO recovery using helper- print("[Test03] Step 5: Verify credential persists after RPO recovery")- guard openAndVerifyItem(name: uniqueName, expectedEmail: "[email protected]", contextPrefix: "03-rpo") else {- XCTFail("Credential '\(uniqueName)' should still exist after RPO recovery - this proves client uploaded to server instead of downloading (which would have lost the credential)")- return- }-- let itemVerifiedScreenshot = XCUIScreen.main.screenshot()- let attachment6 = XCTAttachment(screenshot: itemVerifiedScreenshot)- attachment6.name = "03-6-item-verified-after-rpo"- attachment6.lifetime = .keepAlways- add(attachment6)-- // Verify server revision restored (async)- let finalRevisions = try await TestUserRegistration.getVaultRevisionsByUsername(username: testUser.username)- let finalRevision = finalRevisions.currentRevision- print("[Test03] Final server revision: \(finalRevision)")-- XCTAssertGreaterThanOrEqual(- finalRevision, revisionAfterCreate,- "Server revision should be restored after RPO recovery (expected >= \(revisionAfterCreate), got \(finalRevision))"- )-- print("[Test03] SUCCESS - Revision flow: \(initialRevision) → \(revisionAfterCreate) (create) → \(revisionAfterDelete) (rollback) → \(finalRevision) (recovered)")- }-- // MARK: - Test 04: Forced Logout Recovery-- /// Verifies forced logout recovery mechanism:- /// When a forced logout occurs (e.g., 401 unauthorized due to token invalidation),- /// the client should preserve the encrypted vault locally. On next login with the same- /// credentials, the client should detect the preserved vault and recover by uploading- /// it to the server.- ///- /// This is different from normal logout:- /// - Normal logout: User explicitly logs out → vault is cleared- /// - Forced logout: Server rejects token → vault preserved locally for recovery- ///- /// Test flow:- /// 1. Login and create a credential (vault synced to server)- /// 2. Simulate server data loss by deleting latest vault revision- /// 3. Invalidate refresh tokens via API (simulates token expiry)- /// 4. Trigger API call to cause forced logout (401)- /// 5. Verify app shows login screen with username prefilled (orphan vault preserved)- /// 6. Re-login with same credentials- /// 7. Verify credential still exists (vault was recovered from local preserved copy)- /// 8. Verify server revision is restored- @MainActor- func test04ForcedLogoutRecovery() async throws {- let testUser = try await createTestUser()- let uniqueName = TestConfiguration.generateUniqueName(prefix: "Forced Logout Test")- print("[Test04] Testing forced logout recovery with item: \(uniqueName)")-- app.launch()- loginWithTestUser(testUser)-- let itemsScreen = app.findElement(testID: "items-screen")- var revisionBeforeLogout = 0-- // Step 1: Verify initial state- print("[Test04] Step 1: Verify initial state")- guard assertElementExists(- itemsScreen,- timeout: TestConfiguration.extendedTimeout,- message: "Should be on items screen after launch/unlock",- context: "04-items-screen"- ) else {- return- }-- let initialStateScreenshot = XCUIScreen.main.screenshot()- let attachment1 = XCTAttachment(screenshot: initialStateScreenshot)- attachment1.name = "04-1-initial-state"- attachment1.lifetime = .keepAlways- add(attachment1)-- // Step 2: Create credential while online using helper- print("[Test04] Step 2: Create credential while online")- let forcedLogoutItemParams = CreateItemParams(- name: uniqueName,- serviceUrl: "https://forced-logout-test.example.com",- email: "[email protected]"- )-- guard createItem(params: forcedLogoutItemParams, contextPrefix: "04") else {- return- }-- sleep(1) // Wait for sync-- print("[Test04] Credential created and synced to server")-- // Get revision before logout using username-based API (no auth token needed)- let beforeLogoutRevisions = try await TestUserRegistration.getVaultRevisionsByUsername(username: testUser.username)- revisionBeforeLogout = beforeLogoutRevisions.currentRevision- print("[Test04] Server revision before forced logout: \(revisionBeforeLogout)")-- // Simulate server data loss (delete latest revision)- let deletedCount = try await TestUserRegistration.deleteVaultRevisionsByUsername(- username: testUser.username,- count: 1- )- print("[Test04] Deleted \(deletedCount) vault revision(s) to simulate server data loss")-- let afterRollbackRevisions = try await TestUserRegistration.getVaultRevisionsByUsername(username: testUser.username)- let revisionAfterRollback = afterRollbackRevisions.currentRevision- print("[Test04] Server revision after rollback: \(revisionAfterRollback)")-- // Step 3: Invalidate tokens and trigger forced logout- print("[Test04] Step 3: Invalidate tokens and trigger forced logout")- let beforeForcedLogoutScreenshot = XCUIScreen.main.screenshot()- let attachment3 = XCTAttachment(screenshot: beforeForcedLogoutScreenshot)- attachment3.name = "04-3-before-forced-logout"- attachment3.lifetime = .keepAlways- add(attachment3)-- // Block user via API (this will cause 401 on next auth check)- try await TestUserRegistration.blockUserByUsername(username: testUser.username)- print("[Test04] User blocked")-- // Step 4: Trigger sync to cause forced logout- print("[Test04] Step 4: Trigger sync to cause forced logout")- // Pull to refresh will trigger API call which should fail with 401- // and cause forced logout- print("[Test04] Triggering sync to cause forced logout...")- app.pullToRefresh()-- // Wait for the session expired modal to appear and dismiss it- // The modal says "Your session has expired. Please login again." with an "OK" button- let okButton = app.alerts.buttons["OK"]- let alertAppeared = okButton.waitForExistenceNoIdle(timeout: 10)- if alertAppeared {- print("[Test04] Session expired modal detected, dismissing...")- okButton.tapNoIdle()- sleep(1) // Wait for alert dismissal and navigation- } else {- print("[Test04] No session expired modal detected, continuing...")- }-- let afterForcedLogoutScreenshot = XCUIScreen.main.screenshot()- let attachment4 = XCTAttachment(screenshot: afterForcedLogoutScreenshot)- attachment4.name = "04-4-after-forced-logout"- attachment4.lifetime = .keepAlways- add(attachment4)-- // Step 5: Verify login screen with prefilled username- print("[Test04] Step 5: Verify login screen with prefilled username")- // Should be on login screen after forced logout (modal was already dismissed in step 4)- let loginScreen = app.findElement(testID: "login-screen")- guard assertElementExists(- loginScreen,- timeout: 15,- message: "Should be on login screen after forced logout",- context: "04-login-screen-after-logout"- ) else {- // Unblock user before returning to avoid leaving user in blocked state- try? await TestUserRegistration.unblockUserByUsername(username: testUser.username)- return- }-- // Verify username is prefilled (orphan vault preservation)- // This is a key feature: after forced logout, the username should be preserved- // to help users easily re-login with the same account- let usernameInput = app.findTextField(testID: "username-input")- guard usernameInput.waitForExistenceNoIdle(timeout: 5) else {- captureFailureState(context: "04-username-input-not-found")- XCTFail("Username input should be visible on login screen")- try? await TestUserRegistration.unblockUserByUsername(username: testUser.username)- return- }-- let usernameValue = usernameInput.value as? String ?? ""- print("[Test04] Username field value: '\(usernameValue)'")-- // Verify username is prefilled with the test user's username (normalized)- let normalizedExpectedUsername = testUser.username.lowercased()- if !usernameValue.lowercased().contains(normalizedExpectedUsername.prefix(4)) {- // Username should at least start with the same characters- // (some implementations may normalize differently)- print("[Test04] Warning: Username field may not be prefilled. Expected to contain: '\(normalizedExpectedUsername)', got: '\(usernameValue)'")- } else {- print("[Test04] Username prefilled correctly: '\(usernameValue)'")- }-- let loginScreenScreenshot = XCUIScreen.main.screenshot()- let attachment5 = XCTAttachment(screenshot: loginScreenScreenshot)- attachment5.name = "04-5-login-screen-after-forced-logout"- attachment5.lifetime = .keepAlways- add(attachment5)-- print("[Test04] Forced logout confirmed - on login screen with username prefilled")-- // Unblock user so they can log in again- try await TestUserRegistration.unblockUserByUsername(username: testUser.username)- print("[Test04] User unblocked")-- // Step 6: Re-login with same credentials- print("[Test04] Step 6: Re-login with same credentials")- // Clear username field and enter credentials- usernameInput.clearAndTypeTextNoIdle(testUser.username)-- let passwordInput = app.findTextField(testID: "password-input")- passwordInput.tapNoIdle()- passwordInput.typeTextNoIdle(testUser.password)-- app.hideKeyboardIfVisible()-- let credentialsScreenshot = XCUIScreen.main.screenshot()- let attachment6 = XCTAttachment(screenshot: credentialsScreenshot)- attachment6.name = "04-6-credentials-entered"- attachment6.lifetime = .keepAlways- add(attachment6)-- let loginButton = app.findElement(testID: "login-button")- loginButton.tapNoIdle()-- // Wait for login to complete and vault to load- guard assertElementExists(- itemsScreen,- timeout: TestConfiguration.extendedTimeout,- message: "Should navigate to items screen after re-login",- context: "04-items-after-relogin"- ) else {- return- }-- // Wait for sync to complete- sleep(5)-- let afterReloginScreenshot = XCUIScreen.main.screenshot()- let attachment7 = XCTAttachment(screenshot: afterReloginScreenshot)- attachment7.name = "04-7-after-relogin"- attachment7.lifetime = .keepAlways- add(attachment7)-- print("[Test04] Re-login successful")-- // Step 7: Verify credential still exists using helper- // The credential should still exist because:- // 1. It was in the local preserved vault during forced logout- // 2. On re-login, client detected local vault is more advanced than server- // 3. Client uploaded local vault to recover server- print("[Test04] Step 7: Verify credential still exists")- guard openAndVerifyItem(name: uniqueName, expectedEmail: "[email protected]", contextPrefix: "04-recovery") else {- XCTFail("Credential '\(uniqueName)' should still exist after forced logout recovery - this proves vault was preserved locally and uploaded to server")- return- }-- let itemVerifiedScreenshot = XCUIScreen.main.screenshot()- let attachment8 = XCTAttachment(screenshot: itemVerifiedScreenshot)- attachment8.name = "04-8-item-verified-after-recovery"- attachment8.lifetime = .keepAlways- add(attachment8)-- print("[Test04] Credential verified after forced logout recovery")-- // Verify server revision is restored using username-based API (no auth token needed)- let finalRevisions = try await TestUserRegistration.getVaultRevisionsByUsername(username: testUser.username)- let finalRevision = finalRevisions.currentRevision- print("[Test04] Final server revision: \(finalRevision)")-- XCTAssertGreaterThanOrEqual(- finalRevision, revisionBeforeLogout,- "Server revision should be restored after forced logout recovery (expected >= \(revisionBeforeLogout), got \(finalRevision))"- )-- print("[Test04] SUCCESS - Forced logout recovery verified!")- print("[Test04] Revision flow: \(revisionBeforeLogout) (before) → \(revisionAfterRollback) (rollback) → \(finalRevision) (recovered)")- }-- // MARK: - Helper Methods-- /// Logs in with test user at the beginning of a test.- /// Always logs out first if already logged in to ensure we're using the correct test user.- /// Use this at the start of tests after app.launch().- /// - Parameter testUser: The test user to login with- @MainActor- private func loginWithTestUser(_ testUser: TestUser) {- // Wait for app to settle and reach a known state (unlock, login, or items screen)- // Use longer initial timeout since app may still be loading after launch- let unlockScreen = app.findElement(testID: "unlock-screen")- let loginScreen = app.findElement(testID: "login-screen")- let itemsScreen = app.findElement(testID: "items-screen")-- // Wait up to 15 seconds for any of the expected screens to appear- var screenFound = false- let startTime = Date()- let maxWaitTime: TimeInterval = 15-- while !screenFound && Date().timeIntervalSince(startTime) < maxWaitTime {- if unlockScreen.exists || loginScreen.exists || itemsScreen.exists {- screenFound = true- } else {- Thread.sleep(forTimeInterval: 0.5)- }- }-- if !screenFound {- // Capture screenshot and app hierarchy for debugging- let screenshot = XCUIScreen.main.screenshot()- let attachment = XCTAttachment(screenshot: screenshot)- attachment.name = "FAILURE-no-screen-found"- attachment.lifetime = .keepAlways- add(attachment)-- let hierarchyAttachment = XCTAttachment(string: app.debugDescription)- hierarchyAttachment.name = "FAILURE-hierarchy-no-screen-found"- hierarchyAttachment.lifetime = .keepAlways- add(hierarchyAttachment)-- XCTFail("No expected screen (login, unlock, or items) found after \(maxWaitTime)s. App may have crashed or failed to load.")- return- }-- // Handle unlock screen - logout to start fresh with test user- if unlockScreen.exists {- print("[Helper] Unlock screen detected - logging out to login fresh with test user")-- let logoutButton = app.findElement(testID: "logout-button")- if logoutButton.waitForExistenceNoIdle(timeout: 5) {- logoutButton.tapNoIdle()-- // Handle logout confirmation alert if present- let confirmButton = app.buttons["Logout"]- if confirmButton.waitForExistence(timeout: 3) {- confirmButton.tap()- }- }-- // Wait for login screen- _ = loginScreen.waitForExistenceNoIdle(timeout: 10)- }-- // Check if we're on login screen- if loginScreen.waitForExistenceNoIdle(timeout: 2) {- performLogin(with: testUser)- return- }-- // Check if we're already on items screen (already logged in as correct user)- if itemsScreen.waitForExistenceNoIdle(timeout: 2) {- print("[Helper] Already on items screen, assuming correct user is logged in")- return- }-- // Unknown state - log warning but continue (test will fail with appropriate error if needed)- print("[Helper] Unknown app state after waiting, test may fail")- }-- /// Unlocks the vault if the unlock screen is displayed.- /// Use this after deep links or other actions that may lock the vault.- /// Unlike loginWithTestUser, this does not logout - it just enters the password.- /// - Parameter testUser: The test user whose password to use for unlock- @MainActor- private func unlockVaultIfNeeded(with testUser: TestUser) {- // Wait longer for unlock screen after deep links - app may take time to navigate- let unlockScreen = app.findElement(testID: "unlock-screen")- guard unlockScreen.waitForExistenceNoIdle(timeout: 5) else {- // Not on unlock screen, check if already on items screen- let itemsScreen = app.findElement(testID: "items-screen")- if itemsScreen.waitForExistenceNoIdle(timeout: 2) {- print("[Helper] Already on items screen, no unlock needed")- } else {- print("[Helper] Not on unlock or items screen, proceeding anyway")- }- return- }-- print("[Helper] Unlock screen detected - entering password to unlock")-- // Enter password in unlock screen- let passwordInput = app.findTextField(testID: "unlock-password-input")- if passwordInput.waitForExistenceNoIdle(timeout: 3) {- passwordInput.tapNoIdle()- passwordInput.typeTextNoIdle(testUser.password)- }-- app.hideKeyboardIfVisible()-- // Tap unlock button- let unlockButton = app.findElement(testID: "unlock-button")- if unlockButton.waitForExistenceNoIdle(timeout: 3) {- unlockButton.tapNoIdle()- }-- // Wait for items screen- let itemsScreen = app.findElement(testID: "items-screen")- _ = itemsScreen.waitForExistenceNoIdle(timeout: TestConfiguration.extendedTimeout)- }-- /// Performs login with the given test user credentials.- /// Assumes we're already on the login screen.- /// - Parameter testUser: The test user to login with- @MainActor- private func performLogin(with testUser: TestUser) {- // Check if API URL is already configured to localhost by looking at the displayed URL- // The login screen shows the URL via server-url-link, containing text like "localhost:5100" or "aliasvault.com"- let serverUrlLink = app.findElement(testID: "server-url-link")- var needsApiConfig = true-- if serverUrlLink.waitForExistenceNoIdle(timeout: 5) {- // Check if URL already contains localhost (already configured for local testing)- let urlText = serverUrlLink.label- if urlText.contains("localhost") {- print("[Helper] API URL already configured to localhost, skipping API configuration")- needsApiConfig = false- } else {- print("[Helper] API URL shows '\(urlText)', need to configure to localhost")- }- }-- if needsApiConfig {- // Configure self-hosted URL by tapping the server URL link button- let serverUrlLinkButton = app.findElement(testID: "server-url-link-button")-- if serverUrlLinkButton.waitForExistenceNoIdle(timeout: 5) {- serverUrlLinkButton.tapNoIdle()-- let selfHostedOption = app.findElement(testID: "api-option-custom")- if selfHostedOption.waitForExistenceNoIdle(timeout: 10) {- selfHostedOption.tapNoIdle()-- let customUrlInput = app.findTextField(testID: "custom-api-url-input")- if customUrlInput.waitForExistenceNoIdle(timeout: 5) {- customUrlInput.tapNoIdle()- customUrlInput.clearAndTypeTextNoIdle(TestConfiguration.apiUrl)- print("[Helper] Configured API URL: \(TestConfiguration.apiUrl)")- }-- app.hideKeyboardIfVisible()-- // Tap back to return to login form- let backButton = app.findElement(testID: "back-button")- if backButton.waitForExistenceNoIdle(timeout: 3) {- backButton.tapNoIdle()- }- }- }- }-- // Wait for login screen to be ready- let loginScreen = app.findElement(testID: "login-screen")- _ = loginScreen.waitForExistenceNoIdle(timeout: 5)-- // Enter credentials- let usernameInput = app.findTextField(testID: "username-input")- if usernameInput.waitForExistenceNoIdle(timeout: 5) {- usernameInput.clearAndTypeTextNoIdle(testUser.username)- }-- let passwordInput = app.findTextField(testID: "password-input")- if passwordInput.waitForExistenceNoIdle(timeout: 3) {- passwordInput.tapNoIdle()- passwordInput.typeTextNoIdle(testUser.password)- }-- app.hideKeyboardIfVisible()-- // Tap login button- let loginButton = app.findElement(testID: "login-button")- if loginButton.waitForExistenceNoIdle(timeout: 3) {- loginButton.tapNoIdle()- }-- // Wait for items screen- let itemsScreen = app.findElement(testID: "items-screen")- _ = itemsScreen.waitForExistenceNoIdle(timeout: TestConfiguration.extendedTimeout)- }-- /// Parameters for creating a new item via the helper.- struct CreateItemParams {- let name: String- let serviceUrl: String- let email: String- let username: String?-- init(name: String, serviceUrl: String = "https://example.com", email: String = "[email protected]", username: String? = nil) {- self.name = name- self.serviceUrl = serviceUrl- self.email = email- self.username = username- }- }-- /// Creates a new item with the given parameters.- /// Assumes we're already on the items screen.- /// - Parameters:- /// - params: The item creation parameters- /// - contextPrefix: Prefix for failure context names (e.g., "02" for test02)- /// - Returns: true if item was created successfully, false otherwise- @discardableResult- @MainActor- private func createItem(params: CreateItemParams, contextPrefix: String) -> Bool {- print("[Helper] Creating item: \(params.name)")-- // Tap add button- let addItemButton = app.findElement(testID: "add-item-button")- addItemButton.tapNoIdle()-- let addEditScreen = app.findElement(testID: "add-edit-screen")- guard assertElementExists(- addEditScreen,- timeout: 10,- message: "Add/edit screen should appear",- context: "\(contextPrefix)-add-edit-screen"- ) else {- return false- }-- // Fill item name- let itemNameInput = app.findAndScrollToTextField(testID: "item-name-input")- itemNameInput.tapNoIdle()- itemNameInput.typeTextNoIdle(params.name)-- // Fill service URL- let serviceUrlInput = app.findAndScrollToTextField(testID: "service-url-input")- serviceUrlInput.tapNoIdle()- serviceUrlInput.typeTextNoIdle(params.serviceUrl)-- // Add email- let addEmailButton = app.findElement(testID: "add-email-button")- app.scrollToElement(addEmailButton)- addEmailButton.tapNoIdle()-- let loginEmailInput = app.findAndScrollToTextField(testID: "login-email-input")- loginEmailInput.tapNoIdle()- loginEmailInput.typeTextNoIdle(params.email)-- // Optionally add username- if let username = params.username {- let loginUsernameInput = app.findAndScrollToTextField(testID: "login-username-input")- if loginUsernameInput.exists {- app.scrollToElement(loginUsernameInput)- loginUsernameInput.tapNoIdle()- loginUsernameInput.typeTextNoIdle(username)- }- }-- app.hideKeyboardIfVisible()-- // Save item- let saveButton = app.findElement(testID: "save-button")- saveButton.tapNoIdle()-- guard assertTextAppears(- "Login credentials",- timeout: 10,- message: "Should show item detail screen after save",- context: "\(contextPrefix)-item-saved"- ) else {- return false- }-- // Return to items list- sleep(1)- let backButton = app.findElement(testID: "back-button")- backButton.tapNoIdle()-- let itemsScreen = app.findElement(testID: "items-screen")- guard assertElementExists(- itemsScreen,- timeout: 10,- message: "Should return to items screen after saving",- context: "\(contextPrefix)-return-to-items"- ) else {- return false- }-- // Wait for list to populate- sleep(2)-- print("[Helper] Item '\(params.name)' created successfully")- return true- }-- /// Verifies that an item with the given name exists in the items list.- /// - Parameters:- /// - name: The item name to look for- /// - contextPrefix: Prefix for failure context names- /// - Returns: true if item exists, false otherwise- @discardableResult- @MainActor- private func verifyItemExistsInList(name: String, contextPrefix: String) -> Bool {- let itemCard = app.descendants(matching: .any).matching(- NSPredicate(format: "label == %@", name)- ).firstMatch-- let itemFound = itemCard.waitForExistenceNoIdle(timeout: 10)- if !itemFound {- captureFailureState(context: "\(contextPrefix)-item-not-in-list")- XCTFail("Item '\(name)' should appear in list")- return false- }-- print("[Helper] Item '\(name)' found in list")- return true- }-- /// Opens an item from the list and verifies its details.- /// - Parameters:- /// - name: The item name to open- /// - expectedEmail: The expected email address (optional)- /// - contextPrefix: Prefix for failure context names- /// - Returns: true if item was opened and verified, false otherwise- @discardableResult- @MainActor- private func openAndVerifyItem(name: String, expectedEmail: String? = nil, contextPrefix: String) -> Bool {- let itemCard = app.descendants(matching: .any).matching(- NSPredicate(format: "label == %@", name)- ).firstMatch-- let itemFound = itemCard.waitForExistenceNoIdle(timeout: 10)- if !itemFound {- captureFailureState(context: "\(contextPrefix)-item-not-found")- XCTFail("Item '\(name)' should exist in list")- return false- }-- itemCard.tapNoIdle()-- guard assertTextAppears(- "Login credentials",- timeout: 10,- message: "Should show item detail screen",- context: "\(contextPrefix)-item-detail"- ) else {- return false- }-- if let email = expectedEmail {- guard assertTextContaining(- email,- timeout: 5,- message: "Email '\(email)' should be visible",- context: "\(contextPrefix)-email-preserved"- ) else {- return false- }- }-- print("[Helper] Item '\(name)' verified successfully")- return true- }-}diff --git a/apps/mobile-app/ios/AliasVaultUITests/TestConfiguration.swift b/apps/mobile-app/ios/AliasVaultUITests/TestConfiguration.swiftdeleted file mode 100644index 7b76561f2..000000000--- a/apps/mobile-app/ios/AliasVaultUITests/TestConfiguration.swift+++ /dev/null@@ -1,24 +0,0 @@-import Foundation--/// Configuration for E2E tests-enum TestConfiguration {- /// API URL for testing (defaults to local development server)- static var apiUrl: String {- return ProcessInfo.processInfo.environment["API_URL"] ?? "http://localhost:5100"- }-- /// Generate a unique name for test items- static func generateUniqueName(prefix: String = "E2E Test") -> String {- let timestamp = Int(Date().timeIntervalSince1970 * 1000)- return "\(prefix) \(timestamp)"- }-- /// Default timeout for element waiting (seconds)- static let defaultTimeout: TimeInterval = 10-- /// Extended timeout for operations that may take longer (like login with network)- static let extendedTimeout: TimeInterval = 30-- /// Short timeout for quick checks- static let shortTimeout: TimeInterval = 2-}diff --git a/apps/mobile-app/ios/AliasVaultUITests/TestUserRegistration.swift b/apps/mobile-app/ios/AliasVaultUITests/TestUserRegistration.swiftdeleted file mode 100644index bf0496c61..000000000--- a/apps/mobile-app/ios/AliasVaultUITests/TestUserRegistration.swift+++ /dev/null@@ -1,696 +0,0 @@-import Foundation-import CryptoKit-import SQLite3--// Import the Rust core SRP functions-import RustCoreFramework--// Import VaultModels for VaultVersions and VaultSql-import VaultModels--/// Test user credentials and token.-struct TestUser {- let username: String- let password: String- let token: String- let refreshToken: String-}--/// API response models-struct TokenResponse: Codable {- let token: String- let refreshToken: String-}--struct ApiError: Codable {- let title: String?- let message: String?-}--/// Default encryption settings for Argon2Id.-/// These match the server defaults in apps/server/Utilities/AliasVault.Cryptography/Defaults.cs-enum EncryptionDefaults {- static let type = "Argon2Id"- static let iterations: UInt32 = 5- static let memorySize: UInt32 = 65536- static let parallelism: UInt32 = 1-- static var settingsJson: String {- """- {"DegreeOfParallelism":\(parallelism),"MemorySize":\(memorySize),"Iterations":\(iterations)}- """- }-}--/// Test user registration helper using SRP protocol.-/// Mirrors the browser extension's test-api.ts implementation.-enum TestUserRegistration {-- /// API URL for testing (defaults to local development server)- static var apiUrl: String {- return ProcessInfo.processInfo.environment["API_URL"] ?? "http://localhost:5100"- }-- // MARK: - Username/Password Generation-- /// Generate a random test username.- static func generateTestUsername() -> String {- let randomPart = String((0..<10).map { _ in "abcdefghijklmnopqrstuvwxyz0123456789".randomElement()! })- return "test_\(randomPart)@example.tld"- }-- /// Generate a test password.- /// Uses a static password for easier debugging and test reproducibility.- static func generateTestPassword() -> String {- return "password"- }-- /// Normalize username by converting to lowercase and trimming whitespace.- static func normalizeUsername(_ username: String) -> String {- return username.lowercased().trimmingCharacters(in: .whitespaces)- }-- // MARK: - Argon2 Key Derivation-- /// Derive encryption key from password using Argon2Id via Rust core.- ///- /// Derives against the same parameters the registration request declares, so the account can be- /// opened again with the settings the server stored for it.- static func deriveKeyArgon2(_ password: String, salt: String) throws -> Data {- // Use the Rust core's Argon2 implementation- return try argon2DeriveKey(- password: password,- salt: salt,- encryptionSettings: EncryptionDefaults.settingsJson- )- }-- // MARK: - Hex Conversion-- /// Convert Data to uppercase hex string.- static func bytesToHex(_ data: Data) -> String {- return data.map { String(format: "%02X", $0) }.joined()- }-- // MARK: - Registration-- /// Register a new test user via the API using SRP protocol.- static func registerTestUser(- apiBaseUrl: String,- username: String,- password: String- ) async throws -> TokenResponse {- let baseUrl = apiBaseUrl.trimmingCharacters(in: CharacterSet(charactersIn: "/")) + "/v1/"- let normalizedUsername = normalizeUsername(username)-- // Generate salt using Rust core- let salt = srpGenerateSalt()-- // Derive key from password- let encryptionKey = try deriveKeyArgon2(password, salt: salt)- let passwordHashHex = bytesToHex(encryptionKey)-- // Derive SRP private key and verifier using Rust core- let privateKey = try srpDerivePrivateKey(salt: salt, identity: normalizedUsername, passwordHash: passwordHashHex)- let verifier = try srpDeriveVerifier(privateKey: privateKey)-- // Build registration request- let registerRequest: [String: Any] = [- "username": normalizedUsername,- "salt": salt,- "verifier": verifier,- "encryptionType": EncryptionDefaults.type,- "encryptionSettings": EncryptionDefaults.settingsJson- ]-- let requestData = try JSONSerialization.data(withJSONObject: registerRequest)-- // Send registration request- var request = URLRequest(url: URL(string: "\(baseUrl)Auth/register")!)- request.httpMethod = "POST"- request.setValue("application/json", forHTTPHeaderField: "Content-Type")- request.httpBody = requestData-- let (data, response) = try await URLSession.shared.data(for: request)-- guard let httpResponse = response as? HTTPURLResponse else {- throw NSError(domain: "TestUserRegistration", code: 5,- userInfo: [NSLocalizedDescriptionKey: "Invalid response"])- }-- guard httpResponse.statusCode == 200 else {- let errorMessage: String- if let apiError = try? JSONDecoder().decode(ApiError.self, from: data) {- errorMessage = apiError.title ?? apiError.message ?? "Unknown error"- } else if let text = String(data: data, encoding: .utf8) {- errorMessage = text- } else {- errorMessage = "HTTP \(httpResponse.statusCode)"- }- throw NSError(domain: "TestUserRegistration", code: httpResponse.statusCode,- userInfo: [NSLocalizedDescriptionKey: "Registration failed: \(errorMessage)"])- }-- let tokenResponse = try JSONDecoder().decode(TokenResponse.self, from: data)-- // Upload initial empty vault- try await uploadInitialVault(- apiBaseUrl: apiBaseUrl,- token: tokenResponse.token,- username: normalizedUsername,- encryptionKey: encryptionKey- )-- return tokenResponse- }-- // MARK: - Vault Upload-- /// Upload an initial empty vault to the server.- static func uploadInitialVault(- apiBaseUrl: String,- token: String,- username: String,- encryptionKey: Data- ) async throws {- let baseUrl = apiBaseUrl.trimmingCharacters(in: CharacterSet(charactersIn: "/")) + "/v1/"-- // Create empty vault database (minimal SQLite)- let vaultBase64 = createEmptyVaultDatabase()-- // Encrypt the vault using AES-GCM- let encryptedVault = try symmetricEncrypt(plaintext: vaultBase64, key: encryptionKey)-- // Generate RSA key pair for the vault- let rsaKeyPair = try generateRsaKeyPair()-- // Get current timestamp- let now = ISO8601DateFormatter().string(from: Date())-- // Build vault upload request- let vaultRequest: [String: Any] = [- "username": normalizeUsername(username),- "blob": encryptedVault,- "version": VaultVersions.latestVersion, // From auto-generated VaultVersions.swift- "currentRevisionNumber": VaultVersions.latestRevision,- "encryptionPublicKey": rsaKeyPair.publicKey,- "credentialsCount": 0,- "emailAddressList": [String](),- "privateEmailDomainList": [String](),- "hiddenPrivateEmailDomainList": [String](),- "publicEmailDomainList": [String](),- "createdAt": now,- "updatedAt": now- ]-- let requestData = try JSONSerialization.data(withJSONObject: vaultRequest)-- var request = URLRequest(url: URL(string: "\(baseUrl)Vault")!)- request.httpMethod = "POST"- request.setValue("application/json", forHTTPHeaderField: "Content-Type")- request.setValue("Bearer \(token)", forHTTPHeaderField: "Authorization")- request.httpBody = requestData-- let (data, response) = try await URLSession.shared.data(for: request)-- guard let httpResponse = response as? HTTPURLResponse, httpResponse.statusCode == 200 else {- let errorText = String(data: data, encoding: .utf8) ?? "Unknown error"- throw NSError(domain: "TestUserRegistration", code: 6,- userInfo: [NSLocalizedDescriptionKey: "Failed to upload vault: \(errorText)"])- }- }-- // MARK: - Encryption Helpers-- /// Encrypt data using AES-GCM (matches browser extension's EncryptionUtility).- static func symmetricEncrypt(plaintext: String, key: Data) throws -> String {- guard let plaintextData = plaintext.data(using: .utf8) else {- throw NSError(domain: "TestUserRegistration", code: 7,- userInfo: [NSLocalizedDescriptionKey: "Invalid plaintext encoding"])- }-- let symmetricKey = SymmetricKey(data: key)- let sealedBox = try AES.GCM.seal(plaintextData, using: symmetricKey)-- // Combined format: nonce + ciphertext + tag- guard let combined = sealedBox.combined else {- throw NSError(domain: "TestUserRegistration", code: 8,- userInfo: [NSLocalizedDescriptionKey: "Failed to get combined sealed box"])- }-- return combined.base64EncodedString()- }-- /// Generate RSA key pair for vault encryption.- static func generateRsaKeyPair() throws -> (publicKey: String, privateKey: String) {- let attributes: [String: Any] = [- kSecAttrKeyType as String: kSecAttrKeyTypeRSA,- kSecAttrKeySizeInBits as String: 2048- ]-- var error: Unmanaged<CFError>?- guard let privateKey = SecKeyCreateRandomKey(attributes as CFDictionary, &error) else {- throw error!.takeRetainedValue() as Error- }-- guard let publicKey = SecKeyCopyPublicKey(privateKey) else {- throw NSError(domain: "TestUserRegistration", code: 9,- userInfo: [NSLocalizedDescriptionKey: "Failed to get public key"])- }-- // Export keys as JWK format- let publicKeyJwk = try exportKeyAsJwk(publicKey, isPrivate: false)- let privateKeyJwk = try exportKeyAsJwk(privateKey, isPrivate: true)-- return (publicKeyJwk, privateKeyJwk)- }-- /// Export a SecKey as JWK JSON string.- static func exportKeyAsJwk(_ key: SecKey, isPrivate: Bool) throws -> String {- var error: Unmanaged<CFError>?- guard let keyData = SecKeyCopyExternalRepresentation(key, &error) as Data? else {- throw error!.takeRetainedValue() as Error- }-- // For RSA keys, create a simplified JWK- // This is a basic implementation - production would need full JWK encoding- let base64Key = keyData.base64EncodedString()-- let jwk: [String: Any] = [- "kty": "RSA",- "key_ops": isPrivate ? ["decrypt"] : ["encrypt"],- "ext": true,- "key": base64Key- ]-- let jsonData = try JSONSerialization.data(withJSONObject: jwk)- return String(data: jsonData, encoding: .utf8)!- }-- // MARK: - Empty Vault Creation-- /// Create an empty vault database as base64 string.- /// This creates a real SQLite database with the vault schema using VaultSql.completeSchema.- static func createEmptyVaultDatabase() -> String {- // Create a temporary SQLite database file- let tempDir = FileManager.default.temporaryDirectory- let dbPath = tempDir.appendingPathComponent(UUID().uuidString + ".db").path-- var database: OpaquePointer?-- // Open/create the database- guard sqlite3_open(dbPath, &database) == SQLITE_OK else {- print("Failed to create SQLite database")- return ""- }-- defer {- sqlite3_close(database)- try? FileManager.default.removeItem(atPath: dbPath)- }-- // Execute the complete schema SQL from VaultSql (auto-generated from TypeScript)- let schemaSql = VaultSql.completeSchema- var errorMessage: UnsafeMutablePointer<CChar>?-- let result = sqlite3_exec(database, schemaSql, nil, nil, &errorMessage)- if result != SQLITE_OK {- let error = errorMessage.map { String(cString: $0) } ?? "Unknown error"- print("Failed to execute schema SQL: \(error)")- sqlite3_free(errorMessage)- return ""- }-- // Read the database file and encode as base64- guard let dbData = FileManager.default.contents(atPath: dbPath) else {- print("Failed to read database file")- return ""- }-- return dbData.base64EncodedString()- }-- // MARK: - Public API-- /// Create a test user with random credentials.- static func createTestUser(apiBaseUrl: String? = nil) async throws -> TestUser {- let url = apiBaseUrl ?? apiUrl- let username = generateTestUsername()- let password = generateTestPassword()-- let tokenResponse = try await registerTestUser(- apiBaseUrl: url,- username: username,- password: password- )-- return TestUser(- username: username,- password: password,- token: tokenResponse.token,- refreshToken: tokenResponse.refreshToken- )- }-- /// Check if the API is available.- static func isApiAvailable(apiBaseUrl: String? = nil) async -> Bool {- let url = (apiBaseUrl ?? apiUrl).trimmingCharacters(in: CharacterSet(charactersIn: "/")) + "/v1/"-- var request = URLRequest(url: URL(string: "\(url)Auth/status")!)- request.httpMethod = "GET"- request.setValue("application/json", forHTTPHeaderField: "Content-Type")- request.timeoutInterval = 5-- do {- let (_, response) = try await URLSession.shared.data(for: request)- if let httpResponse = response as? HTTPURLResponse {- // Status endpoint returns 401 when not authenticated, but that means API is running- return httpResponse.statusCode == 401 || httpResponse.statusCode == 200- }- return false- } catch {- return false- }- }-- // MARK: - Test Helpers (DEV API Endpoints)-- /// Delete the newest vault revisions for the authenticated user.- /// This endpoint only works in development mode.- /// Used for testing RPO (Recovery Point Objective) recovery scenarios.- ///- /// - Parameters:- /// - count: Number of newest revisions to delete- /// - token: Authentication token- /// - apiBaseUrl: Optional API base URL (defaults to apiUrl)- /// - Returns: Number of deleted revisions- static func deleteVaultRevisions(- count: Int,- token: String,- apiBaseUrl: String? = nil- ) async throws -> Int {- let url = (apiBaseUrl ?? apiUrl).trimmingCharacters(in: CharacterSet(charactersIn: "/")) + "/v1/"-- var request = URLRequest(url: URL(string: "\(url)Test/vault-revisions/\(count)")!)- request.httpMethod = "DELETE"- request.setValue("application/json", forHTTPHeaderField: "Content-Type")- request.setValue("Bearer \(token)", forHTTPHeaderField: "Authorization")-- let (data, response) = try await URLSession.shared.data(for: request)-- guard let httpResponse = response as? HTTPURLResponse else {- throw NSError(domain: "TestUserRegistration", code: 10,- userInfo: [NSLocalizedDescriptionKey: "Invalid response"])- }-- guard httpResponse.statusCode == 200 else {- let errorText = String(data: data, encoding: .utf8) ?? "Unknown error"- throw NSError(domain: "TestUserRegistration", code: httpResponse.statusCode,- userInfo: [NSLocalizedDescriptionKey: "Failed to delete vault revisions: \(errorText)"])- }-- // Parse response to get deleted count- if let json = try? JSONSerialization.jsonObject(with: data) as? [String: Any],- let deleted = json["deleted"] as? Int {- return deleted- }-- return 0- }-- /// Get vault revision information for the authenticated user.- /// This endpoint only works in development mode.- ///- /// - Parameters:- /// - token: Authentication token- /// - apiBaseUrl: Optional API base URL (defaults to apiUrl)- /// - Returns: Tuple of (count, currentRevision)- static func getVaultRevisions(- token: String,- apiBaseUrl: String? = nil- ) async throws -> (count: Int, currentRevision: Int) {- let url = (apiBaseUrl ?? apiUrl).trimmingCharacters(in: CharacterSet(charactersIn: "/")) + "/v1/"-- var request = URLRequest(url: URL(string: "\(url)Test/vault-revisions")!)- request.httpMethod = "GET"- request.setValue("application/json", forHTTPHeaderField: "Content-Type")- request.setValue("Bearer \(token)", forHTTPHeaderField: "Authorization")-- let (data, response) = try await URLSession.shared.data(for: request)-- guard let httpResponse = response as? HTTPURLResponse else {- throw NSError(domain: "TestUserRegistration", code: 10,- userInfo: [NSLocalizedDescriptionKey: "Invalid response"])- }-- guard httpResponse.statusCode == 200 else {- let errorText = String(data: data, encoding: .utf8) ?? "Unknown error"- throw NSError(domain: "TestUserRegistration", code: httpResponse.statusCode,- userInfo: [NSLocalizedDescriptionKey: "Failed to get vault revisions: \(errorText)"])- }-- // Parse response- if let json = try? JSONSerialization.jsonObject(with: data) as? [String: Any],- let count = json["count"] as? Int,- let currentRevision = json["currentRevision"] as? Int {- return (count, currentRevision)- }-- return (0, 0)- }-- /// Block the authenticated user's account.- /// This endpoint only works in development mode.- /// Used for testing forced logout scenarios - blocked users get 401 from /status endpoint.- ///- /// - Parameters:- /// - token: Authentication token- /// - apiBaseUrl: Optional API base URL (defaults to apiUrl)- static func blockUser(- token: String,- apiBaseUrl: String? = nil- ) async throws {- let url = (apiBaseUrl ?? apiUrl).trimmingCharacters(in: CharacterSet(charactersIn: "/")) + "/v1/"-- var request = URLRequest(url: URL(string: "\(url)Test/block-user")!)- request.httpMethod = "POST"- request.setValue("application/json", forHTTPHeaderField: "Content-Type")- request.setValue("Bearer \(token)", forHTTPHeaderField: "Authorization")-- let (data, response) = try await URLSession.shared.data(for: request)-- guard let httpResponse = response as? HTTPURLResponse else {- throw NSError(domain: "TestUserRegistration", code: 11,- userInfo: [NSLocalizedDescriptionKey: "Invalid response"])- }-- guard httpResponse.statusCode == 200 else {- let errorText = String(data: data, encoding: .utf8) ?? "Unknown error"- throw NSError(domain: "TestUserRegistration", code: httpResponse.statusCode,- userInfo: [NSLocalizedDescriptionKey: "Failed to block user: \(errorText)"])- }- }-- /// Unblock the authenticated user's account.- /// This endpoint only works in development mode.- /// Used after forced logout tests to re-enable the account.- ///- /// - Parameters:- /// - token: Authentication token- /// - apiBaseUrl: Optional API base URL (defaults to apiUrl)- static func unblockUser(- token: String,- apiBaseUrl: String? = nil- ) async throws {- let url = (apiBaseUrl ?? apiUrl).trimmingCharacters(in: CharacterSet(charactersIn: "/")) + "/v1/"-- var request = URLRequest(url: URL(string: "\(url)Test/unblock-user")!)- request.httpMethod = "POST"- request.setValue("application/json", forHTTPHeaderField: "Content-Type")- request.setValue("Bearer \(token)", forHTTPHeaderField: "Authorization")-- let (data, response) = try await URLSession.shared.data(for: request)-- guard let httpResponse = response as? HTTPURLResponse else {- throw NSError(domain: "TestUserRegistration", code: 12,- userInfo: [NSLocalizedDescriptionKey: "Invalid response"])- }-- guard httpResponse.statusCode == 200 else {- let errorText = String(data: data, encoding: .utf8) ?? "Unknown error"- throw NSError(domain: "TestUserRegistration", code: httpResponse.statusCode,- userInfo: [NSLocalizedDescriptionKey: "Failed to unblock user: \(errorText)"])- }- }-- // MARK: - Username-based API calls (for UI tests that can't access app tokens)-- /// Get vault revision information for a user by username.- /// This is an anonymous endpoint that doesn't require authentication.- /// Used by UI tests that cannot access the app's auth token.- ///- /// - Parameters:- /// - username: The username to look up- /// - apiBaseUrl: Optional API base URL (defaults to apiUrl)- /// - Returns: Tuple of (count, currentRevision)- static func getVaultRevisionsByUsername(- username: String,- apiBaseUrl: String? = nil- ) async throws -> (count: Int, currentRevision: Int) {- let url = (apiBaseUrl ?? apiUrl).trimmingCharacters(in: CharacterSet(charactersIn: "/")) + "/v1/"- // Use alphanumerics for safe URL path encoding (encodes @, ., etc.)- let encodedUsername = username.addingPercentEncoding(withAllowedCharacters: .alphanumerics) ?? username-- guard let requestUrl = URL(string: "\(url)Test/vault-revisions/by-username/\(encodedUsername)") else {- throw NSError(domain: "TestUserRegistration", code: 13,- userInfo: [NSLocalizedDescriptionKey: "Invalid URL for username: \(username)"])- }- var request = URLRequest(url: requestUrl)- request.httpMethod = "GET"- request.setValue("application/json", forHTTPHeaderField: "Content-Type")-- let (data, response) = try await URLSession.shared.data(for: request)-- guard let httpResponse = response as? HTTPURLResponse else {- throw NSError(domain: "TestUserRegistration", code: 13,- userInfo: [NSLocalizedDescriptionKey: "Invalid response"])- }-- guard httpResponse.statusCode == 200 else {- let errorText = String(data: data, encoding: .utf8) ?? "Unknown error"- throw NSError(domain: "TestUserRegistration", code: httpResponse.statusCode,- userInfo: [NSLocalizedDescriptionKey: "Failed to get vault revisions: \(errorText)"])- }-- // Parse response- if let json = try? JSONSerialization.jsonObject(with: data) as? [String: Any],- let count = json["count"] as? Int,- let currentRevision = json["currentRevision"] as? Int {- return (count, currentRevision)- }-- return (0, 0)- }-- /// Delete the newest vault revisions for a user by username.- /// This is an anonymous endpoint that doesn't require authentication.- /// Used by UI tests that cannot access the app's auth token.- ///- /// - Parameters:- /// - username: The username to look up- /// - count: Number of newest revisions to delete- /// - apiBaseUrl: Optional API base URL (defaults to apiUrl)- /// - Returns: Number of deleted revisions- static func deleteVaultRevisionsByUsername(- username: String,- count: Int,- apiBaseUrl: String? = nil- ) async throws -> Int {- let url = (apiBaseUrl ?? apiUrl).trimmingCharacters(in: CharacterSet(charactersIn: "/")) + "/v1/"- // Use alphanumerics for safe URL path encoding (encodes @, ., etc.)- let encodedUsername = username.addingPercentEncoding(withAllowedCharacters: .alphanumerics) ?? username-- guard let requestUrl = URL(string: "\(url)Test/vault-revisions/by-username/\(encodedUsername)/\(count)") else {- throw NSError(domain: "TestUserRegistration", code: 14,- userInfo: [NSLocalizedDescriptionKey: "Invalid URL for username: \(username)"])- }- var request = URLRequest(url: requestUrl)- request.httpMethod = "DELETE"- request.setValue("application/json", forHTTPHeaderField: "Content-Type")-- let (data, response) = try await URLSession.shared.data(for: request)-- guard let httpResponse = response as? HTTPURLResponse else {- throw NSError(domain: "TestUserRegistration", code: 14,- userInfo: [NSLocalizedDescriptionKey: "Invalid response"])- }-- guard httpResponse.statusCode == 200 else {- let errorText = String(data: data, encoding: .utf8) ?? "Unknown error"- throw NSError(domain: "TestUserRegistration", code: httpResponse.statusCode,- userInfo: [NSLocalizedDescriptionKey: "Failed to delete vault revisions: \(errorText)"])- }-- // Parse response- if let json = try? JSONSerialization.jsonObject(with: data) as? [String: Any],- let deleted = json["deleted"] as? Int {- return deleted- }-- return 0- }-- /// Block a user's account by username.- /// This is an anonymous endpoint that doesn't require authentication.- /// Used by UI tests that cannot access the app's auth token.- ///- /// - Parameters:- /// - username: The username to block- /// - apiBaseUrl: Optional API base URL (defaults to apiUrl)- static func blockUserByUsername(- username: String,- apiBaseUrl: String? = nil- ) async throws {- let url = (apiBaseUrl ?? apiUrl).trimmingCharacters(in: CharacterSet(charactersIn: "/")) + "/v1/"- // Use alphanumerics for safe URL path encoding (encodes @, ., etc.)- let encodedUsername = username.addingPercentEncoding(withAllowedCharacters: .alphanumerics) ?? username-- guard let requestUrl = URL(string: "\(url)Test/block-user/by-username/\(encodedUsername)") else {- throw NSError(domain: "TestUserRegistration", code: 15,- userInfo: [NSLocalizedDescriptionKey: "Invalid URL for username: \(username)"])- }- var request = URLRequest(url: requestUrl)- request.httpMethod = "POST"- request.setValue("application/json", forHTTPHeaderField: "Content-Type")-- let (data, response) = try await URLSession.shared.data(for: request)-- guard let httpResponse = response as? HTTPURLResponse else {- throw NSError(domain: "TestUserRegistration", code: 15,- userInfo: [NSLocalizedDescriptionKey: "Invalid response"])- }-- guard httpResponse.statusCode == 200 else {- let errorText = String(data: data, encoding: .utf8) ?? "Unknown error"- throw NSError(domain: "TestUserRegistration", code: httpResponse.statusCode,- userInfo: [NSLocalizedDescriptionKey: "Failed to block user: \(errorText)"])- }- }-- /// Unblock a user's account by username.- /// This is an anonymous endpoint that doesn't require authentication.- /// Used by UI tests that cannot access the app's auth token.- ///- /// - Parameters:- /// - username: The username to unblock- /// - apiBaseUrl: Optional API base URL (defaults to apiUrl)- static func unblockUserByUsername(- username: String,- apiBaseUrl: String? = nil- ) async throws {- let url = (apiBaseUrl ?? apiUrl).trimmingCharacters(in: CharacterSet(charactersIn: "/")) + "/v1/"- // Use alphanumerics for safe URL path encoding (encodes @, ., etc.)- let encodedUsername = username.addingPercentEncoding(withAllowedCharacters: .alphanumerics) ?? username-- guard let requestUrl = URL(string: "\(url)Test/unblock-user/by-username/\(encodedUsername)") else {- throw NSError(domain: "TestUserRegistration", code: 16,- userInfo: [NSLocalizedDescriptionKey: "Invalid URL for username: \(username)"])- }- var request = URLRequest(url: requestUrl)- request.httpMethod = "POST"- request.setValue("application/json", forHTTPHeaderField: "Content-Type")-- let (data, response) = try await URLSession.shared.data(for: request)-- guard let httpResponse = response as? HTTPURLResponse else {- throw NSError(domain: "TestUserRegistration", code: 16,- userInfo: [NSLocalizedDescriptionKey: "Invalid response"])- }-- guard httpResponse.statusCode == 200 else {- let errorText = String(data: data, encoding: .utf8) ?? "Unknown error"- throw NSError(domain: "TestUserRegistration", code: httpResponse.statusCode,- userInfo: [NSLocalizedDescriptionKey: "Failed to unblock user: \(errorText)"])- }- }-}diff --git a/apps/mobile-app/ios/AliasVaultUITests/XCUIElementHelpers.swift b/apps/mobile-app/ios/AliasVaultUITests/XCUIElementHelpers.swiftdeleted file mode 100644index a267f4873..000000000--- a/apps/mobile-app/ios/AliasVaultUITests/XCUIElementHelpers.swift+++ /dev/null@@ -1,168 +0,0 @@-import XCTest--// MARK: - XCUIElement Extensions--extension XCUIElement {- /// Wait for element to exist without waiting for app idle.- /// Essential for React Native apps that have continuous timers/animations.- @MainActor- func waitForExistenceNoIdle(timeout: TimeInterval = 10) -> Bool {- let expectation = XCTNSPredicateExpectation(- predicate: NSPredicate(format: "exists == true"),- object: self- )- return XCTWaiter.wait(for: [expectation], timeout: timeout) == .completed- }-- /// Tap element without waiting for app idle.- /// Uses `press(forDuration:)` which bypasses the idle wait unlike `tap()`.- @MainActor- func tapNoIdle() {- self.coordinate(withNormalizedOffset: CGVector(dx: 0.5, dy: 0.5)).press(forDuration: 0.01)- }-- /// Clear text field and enter new text without waiting for idle.- /// Waits for keyboard to be ready before typing to prevent missing characters.- @MainActor- func clearAndTypeTextNoIdle(_ text: String, app: XCUIApplication? = nil) {- // Tap to focus- self.tapNoIdle()-- // Wait for keyboard to appear (critical for preventing missing characters)- let application = app ?? XCUIApplication()- let keyboardReady = application.keyboards.firstMatch.waitForExistenceNoIdle(timeout: 3)- if !keyboardReady {- // Retry tap if keyboard didn't appear- Thread.sleep(forTimeInterval: 0.2)- self.tapNoIdle()- _ = application.keyboards.firstMatch.waitForExistenceNoIdle(timeout: 2)- }-- // Small delay to ensure keyboard is fully ready- Thread.sleep(forTimeInterval: 0.1)-- // Clear existing text if any- if let currentValue = self.value as? String, !currentValue.isEmpty {- let deleteString = String(repeating: XCUIKeyboardKey.delete.rawValue, count: currentValue.count)- self.typeText(deleteString)- }-- // Type the new text- self.typeText(text)- }-- /// Type text with keyboard wait to prevent missing characters.- /// Use this instead of raw typeText() for more reliable input.- @MainActor- func typeTextNoIdle(_ text: String, app: XCUIApplication? = nil) {- // Wait for keyboard to appear- let application = app ?? XCUIApplication()- let keyboardReady = application.keyboards.firstMatch.waitForExistenceNoIdle(timeout: 3)- if !keyboardReady {- // Tap to focus if keyboard not visible- self.tapNoIdle()- _ = application.keyboards.firstMatch.waitForExistenceNoIdle(timeout: 2)- }-- // Small delay to ensure keyboard is fully ready- Thread.sleep(forTimeInterval: 0.1)-- // Type the text- self.typeText(text)- }-}--// MARK: - XCUIApplication Extensions--extension XCUIApplication {- /// Find any element by testID (accessibilityIdentifier).- @MainActor- func findElement(testID: String) -> XCUIElement {- return self.descendants(matching: .any).matching(identifier: testID).firstMatch- }-- /// Find a text field by testID. Checks textFields, secureTextFields, and falls back to any element.- @MainActor- func findTextField(testID: String) -> XCUIElement {- // Check textFields first- let textField = self.textFields.matching(identifier: testID).firstMatch- if textField.exists { return textField }-- // Check secureTextFields- let secureField = self.secureTextFields.matching(identifier: testID).firstMatch- if secureField.exists { return secureField }-- // Fall back to any element with that identifier- return self.descendants(matching: .any).matching(identifier: testID).firstMatch- }-- /// Find a text field and scroll to it if not visible.- @MainActor- func findAndScrollToTextField(testID: String) -> XCUIElement {- let element = findTextField(testID: testID)- if element.exists && !element.isHittable {- scrollToElement(element)- }- return element- }-- /// Wait for static text to appear.- @MainActor- func waitForText(_ text: String, timeout: TimeInterval = 10) -> Bool {- return self.staticTexts[text].waitForExistenceNoIdle(timeout: timeout)- }-- /// Wait for any element containing the specified text (searches labels and values).- @MainActor- func waitForTextContaining(_ text: String, timeout: TimeInterval = 10) -> Bool {- let predicate = NSPredicate(format: "label CONTAINS[c] %@ OR value CONTAINS[c] %@", text, text)- let element = self.descendants(matching: .any).matching(predicate).firstMatch- return element.waitForExistenceNoIdle(timeout: timeout)- }-- /// Hide keyboard if visible by tapping outside.- @MainActor- func hideKeyboardIfVisible() {- if self.keyboards.count > 0 {- let coordinate = self.coordinate(withNormalizedOffset: CGVector(dx: 0.5, dy: 0.3))- coordinate.press(forDuration: 0.01)- }- }-- /// Perform pull-to-refresh gesture.- @MainActor- func pullToRefresh(on element: XCUIElement? = nil) {- let scrollView = element ?? self.scrollViews.firstMatch- let startPoint = scrollView.coordinate(withNormalizedOffset: CGVector(dx: 0.5, dy: 0.3))- let endPoint = scrollView.coordinate(withNormalizedOffset: CGVector(dx: 0.5, dy: 0.8))- startPoint.press(forDuration: 0.1, thenDragTo: endPoint)- }-- /// Scroll to make an element visible within a scroll view.- @MainActor- func scrollToElement(_ element: XCUIElement, in scrollView: XCUIElement? = nil) {- guard !element.isHittable else { return }-- let targetScrollView = scrollView ?? self.scrollViews.firstMatch- var attempts = 0-- while !element.isHittable && attempts < 5 {- let startPoint = targetScrollView.coordinate(withNormalizedOffset: CGVector(dx: 0.5, dy: 0.7))- let endPoint = targetScrollView.coordinate(withNormalizedOffset: CGVector(dx: 0.5, dy: 0.3))- startPoint.press(forDuration: 0.1, thenDragTo: endPoint)- Thread.sleep(forTimeInterval: 0.3)- attempts += 1- }- }-- /// Open a deep link URL.- @MainActor- func openDeepLink(_ urlString: String) {- guard let url = URL(string: urlString) else {- print("[openDeepLink] Invalid URL: \(urlString)")- return- }- self.open(url)- sleep(2) // Wait for deep link to be processed- }-}diff --git a/docs/docs/contributing/development/mobile-apps/ios/e2e-testing.md b/docs/docs/contributing/development/mobile-apps/ios/e2e-testing.mdindex a8c122aaa..95a377829 100644--- a/docs/docs/contributing/development/mobile-apps/ios/e2e-testing.md+++ b/docs/docs/contributing/development/mobile-apps/ios/e2e-testing.md@@ -4,14 +4,11 @@ sidebar_label: "Testing guide"---# Testing guide-This guide explains how to run the iOS test suites for the AliasVault mobile app.+This guide explains how to run the iOS test suite for the AliasVault mobile app.## Overview-The iOS app has two test targets:--1. **AliasVaultUITests** - End-to-end UI tests that test full user flows-2. **VaultStoreKitTests** - Unit tests for the native VaultStoreKit framework+The iOS app has one test target: **VaultStoreKitTests**, the unit tests for the native VaultStoreKit framework.## Prerequisites@@ -19,7 +16,6 @@ The iOS app has two test targets:- iOS Simulator configured- Node.js 20+- CocoaPods dependencies installed (`cd apps/mobile-app && npx pod-install`)-- For UI tests: connect to your local API dev instance (by default `http://localhost:5100`)## Running Tests@@ -40,8 +36,6 @@ The iOS app has two test targets:### Via Command Line (xcodebuild)-#### Run All Tests-```bashcd apps/mobile-app/ios@@ -50,61 +44,12 @@ xcodebuild test \-workspace AliasVault.xcworkspace \-scheme AliasVault \-destination 'platform=iOS Simulator,name=iPhone 17 Pro' \+ -only-testing:VaultStoreKitTests \-resultBundlePath ./test-results```-#### Run UI Tests Only--```bash-xcodebuild test \- -workspace AliasVault.xcworkspace \- -scheme AliasVault \- -destination 'platform=iOS Simulator,name=iPhone 17 Pro' \- -only-testing:AliasVaultUITests-```--#### Run VaultStoreKit Unit Tests Only--```bash-xcodebuild test \- -workspace AliasVault.xcworkspace \- -scheme AliasVault \- -destination 'platform=iOS Simulator,name=iPhone 17 Pro' \- -only-testing:VaultStoreKitTests-```--#### Run a Specific Test--```bash-# Run a specific test class-xcodebuild test \- -workspace AliasVault.xcworkspace \- -scheme AliasVault \- -destination 'platform=iOS Simulator,name=iPhone 17 Pro' \- -only-testing:AliasVaultUITests/AliasVaultUITests--# Run a specific test method-xcodebuild test \- -workspace AliasVault.xcworkspace \- -scheme AliasVault \- -destination 'platform=iOS Simulator,name=iPhone 17 Pro' \- -only-testing:AliasVaultUITests/AliasVaultUITests/test01AppLaunch-```--#### With Custom API URL (for UI tests)--Point `API_URL` at your API dev instance (by default `5100`):--```bash-API_URL="http://your-server:5100" xcodebuild test \- -workspace AliasVault.xcworkspace \- -scheme AliasVault \- -destination 'platform=iOS Simulator,name=iPhone 17 Pro' \- -only-testing:AliasVaultUITests-```-### List Available Simulators```bashxcrun simctl list devices available-```\ No newline at end of file+```