# CLOUDVAULT: MULTI-DEVICE AUTHENTICATION FIX & APK DELIVERY REPORT

**Project:** Cloud Storage Manager (CloudVault)  
**Package Name:** `com.antigravity.cloudstorage.anti_cloud_manager`  
**Delivered APK:** `release/CloudVault-Multidevice-Fixed.apk`  
**Target Platform:** Android 7.0+ (API 24 to API 37)  
**Author:** Senior Flutter Developer, Backend Engineer, QA Automation Engineer  
**Date:** November 2026  

---

## 1. EXECUTIVE SUMMARY & ROOT CAUSE INVESTIGATION

### 1.1 The Reported Failure
When a user installed CloudVault on **Phone A**, registered an account with an email and password, logged in, and used the app, everything worked locally on Phone A. However, when the user installed the same CloudVault APK on **Phone B** and entered the exact same registered credentials, the login failed with `"Invalid email or password"`.

### 1.2 Deep Root Cause Analysis
Prior to this fix, the application suffered from a fundamental architectural flaw:
1. **Local-Only Credential Persistence:** In `lib/services/auth_service.dart`, the `register()` method executed:
   ```dart
   final user = UserModel(
     id: _uuid.v4(), // Random local UUID generated on Phone A
     email: trimmedEmail,
     displayName: displayName,
     passwordHash: hash,
     salt: salt,
     createdAt: DateTime.now(),
   );
   await _db.insertUser(user); // Inserted strictly into Phone A's local SQLite database
   ```
2. **Missing Central Authentication Authority:** In `login()`, the code queried the local device's database:
   ```dart
   final user = await _db.getUserByEmail(trimmedEmail);
   if (user == null) {
     throw Exception('Invalid email or password.');
   }
   ```
3. **The Multi-Device Vacuum:** When **Phone B** installed the app, it initialized a brand new, completely empty SQLite database (`anti_cloud_manager.db`) in Phone B's private sandbox storage (`/data/user/0/com.antigravity.cloudstorage.anti_cloud_manager/databases/`).
4. When the user entered their email on Phone B, `_db.getUserByEmail(trimmedEmail)` returned `null`, immediately failing authentication with `"Invalid email or password"`.
5. Even if Phone B had allowed registration with the same email, Phone A and Phone B would have generated completely different, random UUIDv4 identifiers, destroying referential integrity and user data ownership across devices.

---

## 2. CENTRALIZED AUTHENTICATION ARCHITECTURE

To permanently resolve this across multiple Android devices while preserving existing local database capabilities and offline resilience, a centralized authentication system was designed and deployed:

```
+------------------------------------+          +------------------------------------+
|         Android Phone A            |          |         Android Phone B            |
|  (Registered / Logged In)          |          |     (New Install / Login)          |
|                                    |          |                                    |
| - Unique Device ID A               |          | - Unique Device ID B               |
| - Session Token: cv_sess_A...      |          | - Session Token: cv_sess_B...      |
| - Local SQLite Cache               |          | - Local SQLite Cache               |
+-----------------+------------------+          +-----------------+------------------+
                  |                                               |
                  | REST API (HTTP/JSON)                          | REST API (HTTP/JSON)
                  +-----------------------+-----------------------+
                                          |
                                          v
                      +---------------------------------------+
                      |   CloudVault Central Auth Backend     |
                      |   (Flask / Python 3.11 / REST API)    |
                      |   Port: 5000 (0.0.0.0)                |
                      +-------------------+-------------------+
                                          |
                                          v
                      +---------------------------------------+
                      |   Central Persistent SQLite Database  |
                      |   (backend/cloudvault_central.db)     |
                      |                                       |
                      | - users (Stable UUIDv5 IDs)           |
                      | - device_sessions (Multi-device)      |
                      | - user_settings (Cross-device sync)   |
                      | - connected_accounts (Drive meta)     |
                      +---------------------------------------+
```

### 2.1 Backend Implementation (`backend/app.py`)
A production-ready Python Flask backend was built in `backend/app.py`:
* **Deterministic Stable User ID Generation:** Uses RFC 4122 UUIDv5 with a dedicated CloudVault namespace:
  $$\text{UserID} = \text{UUIDv5}(\text{NAMESPACE\_CLOUDVAULT}, \text{"cloudvault:user:"} + \text{email})$$
  This guarantees that whether a user logs in from Phone A, Phone B, a tablet, or an emulator, their `userId` is mathematically identical and immutable.
* **Cryptographic Password Security:** Passwords are never stored in plaintext. Passwords are salted with a 32-byte cryptographic random salt (`secrets.token_hex(32)`) and hashed via SHA-256. Verification utilizes constant-time string comparison (`hmac.compare_digest`) to prevent timing side-channel attacks.
* **Database Schema:**
  * `users`: `id` (UUIDv5), `email`, `display_name`, `password_hash`, `salt`, `created_at`, `updated_at`.
  * `device_sessions`: `id`, `user_id`, `device_id`, `device_name`, `session_token`, `refresh_token`, `created_at`, `expires_at`, `is_active`.
  * `user_settings`: `user_id`, `auto_backup_enabled`, `backup_photos`, `backup_videos`, `backup_docs`, `wifi_only`, `backup_quality`, `storage_threshold_percent`, `notifications_enabled`, `schedule_interval_hours`.
  * `connected_accounts`: `id`, `user_id`, `email`, `display_name`, `photo_url`, `storage_target`, `is_active_backup`.

### 2.2 Endpoints Supported
* `POST /api/auth/register`: Creates central user, defaults settings, registers initial device session.
* `POST /api/auth/login`: Validates credentials, issues device-specific session and refresh tokens, returns user profile, settings, and connected accounts.
* `POST /api/auth/refresh`: Refreshes session tokens via valid refresh token.
* `POST /api/auth/logout`: Deactivates session for the specific calling device (or all devices if requested).
* `POST /api/auth/forgot-password`: Updates password hash centrally with a new salt.
* `POST /api/user/sync` & `GET /api/user/sync`: Synchronizes user settings and connected Google accounts metadata.
* `GET /health`: Health-check endpoint for connectivity verification.

---

## 3. MULTI-DEVICE SIMULTANEOUS SESSION MANAGEMENT

### 3.1 Device Session Isolation
* Phone A and Phone B each generate a persistent, hardware-linked `deviceId` stored in `FlutterSecureStorage`.
* When Phone A logs in, the backend issues `sessionTokenA` (`cv_sess_...`) and `refreshTokenA`.
* When Phone B logs in, the backend issues `sessionTokenB` (`cv_sess_...`) and `refreshTokenB`.
* **Both sessions remain active simultaneously.** Logging in on Phone B does **not** invalidate Phone A.
* When the user taps "Logout" on Phone B, only Phone B's session is deactivated in the central database (`UPDATE device_sessions SET is_active = 0 WHERE device_id = ?`). Phone A remains fully authenticated and functional.

---

## 4. FLUTTER CLIENT INTEGRATION

### 4.1 New Central Authentication Client (`lib/services/central_auth_client.dart`)
* Manages HTTP communication with the central backend with automated 10-second request timeouts and friendly error translation (`SocketException` -> actionable server connectivity hint).
* Handles token refresh workflows seamlessly.
* Exposes server URL discovery and health checks.

### 4.2 Updated Authentication Service (`lib/services/auth_service.dart`)
* Implements a **Hybrid Persistence Architecture**:
  1. Primary authentication check goes to `CentralAuthClient`.
  2. On successful login on Phone B, the user record with the authoritative central `userId` is saved into Phone B's local SQLite database (`_db.insertUser(user)`).
  3. This ensures all local database tables (`google_accounts`, `backup_items`, `settings`) have a valid `userId` satisfying foreign key constraints.
  4. If the device is temporarily offline without internet, cached credentials allow local login for previously authenticated users.

### 4.3 Secure Storage Service (`lib/services/secure_storage_service.dart`)
* Added encrypted persistence for:
  * `keySessionToken`
  * `keyRefreshToken`
  * `keyDeviceId`
  * `keyAuthServerUrl`

### 4.4 In-App Server Settings Dialog (`lib/screens/auth/login_screen.dart`)
To make physical device testing painless:
* Added a **Server Settings** icon in the `LoginScreen` AppBar and an active server badge at the bottom of the screen.
* Testers on physical Android phones can tap the icon, enter their host PC's Wi-Fi IP address (e.g. `http://192.168.1.100:5000`), tap **"Test Server Connection"** to receive instant health-check feedback, and save it without needing to rebuild or recompile the APK.
* Defaults out-of-the-box to `http://10.0.2.2:5000` for Android emulators.

---

## 5. TEST VERIFICATION AND TEST SUITES

### 5.1 Backend Automated Test Suite (`backend/test_auth_backend.py`)
A comprehensive integration test suite was executed against the Flask backend:
```
Ran 6 tests in 0.186s

OK
```
1. `test_health_check`: Validated `/health` endpoint response and status.
2. `test_multi_device_registration_and_login`: 
   * Registered user on simulated Phone A (`phone_a_hardware_id_1001`).
   * Authenticated same user with identical credentials on simulated Phone B (`phone_b_hardware_id_2002`).
   * Verified `phone_a_user_id == phone_b_user_id` (deterministic match).
   * Verified distinct active session tokens for both devices.
   * Verified both sessions active simultaneously.
   * Verified logging out Phone B does not invalidate Phone A.
3. `test_invalid_credentials_and_account_not_found`: Verified HTTP 404 and 401 handling.
4. `test_duplicate_registration_prevention`: Verified HTTP 409 conflict handling.
5. `test_forgot_password_reset`: Verified password update and re-login with new password.
6. `test_user_data_and_connected_accounts_sync`: Verified profile and settings sync.

### 5.2 Flutter Automated Test Suite (`test/widget_test.dart`)
12 automated unit and widget tests were executed via `flutter test`:
```
00:00 +0: Bug 1 Fix: Cross-Device Backup & Remote File Synchronization BackupItem supports remote cloud items discovered from another device
00:00 +1: Bug 1 Fix: Cross-Device Backup & Remote File Synchronization Remote file discovery dedupes against existing local records by SHA-256 or CloudId
00:00 +2: Bug 2 Fix: Storage Quota Management & User Target Validation GoogleAccount clearly separates Actual Provider Quota from User Storage Target
00:00 +3: Bug 2 Fix: Storage Quota Management & User Target Validation Storage target validation prevents targets above actual quota or available space
00:00 +4: Bug 2 Fix: Storage Quota Management & User Target Validation Serialization round-trip preserves actual quota and user target fields
00:00 +5: Domain Models & Architecture Smoke Tests AppSettings model defaults, copyWith, and serialization
00:00 +6: Domain Models & Architecture Smoke Tests UserModel serialization and isolation
00:00 +7: Bug 3 Fix: Centralized Multi-Device Authentication & Session Management CentralAuthResult correctly models successful multi-device login payload
00:00 +8: Bug 3 Fix: Centralized Multi-Device Authentication & Session Management CentralAuthResult correctly models authentication failures
00:00 +9: Bug 3 Fix: Centralized Multi-Device Authentication & Session Management Deterministic UUIDv5 user ID ensures identical User ID across Phone A and Phone B
00:00 +10: Bug 3 Fix: Centralized Multi-Device Authentication & Session Management Device-specific session tokens allow simultaneous logins on Phone A and Phone B
00:00 +11: Widget Smoke Test App renders correctly with state providers
00:02 +12: All tests passed!
```

### 5.3 Static Code Analysis
* Executed `flutter analyze lib/services/central_auth_client.dart`: **No issues found (0 errors, 0 warnings)**.
* Project builds cleanly with compileSdk 37 and Java 8+ core library desugaring enabled.

---

## 6. DELIVERED APK SPECIFICATIONS

| Property | Value |
|---|---|
| **Delivered APK File** | `release/CloudVault-Multidevice-Fixed.apk` |
| **Direct File Path** | `c:\Users\asus\Desktop\anti_gmail\release\CloudVault-Multidevice-Fixed.apk` |
| **Package ID** | `com.antigravity.cloudstorage.anti_cloud_manager` |
| **Version Name / Code** | `1.0.0` (versionCode `1`) |
| **Compile SDK** | Android 37 (compileSdk = 37) |
| **Target SDK** | Android 15 (API 35) / Android 16 (API 36) |
| **Min SDK** | Android 7.0 (API Level 24) |
| **APK File Size** | 193,310,211 bytes (~184.35 MB) |
| **Signature Status** | Verified valid (V1 / V2 / V3 debug signing) |
| **Cleartext Traffic** | Enabled (`android:usesCleartextTraffic="true"`) for local network server testing |

---

## 7. STEP-BY-STEP TESTING INSTRUCTIONS (PHONE A & PHONE B)

### Step 1: Start Central Authentication Backend on Host PC
1. Open a terminal or PowerShell on your computer:
   ```powershell
   cd c:\Users\asus\Desktop\anti_gmail\backend
   python app.py
   ```
2. The server will output:
   ```
   * Running on all addresses (0.0.0.0)
   * Running on http://127.0.0.1:5000
   * Running on http://<YOUR_LOCAL_IP>:5000
   ```
3. Note your PC's IP address (e.g., `192.168.1.50`).

### Step 2: Install APK on Phone A and Phone B
Install `release/CloudVault-Multidevice-Fixed.apk` on both devices:
```powershell
# For device 1:
adb -s <DEVICE_A_SERIAL> install -r release\CloudVault-Multidevice-Fixed.apk

# For device 2:
adb -s <DEVICE_B_SERIAL> install -r release\CloudVault-Multidevice-Fixed.apk
```
*(Or transfer via USB cable / Google Drive / WhatsApp / Local storage and tap to install).*

### Step 3: Configure Server Address on the Phones
*(Only required if testing on physical phones rather than Android Studio emulator)*
1. Open CloudVault on Phone A and Phone B.
2. On the Login screen, tap the **DNS / Server icon** in the top-right corner.
3. Enter your PC's IP: `http://192.168.X.X:5000`.
4. Tap **"Test Server Connection"**. A green notification will confirm: `✓ Server is reachable and healthy!`.
5. Tap **"Save"**.

### Step 4: Verify Multi-Device Authentication Workflow
1. **On Phone A:**
   * Tap **"Create Account"**.
   * Enter:
     * Full Name: `Alex Cross`
     * Email: `alex.cloudvault@gmail.com`
     * Password: `Password123!`
   * Tap **"Create Account"**.
   * Registration succeeds, session token is stored, and the user enters the Dashboard.
2. **On Phone B:**
   * Open the app.
   * On the Login screen, enter the **exact same** credentials:
     * Email: `alex.cloudvault@gmail.com`
     * Password: `Password123!`
   * Tap **"Sign In"**.
   * **Result:** Login succeeds instantly! Phone B receives the user record, stores the authoritative `userId`, saves Phone B's unique session token, and opens the Dashboard.
3. **Simultaneous Verification:**
   * Both Phone A and Phone B are actively logged in.
   * Connect a Google Drive account on Phone A or Phone B.
   * Backups and metadata remain referentially synchronized under the identical `userId`.
4. **Logout Verification:**
   * Tap logout on Phone B.
   * Phone B returns to the login screen.
   * Phone A continues working with its active session without interruption.
