Colota - Android GPS Location tracker
feat: encrypted backup and restore (#380)
Max Dietrichdd8257f10fc0
diff --git a/README.md b/README.mdindex 0f20019d..941d5dba 100644--- a/README.md+++ b/README.md@@ -19,6 +19,7 @@ Colota sends your location to your own server over HTTP(S). It works offline, su- **Works Offline** - Fully functional without a server. Export as CSV, GeoJSON, GPX or KML.- **Offline Maps** - Download map areas to your device for use without an internet connection.- **Scheduled Export** - Automatic daily, weekly or monthly exports to a local directory with file retention management.+- **Encrypted Backup** - Single password-encrypted archive of all data (locations, settings, geofences, credentials) for migration or offsite storage.- **Location History** - View daily summaries, trip segmentation, calendar with activity dots and per-trip export.- **Reliable Tracking** - Foreground service, auto-start on boot and exponential backoff retry.- **Geofencing** - Pause zones that automatically stop recording locations.@@ -27,7 +28,7 @@ Colota sends your location to your own server over HTTP(S). It works offline, su- **Display Settings** - Choose between metric and imperial units, 12h or 24h time format. Auto-detected from device locale on first use.- **App Shortcuts** - Long-press the app icon to start or stop tracking directly from the home screen, compatible with automation apps like Tasker and Samsung Routines.- **Quick Setup** - Configure devices via `colota://setup` deep links or QR codes.-- **Authentication** - Basic Auth, Bearer Token or custom headers with AES-256-GCM encryption. Optional mutual TLS (mTLS) with a PKCS12 client certificate stored in Android Keystore.+- **Authentication** - Basic Auth, Bearer Token or custom headers. Optional mutual TLS (mTLS) with a PKCS12 client certificate stored in Android Keystore.- **Dark Mode** - Full light and dark theme support.## Screenshotsdiff --git a/apps/docs/docs/development/architecture.md b/apps/docs/docs/development/architecture.mdindex f4a56189..a1d79b66 100644--- a/apps/docs/docs/development/architecture.md+++ b/apps/docs/docs/development/architecture.md@@ -48,10 +48,14 @@ The mobile app has a **React Native** UI layer and **native Kotlin** modules forAll native code lives in `apps/mobile/android/app/src/`, organized by build flavor:-- `src/main/java/com/colota/` - Shared code: `bridge/`, `service/`, `data/`, `sync/`, `util/`, `location/` (interface)+- `src/main/java/com/colota/` - Shared code: `bridge/`, `service/`, `data/`, `sync/`, `util/`, `location/` (interface), `backup/`, `export/`- `src/gms/java/com/colota/location/` - Google Play Services location provider- `src/foss/java/com/colota/location/` - Native Android location provider+### Bridge Modules++Two React Native bridge modules are registered by `LocationServicePackage`: `LocationServiceModule` (the primary tracking-side bridge) and `BackupServiceModule` (the encrypted-backup bridge).+### LocationServiceModuleThe primary React Native bridge module (exposed as `"LocationServiceModule"`). Handles all JS-to-native communication for:@@ -72,6 +76,33 @@ Emits events back to JavaScript:- `onProfileSwitch` - a tracking profile was activated or deactivated- `onAutoExportComplete` - auto-export finished with `{success, fileName, rowCount, error}`+### BackupServiceModule++Second React Native bridge module (exposed as `"BackupServiceModule"`). Owns the encrypted backup pipeline end-to-end so the JS layer never touches credentials, the SQLite file, or the Argon2 key directly. JS-callable methods:++- `pickBackupDestination` / `pickBackupSource` - launches the Storage Access Framework picker (`ACTION_CREATE_DOCUMENT` / `ACTION_OPEN_DOCUMENT`); a single in-flight picker is enforced via a 5-minute timeout.+- `createBackup(uri, password)` - validates password strength, claims an operation mutex, runs `BackupBuilder` against a cacheDir-staged file, then atomically copies into the SAF destination. Stops promotion to a foreground service when finished.+- `restoreBackup(uri, password)` - cancels the location service and any auto-export work, polls until both stop, runs `BackupRestorer`, then forces `tracking_enabled=false` so the destination device doesn't auto-resume.+- `applyRestore` - JS calls this after the success dialog is dismissed; it triggers `reactHost.reload()` so all modules re-read state from the restored DB.++Both `createBackup` and `restoreBackup` await `BackupOrphanCleanup.awaitComplete()` before claiming the operation mutex, ensuring the launch-time orphan sweeper can't race active operations.++Errors are surfaced to JS as `E_BACKUP_<ERROR_NAME>` codes that map onto the `BackupError` enum (`WRONG_PASSWORD`, `BAD_MAGIC`, `UNSUPPORTED_VERSION`, `UNSUPPORTED_KDF`, `UNSUPPORTED_SCHEMA`, `MISSING_ENTRY`, `INTEGRITY_FAIL`, `TRUNCATED`, `TAMPERED`, `SECRETS_PARTIAL`).++### Backup Pipeline++Native-only modules in `backup/` package. The on-disk format is documented in `BackupFormat.kt`.++| Module | Purpose |+| --- | --- |+| `BackupCrypto` | Chunked AES-256-GCM encrypt/decrypt keyed by Argon2id. Each chunk binds the file header into its GCM AAD so any header tamper invalidates the first tag. Argon2 is deferred until the first ciphertext chunk arrives so wrong-password rejection costs no key derivation. |+| `BackupFormat` | On-disk layout constants, `BackupHeader` data class, `BackupError` enum, and `BackupException`. 76-byte header (magic, format version, KDF id, KDF params, 32-byte salt, 8-byte nonce prefix, chunk size, reserved) followed by length-prefixed ciphertext chunks and an end-marker + chunk-count footer. |+| `BackupBuilder` | Snapshots the SQLite database via `DatabaseHelper.snapshotTo` (uses `VACUUM INTO` on API 30+, file-copy with WAL checkpoint as fallback), runs `quick_check`, extracts secrets via `SecureStorageHelper.exportPlaintextForBackup()`, deflates everything into a zip, then streams it through `BackupCrypto.encrypt`. Picks Argon2 memory by `ActivityManager.isLowRamDevice` (32 MiB / 64 MiB). |+| `BackupRestorer` | Decrypts the file via a `PipedInputStream` into a `ZipInputStream`, extracts entries to a temp dir with bounded reads (zip-bomb defense), validates the manifest schema version, runs `PRAGMA integrity_check` on the candidate DB, calls `DatabaseHelper.migrateCandidate` to run any required migrations on the candidate, then atomically swaps the live DB via `DatabaseHelper.replaceLiveDatabase`, then re-imports secrets. A failed secrets commit is surfaced as `SECRETS_PARTIAL` so the UI can prompt the user to re-enter credentials. |+| `BackupForegroundService` | Notification-only foreground service shown during long backups/restores. Uses `FOREGROUND_SERVICE_TYPE_DATA_SYNC`. Holds no work itself - the actual encryption stays in `BackupServiceModule`'s coroutine so the password `CharArray` lives only on the heap, not in service state. |+| `BackupOrphanCleanup` | Singleton kicked off from `MainApplication.onCreate` on a daemon thread. Sweeps `cacheDir/backup_temp`, `cacheDir/restore_temp`, `cacheDir/pending_backup.colota`, and `<dbDir>/Colota.db.incoming` left behind by a process death mid-operation. Exposes a `CompletableDeferred` so `BackupServiceModule` can await completion before claiming the operation mutex. |+| `PasswordStrength` | Mirror of the JS-side `passwordStrength.ts`. Enforces the 12-character floor and ~50-bit entropy floor; sequential runs and `<4` distinct chars cap the score. |+### LocationProvider AbstractionLocation services are abstracted behind a `LocationProvider` interface (`location/LocationProvider.kt`), with flavor-specific implementations:@@ -118,6 +149,12 @@ SQLite database singleton with five tables:Uses WAL (Write-Ahead Logging) mode and prepared statements for performance.+Three additional methods support the backup pipeline:++- `snapshotTo(destFile)` - produces a transactional copy of the live DB. Uses `VACUUM INTO` on API 30+; falls back to a file copy with a `wal_checkpoint(FULL)` on API 26-29.+- `migrateCandidate(file)` - runs schema migrations on a candidate file in `DELETE` journal mode before it is swapped in, so a migration failure leaves the live DB untouched.+- `replaceLiveDatabase(context, newDb)` - drains the live WAL via `wal_checkpoint(TRUNCATE)`, deletes the live `-wal`/`-shm`/`-journal` sidecars, then atomically moves the candidate into place. Handles `AtomicMoveNotSupportedException` by staging through an `<dbName>.incoming` file. Synchronizes with `getInstance()` so concurrent callers either see the old singleton or the new file.+### SyncManagerOrchestrates batch location uploads with:@@ -179,6 +216,11 @@ Centralized constants for condition type strings (`charging`, `android_auto`, `sWraps Android's `EncryptedSharedPreferences` for encrypted credential storage (AES-256-GCM for values, AES-256-SIV for keys). Stores Basic Auth passwords, Bearer tokens, custom headers, and the user-imported server CA (public cert, no key material). Client certificate private keys live in Android Keystore instead, not here - see `ClientCertSslContextProvider`.+For backups, two `internal` methods support the export/import flow without exposing plaintext secrets to other modules:++- `exportPlaintextForBackup()` - returns the BACKED_UP_KEYS as a `Map<String, String>` for inclusion in the encrypted backup container.+- `importPlaintextFromBackup(secrets)` - clears all BACKED_UP_KEYS then writes the new map in a single sync `commit()`. Throws on commit failure so the restore path can report `SECRETS_PARTIAL`.+### Other Modules| Module | Purpose |@@ -224,6 +266,7 @@ Wraps Android's `EncryptedSharedPreferences` for encrypted credential storage (A| `AutoExportScreen` | Configure scheduled auto-export: directory, format, frequency, time of day, weekday or day-of-month, export range and file retention || `OfflineMapsScreen` | Download and manage offline map areas - interactive bounding box picker, size estimate, progress tracking, and area deletion || `DataManagementScreen` | Clear sent history, delete old data, vacuum database, sync controls |+| `BackupRestoreScreen` | Create or restore a password-encrypted `.colota` archive of all data, with strength meter and no-recovery confirmation || `SetupImportScreen` | Confirmation screen for `colota://setup` deep link imports || `ActivityLogScreen` | In-app log viewer with level filtering, search, and export || `AboutScreen` | App version, device info, links to repository and privacy policy |@@ -236,6 +279,7 @@ Wraps Android's `EncryptedSharedPreferences` for encrypted credential storage (A| `LocationServicePermission` | Sequential Android permission requests (fine location → background location → notifications → battery exemption) || `ProfileService` | Thin wrapper over `NativeLocationService` for tracking profile CRUD and trip event queries || `SettingsService` | Bridges UI state to native SQLite with type conversion (seconds↔ms, objects↔JSON) |+| `BackupService` | Thin TypeScript wrapper over the native `BackupServiceModule` exposing `pickBackupDestination`, `pickBackupSource`, `createBackup`, `restoreBackup`, `applyRestore`. Surfaces typed `BackupErrorCode` strings for screen-side messaging || `modalService` | Centralized alert and confirm dialogs via `showAlert()` and `showConfirm()` |### Map Componentsdiff --git a/apps/docs/docs/development/local-setup.md b/apps/docs/docs/development/local-setup.mdindex 2916368e..be5dd29f 100644--- a/apps/docs/docs/development/local-setup.md+++ b/apps/docs/docs/development/local-setup.md@@ -113,12 +113,14 @@ colota/│ │ │ │ ├── service/ # Foreground service, config & notifications│ │ │ │ ├── data/ # SQLite & geofencing│ │ │ │ ├── sync/ # Network sync & payloads+│ │ │ │ ├── export/ # Auto-export worker, scheduler & converters+│ │ │ │ ├── backup/ # Encrypted backup builder, restorer & crypto│ │ │ │ ├── util/ # Helpers & encryption│ │ │ │ └── location/ # LocationProvider interface│ │ │ ├── gms/java/com/colota/location/ # GMS implementation│ │ │ └── foss/java/com/colota/location/ # Native implementation│ │ ├── src/-│ │ │ ├── screens/ # 17 app screens+│ │ │ ├── screens/ # 23 app screens│ │ │ ├── components/ # UI and feature components│ │ │ ├── hooks/ # Custom React hooks│ │ │ ├── services/ # Native bridge servicesdiff --git a/apps/docs/docs/development/permissions.md b/apps/docs/docs/development/permissions.mdindex 32dfc954..87a0ff2f 100644--- a/apps/docs/docs/development/permissions.md+++ b/apps/docs/docs/development/permissions.md@@ -56,7 +56,7 @@ android.permission.FOREGROUND_SERVICE_LOCATIONandroid.permission.FOREGROUND_SERVICE_DATA_SYNC```-Android requires apps to declare a foreground service with a persistent notification to run in the background. The `FOREGROUND_SERVICE_LOCATION` type specifically indicates the service accesses location data. This is what keeps the "Colota is tracking" notification visible. The `FOREGROUND_SERVICE_DATA_SYNC` type is used by the auto-export WorkManager service for scheduled background exports.+Android requires apps to declare a foreground service with a persistent notification to run in the background. The `FOREGROUND_SERVICE_LOCATION` type specifically indicates the service accesses location data. This is what keeps the "Colota is tracking" notification visible. The `FOREGROUND_SERVICE_DATA_SYNC` type is used by the auto-export WorkManager service for scheduled background exports and by the encrypted backup/restore service for the encryption phase.### Networkdiff --git a/apps/docs/docs/faq.md b/apps/docs/docs/faq.mdindex 4de951d1..df02e026 100644--- a/apps/docs/docs/faq.md+++ b/apps/docs/docs/faq.md@@ -48,6 +48,18 @@ Yes. Go to **Settings > Offline Maps** to download map areas to your device. PanYes. Tap **Export** on the Dashboard to export in CSV, GeoJSON, GPX, or KML. See [Data Export](/docs/guides/data-export) for details.+### Can I back up everything and move to a new device?++Yes. Go to **Settings → Backup & Restore** to create a single password-encrypted `.colota` file containing your locations, settings, geofences and credentials. Restore it on the new device with the same password. See [Backup & Restore](/docs/guides/backup-restore) for details.++### I forgot my backup password, can I recover it?++No. Backups are encrypted with a key derived from your password. There is no recovery code, no email reset and no developer override. If the password is lost the data inside is unrecoverable. Store the password in a password manager before creating the backup.++### Will restoring a backup overwrite my current data?++Yes. Restore is replace-everything: locations, settings, geofences and credentials currently on the device are replaced by what's in the backup. There is no merge mode. If you want to keep the current data, take a backup of it first.+### What happens when the phone restarts?If auto-start on boot is enabled, Colota automatically resumes tracking after a device restart when tracking was active before.diff --git a/apps/docs/docs/guides/backup-restore.md b/apps/docs/docs/guides/backup-restore.mdnew file mode 100644index 00000000..1cba5782--- /dev/null+++ b/apps/docs/docs/guides/backup-restore.md@@ -0,0 +1,103 @@+---+sidebar_position: 3+---++# Backup & Restore++Bundle your locations, settings and credentials into a single password-encrypted file you can store anywhere - cloud drive, USB stick, another device.++Use this when you want a full archive of your data, when you're moving to a new device, or as insurance before clearing data. For day-to-day analysis or sharing tracks, use [Data Export](data-export.md) instead.++## What's Included++| Included | Excluded |+| --- | --- |+| Location history (the full SQLite database) | Activity log (would leak endpoints and SSIDs) |+| Settings (sync, GPS, server, appearance) | Offline map tiles (re-download after restore) |+| Geofences and tracking profiles | Cached map tiles |+| Auth credentials (Basic, Bearer, custom headers) | mTLS client certificate (private key in OS keystore - re-import the `.p12` after restore) |+| mTLS Trusted Server CA (public cert bytes) | |++The auth credentials Colota uses to reach your tracking endpoint (Basic Auth, Bearer token, custom headers) are stored as plaintext inside the encrypted container - they are protected by the backup password, not by the device's hardware-backed key. The leaked credentials let an attacker do whatever your server lets those credentials do. If you configured Colota with a credential limited to writing location data, that's all an attacker gets. If you used a credential tied to a user with broader privileges, or any token with more scope than posting locations requires, the attacker inherits that scope. Configure Colota with the minimum permission its endpoint actually needs. On restore the credentials are rewrapped under the destination device's key.++## Creating a Backup++1. Go to **Settings → Backup & Restore**+2. Enter a password (12 characters minimum) and confirm it+3. Wait for the strength meter to reach at least **OK**+4. Tap **Create backup**+5. Acknowledge the no-recovery warning+6. Choose where to save the `.colota` file++The app encrypts the file as it writes. You can leave the screen and the backup keeps running in the foreground until it finishes; a notification shows progress.++### Password Requirements++- **12 characters minimum** (hard limit)+- **~50 bits of entropy minimum** (soft strength meter)+- Sequences like `abcd` and `1234` cap the score, as do passwords with fewer than 4 distinct characters++A random 16-character password from a password manager, or a 4-5 word passphrase, both clear the bar comfortably. Common words and short tweaks of dictionary words do not.++:::warning++No password recovery If you lose the password, the backup cannot be opened. Ever. There is no recovery code, no email reset, no developer override. Store the password somewhere you trust before you create the backup.++:::++## Restoring from a Backup++:::danger++Replaces all current data Restoring overwrites every location, setting, geofence and credential currently on the device. There is no merge mode and no undo. Take a backup of the current device first if you might want to roll back.++:::++1. Go to **Settings → Backup & Restore**+2. Tap **Choose backup file** and pick the `.colota` file+3. Enter the backup password when prompted+4. Confirm the replace warning+5. The app pauses tracking, swaps the database and restarts itself+6. Re-enable tracking from the Home screen when you're ready++### What Gets Paused++To swap the database safely, the restore stops the location tracking service and any in-flight auto-export. If a writer can't be stopped within ~5 seconds the restore aborts before touching your data.++After restore, tracking is left **off** so the new device doesn't silently start uploading on the old credentials. Re-enable it when you've checked the data is correct.++## Compatibility++| Source backup schema | Destination app schema | Result |+| ---------------------- | ---------------------- | ------------------------------ |+| Same as destination | - | Direct restore |+| Older than destination | - | Restored, then auto-migrated |+| Newer than destination | - | Refused - update the app first |++Backups are forward-compatible (open in the same or newer app version) but not backward-compatible. If you upgraded recently and need to restore an older backup, just install the latest version.++## File Format++| Property | Value |+| --------- | -------------------------- |+| Extension | `.colota` |+| MIME type | `application/octet-stream` |++Each file is authenticated end-to-end with a key derived from your password. Wrong password, a flipped byte, or truncation all fail to open. The format and implementation live in [`BackupFormat.kt`](https://github.com/dietrichmax/colota/blob/main/apps/mobile/android/app/src/main/java/com/colota/backup/BackupFormat.kt) and [`BackupCrypto.kt`](https://github.com/dietrichmax/colota/blob/main/apps/mobile/android/app/src/main/java/com/colota/backup/BackupCrypto.kt) if you want to verify.++## Failure Modes++| Error message | Cause |+| ------------------------------------------- | --------------------------------------------------------- |+| Incorrect password, or corrupted near start | Wrong password, or the first chunk has been tampered with |+| This file is not a Colota backup | Magic bytes don't match - file is something else |+| Made with a newer version of Colota | Schema is ahead of the installed app |+| Backup file is corrupted / incomplete | Mid-file tamper or truncation |+| Backup file is missing required data | Container is missing the database or manifest entry |+| Credentials could not be applied | Database restored, but credential write failed |++If a backup fails mid-encrypt, the app deletes the partial `.colota` file at the destination. If that cleanup fails (some cloud providers reject delete on freshly-created files), the error message tells you to delete it manually.++## Storage Reference++A backup is roughly the size of your SQLite database after deflate compression (typically 30-60% of the raw DB size). Use the [Data Management](data-management.md) screen to see the current database size before backing up.diff --git a/apps/docs/docs/guides/data-export.md b/apps/docs/docs/guides/data-export.mdindex 4a7520a8..52ab244d 100644--- a/apps/docs/docs/guides/data-export.md+++ b/apps/docs/docs/guides/data-export.md@@ -6,6 +6,12 @@ sidebar_position: 2Export your location history in multiple formats.+:::tip Looking for a full archive?++Data Export produces shareable, human-readable formats (CSV, GeoJSON, GPX, KML) of your location history. If you instead want a single password-encrypted archive of **everything** - locations, settings, geofences and credentials - for device migration or offsite storage, use [Backup & Restore](backup-restore.md).++:::+## Supported Formats| Format | Extension | Use Case |diff --git a/apps/docs/docs/guides/data-management.md b/apps/docs/docs/guides/data-management.mdindex 1a619a73..f6b77c27 100644--- a/apps/docs/docs/guides/data-management.md+++ b/apps/docs/docs/guides/data-management.md@@ -23,6 +23,8 @@ import ScreenshotGallery from '@site/src/components/ScreenshotGallery'In [offline mode](/docs/configuration/server-settings#offline-mode), sync-related actions (Sync Now, Clear Sent History, Clear Queue) are hidden since no queue is used. A **Delete All Locations** action is available instead. Data export remains fully available - see [Data Export](data-export.md).+For a full archive of locations, settings and credentials in a single password-encrypted file, use **Settings → Backup & Restore** - see [Backup & Restore](backup-restore.md).+## Storage Reference- ~200 bytes per locationdiff --git a/apps/docs/docs/guides/deep-link-setup.md b/apps/docs/docs/guides/deep-link-setup.mdindex 85713682..fc7bdc75 100644--- a/apps/docs/docs/guides/deep-link-setup.md+++ b/apps/docs/docs/guides/deep-link-setup.md@@ -134,4 +134,3 @@ print(f'colota://setup?config={encoded}')- The configuration URL is not encrypted. Avoid putting sensitive tokens in QR codes displayed in public.- All settings are shown to the user for confirmation before being applied.-- Auth credentials are stored in AES-256-GCM encrypted storage on device after import.diff --git a/apps/docs/docs/introduction.md b/apps/docs/docs/introduction.mdindex 90b0a8e1..842c241a 100644--- a/apps/docs/docs/introduction.md+++ b/apps/docs/docs/introduction.md@@ -14,6 +14,7 @@ Colota is a self-hosted GPS tracking app for Android. It sends your location to- **Works Offline** - Fully functional without a server. Export as CSV, GeoJSON, GPX, or KML.- **Offline Maps** - Download map areas to your device for use without an internet connection.- **Scheduled Export** - Automatic daily, weekly or monthly exports to a local directory with file retention management.+- **Encrypted Backup** - Single password-encrypted archive of locations, settings, geofences and credentials.- **Location History** - View daily summaries, trip segmentation, calendar with activity dots and per-trip export.- **Reliable Tracking** - Foreground service, auto-start on boot and exponential backoff retry.- **Geofencing** - Pause zones that stop recording locations. Optionally stop GPS entirely when on WiFi or when the device is motionless.@@ -21,12 +22,12 @@ Colota is a self-hosted GPS tracking app for Android. It sends your location to- **Flexible Sync** - Instant, batch, Wi-Fi only or offline modes.- **Display Settings** - Choose between metric and imperial units, 12h or 24h time format. Auto-detected from device locale on first use.- **Quick Setup** - Configure devices via `colota://setup` deep links or QR codes.-- **Authentication** - Basic Auth, Bearer Token or custom headers with AES-256-GCM encryption.+- **Authentication** - Basic Auth, Bearer Token or custom headers- **Dark Mode** - Full light and dark theme support.## App Screens-Colota has twenty-one screens, each focused on a specific task:+Colota has twenty-two screens, each focused on a specific task:| Screen | Purpose || --- | --- |@@ -48,6 +49,7 @@ Colota has twenty-one screens, each focused on a specific task:| **Export Data** | Export tracked locations as CSV, GeoJSON, GPX, or KML || **Auto-Export** | Configure scheduled exports: directory, format, frequency, time of day (with weekday or day-of-month for weekly/monthly), export range and file retention || **Data Management** | Clear sent history, delete old data, vacuum the database |+| **Backup & Restore** | Create or restore a single password-encrypted `.colota` archive of all data (locations, settings, geofences, credentials) || **Setup Import** | Confirmation screen for deep link configuration imports (`colota://setup`) || **Activity Log** | In-app log viewer with level filtering, search, and export for bug reports || **About** | App version, device info, links to repository and privacy policy |diff --git a/apps/docs/docs/security.md b/apps/docs/docs/security.mdindex 9ee8ec7b..5098765e 100644--- a/apps/docs/docs/security.md+++ b/apps/docs/docs/security.md@@ -35,6 +35,20 @@ Location history is stored in a local SQLite database on the device. The databasThe database is not accessible to other apps (standard Android sandboxing).+## Encrypted Backups++Colota can produce a single password-encrypted archive of your full dataset (locations, settings, geofences, credentials) for off-device storage or device migration. See the [Backup & Restore guide](/docs/guides/backup-restore) for the user-facing flow. The relevant security properties:++- **Cipher**: AES-256-GCM, chunked at 1 MiB of plaintext per chunk. Each chunk's GCM tag binds the file header as additional authenticated data, so any flip in the header (KDF parameters, salt, nonce prefix) invalidates the very first tag.+- **Key derivation**: Argon2id with 64 MiB memory, 3 iterations and 1 lane on standard devices; 32 MiB on devices flagged as low-RAM by Android. The salt is 32 bytes from `SecureRandom`, fresh per backup.+- **Password floor**: 12 characters, with a strength meter that enforces ~50 bits of entropy (passwords with sequential runs or fewer than 4 distinct characters are capped).+- **No recovery**: forgotten password means an unreadable file. There is no escrow, recovery code or developer override.+- **Credential handling**: the auth credentials Colota uses to talk to your tracking endpoint (Basic Auth username/password, Bearer token, custom HTTP headers) are extracted from `EncryptedSharedPreferences` and written as plaintext **inside** the encrypted container. They are protected by the backup password, not by the device's hardware-backed key. The blast radius equals whatever your server lets those credentials do - a credential limited to writing locations caps damage at fake location posts; a credential tied to a user with broader privileges, or any token with more scope than the endpoint actually needs, gives the attacker that same scope. Configure Colota with the minimum permission its endpoint requires. On restore the credentials are re-wrapped under the destination device's key.+- **mTLS**: the user-imported Trusted Server CA (public cert bytes) is included so a self-signed server stays reachable after restore. The mTLS **client certificate is not backed up** by design - the private key lives in the Android KeyChain (often hardware-backed) and cannot leave the source device. Re-import the `.p12` on the destination device after restore.+- **Format independence**: the on-disk format is FOSS (BouncyCastle, no Tink/Google dependency) and stays stable independently of the in-app `EncryptedSharedPreferences` implementation.++The format is fully documented in [`BackupFormat.kt`](https://github.com/dietrichmax/colota/blob/main/apps/mobile/android/app/src/main/java/com/colota/backup/BackupFormat.kt).+## What Colota Does Not Do- No analytics, telemetry or crash reportingdiff --git a/apps/docs/sidebars.ts b/apps/docs/sidebars.tsindex b98411a2..3a3f44fe 100644--- a/apps/docs/sidebars.ts+++ b/apps/docs/sidebars.ts@@ -49,6 +49,7 @@ const sidebars: SidebarsConfig = {"guides/app-shortcuts","guides/data-export","guides/data-management",+ "guides/backup-restore","guides/deep-link-setup","guides/battery-optimization","guides/offline-maps",diff --git a/apps/docs/src/pages/privacy-policy.md b/apps/docs/src/pages/privacy-policy.mdindex c4ea038f..b424a57d 100644--- a/apps/docs/src/pages/privacy-policy.md+++ b/apps/docs/src/pages/privacy-policy.md@@ -4,7 +4,7 @@ title: Privacy Policy# Privacy Policy-**Last updated: May 11, 2026**+**Last updated: May 20, 2026**Colota ("the App") is a self-hosted GPS tracking application for Android, developed by Max Dietrich. This privacy policy explains what data the App collects, how it is used, and your rights regarding that data.@@ -52,7 +52,15 @@ Collected data is stored in a local SQLite database on your device. The data isIf you configure auto-export, the App will write export files (CSV, GeoJSON, GPX, or KML) to a directory you select on your device. No data leaves your device as part of this process.-Authentication credentials (if configured) are encrypted using **AES-256-GCM** via Android's `EncryptedSharedPreferences`.+Authentication credentials (if configured) are encrypted.++### Encrypted Backups++You can create a password-encrypted backup containing your location history, geofences, settings and authentication credentials. The password is never stored; if you lose it, the backup cannot be recovered, and a weak password weakens the protection.++Backups are written to a destination you choose via the Android file picker. If you pick a cloud-synced folder, the encrypted file leaves your device through that provider.++Restoring a backup overwrites the current database and credentials.The App supports configuration via `colota://setup` deep links. These links can include server endpoints and authentication credentials. You must explicitly confirm before any configuration is applied. Only open setup links from sources you trust.@@ -99,7 +107,7 @@ Since all data is stored locally on your device, you have full control:- **Access**: View all data in the app's Data Management screen- **Export**: Export your data at any time in multiple formats- **Delete**: Delete any or all data at any time-- **Portability**: Export and transfer your data freely+- **Portability**: Export your data freely, including as a full encrypted backup for device-to-device transfer## Permissionsdiff --git a/apps/mobile/App.tsx b/apps/mobile/App.tsxindex a5ed653a..9af25ee4 100644--- a/apps/mobile/App.tsx+++ b/apps/mobile/App.tsx@@ -34,7 +34,8 @@ import {OfflineMapsScreen,AppearanceScreen,ConnectionScreen,- TrackingSyncScreen+ TrackingSyncScreen,+ BackupRestoreScreen} from "./src/screens/"import { BottomTabBar } from "./src/components"import { loadDisplayPreferences } from "./src/utils/geo"@@ -142,6 +143,11 @@ const SCREEN_CONFIG: readonly ScreenConfig[] = [component: ActivityLogScreen,title: "Activity Log"},+ {+ name: "Backup & Restore",+ component: BackupRestoreScreen,+ title: "Backup & Restore"+ },{name: "Appearance",component: AppearanceScreen,diff --git a/apps/mobile/android/app/build.gradle b/apps/mobile/android/app/build.gradleindex 4e59edf0..5fe2c38d 100644--- a/apps/mobile/android/app/build.gradle+++ b/apps/mobile/android/app/build.gradle@@ -200,6 +200,7 @@ dependencies {gmsImplementation 'com.google.android.gms:play-services-location:21.3.0'implementation 'org.jetbrains.kotlinx:kotlinx-coroutines-android:1.11.0'implementation 'androidx.security:security-crypto:1.1.0'+ implementation 'org.bouncycastle:bcprov-jdk18on:1.84'implementation 'androidx.car.app:app:1.7.0'implementation 'androidx.work:work-runtime:2.11.2'implementation 'androidx.documentfile:documentfile:1.1.0'diff --git a/apps/mobile/android/app/src/main/AndroidManifest.xml b/apps/mobile/android/app/src/main/AndroidManifest.xmlindex c58177bf..22534278 100644--- a/apps/mobile/android/app/src/main/AndroidManifest.xml+++ b/apps/mobile/android/app/src/main/AndroidManifest.xml@@ -93,6 +93,12 @@android:foregroundServiceType="dataSync"android:exported="false" />+ <!-- Backup/Restore foreground service -->+ <service+ android:name=".backup.BackupForegroundService"+ android:foregroundServiceType="shortService"+ android:exported="false" />+<!-- Boot Receiver --><receiverandroid:name=".service.LocationBootReceiver"diff --git a/apps/mobile/android/app/src/main/java/com/colota/MainApplication.kt b/apps/mobile/android/app/src/main/java/com/colota/MainApplication.ktindex 38330e67..5b5ad663 100644--- a/apps/mobile/android/app/src/main/java/com/colota/MainApplication.kt+++ b/apps/mobile/android/app/src/main/java/com/colota/MainApplication.kt@@ -12,6 +12,7 @@ import com.facebook.react.ReactHostimport com.facebook.react.ReactPackageimport com.facebook.react.ReactNativeApplicationEntryPoint.loadReactNativeimport com.facebook.react.defaults.DefaultReactHost.getDefaultReactHost+import com.Colota.backup.BackupOrphanCleanupimport com.Colota.bridge.LocationServicePackageclass MainApplication : Application(), ReactApplication {@@ -26,5 +27,6 @@ class MainApplication : Application(), ReactApplication {override fun onCreate() {super.onCreate()loadReactNative(this)+ BackupOrphanCleanup.start(this)}}diff --git a/apps/mobile/android/app/src/main/java/com/colota/backup/BackupBuilder.kt b/apps/mobile/android/app/src/main/java/com/colota/backup/BackupBuilder.ktnew file mode 100644index 00000000..addffab6--- /dev/null+++ b/apps/mobile/android/app/src/main/java/com/colota/backup/BackupBuilder.kt@@ -0,0 +1,121 @@+/**+ * Copyright (C) 2026 Max Dietrich+ * Licensed under the GNU AGPLv3. See LICENSE in the project root for details.+ */++package com.Colota.backup++import android.app.ActivityManager+import android.content.Context+import android.database.sqlite.SQLiteDatabase+import com.Colota.BuildConfig+import com.Colota.data.DatabaseHelper+import com.Colota.util.SecureStorageHelper+import org.json.JSONObject+import java.io.File+import java.io.OutputStream+import java.time.Instant+import java.util.zip.Deflater+import java.util.zip.ZipEntry+import java.util.zip.ZipOutputStream++class BackupBuilder @JvmOverloads constructor(+ private val context: Context,+ private val databaseHelper: DatabaseHelper = DatabaseHelper.getInstance(context),+ private val secureStorageHelper: SecureStorageHelper = SecureStorageHelper.getInstance(context),+ private val crypto: BackupCrypto = BackupCrypto(),+) {++ fun build(output: OutputStream, password: CharArray) {+ val workDir = File(context.cacheDir, WORK_DIR_NAME).apply {+ deleteRecursively()+ mkdirs()+ }+ try {+ val dbSnapshot = File(workDir, "db.sqlite")+ databaseHelper.snapshotTo(dbSnapshot)+ verifySnapshotIntegrity(dbSnapshot)++ val secrets = secureStorageHelper.exportPlaintextForBackup()+ val secretsJson = JSONObject(secrets).toString()++ val manifestJson = buildManifest().toString()++ val zipFile = File(workDir, "bundle.zip")+ zipFile.outputStream().buffered().use { zipOut ->+ ZipOutputStream(zipOut).use { zip ->+ zip.setLevel(Deflater.BEST_SPEED)+ addEntry(zip, "manifest.json", manifestJson.toByteArray(Charsets.UTF_8))+ addEntry(zip, "secrets.json", secretsJson.toByteArray(Charsets.UTF_8))+ addDeflatedFileEntry(zip, "db/colota.sqlite", dbSnapshot)+ }+ }++ val argon2MemoryKib = pickArgon2MemoryKib()+ zipFile.inputStream().buffered().use { zipIn ->+ crypto.encrypt(+ zipIn, output, password,+ argon2MemoryKib = argon2MemoryKib,+ )+ }+ } finally {+ workDir.deleteRecursively()+ }+ }++ private fun buildManifest(): JSONObject {+ return JSONObject().apply {+ put("schema", JSONObject().apply { put("db", DatabaseHelper.DATABASE_VERSION) })+ put("createdAt", Instant.now().toString())+ put("appVersion", BuildConfig.VERSION_NAME)+ put("appBuild", BuildConfig.VERSION_CODE)+ }+ }++ private fun addEntry(zip: ZipOutputStream, name: String, data: ByteArray) {+ zip.putNextEntry(ZipEntry(name))+ zip.write(data)+ zip.closeEntry()+ }++ private fun addDeflatedFileEntry(zip: ZipOutputStream, name: String, file: File) {+ zip.putNextEntry(ZipEntry(name))+ file.inputStream().buffered().use { it.copyTo(zip) }+ zip.closeEntry()+ }++ // integrity_check (vs quick_check) catches cross-page corruption from a torn copy+ // on the API < 30 fallback path. Slower but only runs on the snapshot, not the live DB.+ private fun verifySnapshotIntegrity(dbFile: File) {+ val db = SQLiteDatabase.openDatabase(dbFile.absolutePath, null, SQLiteDatabase.OPEN_READONLY)+ val result = try {+ db.rawQuery("PRAGMA integrity_check", null).use { c ->+ if (c.moveToFirst()) c.getString(0) else "no result"+ }+ } finally {+ db.close()+ }+ if (result != "ok") {+ throw IllegalStateException(+ "Snapshot integrity check failed ($result). Try again, ideally with tracking paused."+ )+ }+ }++ // Pick by device class only. Transient availMem would silently weaken the+ // backup based on whatever the user had open at the moment; deriveKey+ // catches OOM and surfaces it as a real error if 64 MiB truly won't fit.+ private fun pickArgon2MemoryKib(): Int {+ val am = context.getSystemService(Context.ACTIVITY_SERVICE) as? ActivityManager+ ?: return BackupFormat.ARGON2_MEMORY_KIB+ return if (am.isLowRamDevice) {+ BackupFormat.ARGON2_MEMORY_KIB_LOW_RAM+ } else {+ BackupFormat.ARGON2_MEMORY_KIB+ }+ }++ companion object {+ private const val WORK_DIR_NAME = "backup_temp"+ }+}diff --git a/apps/mobile/android/app/src/main/java/com/colota/backup/BackupCrypto.kt b/apps/mobile/android/app/src/main/java/com/colota/backup/BackupCrypto.ktnew file mode 100644index 00000000..6a478a8b--- /dev/null+++ b/apps/mobile/android/app/src/main/java/com/colota/backup/BackupCrypto.kt@@ -0,0 +1,363 @@+/**+ * Copyright (C) 2026 Max Dietrich+ * Licensed under the GNU AGPLv3. See LICENSE in the project root for details.+ */++package com.Colota.backup++import org.bouncycastle.crypto.generators.Argon2BytesGenerator+import org.bouncycastle.crypto.params.Argon2Parameters+import java.io.DataInputStream+import java.io.DataOutputStream+import java.io.EOFException+import java.io.InputStream+import java.io.OutputStream+import java.nio.ByteBuffer+import java.nio.ByteOrder+import java.nio.CharBuffer+import java.nio.charset.StandardCharsets+import java.security.SecureRandom+import java.util.Arrays+import javax.crypto.AEADBadTagException+import javax.crypto.Cipher+import javax.crypto.spec.GCMParameterSpec+import javax.crypto.spec.SecretKeySpec++/** Chunked AES-256-GCM keyed by Argon2id. On-disk layout: [BackupFormat]. */+class BackupCrypto(private val random: SecureRandom = SecureRandom()) {++ fun encrypt(+ input: InputStream,+ output: OutputStream,+ password: CharArray,+ chunkSize: Int = BackupFormat.DEFAULT_CHUNK_SIZE,+ argon2MemoryKib: Int = BackupFormat.ARGON2_MEMORY_KIB,+ ) {+ require(chunkSize in 16..BackupFormat.MAX_READ_CHUNK_SIZE) {+ "chunkSize must be in 16..${BackupFormat.MAX_READ_CHUNK_SIZE}: $chunkSize"+ }+ val salt = ByteArray(BackupFormat.SALT_BYTES).also { random.nextBytes(it) }+ val noncePrefix = ByteArray(BackupFormat.NONCE_PREFIX_BYTES).also { random.nextBytes(it) }+ val kdfParams = encodeArgon2Params(argon2MemoryKib)++ val header = BackupHeader(+ formatVersion = BackupFormat.FORMAT_VERSION,+ kdfId = BackupFormat.KDF_ARGON2ID,+ kdfParams = kdfParams,+ salt = salt,+ noncePrefix = noncePrefix,+ chunkSize = chunkSize,+ )++ val headerBytes = serializeHeader(header)+ output.write(headerBytes)+ output.flush()++ val key = deriveKey(password, salt, kdfParams)+ try {+ val totalChunks = encryptBody(input, output, key, header, headerBytes)+ // Empty plaintext would skip Argon2 on decrypt, masking wrong-password errors.+ // Real backups always emit at least a manifest entry; refuse the degenerate case.+ if (totalChunks == 0) {+ throw IllegalStateException("Refusing to encrypt empty plaintext")+ }+ writeFooter(output, totalChunks)+ output.flush()+ } finally {+ Arrays.fill(key, 0.toByte())+ }+ }++ fun decrypt(input: InputStream, output: OutputStream, password: CharArray) {+ val header = readHeader(input)+ val headerBytes = serializeHeader(header)+ decryptBody(input, output, password, header, headerBytes)+ output.flush()+ }++ private fun deriveKey(password: CharArray, salt: ByteArray, kdfParams: ByteArray): ByteArray {+ val argon2 = decodeArgon2Params(kdfParams)+ val params = Argon2Parameters.Builder(Argon2Parameters.ARGON2_id)+ .withVersion(Argon2Parameters.ARGON2_VERSION_13)+ .withSalt(salt)+ .withMemoryAsKB(argon2.memoryKib)+ .withIterations(argon2.iterations)+ .withParallelism(argon2.parallelism)+ .build()++ val passwordBytes = passwordToBytes(password)+ try {+ val generator = Argon2BytesGenerator()+ generator.init(params)+ val out = ByteArray(BackupFormat.KEY_BYTES)+ try {+ generator.generateBytes(passwordBytes, out)+ } catch (e: OutOfMemoryError) {+ throw IllegalStateException(+ "Not enough RAM to derive backup key (need ${argon2.memoryKib} KiB)",+ e,+ )+ }+ return out+ } finally {+ Arrays.fill(passwordBytes, 0.toByte())+ }+ }++ private fun encryptBody(+ input: InputStream,+ output: OutputStream,+ key: ByteArray,+ header: BackupHeader,+ headerBytes: ByteArray,+ ): Int {+ val secretKey = SecretKeySpec(key, "AES")+ val buffer = ByteArray(header.chunkSize)+ val dataOut = DataOutputStream(output)+ // One Cipher reused across chunks; init() per chunk binds a fresh nonce.+ val cipher = Cipher.getInstance("AES/GCM/NoPadding")+ var chunkIndex = 0++ try {+ while (true) {+ val read = readFully(input, buffer, header.chunkSize)+ if (read == 0) break++ val nonce = chunkNonce(header.noncePrefix, chunkIndex)+ val spec = GCMParameterSpec(BackupFormat.GCM_TAG_BITS, nonce)+ cipher.init(Cipher.ENCRYPT_MODE, secretKey, spec)+ cipher.updateAAD(chunkAad(headerBytes, chunkIndex))+ val ciphertextWithTag = cipher.doFinal(buffer, 0, read)++ dataOut.writeInt(read)+ dataOut.write(ciphertextWithTag)+ Arrays.fill(ciphertextWithTag, 0.toByte())+ chunkIndex++++ if (read < header.chunkSize) break+ }+ } finally {+ Arrays.fill(buffer, 0.toByte())+ }++ return chunkIndex+ }++ private fun decryptBody(+ input: InputStream,+ output: OutputStream,+ password: CharArray,+ header: BackupHeader,+ headerBytes: ByteArray,+ ) {+ val dataIn = DataInputStream(input)+ // One Cipher reused across chunks; init() per chunk binds a fresh nonce.+ val cipher = Cipher.getInstance("AES/GCM/NoPadding")+ var chunkIndex = 0+ var key: ByteArray? = null+ var secretKey: SecretKeySpec? = null++ try {+ while (true) {+ val plainLen = try {+ dataIn.readInt()+ } catch (e: EOFException) {+ throw BackupException(BackupError.TRUNCATED, "Stream ended before footer", e)+ }++ if (plainLen == BackupFormat.END_MARKER) {+ val declared = try {+ dataIn.readInt()+ } catch (e: EOFException) {+ throw BackupException(BackupError.TRUNCATED, "Missing totalChunks footer", e)+ }+ if (declared != chunkIndex) {+ throw BackupException(+ BackupError.TRUNCATED,+ "Chunk count mismatch: header=$declared actual=$chunkIndex"+ )+ }+ return+ }++ if (plainLen <= 0 || plainLen > header.chunkSize) {+ throw BackupException(BackupError.TAMPERED, "Invalid chunk length: $plainLen")+ }++ val ciphertextWithTag = ByteArray(plainLen + BackupFormat.GCM_TAG_BYTES)+ try {+ dataIn.readFully(ciphertextWithTag)+ } catch (e: EOFException) {+ throw BackupException(BackupError.TRUNCATED, "Chunk $chunkIndex truncated", e)+ }++ // Defer Argon2 (~hundreds of ms) until we know at least one chunk exists.+ if (key == null) {+ key = deriveKey(password, header.salt, header.kdfParams)+ secretKey = SecretKeySpec(key, "AES")+ }++ val nonce = chunkNonce(header.noncePrefix, chunkIndex)+ val spec = GCMParameterSpec(BackupFormat.GCM_TAG_BITS, nonce)+ cipher.init(Cipher.DECRYPT_MODE, secretKey, spec)+ cipher.updateAAD(chunkAad(headerBytes, chunkIndex))++ val plaintext = try {+ cipher.doFinal(ciphertextWithTag)+ } catch (e: AEADBadTagException) {+ // Chunk 0 binds the header in AAD - tag fail there is indistinguishable from wrong password.+ val reason = if (chunkIndex == 0) BackupError.WRONG_PASSWORD else BackupError.TAMPERED+ val message = if (chunkIndex == 0) {+ "Wrong password or corrupted backup header"+ } else {+ "GCM tag check failed at chunk $chunkIndex"+ }+ throw BackupException(reason, message, e)+ }++ output.write(plaintext)+ Arrays.fill(plaintext, 0.toByte())+ Arrays.fill(ciphertextWithTag, 0.toByte())+ chunkIndex+++ }+ } finally {+ key?.let { Arrays.fill(it, 0.toByte()) }+ }+ }++ // Header is bound into every chunk's AAD; any flip fails decryption.+ private fun serializeHeader(header: BackupHeader): ByteArray {+ val buf = ByteBuffer.allocate(BackupFormat.HEADER_BYTES).order(ByteOrder.BIG_ENDIAN)+ buf.put(BackupFormat.MAGIC.toByteArray(StandardCharsets.US_ASCII))+ buf.put(header.formatVersion)+ buf.put(header.kdfId)+ buf.put(header.kdfParams)+ buf.put(header.salt)+ buf.put(header.noncePrefix)+ buf.putInt(header.chunkSize)+ buf.put(ByteArray(6))+ return buf.array()+ }++ fun readHeader(input: InputStream): BackupHeader {+ val raw = ByteArray(BackupFormat.HEADER_BYTES)+ try {+ DataInputStream(input).readFully(raw)+ } catch (e: EOFException) {+ throw BackupException(BackupError.TRUNCATED, "Header shorter than expected", e)+ }++ val magic = String(raw, 0, BackupFormat.MAGIC_BYTES, StandardCharsets.US_ASCII)+ if (magic != BackupFormat.MAGIC) {+ throw BackupException(BackupError.BAD_MAGIC, "Magic was '$magic'")+ }++ val buf = ByteBuffer.wrap(raw).order(ByteOrder.BIG_ENDIAN)+ buf.position(BackupFormat.MAGIC_BYTES)+ val formatVersion = buf.get()+ if (formatVersion != BackupFormat.FORMAT_VERSION) {+ throw BackupException(BackupError.UNSUPPORTED_VERSION, "version=$formatVersion")+ }++ val kdfId = buf.get()+ if (kdfId != BackupFormat.KDF_ARGON2ID) {+ throw BackupException(BackupError.UNSUPPORTED_KDF, "kdfId=$kdfId")+ }++ val kdfParams = ByteArray(BackupFormat.KDF_PARAMS_BYTES).also { buf.get(it) }+ val salt = ByteArray(BackupFormat.SALT_BYTES).also { buf.get(it) }+ val noncePrefix = ByteArray(BackupFormat.NONCE_PREFIX_BYTES).also { buf.get(it) }+ val chunkSize = buf.getInt()++ // Mirrors BackupHeader.init bounds; raises BackupException not IllegalArgumentException.+ if (chunkSize < 16 || chunkSize > BackupFormat.MAX_READ_CHUNK_SIZE) {+ throw BackupException(BackupError.TAMPERED, "chunkSize out of range: $chunkSize")+ }++ return BackupHeader(formatVersion, kdfId, kdfParams, salt, noncePrefix, chunkSize)+ }++ private fun writeFooter(output: OutputStream, totalChunks: Int) {+ val buf = ByteBuffer.allocate(BackupFormat.FOOTER_BYTES).order(ByteOrder.BIG_ENDIAN)+ buf.putInt(BackupFormat.END_MARKER)+ buf.putInt(totalChunks)+ output.write(buf.array())+ }++ private fun encodeArgon2Params(memoryKib: Int): ByteArray {+ val buf = ByteBuffer.allocate(BackupFormat.KDF_PARAMS_BYTES).order(ByteOrder.BIG_ENDIAN)+ buf.putInt(memoryKib)+ buf.putInt(BackupFormat.ARGON2_ITERATIONS)+ buf.putInt(BackupFormat.ARGON2_PARALLELISM)+ buf.putInt(0)+ return buf.array()+ }++ private fun decodeArgon2Params(params: ByteArray): Argon2Params {+ val buf = ByteBuffer.wrap(params).order(ByteOrder.BIG_ENDIAN)+ val memoryKib = buf.getInt()+ val iterations = buf.getInt()+ val parallelism = buf.getInt()+ val reserved = buf.getInt()+ // Bounds reject weaker-than-we-produce floors and DoS-via-huge-memory ceilings.+ if (memoryKib !in BackupFormat.ARGON2_MEMORY_KIB_LOW_RAM..BackupFormat.ARGON2_MEMORY_KIB) {+ throw BackupException(BackupError.TAMPERED, "Argon2 memory out of range: $memoryKib")+ }+ if (iterations !in BackupFormat.ARGON2_ITERATIONS..BackupFormat.ARGON2_ITERATIONS_MAX) {+ throw BackupException(BackupError.TAMPERED, "Argon2 iterations out of range: $iterations")+ }+ if (parallelism !in 1..BackupFormat.ARGON2_PARALLELISM_MAX) {+ throw BackupException(BackupError.TAMPERED, "Argon2 parallelism out of range: $parallelism")+ }+ if (reserved != 0) {+ throw BackupException(BackupError.TAMPERED, "Reserved kdfParams bytes nonzero: $reserved")+ }+ return Argon2Params(memoryKib, iterations, parallelism)+ }++ private fun chunkNonce(noncePrefix: ByteArray, chunkIndex: Int): ByteArray {+ val nonce = ByteArray(BackupFormat.GCM_NONCE_BYTES)+ ByteBuffer.wrap(nonce).order(ByteOrder.BIG_ENDIAN)+ .put(noncePrefix)+ .putInt(chunkIndex)+ return nonce+ }++ private fun chunkAad(headerBytes: ByteArray, chunkIndex: Int): ByteArray {+ val buf = ByteBuffer.allocate(headerBytes.size + 4).order(ByteOrder.BIG_ENDIAN)+ buf.put(headerBytes)+ buf.putInt(chunkIndex)+ return buf.array()+ }++ private fun readFully(input: InputStream, buffer: ByteArray, want: Int): Int {+ var total = 0+ while (total < want) {+ val read = input.read(buffer, total, want - total)+ if (read < 0) break+ total += read+ }+ return total+ }++ // Encode into a buffer we own so the intermediate UTF-8 bytes are wiped.+ // (The upstream JVM String from the RN bridge is still uncleanable.)+ private fun passwordToBytes(password: CharArray): ByteArray {+ val encoder = StandardCharsets.UTF_8.newEncoder()+ val maxBytes = (password.size * encoder.maxBytesPerChar()).toInt().coerceAtLeast(1)+ val owned = ByteBuffer.allocate(maxBytes)+ try {+ val charBuf = CharBuffer.wrap(password)+ val r1 = encoder.encode(charBuf, owned, true)+ if (r1.isError) r1.throwException()+ val r2 = encoder.flush(owned)+ if (r2.isError) r2.throwException()+ val out = ByteArray(owned.position())+ owned.flip()+ owned.get(out)+ return out+ } finally {+ Arrays.fill(owned.array(), 0.toByte())+ }+ }+}diff --git a/apps/mobile/android/app/src/main/java/com/colota/backup/BackupForegroundService.kt b/apps/mobile/android/app/src/main/java/com/colota/backup/BackupForegroundService.ktnew file mode 100644index 00000000..d066eb90--- /dev/null+++ b/apps/mobile/android/app/src/main/java/com/colota/backup/BackupForegroundService.kt@@ -0,0 +1,108 @@+/**+ * Copyright (C) 2026 Max Dietrich+ * Licensed under the GNU AGPLv3. See LICENSE in the project root for details.+ */++package com.Colota.backup++import android.app.NotificationChannel+import android.app.NotificationManager+import android.app.Service+import android.content.Context+import android.content.Intent+import android.content.pm.ServiceInfo+import android.os.Build+import android.os.IBinder+import androidx.core.app.NotificationCompat+import androidx.core.content.ContextCompat+import com.Colota.util.AppLogger++// Notification-only shell; work stays in BackupServiceModule's coroutine to keep the password CharArray on heap.+class BackupForegroundService : Service() {++ companion object {+ private const val TAG = "BackupForegroundService"+ private const val CHANNEL_ID = "backup_restore"+ private const val NOTIFICATION_ID = 9201+ private const val EXTRA_MESSAGE = "message"++ // Must be called from Main (Android 12+ rejects background FGS starts).+ // Throws on rejection so the caller can abort rather than risk a mid-op kill.+ fun start(context: Context, message: String) {+ val intent = Intent(context, BackupForegroundService::class.java).apply {+ putExtra(EXTRA_MESSAGE, message)+ }+ try {+ ContextCompat.startForegroundService(context, intent)+ } catch (e: Exception) {+ AppLogger.e(TAG, "FGS start denied: ${e.message}")+ throw IllegalStateException(+ "Cannot start backup service. Bring the app to the foreground and try again.",+ e,+ )+ }+ }++ fun stop(context: Context) {+ try {+ context.stopService(Intent(context, BackupForegroundService::class.java))+ } catch (e: Exception) {+ AppLogger.w(TAG, "stopService failed: ${e.message}")+ }+ }+ }++ override fun onBind(intent: Intent?): IBinder? = null++ override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {+ // System-restart redelivery: no work to do, stop so the notification doesn't linger.+ if (intent == null) {+ stopSelf(startId)+ return START_NOT_STICKY+ }++ ensureChannel()+ val message = intent.getStringExtra(EXTRA_MESSAGE) ?: "Working..."+ val notification = NotificationCompat.Builder(this, CHANNEL_ID)+ .setSmallIcon(android.R.drawable.ic_menu_save)+ .setContentTitle("Colota Backup")+ .setContentText(message)+ .setOngoing(true)+ .setPriority(NotificationCompat.PRIORITY_LOW)+ .build()++ try {+ // API 34+ enforces shortService (3-min cap, no extra permission); pre-34 tolerates a typeless start.+ if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.UPSIDE_DOWN_CAKE) {+ startForeground(+ NOTIFICATION_ID,+ notification,+ ServiceInfo.FOREGROUND_SERVICE_TYPE_SHORT_SERVICE,+ )+ } else {+ startForeground(NOTIFICATION_ID, notification)+ }+ } catch (e: Exception) {+ AppLogger.w(TAG, "startForeground denied; service runs as background: ${e.message}")+ }+ return START_NOT_STICKY+ }++ // shortService 3-min cap. API 35+ (startId, fgsType) overload's default impl delegates here.+ override fun onTimeout(startId: Int) {+ AppLogger.w(TAG, "shortService timeout reached; backup/restore stopping")+ stopSelf(startId)+ }++ private fun ensureChannel() {+ if (Build.VERSION.SDK_INT < Build.VERSION_CODES.O) return+ val nm = getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager+ if (nm.getNotificationChannel(CHANNEL_ID) != null) return+ val channel = NotificationChannel(+ CHANNEL_ID,+ "Backup & Restore",+ NotificationManager.IMPORTANCE_LOW,+ ).apply { description = "Shown while a backup or restore is in progress" }+ nm.createNotificationChannel(channel)+ }+}diff --git a/apps/mobile/android/app/src/main/java/com/colota/backup/BackupFormat.kt b/apps/mobile/android/app/src/main/java/com/colota/backup/BackupFormat.ktnew file mode 100644index 00000000..8e6c6760--- /dev/null+++ b/apps/mobile/android/app/src/main/java/com/colota/backup/BackupFormat.kt@@ -0,0 +1,125 @@+/**+ * Copyright (C) 2026 Max Dietrich+ * Licensed under the GNU AGPLv3. See LICENSE in the project root for details.+ */++package com.Colota.backup++/**+ * On-disk layout of an encrypted Colota backup file.+ *+ * Header (76 bytes, plaintext):+ * magic 8 "COLOTABK" (version-agnostic; dispatch on formatVer)+ * formatVer 1+ * kdfId 1 0=Argon2id (1=PBKDF2 reserved)+ * kdfParams 16 algorithm-specific+ * salt 32 random per backup+ * noncePrefix 8 random; combined with 4-byte chunk index to form+ * the 12-byte AES-GCM nonce+ * chunkSize 4 uint32 BE, plaintext bytes per chunk+ * reserved 6 zero+ *+ * Body (repeated):+ * plainLen 4 uint32 BE, 1..chunkSize for each chunk+ * ciphertext plainLen+ * gcmTag 16+ *+ * Footer (8 bytes):+ * endMarker 4 0xFFFFFFFF (sentinel; never a valid plainLen)+ * totalChunks 4 uint32 BE, used to detect truncation pre-decrypt+ */+object BackupFormat {+ const val MAGIC = "COLOTABK"+ const val MAGIC_BYTES = 8+ const val FORMAT_VERSION: Byte = 1++ const val KDF_ARGON2ID: Byte = 0+ const val KDF_PBKDF2: Byte = 1++ const val KDF_PARAMS_BYTES = 16+ const val SALT_BYTES = 32+ // 8 bytes is enough since the per-backup salt makes the key unique per file.+ const val NONCE_PREFIX_BYTES = 8+ const val GCM_NONCE_BYTES = 12+ const val GCM_TAG_BYTES = 16+ const val GCM_TAG_BITS = 128+ const val KEY_BYTES = 32++ const val DEFAULT_CHUNK_SIZE = 1024 * 1024+ // Reader-side cap so a hostile chunkSize can't OOM low-RAM devices.+ const val MAX_READ_CHUNK_SIZE = 4 * 1024 * 1024++ const val HEADER_BYTES = MAGIC_BYTES + 1 + 1 + KDF_PARAMS_BYTES ++ SALT_BYTES + NONCE_PREFIX_BYTES + 4 + 6++ const val END_MARKER: Int = -1+ const val FOOTER_BYTES = 8++ const val ARGON2_MEMORY_KIB = 64 * 1024+ const val ARGON2_MEMORY_KIB_LOW_RAM = 32 * 1024+ const val ARGON2_ITERATIONS = 3+ const val ARGON2_ITERATIONS_MAX = 10+ const val ARGON2_PARALLELISM = 1+ // Validation upper bound; widened past the producer default so future bumps don't reject old decoders.+ const val ARGON2_PARALLELISM_MAX = 16+}++data class BackupHeader(+ val formatVersion: Byte,+ val kdfId: Byte,+ val kdfParams: ByteArray,+ val salt: ByteArray,+ val noncePrefix: ByteArray,+ val chunkSize: Int,+) {+ init {+ require(kdfParams.size == BackupFormat.KDF_PARAMS_BYTES)+ require(salt.size == BackupFormat.SALT_BYTES)+ require(noncePrefix.size == BackupFormat.NONCE_PREFIX_BYTES)+ require(chunkSize in 16..BackupFormat.MAX_READ_CHUNK_SIZE) { "chunkSize out of range: $chunkSize" }+ }++ override fun equals(other: Any?): Boolean {+ if (this === other) return true+ if (other !is BackupHeader) return false+ return formatVersion == other.formatVersion &&+ kdfId == other.kdfId &&+ kdfParams.contentEquals(other.kdfParams) &&+ salt.contentEquals(other.salt) &&+ noncePrefix.contentEquals(other.noncePrefix) &&+ chunkSize == other.chunkSize+ }++ override fun hashCode(): Int {+ var result = formatVersion.toInt()+ result = 31 * result + kdfId+ result = 31 * result + kdfParams.contentHashCode()+ result = 31 * result + salt.contentHashCode()+ result = 31 * result + noncePrefix.contentHashCode()+ result = 31 * result + chunkSize+ return result+ }+}++internal data class Argon2Params(+ val memoryKib: Int,+ val iterations: Int,+ val parallelism: Int,+)++enum class BackupError {+ BAD_MAGIC,+ UNSUPPORTED_VERSION,+ UNSUPPORTED_KDF,+ UNSUPPORTED_SCHEMA,+ MISSING_ENTRY,+ INTEGRITY_FAIL,+ TRUNCATED,+ TAMPERED,+ WRONG_PASSWORD,+ // DB swapped successfully but secrets commit failed; user must re-enter credentials.+ SECRETS_PARTIAL,+}++class BackupException(val error: BackupError, message: String? = null, cause: Throwable? = null) :+ Exception(message ?: error.name, cause)diff --git a/apps/mobile/android/app/src/main/java/com/colota/backup/BackupOrphanCleanup.kt b/apps/mobile/android/app/src/main/java/com/colota/backup/BackupOrphanCleanup.ktnew file mode 100644index 00000000..afd8d613--- /dev/null+++ b/apps/mobile/android/app/src/main/java/com/colota/backup/BackupOrphanCleanup.kt@@ -0,0 +1,47 @@+/**+ * Copyright (C) 2026 Max Dietrich+ * Licensed under the GNU AGPLv3. See LICENSE in the project root for details.+ */++package com.Colota.backup++import android.content.Context+import com.Colota.data.DatabaseHelper+import com.Colota.util.AppLogger+import kotlinx.coroutines.CompletableDeferred+import java.io.File+import java.util.concurrent.atomic.AtomicBoolean++// Sweeps temp files left by a process death mid-op. Run from Application.onCreate;+// callers await before claiming new temp dirs.+object BackupOrphanCleanup {++ private const val TAG = "BackupOrphanCleanup"++ private val started = AtomicBoolean(false)+ private val completed = CompletableDeferred<Unit>()++ fun start(context: Context) {+ if (!started.compareAndSet(false, true)) return+ val appContext = context.applicationContext+ Thread({+ try {+ File(appContext.cacheDir, "backup_temp").deleteRecursively()+ File(appContext.cacheDir, "restore_temp").deleteRecursively()+ File(appContext.cacheDir, "pending_backup.colota").delete()+ val dbDir = appContext.getDatabasePath(DatabaseHelper.DATABASE_NAME).parentFile+ if (dbDir != null) {+ File(dbDir, "${DatabaseHelper.DATABASE_NAME}.incoming").delete()+ }+ } catch (e: Exception) {+ AppLogger.w(TAG, "Cleanup sweep failed: ${e.message}")+ } finally {+ completed.complete(Unit)+ }+ }, "BackupCacheCleanup").apply { isDaemon = true }.start()+ }++ suspend fun awaitComplete() {+ completed.await()+ }+}diff --git a/apps/mobile/android/app/src/main/java/com/colota/backup/BackupPickerCoordinator.kt b/apps/mobile/android/app/src/main/java/com/colota/backup/BackupPickerCoordinator.ktnew file mode 100644index 00000000..ed0fae87--- /dev/null+++ b/apps/mobile/android/app/src/main/java/com/colota/backup/BackupPickerCoordinator.kt@@ -0,0 +1,146 @@+/**+ * Copyright (C) 2026 Max Dietrich+ * Licensed under the GNU AGPLv3. See LICENSE in the project root for details.+ */++package com.Colota.backup++import android.app.Activity+import android.content.Intent+import android.net.Uri+import android.provider.OpenableColumns+import com.facebook.react.bridge.Arguments+import com.facebook.react.bridge.BaseActivityEventListener+import com.facebook.react.bridge.Promise+import com.facebook.react.bridge.ReactApplicationContext+import kotlinx.coroutines.CoroutineScope+import kotlinx.coroutines.Job+import kotlinx.coroutines.delay+import kotlinx.coroutines.launch++// SAF picker plumbing for BackupServiceModule. One in-flight promise; timeout releases the slot+// so a never-returning picker activity can't permanently block.+class BackupPickerCoordinator(+ private val reactContext: ReactApplicationContext,+ private val scope: CoroutineScope,+) {+ companion object {+ private const val REQUEST_PICK_DESTINATION = 9101+ private const val REQUEST_PICK_SOURCE = 9102+ private const val DEFAULT_FILENAME = "colota_backup.colota"+ private const val MIME_BACKUP = "application/octet-stream"+ private const val PICKER_TIMEOUT_MS = 5L * 60_000L+ }++ private val lock = Any()++ @Volatile private var pendingPromise: Promise? = null+ @Volatile private var timeoutJob: Job? = null++ private val activityEventListener = object : BaseActivityEventListener() {+ override fun onActivityResult(+ activity: Activity,+ requestCode: Int,+ resultCode: Int,+ data: Intent?,+ ) {+ if (requestCode != REQUEST_PICK_DESTINATION && requestCode != REQUEST_PICK_SOURCE) return+ val promise = synchronized(lock) {+ val p = pendingPromise+ pendingPromise = null+ timeoutJob?.cancel()+ timeoutJob = null+ p+ } ?: return++ if (resultCode != Activity.RESULT_OK || data?.data == null) {+ promise.resolve(null)+ return+ }+ val uri = data.data!!+ if (requestCode == REQUEST_PICK_SOURCE) {+ // Source picker returns the filename too so the password prompt has context.+ val result = Arguments.createMap().apply {+ putString("uri", uri.toString())+ putString("displayName", queryDisplayName(uri))+ }+ promise.resolve(result)+ } else {+ promise.resolve(uri.toString())+ }+ }+ }++ // Some providers (Drive, MTP) hide DISPLAY_NAME; callers must tolerate null.+ private fun queryDisplayName(uri: Uri): String? {+ return try {+ reactContext.contentResolver+ .query(uri, arrayOf(OpenableColumns.DISPLAY_NAME), null, null, null)+ ?.use { cursor ->+ if (cursor.moveToFirst() && !cursor.isNull(0)) cursor.getString(0) else null+ }+ } catch (e: Exception) {+ null+ }+ }++ init {+ reactContext.addActivityEventListener(activityEventListener)+ }++ fun dispose() {+ reactContext.removeActivityEventListener(activityEventListener)+ }++ fun pickDestination(promise: Promise) {+ val activity = reactContext.currentActivity+ if (activity == null) {+ promise.reject("E_NO_ACTIVITY", "No current activity")+ return+ }+ if (!claim(promise)) return+ val intent = Intent(Intent.ACTION_CREATE_DOCUMENT).apply {+ addCategory(Intent.CATEGORY_OPENABLE)+ type = MIME_BACKUP+ putExtra(Intent.EXTRA_TITLE, DEFAULT_FILENAME)+ }+ activity.startActivityForResult(intent, REQUEST_PICK_DESTINATION)+ }++ fun pickSource(promise: Promise) {+ val activity = reactContext.currentActivity+ if (activity == null) {+ promise.reject("E_NO_ACTIVITY", "No current activity")+ return+ }+ if (!claim(promise)) return+ val intent = Intent(Intent.ACTION_OPEN_DOCUMENT).apply {+ addCategory(Intent.CATEGORY_OPENABLE)+ type = MIME_BACKUP+ }+ activity.startActivityForResult(intent, REQUEST_PICK_SOURCE)+ }++ // Timeout releases the slot if the activity result never arrives.+ private fun claim(promise: Promise): Boolean {+ synchronized(lock) {+ if (pendingPromise != null) {+ promise.reject("E_BUSY", "Another picker is already open")+ return false+ }+ pendingPromise = promise+ timeoutJob = scope.launch {+ delay(PICKER_TIMEOUT_MS)+ val stale = synchronized(lock) {+ if (pendingPromise === promise) {+ pendingPromise = null+ timeoutJob = null+ promise+ } else null+ }+ stale?.reject("E_PICKER_TIMEOUT", "File picker timed out")+ }+ }+ return true+ }+}diff --git a/apps/mobile/android/app/src/main/java/com/colota/backup/BackupRestorer.kt b/apps/mobile/android/app/src/main/java/com/colota/backup/BackupRestorer.ktnew file mode 100644index 00000000..0dca34ad--- /dev/null+++ b/apps/mobile/android/app/src/main/java/com/colota/backup/BackupRestorer.kt@@ -0,0 +1,205 @@+/**+ * Copyright (C) 2026 Max Dietrich+ * Licensed under the GNU AGPLv3. See LICENSE in the project root for details.+ */++package com.Colota.backup++import android.content.Context+import android.database.sqlite.SQLiteDatabase+import com.Colota.data.DatabaseHelper+import com.Colota.util.SecureStorageHelper+import org.json.JSONObject+import java.io.File+import java.io.InputStream+import java.io.PipedInputStream+import java.io.PipedOutputStream+import java.util.zip.ZipInputStream++// Order: migrate, integrity-check, swap DB, import secrets.+// Secrets failure after the swap throws SECRETS_PARTIAL so the caller can warn the user.+class BackupRestorer @JvmOverloads constructor(+ private val context: Context,+ private val secureStorageHelper: SecureStorageHelper = SecureStorageHelper.getInstance(context),+ private val crypto: BackupCrypto = BackupCrypto(),+) {++ fun restore(input: InputStream, password: CharArray) {+ val workDir = File(context.cacheDir, WORK_DIR_NAME).apply {+ deleteRecursively()+ mkdirs()+ }+ try {+ val extracted = decryptAndExtract(input, password, workDir)++ val manifestBytes = extracted.manifest+ ?: throw BackupException(BackupError.MISSING_ENTRY, MANIFEST_ENTRY)+ val dbFile = extracted.dbFile+ ?: throw BackupException(BackupError.MISSING_ENTRY, DB_ENTRY)++ val manifest = JSONObject(String(manifestBytes, Charsets.UTF_8))+ val backupSchema = manifest.optJSONObject("schema")?.optInt("db", -1) ?: -1+ if (backupSchema > DatabaseHelper.DATABASE_VERSION) {+ throw BackupException(+ BackupError.UNSUPPORTED_SCHEMA,+ "Backup schema $backupSchema is newer than installed app schema " ++ "${DatabaseHelper.DATABASE_VERSION}; upgrade Colota first."+ )+ }++ verifyDatabaseIntegrity(dbFile)++ // Migrate before the swap so a failure leaves the live DB untouched.+ try {+ DatabaseHelper.migrateCandidate(dbFile)+ } catch (e: IllegalStateException) {+ throw BackupException(BackupError.UNSUPPORTED_SCHEMA, e.message ?: "Migration refused", e)+ } catch (e: Exception) {+ throw BackupException(BackupError.INTEGRITY_FAIL, "Schema migration failed: ${e.message}", e)+ }++ val secretsMap = extracted.secrets?.let { parseSecrets(it) }++ DatabaseHelper.replaceLiveDatabase(context, dbFile)++ if (secretsMap != null) {+ try {+ secureStorageHelper.importPlaintextFromBackup(secretsMap)+ } catch (e: Exception) {+ throw BackupException(+ BackupError.SECRETS_PARTIAL,+ "Database restored, but credentials could not be applied. Re-enter them in Connection settings.",+ e,+ )+ }+ }+ } finally {+ workDir.deleteRecursively()+ }+ }++ private fun decryptAndExtract(+ input: InputStream,+ password: CharArray,+ destDir: File,+ ): ExtractedEntries {+ val pipeBuffer = 1024 * 1024+ val pipedOut = PipedOutputStream()+ val pipedIn = PipedInputStream(pipedOut, pipeBuffer)++ // Read decryptError after join() for happens-before.+ var decryptError: Throwable? = null++ val decryptThread = Thread({+ try {+ pipedOut.use { crypto.decrypt(input, it, password) }+ } catch (t: Throwable) {+ decryptError = t+ try { pipedOut.close() } catch (_: Exception) {}+ }+ }, "BackupRestoreDecryptor").apply { isDaemon = true }+ decryptThread.start()++ val extracted = try {+ ZipInputStream(pipedIn).use { zip -> readEntriesFromStream(zip, destDir) }+ } catch (e: Exception) {+ decryptThread.join()+ decryptError?.let { throw it }+ throw e+ }++ decryptThread.join()+ decryptError?.let { throw it }+ return extracted+ }++ private fun readEntriesFromStream(zip: ZipInputStream, destDir: File): ExtractedEntries {+ var manifest: ByteArray? = null+ var secrets: ByteArray? = null+ var dbFile: File? = null++ // Zip-Slip defense: output paths are constants, never derived from entry.name.+ var entry = zip.nextEntry+ while (entry != null) {+ if (!entry.isDirectory) {+ when (entry.name) {+ MANIFEST_ENTRY -> manifest = readBoundedZipEntry(zip, MANIFEST_ENTRY, MAX_MANIFEST_BYTES)+ SECRETS_ENTRY -> secrets = readBoundedZipEntry(zip, SECRETS_ENTRY, MAX_SECRETS_BYTES)+ DB_ENTRY -> {+ val outFile = File(destDir, "extracted_db.sqlite")+ outFile.outputStream().use { out -> zip.copyTo(out) }+ dbFile = outFile+ }+ else -> { /* unknown entries ignored for forward compatibility */ }+ }+ }+ entry = zip.nextEntry+ }+ return ExtractedEntries(manifest, secrets, dbFile)+ }++ // Cap guards against zip-bomb-style entries within an authenticated bundle.+ private fun readBoundedZipEntry(zip: ZipInputStream, name: String, maxBytes: Int): ByteArray {+ val out = java.io.ByteArrayOutputStream()+ val buf = ByteArray(8 * 1024)+ var total = 0+ while (true) {+ val n = zip.read(buf)+ if (n <= 0) break+ total += n+ if (total > maxBytes) {+ throw BackupException(+ BackupError.TAMPERED,+ "Entry $name exceeds $maxBytes-byte cap"+ )+ }+ out.write(buf, 0, n)+ }+ return out.toByteArray()+ }++ private fun verifyDatabaseIntegrity(dbFile: File) {+ val sqlite = try {+ SQLiteDatabase.openDatabase(dbFile.absolutePath, null, SQLiteDatabase.OPEN_READONLY)+ } catch (e: Exception) {+ throw BackupException(BackupError.INTEGRITY_FAIL, "Cannot open backup DB: ${e.message}", e)+ }+ try {+ sqlite.rawQuery("PRAGMA integrity_check", null).use { cursor ->+ val result = if (cursor.moveToFirst()) cursor.getString(0) else "no result"+ if (result != "ok") {+ throw BackupException(BackupError.INTEGRITY_FAIL, "integrity_check returned: $result")+ }+ }+ } finally {+ sqlite.close()+ }+ }++ // Empty values are kept; importPlaintextFromBackup treats them as "remove".+ private fun parseSecrets(bytes: ByteArray): Map<String, String> {+ val json = JSONObject(String(bytes, Charsets.UTF_8))+ val out = mutableMapOf<String, String>()+ val keys = json.keys()+ while (keys.hasNext()) {+ val key = keys.next()+ out[key] = json.optString(key, "")+ }+ return out+ }++ private data class ExtractedEntries(+ val manifest: ByteArray?,+ val secrets: ByteArray?,+ val dbFile: File?,+ )++ companion object {+ private const val WORK_DIR_NAME = "restore_temp"+ private const val MANIFEST_ENTRY = "manifest.json"+ private const val SECRETS_ENTRY = "secrets.json"+ private const val DB_ENTRY = "db/colota.sqlite"+ private const val MAX_MANIFEST_BYTES = 256 * 1024+ private const val MAX_SECRETS_BYTES = 64 * 1024+ }+}diff --git a/apps/mobile/android/app/src/main/java/com/colota/backup/PasswordStrength.kt b/apps/mobile/android/app/src/main/java/com/colota/backup/PasswordStrength.ktnew file mode 100644index 00000000..3986d4ad--- /dev/null+++ b/apps/mobile/android/app/src/main/java/com/colota/backup/PasswordStrength.kt@@ -0,0 +1,66 @@+/**+ * Copyright (C) 2026 Max Dietrich+ * Licensed under the GNU AGPLv3. See LICENSE in the project root for details.+ */++package com.Colota.backup++import kotlin.math.ln+import kotlin.math.min++// Authoritative scoring. Used by createBackup (gate) and the JS strength meter (via bridge).+object PasswordStrength {++ const val MIN_LENGTH = 12+ private const val MIN_BITS = 50.0++ data class Result(val score: Int, val label: String, val bits: Double)++ fun evaluate(password: CharArray): Result {+ if (password.isEmpty()) return Result(0, "", 0.0)+ if (password.size < MIN_LENGTH) return Result(0, "Too short", 0.0)+ val b = bits(password)+ return when {+ b < MIN_BITS -> Result(1, "Weak", b)+ b < 70.0 -> Result(2, "OK", b)+ b < 90.0 -> Result(3, "Good", b)+ else -> Result(4, "Strong", b)+ }+ }++ // CharArray rather than String so password material stays wipeable end-to-end.+ private fun bits(password: CharArray): Double {+ if (password.size < MIN_LENGTH) return 0.0++ var charset = 0+ if (password.any { it in 'a'..'z' }) charset += 26+ if (password.any { it in 'A'..'Z' }) charset += 26+ if (password.any { it in '0'..'9' }) charset += 10+ // ASCII-only check; Unicode letters (e.g. 'é', Cyrillic) get the punctuation bonus.+ if (password.any { it !in 'a'..'z' && it !in 'A'..'Z' && it !in '0'..'9' }) charset += 32++ if (charset == 0) return 0.0+ var bits = password.size * (ln(charset.toDouble()) / ln(2.0))++ val uniqueChars = password.toSet().size+ if (uniqueChars < 4) bits = min(bits, 20.0)++ if (looksSequential(password)) bits = min(bits, 30.0)++ return bits+ }++ fun isAcceptable(password: CharArray): Boolean = bits(password) >= MIN_BITS++ private fun looksSequential(password: CharArray): Boolean {+ for (i in 0..password.size - 4) {+ val c0 = password[i].code+ val c1 = password[i + 1].code+ val c2 = password[i + 2].code+ val c3 = password[i + 3].code+ if (c1 - c0 == 1 && c2 - c1 == 1 && c3 - c2 == 1) return true+ if (c0 - c1 == 1 && c1 - c2 == 1 && c2 - c3 == 1) return true+ }+ return false+ }+}diff --git a/apps/mobile/android/app/src/main/java/com/colota/bridge/BackupServiceModule.kt b/apps/mobile/android/app/src/main/java/com/colota/bridge/BackupServiceModule.ktnew file mode 100644index 00000000..614e68c6--- /dev/null+++ b/apps/mobile/android/app/src/main/java/com/colota/bridge/BackupServiceModule.kt@@ -0,0 +1,362 @@+/**+ * Copyright (C) 2026 Max Dietrich+ * Licensed under the GNU AGPLv3. See LICENSE in the project root for details.+ */++package com.Colota.bridge++import android.content.Intent+import android.net.Uri+import android.os.StatFs+import android.provider.DocumentsContract+import com.Colota.backup.BackupBuilder+import com.Colota.backup.BackupException+import com.Colota.backup.BackupForegroundService+import com.Colota.backup.BackupOrphanCleanup+import com.Colota.backup.BackupPickerCoordinator+import com.Colota.backup.BackupRestorer+import com.Colota.backup.PasswordStrength+import com.Colota.data.DatabaseHelper+import com.Colota.data.SettingsKeys+import com.Colota.export.AutoExportScheduler+import com.Colota.export.AutoExportWorker+import com.Colota.service.LocationForegroundService+import com.Colota.util.AppLogger+import com.facebook.react.ReactApplication+import com.facebook.react.bridge.Arguments+import com.facebook.react.bridge.Promise+import com.facebook.react.bridge.ReactApplicationContext+import com.facebook.react.bridge.ReactContextBaseJavaModule+import com.facebook.react.bridge.ReactMethod+import com.facebook.react.bridge.ReadableArray+import com.facebook.react.bridge.UiThreadUtil+import androidx.work.WorkManager+import android.provider.OpenableColumns+import kotlinx.coroutines.CoroutineScope+import kotlinx.coroutines.Dispatchers+import kotlinx.coroutines.SupervisorJob+import kotlinx.coroutines.cancel+import kotlinx.coroutines.delay+import kotlinx.coroutines.launch+import kotlinx.coroutines.sync.Mutex+import kotlinx.coroutines.withContext+import java.io.File+import java.util.Arrays++class BackupServiceModule(reactContext: ReactApplicationContext) :+ ReactContextBaseJavaModule(reactContext) {++ companion object {+ private const val TAG = "BackupServiceModule"+ private const val PENDING_BACKUP_FILE = "pending_backup.colota"++ // Backup pipeline holds DB snapshot + zip + encrypted file simultaneously.+ private const val BACKUP_FREE_SPACE_MULTIPLIER = 3+ private const val BACKUP_FREE_SPACE_HEADROOM_BYTES = 50L * 1024 * 1024++ // Cloud DocumentsProviders (Drive, MTP) often don't expose OpenableColumns.SIZE.+ // Use this ceiling as the assumed size so an opaque multi-gigabyte file can't fill the cache mid-decrypt.+ private const val UNKNOWN_BACKUP_SIZE_CEILING_BYTES = 2L * 1024 * 1024 * 1024++ private const val SERVICE_STOP_TIMEOUT_MS = 5_000L+ private const val SERVICE_STOP_POLL_MS = 50L+ }++ private val scope = CoroutineScope(Dispatchers.IO + SupervisorJob())+ private val operationMutex = Mutex()+ private val pickerCoordinator = BackupPickerCoordinator(reactContext, scope)++ override fun getName() = "BackupServiceModule"++ override fun invalidate() {+ super.invalidate()+ pickerCoordinator.dispose()+ scope.cancel()+ }++ @ReactMethod+ fun pickBackupDestination(promise: Promise) {+ pickerCoordinator.pickDestination(promise)+ }++ @ReactMethod+ fun pickBackupSource(promise: Promise) {+ pickerCoordinator.pickSource(promise)+ }++ @ReactMethod+ fun passwordStrength(passwordCodes: ReadableArray, promise: Promise) {+ val passwordChars = readableArrayToCharArray(passwordCodes)+ try {+ val result = PasswordStrength.evaluate(passwordChars)+ val map = Arguments.createMap().apply {+ putInt("score", result.score)+ putString("label", result.label)+ putDouble("bits", result.bits)+ }+ promise.resolve(map)+ } finally {+ Arrays.fill(passwordChars, 0.toChar())+ }+ }++ // Password arrives as Array<Number> of UTF-16 code units so the JVM never holds+ // a non-wipeable String. Convert to CharArray immediately and wipe in finally.+ @ReactMethod+ fun createBackup(uriString: String, passwordCodes: ReadableArray, promise: Promise) {+ val passwordChars = readableArrayToCharArray(passwordCodes)+ if (passwordChars.size < PasswordStrength.MIN_LENGTH) {+ Arrays.fill(passwordChars, 0.toChar())+ promise.reject(+ "E_PASSWORD_TOO_SHORT",+ "Password must be at least ${PasswordStrength.MIN_LENGTH} characters",+ )+ return+ }+ if (!PasswordStrength.isAcceptable(passwordChars)) {+ Arrays.fill(passwordChars, 0.toChar())+ promise.reject(+ "E_PASSWORD_TOO_WEAK",+ "Password is too predictable. Use a longer or more random password.",+ )+ return+ }+ scope.launch {+ // Block until the orphan sweep finishes so it can't delete temp dirs we're about to create.+ BackupOrphanCleanup.awaitComplete()+ if (!operationMutex.tryLock()) {+ Arrays.fill(passwordChars, 0.toChar())+ promise.reject("E_BUSY", "Another backup or restore is in progress")+ return@launch+ }+ val pendingFile = File(reactApplicationContext.cacheDir, PENDING_BACKUP_FILE)+ var safCopyStarted = false+ val uri = Uri.parse(uriString)+ try {+ ensureFreeSpaceForBackup()++ startForegroundOnMain("Encrypting backup...")++ pendingFile.outputStream().use { out ->+ BackupBuilder(reactApplicationContext).build(out, passwordChars)+ }++ // Stage locally first so a crash mid-encrypt doesn't leave a half-written SAF file.+ safCopyStarted = true+ val resolver = reactApplicationContext.contentResolver+ resolver.openOutputStream(uri, "wt")?.use { safOut ->+ pendingFile.inputStream().use { it.copyTo(safOut) }+ } ?: throw IllegalStateException("Could not open output stream for $uriString")++ promise.resolve(true)+ } catch (e: Exception) {+ AppLogger.e(TAG, "createBackup failed", e)+ val cleanupOk = if (safCopyStarted) cleanupPartialSafBackup(uri) else true+ val baseMessage = e.message ?: "Backup failed"+ val message = if (cleanupOk) {+ baseMessage+ } else {+ "$baseMessage A partial backup file remains at the chosen location and should be deleted manually."+ }+ promise.reject(errorCode(e), message, e)+ } finally {+ pendingFile.delete()+ Arrays.fill(passwordChars, 0.toChar())+ BackupForegroundService.stop(reactApplicationContext)+ operationMutex.unlock()+ }+ }+ }++ @ReactMethod+ fun restoreBackup(uriString: String, passwordCodes: ReadableArray, promise: Promise) {+ val passwordChars = readableArrayToCharArray(passwordCodes)+ if (passwordChars.isEmpty()) {+ promise.reject("E_PASSWORD_EMPTY", "Password is required")+ return+ }+ scope.launch {+ BackupOrphanCleanup.awaitComplete()+ if (!operationMutex.tryLock()) {+ Arrays.fill(passwordChars, 0.toChar())+ promise.reject("E_BUSY", "Another backup or restore is in progress")+ return@launch+ }+ try {+ val uri = Uri.parse(uriString)+ ensureFreeSpaceForRestore(uri)++ startForegroundOnMain("Restoring backup...")++ pauseAllDbWriters()++ val input = reactApplicationContext.contentResolver.openInputStream(uri)+ ?: throw IllegalStateException("Could not open input stream for $uriString")+ input.use { BackupRestorer(reactApplicationContext).restore(it, passwordChars) }++ // Swap is done; clear the writer block so the post-restore saveSetting can land on the new DB.+ DatabaseHelper.setRestoreInProgress(false)++ // Don't silently resume tracking on the destination device.+ DatabaseHelper.getInstance(reactApplicationContext)+ .saveSetting(SettingsKeys.TRACKING_ENABLED, "false")++ promise.resolve(true)+ } catch (e: Exception) {+ AppLogger.e(TAG, "restoreBackup failed", e)+ promise.reject(errorCode(e), e.message ?: "Restore failed", e)+ } finally {+ Arrays.fill(passwordChars, 0.toChar())+ BackupForegroundService.stop(reactApplicationContext)+ DatabaseHelper.setRestoreInProgress(false)+ operationMutex.unlock()+ }+ }+ }++ // Called by JS after the success alert is dismissed so the alert isn't torn down by reload.+ @ReactMethod+ fun applyRestore(promise: Promise) {+ reloadReactNative()+ promise.resolve(true)+ }++ // Aborts the restore if a writer doesn't stop in time; a live writer racing the swap can corrupt the new DB.+ private suspend fun pauseAllDbWriters() {+ val ctx = reactApplicationContext+ val wm = WorkManager.getInstance(ctx.applicationContext)++ // Persist tracking-disabled to the live DB before gating writers so a later failure+ // here can't leave TRACKING_ENABLED=true with the service stopped, which would+ // resurrect tracking on next boot without the user knowing the restore aborted.+ DatabaseHelper.getInstance(ctx).saveSetting(SettingsKeys.TRACKING_ENABLED, "false")++ // Block JS-bridge writers before stopping native writers so the gap can't be back-filled.+ DatabaseHelper.setRestoreInProgress(true)++ try {+ AutoExportScheduler.cancel(ctx)+ // WorkManager auto-tags every request with the worker's class name; covers manual + alarm-fired paths.+ wm.cancelAllWorkByTag(AutoExportWorker::class.java.name)+ } catch (e: Exception) {+ AppLogger.w(TAG, "Failed to cancel work: ${e.message}")+ }++ ctx.stopService(Intent(ctx, LocationForegroundService::class.java))++ val deadline = System.currentTimeMillis() + SERVICE_STOP_TIMEOUT_MS+ while (+ (LocationForegroundService.isRunning || AutoExportWorker.isRunning)+ && System.currentTimeMillis() < deadline+ ) {+ delay(SERVICE_STOP_POLL_MS)+ }+ val stragglers = buildList {+ if (LocationForegroundService.isRunning) add("location service")+ if (AutoExportWorker.isRunning) add("auto-export worker")+ }+ if (stragglers.isNotEmpty()) {+ throw IllegalStateException(+ "Refusing to restore: ${stragglers.joinToString(", ")} still running " ++ "after ${SERVICE_STOP_TIMEOUT_MS}ms"+ )+ }+ }++ private fun ensureFreeSpaceForRestore(uri: Uri) {+ val resolver = reactApplicationContext.contentResolver+ val backupSize = try {+ resolver.query(uri, arrayOf(OpenableColumns.SIZE), null, null, null)?.use { cursor ->+ if (cursor.moveToFirst() && !cursor.isNull(0)) cursor.getLong(0) else -1L+ } ?: -1L+ } catch (e: Exception) {+ AppLogger.w(TAG, "Could not query backup file size: ${e.message}")+ -1L+ }++ // Fall back to a hard ceiling when the provider hides SIZE; otherwise an opaque+ // multi-GB file would skip this check and fill the cache partition mid-decrypt.+ val effectiveSize = if (backupSize > 0) backupSize else UNKNOWN_BACKUP_SIZE_CEILING_BYTES+ val needed = effectiveSize * 2 + BACKUP_FREE_SPACE_HEADROOM_BYTES+ val cacheDir = reactApplicationContext.cacheDir+ val available = StatFs(cacheDir.absolutePath).availableBytes+ if (available < needed) {+ val neededMb = needed / (1024 * 1024)+ val availableMb = available / (1024 * 1024)+ throw IllegalStateException(+ "Not enough free space for restore. Need ~${neededMb} MB, have ${availableMb} MB."+ )+ }+ }++ // Some OEM ROMs reject FGS starts from background threads.+ private suspend fun startForegroundOnMain(message: String) {+ withContext(Dispatchers.Main) {+ BackupForegroundService.start(reactApplicationContext, message)+ }+ }++ private fun reloadReactNative() {+ UiThreadUtil.runOnUiThread {+ try {+ val app = reactApplicationContext.applicationContext as? ReactApplication+ app?.reactHost?.reload("Backup restore")+ } catch (e: Exception) {+ AppLogger.e(TAG, "Failed to reload React Native after restore", e)+ }+ }+ }++ // Some SAF providers (Drive, MTP) refuse deleteDocument on CREATE_DOCUMENT URIs;+ // truncating to 0 bytes is better than leaving a partial blob that looks legitimate.+ // Returns true if the partial file was deleted or truncated, false if cleanup failed+ // and a partial blob is still on disk - the caller surfaces that to the user.+ private fun cleanupPartialSafBackup(uri: Uri): Boolean {+ val resolver = reactApplicationContext.contentResolver+ val deleted = try {+ DocumentsContract.deleteDocument(resolver, uri)+ } catch (e: Exception) {+ AppLogger.w(TAG, "deleteDocument threw: ${e.message}")+ false+ }+ if (deleted) return true++ return try {+ resolver.openOutputStream(uri, "wt")?.use { /* truncate to empty */ }+ ?.let { true }+ ?: run {+ AppLogger.w(TAG, "Could not open SAF stream to truncate partial backup")+ false+ }+ } catch (e: Exception) {+ AppLogger.w(TAG, "Could not truncate partial SAF backup: ${e.message}")+ false+ }+ }++ private fun ensureFreeSpaceForBackup() {+ val dbFile = reactApplicationContext.getDatabasePath(DatabaseHelper.DATABASE_NAME)+ val dbBytes = if (dbFile.exists()) dbFile.length() else 0L+ val needed = dbBytes * BACKUP_FREE_SPACE_MULTIPLIER + BACKUP_FREE_SPACE_HEADROOM_BYTES++ val cacheDir = reactApplicationContext.cacheDir+ val available = StatFs(cacheDir.absolutePath).availableBytes+ if (available < needed) {+ val neededMb = needed / (1024 * 1024)+ val availableMb = available / (1024 * 1024)+ throw IllegalStateException(+ "Not enough free space for backup. Need ~${neededMb} MB, have ${availableMb} MB."+ )+ }+ }++ private fun errorCode(e: Exception): String = when (e) {+ is BackupException -> "E_BACKUP_${e.error.name}"+ is IllegalStateException -> "E_BACKUP_PRECONDITION"+ else -> "E_BACKUP_UNKNOWN"+ }++ private fun readableArrayToCharArray(codes: ReadableArray): CharArray {+ return CharArray(codes.size()) { i -> codes.getInt(i).toChar() }+ }+}diff --git a/apps/mobile/android/app/src/main/java/com/colota/bridge/LocationServiceModule.kt b/apps/mobile/android/app/src/main/java/com/colota/bridge/LocationServiceModule.ktindex 41d0ca40..98a53b35 100644--- a/apps/mobile/android/app/src/main/java/com/colota/bridge/LocationServiceModule.kt+++ b/apps/mobile/android/app/src/main/java/com/colota/bridge/LocationServiceModule.kt@@ -59,7 +59,9 @@ class LocationServiceModule(reactContext: ReactApplicationContext) :ReactContextBaseJavaModule(reactContext),LifecycleEventListener {- private val dbHelper = DatabaseHelper.getInstance(reactContext)+ // Resolved on each access so a restore that nulls the singleton can't leave this+ // module pointing at the closed pre-restore helper between swap and React reload.+ private val dbHelper get() = DatabaseHelper.getInstance(reactApplicationContext)private val fileOps = FileOperations(reactContext)private val deviceInfo = DeviceInfoHelper(reactContext)private val geofenceHelper = GeofenceHelper(reactContext)diff --git a/apps/mobile/android/app/src/main/java/com/colota/bridge/LocationServicePackage.kt b/apps/mobile/android/app/src/main/java/com/colota/bridge/LocationServicePackage.ktindex f0a41eb6..66ba0f74 100644--- a/apps/mobile/android/app/src/main/java/com/colota/bridge/LocationServicePackage.kt+++ b/apps/mobile/android/app/src/main/java/com/colota/bridge/LocationServicePackage.kt@@ -23,7 +23,8 @@ class LocationServicePackage : ReactPackage {return listOf(LocationServiceModule(reactContext),MtlsBridgeModule(reactContext),- BuildConfigModule(reactContext)+ BuildConfigModule(reactContext),+ BackupServiceModule(reactContext))}diff --git a/apps/mobile/android/app/src/main/java/com/colota/data/DatabaseHelper.kt b/apps/mobile/android/app/src/main/java/com/colota/data/DatabaseHelper.ktindex 8eb5fbb1..f923b39f 100644--- a/apps/mobile/android/app/src/main/java/com/colota/data/DatabaseHelper.kt+++ b/apps/mobile/android/app/src/main/java/com/colota/data/DatabaseHelper.kt@@ -12,6 +12,7 @@ import com.Colota.util.geo.haversineDistanceimport android.content.Contextimport android.database.sqlite.SQLiteDatabaseimport android.database.sqlite.SQLiteOpenHelper+import android.os.Buildimport java.time.LocalDateimport java.time.ZoneIdimport org.json.JSONObject@@ -30,8 +31,8 @@ class DatabaseHelper private constructor(context: Context) :SQLiteOpenHelper(context, DATABASE_NAME, null, DATABASE_VERSION) {companion object {- private const val DATABASE_NAME = "Colota.db"- private const val DATABASE_VERSION = 5+ const val DATABASE_NAME = "Colota.db"+ const val DATABASE_VERSION = 5const val TABLE_LOCATIONS = "locations"const val TABLE_QUEUE = "queue"@@ -68,10 +69,149 @@ class DatabaseHelper private constructor(context: Context) :@Volatileprivate var INSTANCE: DatabaseHelper? = null- /**- * Returns the singleton instance of the [DatabaseHelper].- * Using the Application Context prevents memory leaks.- */+ // Set true while a restore is replacing the DB; JS-bridge writers must short-circuit+ // so a write doesn't race the file swap. Cleared by BackupServiceModule in its finally.+ @Volatile+ private var restoreInProgress: Boolean = false++ @JvmStatic+ fun setRestoreInProgress(value: Boolean) {+ restoreInProgress = value+ }++ // Drain the WAL into main, then best-effort delete sidecars before the rename. SQLite's+ // WAL salt+checksum makes replay unlikely, but stale sidecars next to the new DB are untidy.+ @JvmStatic+ fun replaceLiveDatabase(context: Context, newDb: java.io.File) {+ synchronized(this) {+ INSTANCE?.close()+ INSTANCE = null++ val target = context.applicationContext.getDatabasePath(DATABASE_NAME)+ target.parentFile?.mkdirs()++ drainLiveWal(target)++ bestEffortDelete(java.io.File("${target.absolutePath}-wal"))+ bestEffortDelete(java.io.File("${target.absolutePath}-shm"))+ bestEffortDelete(java.io.File("${target.absolutePath}-journal"))++ val staging = java.io.File(target.parentFile, "${DATABASE_NAME}.incoming")+ try {+ try {+ java.nio.file.Files.move(+ newDb.toPath(),+ target.toPath(),+ java.nio.file.StandardCopyOption.REPLACE_EXISTING,+ java.nio.file.StandardCopyOption.ATOMIC_MOVE,+ )+ } catch (_: java.nio.file.AtomicMoveNotSupportedException) {+ newDb.inputStream().use { input ->+ staging.outputStream().use { input.copyTo(it) }+ }+ java.nio.file.Files.move(+ staging.toPath(),+ target.toPath(),+ java.nio.file.StandardCopyOption.REPLACE_EXISTING,+ java.nio.file.StandardCopyOption.ATOMIC_MOVE,+ )+ newDb.delete()+ }+ } finally {+ if (staging.exists()) staging.delete()+ }+ }+ }++ // Sidecar deletes are non-critical; SQLite recovers fine without them. A SecurityException+ // from a sandbox-restricted FS shouldn't abort the whole swap.+ private fun bestEffortDelete(file: java.io.File) {+ try {+ file.delete()+ } catch (e: SecurityException) {+ AppLogger.w(TAG, "Could not delete ${file.name}: ${e.message}")+ }+ }++ // Truncating checkpoint moves uncheckpointed WAL pages into main before sidecar delete.+ private fun drainLiveWal(target: java.io.File) {+ if (!target.exists()) return+ try {+ val db = SQLiteDatabase.openDatabase(+ target.absolutePath,+ null,+ SQLiteDatabase.OPEN_READWRITE,+ )+ try {+ db.rawQuery("PRAGMA wal_checkpoint(TRUNCATE)", null).use { it.moveToFirst() }+ } finally {+ db.close()+ }+ } catch (e: Exception) {+ AppLogger.w(TAG, "Could not drain WAL before replace: ${e.message}")+ }+ }++ // Run before the swap so a migration failure leaves the live DB untouched.+ @JvmStatic+ fun migrateCandidate(candidateFile: java.io.File) {+ val db = SQLiteDatabase.openDatabase(+ candidateFile.absolutePath,+ null,+ SQLiteDatabase.OPEN_READWRITE,+ )+ try {+ // DELETE mode: migration writes go straight to main, not a -wal that the rename ignores.+ db.rawQuery("PRAGMA journal_mode=DELETE", null).use { it.moveToFirst() }++ val current = db.version+ if (current > DATABASE_VERSION) {+ throw IllegalStateException(+ "Candidate schema $current is newer than app schema $DATABASE_VERSION"+ )+ }+ if (current < DATABASE_VERSION) {+ db.beginTransaction()+ try {+ applyMigrations(db, current, DATABASE_VERSION)+ db.version = DATABASE_VERSION+ db.setTransactionSuccessful()+ } finally {+ db.endTransaction()+ }+ }+ } finally {+ db.close()+ }+ }++ private fun applyMigrations(db: SQLiteDatabase, oldVersion: Int, newVersion: Int) {+ AppLogger.i(TAG, "Migrating database from v$oldVersion to v$newVersion")+ if (oldVersion < 2) {+ db.execSQL(CREATE_PROFILES_TABLE)+ db.execSQL(CREATE_PROFILES_INDEX)+ }+ if (oldVersion < 3) {+ db.execSQL("ALTER TABLE $TABLE_LOCATIONS ADD COLUMN sent INTEGER NOT NULL DEFAULT 0")+ db.execSQL("""+ UPDATE $TABLE_LOCATIONS SET sent = 1+ WHERE NOT EXISTS (+ SELECT 1 FROM $TABLE_QUEUE+ WHERE $TABLE_QUEUE.location_id = $TABLE_LOCATIONS.id+ )+ """.trimIndent())+ }+ if (oldVersion < 4) {+ db.execSQL("ALTER TABLE $TABLE_GEOFENCES ADD COLUMN pause_on_wifi INTEGER NOT NULL DEFAULT 0")+ db.execSQL("ALTER TABLE $TABLE_GEOFENCES ADD COLUMN pause_on_motionless INTEGER NOT NULL DEFAULT 0")+ db.execSQL("ALTER TABLE $TABLE_GEOFENCES ADD COLUMN motionless_timeout_minutes INTEGER NOT NULL DEFAULT 10")+ }+ if (oldVersion < 5) {+ db.execSQL("ALTER TABLE $TABLE_GEOFENCES ADD COLUMN heartbeat_enabled INTEGER NOT NULL DEFAULT 0")+ db.execSQL("ALTER TABLE $TABLE_GEOFENCES ADD COLUMN heartbeat_interval_minutes INTEGER NOT NULL DEFAULT 15")+ }+ }+@JvmStaticfun getInstance(context: Context): DatabaseHelper {return INSTANCE ?: synchronized(this) {@@ -202,32 +342,7 @@ class DatabaseHelper private constructor(context: Context) :}override fun onUpgrade(db: SQLiteDatabase, oldVersion: Int, newVersion: Int) {- AppLogger.i(TAG, "Upgrading database from v$oldVersion to v$newVersion")- if (oldVersion < 2) {- db.execSQL(CREATE_PROFILES_TABLE)- db.execSQL(CREATE_PROFILES_INDEX)- }- if (oldVersion < 3) {- db.execSQL("ALTER TABLE $TABLE_LOCATIONS ADD COLUMN sent INTEGER NOT NULL DEFAULT 0")- // NOT EXISTS uses idx_queue_location; the original NOT IN (SELECT ...) ran- // a full queue scan per row and OOM'd users with weeks of accumulated data.- db.execSQL("""- UPDATE $TABLE_LOCATIONS SET sent = 1- WHERE NOT EXISTS (- SELECT 1 FROM $TABLE_QUEUE- WHERE $TABLE_QUEUE.location_id = $TABLE_LOCATIONS.id- )- """.trimIndent())- }- if (oldVersion < 4) {- db.execSQL("ALTER TABLE $TABLE_GEOFENCES ADD COLUMN pause_on_wifi INTEGER NOT NULL DEFAULT 0")- db.execSQL("ALTER TABLE $TABLE_GEOFENCES ADD COLUMN pause_on_motionless INTEGER NOT NULL DEFAULT 0")- db.execSQL("ALTER TABLE $TABLE_GEOFENCES ADD COLUMN motionless_timeout_minutes INTEGER NOT NULL DEFAULT 10")- }- if (oldVersion < 5) {- db.execSQL("ALTER TABLE $TABLE_GEOFENCES ADD COLUMN heartbeat_enabled INTEGER NOT NULL DEFAULT 0")- db.execSQL("ALTER TABLE $TABLE_GEOFENCES ADD COLUMN heartbeat_interval_minutes INTEGER NOT NULL DEFAULT 15")- }+ applyMigrations(db, oldVersion, newVersion)}override fun onOpen(db: SQLiteDatabase) {@@ -239,6 +354,13 @@ class DatabaseHelper private constructor(context: Context) :}+ // Writers that race the restore swap can land on the orphaned (pre-rename) inode and lose data.+ private fun requireNotRestoring() {+ if (restoreInProgress) {+ throw IllegalStateException("Database is being restored; try again in a moment")+ }+ }+fun saveLocation(latitude: Double,longitude: Double,@@ -251,6 +373,7 @@ class DatabaseHelper private constructor(context: Context) :timestamp: Long,endpoint: String? = null): Long {+ requireNotRestoring()val values = ContentValues().apply {put("latitude", latitude)put("longitude", longitude)@@ -386,6 +509,7 @@ class DatabaseHelper private constructor(context: Context) :* @return The queue ID of the inserted row*/fun addToQueue(locationId: Long, payload: String): Long {+ requireNotRestoring()val values = ContentValues().apply {put("location_id", locationId)put("payload", payload)@@ -421,6 +545,7 @@ class DatabaseHelper private constructor(context: Context) :}fun removeFromQueueByLocationId(locationId: Long): Int {+ requireNotRestoring()return writableDatabase.delete(TABLE_QUEUE,"location_id = ?",@@ -429,6 +554,7 @@ class DatabaseHelper private constructor(context: Context) :}fun removeBatchFromQueue(queueIds: List<Long>) {+ requireNotRestoring()if (queueIds.isEmpty()) returnval placeholders = queueIds.joinToString(",") { "?" }@@ -446,6 +572,7 @@ class DatabaseHelper private constructor(context: Context) :}fun deleteLocations(locationIds: List<Long>) {+ requireNotRestoring()if (locationIds.isEmpty()) returnval placeholders = locationIds.joinToString(",") { "?" }val args = locationIds.map { it.toString() }.toTypedArray()@@ -453,6 +580,7 @@ class DatabaseHelper private constructor(context: Context) :}fun incrementRetryCount(queueId: Long, error: String? = null) {+ requireNotRestoring()writableDatabase.execSQL("UPDATE $TABLE_QUEUE SET retry_count = retry_count + 1, last_error = ? WHERE id = ?",arrayOf<Any>(error ?: "", queueId)@@ -488,6 +616,7 @@ class DatabaseHelper private constructor(context: Context) :}fun markLocationsSent(locationIds: List<Long>) {+ requireNotRestoring()if (locationIds.isEmpty()) returnval placeholders = locationIds.joinToString(",") { "?" }val args = locationIds.map { it.toString() }.toTypedArray()@@ -508,8 +637,38 @@ class DatabaseHelper private constructor(context: Context) :return java.io.File(dbPath).length() / (1024.0 * 1024.0)}+ fun snapshotTo(destFile: java.io.File) {+ requireNotRestoring()+ val db = writableDatabase+ val srcPath = db.path ?: throw IllegalStateException("Database path is null")++ // VACUUM INTO is transactional even under concurrent writers (SQLite 3.27+, API 30+).+ if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) {+ db.execSQL("VACUUM INTO ?", arrayOf(destFile.absolutePath))+ return+ }++ // API 26-29 fallback: hold an IMMEDIATE write lock around the checkpoint + copy.+ // beginTransactionNonExclusive maps to BEGIN IMMEDIATE in Android's SQLite,+ // so other writers must queue at the file lock, preventing -wal appends from+ // tearing the main-file copy. Readers continue via WAL snapshots.+ db.beginTransactionNonExclusive()+ try {+ db.rawQuery("PRAGMA wal_checkpoint(TRUNCATE)", null).use { it.moveToFirst() }+ java.io.File(srcPath).inputStream().use { input ->+ destFile.outputStream().use { output ->+ input.copyTo(output)+ }+ }+ db.setTransactionSuccessful()+ } finally {+ db.endTransaction()+ }+ }+fun clearSentHistory(): Int {+ requireNotRestoring()AppLogger.d(TAG, "Clearing sent history")return writableDatabase.delete(TABLE_LOCATIONS,@@ -519,6 +678,7 @@ class DatabaseHelper private constructor(context: Context) :}fun clearQueue(): Int {+ requireNotRestoring()AppLogger.d(TAG, "Clearing queue")// Deleting locations cascades to their queue entries via FK ON DELETE CASCADEreturn writableDatabase.delete(@@ -529,16 +689,19 @@ class DatabaseHelper private constructor(context: Context) :}fun clearAllLocations(): Int {+ requireNotRestoring()writableDatabase.delete(TABLE_QUEUE, null, null) // FK constraint: queue references locationsreturn writableDatabase.delete(TABLE_LOCATIONS, null, null)}fun deleteOlderThan(days: Int): Int {+ requireNotRestoring()val cutoff = (System.currentTimeMillis() - days.toLong() * 24 * 60 * 60 * 1000) / 1000return writableDatabase.delete(TABLE_LOCATIONS, "timestamp < ?", arrayOf(cutoff.toString()))}fun deleteInRange(startTs: Long, endTs: Long): Int {+ requireNotRestoring()return writableDatabase.delete(TABLE_LOCATIONS,"timestamp >= ? AND timestamp <= ?",@@ -548,6 +711,7 @@ class DatabaseHelper private constructor(context: Context) :/** Reclaims unused space. Call from background thread only. */fun vacuum() {+ requireNotRestoring()AppLogger.d(TAG, "Starting VACUUM + ANALYZE")try {writableDatabase.execSQL("VACUUM")@@ -560,14 +724,15 @@ class DatabaseHelper private constructor(context: Context) :fun saveSetting(key: String, value: String) {+ requireNotRestoring()val values = ContentValues().apply {put("key", key)put("value", value)}writableDatabase.insertWithOnConflict(- TABLE_SETTINGS,- null,- values,+ TABLE_SETTINGS,+ null,+ values,SQLiteDatabase.CONFLICT_REPLACE)}diff --git a/apps/mobile/android/app/src/main/java/com/colota/export/AutoExportWorker.kt b/apps/mobile/android/app/src/main/java/com/colota/export/AutoExportWorker.ktindex 9224d923..e46ebe22 100644--- a/apps/mobile/android/app/src/main/java/com/colota/export/AutoExportWorker.kt+++ b/apps/mobile/android/app/src/main/java/com/colota/export/AutoExportWorker.kt@@ -43,6 +43,12 @@ class AutoExportWorker(private const val FOREGROUND_NOTIFICATION_ID = 9002// OneTimeWorkRequest has no default retry cap - bound transient IO retries here.private const val MAX_RETRIES = 3++ // BackupServiceModule.pauseAllDbWriters polls this before the restore swap.+ @Volatile+ @JvmStatic+ var isRunning: Boolean = false+ private set}override suspend fun getForegroundInfo(): ForegroundInfo {@@ -62,9 +68,11 @@ class AutoExportWorker(override suspend fun doWork(): Result {val isManualRun = tags.contains(AutoExportScheduler.IMMEDIATE_WORK_TAG)+ isRunning = truereturn try {executeWork(isManualRun)} finally {+ isRunning = falseif (!isManualRun) {try {AutoExportScheduler.scheduleNext(appContext)diff --git a/apps/mobile/android/app/src/main/java/com/colota/service/LocationForegroundService.kt b/apps/mobile/android/app/src/main/java/com/colota/service/LocationForegroundService.ktindex db1317f2..95c3bea2 100644--- a/apps/mobile/android/app/src/main/java/com/colota/service/LocationForegroundService.kt+++ b/apps/mobile/android/app/src/main/java/com/colota/service/LocationForegroundService.kt@@ -115,6 +115,13 @@ class LocationForegroundService : Service() {companion object {private const val TAG = "LocationService"++ // Polled by BackupServiceModule.pauseAllDbWriters before the restore swap.+ @Volatile+ @JvmStatic+ var isRunning: Boolean = false+ private set+/** Multiplier applied to the tracking interval for the geofence entry delay. */private const val ENTRY_DELAY_MULTIPLIER = 3.5/** Debounce before resuming GPS after unmetered network is lost (ms). */@@ -139,6 +146,7 @@ class LocationForegroundService : Service() {override fun onCreate() {super.onCreate()+ isRunning = trueserviceScope = CoroutineScope(Dispatchers.IO + SupervisorJob())@@ -334,23 +342,33 @@ class LocationForegroundService : Service() {override fun onDestroy() {AppLogger.d(TAG, "Service destroyed")- motionDetector?.stop()- entryDelayJob?.cancel()- entryDelayJob = null- pendingPauseZone = null- unregisterWifiPause()- cancelHeartbeat()- unregisterLocationProvidersReceiver()- unregisterDebugMotionReceiver()- conditionMonitor.stop()- stopLocationUpdates()- syncManager.stopPeriodicSync()- networkManager.destroy()+ // Teardown DB writes throw during a restore; swallow so the throw can't+ // bubble out of onDestroy and kill the process. State is overwritten by the swap.+ try {+ motionDetector?.stop()+ entryDelayJob?.cancel()+ entryDelayJob = null+ pendingPauseZone = null+ unregisterWifiPause()+ cancelHeartbeat()+ unregisterLocationProvidersReceiver()+ unregisterDebugMotionReceiver()+ conditionMonitor.stop()+ stopLocationUpdates()+ syncManager.stopPeriodicSync()+ networkManager.destroy()+ } catch (e: IllegalStateException) {+ AppLogger.w(TAG, "Teardown step skipped: ${e.message}")+ } catch (e: Exception) {+ AppLogger.e(TAG, "Unexpected error during service teardown", e)+ }+ // Critical teardown: must run so pauseAllDbWriters' poll loop sees isRunning=false.serviceScope?.cancel()serviceScope = nullnotificationManager.cancel(NotificationHelper.NOTIFICATION_ID)+ isRunning = falsesuper.onDestroy()}diff --git a/apps/mobile/android/app/src/main/java/com/colota/util/SecureStorageHelper.kt b/apps/mobile/android/app/src/main/java/com/colota/util/SecureStorageHelper.ktindex 19d15418..97cba4a3 100644--- a/apps/mobile/android/app/src/main/java/com/colota/util/SecureStorageHelper.kt+++ b/apps/mobile/android/app/src/main/java/com/colota/util/SecureStorageHelper.kt@@ -30,6 +30,14 @@ class SecureStorageHelper private constructor(context: Context) {const val KEY_MTLS_SERVER_CA_B64 = "mtls_server_ca_b64"const val KEY_MTLS_KEYCHAIN_ALIAS = "mtls_keychain_alias"+ // KEY_MTLS_KEYCHAIN_ALIAS is intentionally excluded: the private key it points at lives in+ // Android KeyChain and can't leave the source device. Re-import the cert on the destination.+ private val BACKED_UP_KEYS = listOf(+ KEY_AUTH_TYPE, KEY_USERNAME, KEY_PASSWORD,+ KEY_BEARER_TOKEN, KEY_CUSTOM_HEADERS,+ KEY_MTLS_SERVER_CA_B64,+ )+@Volatileprivate var INSTANCE: SecureStorageHelper? = null@@ -109,6 +117,22 @@ class SecureStorageHelper private constructor(context: Context) {/*** Builds the full set of auth + custom headers for HTTP requests.*/+ internal fun exportPlaintextForBackup(): Map<String, String> {+ return BACKED_UP_KEYS.mapNotNull { key -> getString(key)?.let { key to it } }.toMap()+ }++ // Clear-then-set so credentials added after the backup don't survive the restore. Sync commit.+ internal fun importPlaintextFromBackup(secrets: Map<String, String>) {+ val editor = prefs.edit()+ BACKED_UP_KEYS.forEach { editor.remove(it) }+ secrets.forEach { (key, value) ->+ if (value.isNotEmpty()) editor.putString(key, value)+ }+ if (!editor.commit()) {+ throw IllegalStateException("EncryptedSharedPreferences.commit() returned false")+ }+ }+fun getAuthHeaders(): Map<String, String> {val headers = mutableMapOf<String, String>()diff --git a/apps/mobile/android/app/src/test/java/com/Colota/backup/BackupBuilderTest.kt b/apps/mobile/android/app/src/test/java/com/Colota/backup/BackupBuilderTest.ktnew file mode 100644index 00000000..c0d8826c--- /dev/null+++ b/apps/mobile/android/app/src/test/java/com/Colota/backup/BackupBuilderTest.kt@@ -0,0 +1,168 @@+/**+ * Copyright (C) 2026 Max Dietrich+ * Licensed under the GNU AGPLv3. See LICENSE in the project root for details.+ */++package com.Colota.backup++import android.content.ContentValues+import androidx.test.core.app.ApplicationProvider+import com.Colota.data.DatabaseHelper+import com.Colota.util.AppLogger+import com.Colota.util.SecureStorageHelper+import io.mockk.Runs+import io.mockk.every+import io.mockk.just+import io.mockk.mockk+import io.mockk.mockkObject+import io.mockk.unmockkObject+import org.json.JSONObject+import org.junit.After+import org.junit.Assert.assertEquals+import org.junit.Assert.assertFalse+import org.junit.Assert.assertNotNull+import org.junit.Assert.assertTrue+import org.junit.Before+import org.junit.Test+import org.junit.runner.RunWith+import org.robolectric.RobolectricTestRunner+import java.io.ByteArrayInputStream+import java.io.ByteArrayOutputStream+import java.io.File+import java.util.zip.ZipInputStream++@RunWith(RobolectricTestRunner::class)+class BackupBuilderTest {++ private lateinit var db: DatabaseHelper+ private lateinit var secureStorage: SecureStorageHelper+ private lateinit var builder: BackupBuilder++ private val password = "correct horse battery staple".toCharArray()++ @Before+ fun setUp() {+ resetDbSingleton()+ mockkObject(AppLogger)+ every { AppLogger.d(any(), any()) } just Runs+ every { AppLogger.i(any(), any()) } just Runs+ every { AppLogger.w(any(), any()) } just Runs+ every { AppLogger.e(any(), any(), any()) } just Runs++ val context = ApplicationProvider.getApplicationContext<android.content.Context>()+ db = DatabaseHelper.getInstance(context)++ secureStorage = mockk(relaxed = true)+ every { secureStorage.exportPlaintextForBackup() } returns mapOf(+ "auth_type" to "bearer",+ "auth_bearer_token" to "test-token-12345",+ )++ builder = BackupBuilder(context, db, secureStorage)+ }++ @After+ fun tearDown() {+ db.close()+ resetDbSingleton()+ unmockkObject(AppLogger)+ }++ @Test+ fun `backup round-trip recovers database, secrets, and manifest`() {+ seedDatabase()++ val encrypted = ByteArrayOutputStream().apply {+ builder.build(this, password)+ }.toByteArray()++ val zipBytes = decryptToZip(encrypted)+ val entries = readZipEntries(zipBytes)++ assertNotNull(entries["manifest.json"])+ assertNotNull(entries["secrets.json"])+ assertNotNull(entries["db/colota.sqlite"])++ val manifest = JSONObject(String(entries.getValue("manifest.json"), Charsets.UTF_8))+ assertEquals(DatabaseHelper.DATABASE_VERSION, manifest.getJSONObject("schema").getInt("db"))+ assertTrue("createdAt missing", manifest.getString("createdAt").isNotBlank())+ assertTrue("appVersion missing", manifest.getString("appVersion").isNotBlank())++ val secrets = JSONObject(String(entries.getValue("secrets.json"), Charsets.UTF_8))+ assertEquals("bearer", secrets.getString("auth_type"))+ assertEquals("test-token-12345", secrets.getString("auth_bearer_token"))++ val dbBytes = entries.getValue("db/colota.sqlite")+ assertTrue("DB snapshot too small", dbBytes.size > 1024)+ assertEquals("SQLite format 3", String(dbBytes, 0, 15, Charsets.US_ASCII))+ }++ @Test+ fun `cacheDir backup_temp is cleared after build`() {+ val context = ApplicationProvider.getApplicationContext<android.content.Context>()+ val workDir = File(context.cacheDir, "backup_temp")+ workDir.mkdirs()+ File(workDir, "stale").writeText("leftover")++ builder.build(ByteArrayOutputStream(), password)++ assertFalse("stale temp file must be cleaned", File(workDir, "stale").exists())+ }++ @Test+ fun `cacheDir backup_temp is cleared even if encrypt fails`() {+ every { secureStorage.exportPlaintextForBackup() } throws RuntimeException("boom")++ val context = ApplicationProvider.getApplicationContext<android.content.Context>()+ val workDir = File(context.cacheDir, "backup_temp")++ try {+ builder.build(ByteArrayOutputStream(), password)+ } catch (_: RuntimeException) {+ // expected+ }++ assertFalse("workDir must be removed on failure", workDir.exists())+ }++ private fun seedDatabase() {+ val sqlite = db.writableDatabase+ for (i in 0..9) {+ val values = ContentValues().apply {+ put("latitude", 52.5 + i * 0.001)+ put("longitude", 13.4 + i * 0.001)+ put("accuracy", 5)+ put("timestamp", System.currentTimeMillis() / 1000 + i)+ put("created_at", System.currentTimeMillis())+ put("sent", 0)+ }+ val id = sqlite.insert(DatabaseHelper.TABLE_LOCATIONS, null, values)+ check(id != -1L) { "seed insert failed at row $i" }+ }+ db.saveSetting("themeMode", "dark")+ }++ private fun decryptToZip(encrypted: ByteArray): ByteArray {+ val out = ByteArrayOutputStream()+ BackupCrypto().decrypt(ByteArrayInputStream(encrypted), out, password)+ return out.toByteArray()+ }++ private fun readZipEntries(zipBytes: ByteArray): Map<String, ByteArray> {+ val result = mutableMapOf<String, ByteArray>()+ ZipInputStream(ByteArrayInputStream(zipBytes)).use { zip ->+ var entry = zip.nextEntry+ while (entry != null) {+ result[entry.name] = zip.readBytes()+ entry = zip.nextEntry+ }+ }+ return result+ }++ private fun resetDbSingleton() {+ val field = DatabaseHelper::class.java.getDeclaredField("INSTANCE")+ field.isAccessible = true+ field.set(null, null)+ }+}diff --git a/apps/mobile/android/app/src/test/java/com/Colota/backup/BackupCryptoTest.kt b/apps/mobile/android/app/src/test/java/com/Colota/backup/BackupCryptoTest.ktnew file mode 100644index 00000000..196b26ff--- /dev/null+++ b/apps/mobile/android/app/src/test/java/com/Colota/backup/BackupCryptoTest.kt@@ -0,0 +1,243 @@+/**+ * Copyright (C) 2026 Max Dietrich+ * Licensed under the GNU AGPLv3. See LICENSE in the project root for details.+ */++package com.Colota.backup++import org.junit.Assert.assertArrayEquals+import org.junit.Assert.assertEquals+import org.junit.Assert.assertTrue+import org.junit.Assert.fail+import org.junit.Test+import java.io.ByteArrayInputStream+import java.io.ByteArrayOutputStream++class BackupCryptoTest {++ private val crypto = BackupCrypto()+ private val password = "correct horse battery staple".toCharArray()+ private val smallChunk = 64++ @Test+ fun `empty input is rejected at encrypt time`() {+ try {+ encrypt(ByteArray(0))+ fail("Expected IllegalStateException")+ } catch (e: IllegalStateException) {+ assertTrue(e.message?.contains("empty") == true)+ }+ }++ @Test+ fun `round-trip single-chunk input`() {+ val plaintext = "hello world".toByteArray()+ val encrypted = encrypt(plaintext)+ val decrypted = decrypt(encrypted)+ assertArrayEquals(plaintext, decrypted)+ }++ @Test+ fun `round-trip exactly chunk-aligned input`() {+ val plaintext = ByteArray(smallChunk * 3) { it.toByte() }+ val encrypted = encrypt(plaintext, smallChunk)+ val decrypted = decrypt(encrypted)+ assertArrayEquals(plaintext, decrypted)+ }++ @Test+ fun `round-trip multi-chunk input with partial final chunk`() {+ val plaintext = ByteArray(smallChunk * 3 + 17) { (it * 7).toByte() }+ val encrypted = encrypt(plaintext, smallChunk)+ val decrypted = decrypt(encrypted)+ assertArrayEquals(plaintext, decrypted)+ }++ @Test+ fun `wrong password fails on first chunk`() {+ val plaintext = "secret".toByteArray()+ val encrypted = encrypt(plaintext)++ try {+ crypto.decrypt(+ ByteArrayInputStream(encrypted),+ ByteArrayOutputStream(),+ "wrong password".toCharArray(),+ )+ fail("Expected WRONG_PASSWORD")+ } catch (e: BackupException) {+ assertEquals(BackupError.WRONG_PASSWORD, e.error)+ }+ }++ @Test+ fun `bad magic is rejected`() {+ val encrypted = encrypt("hi".toByteArray())+ encrypted[0] = 'X'.code.toByte()++ try {+ decrypt(encrypted)+ fail("Expected BAD_MAGIC")+ } catch (e: BackupException) {+ assertEquals(BackupError.BAD_MAGIC, e.error)+ }+ }++ @Test+ fun `truncated stream is rejected`() {+ val encrypted = encrypt("some data here".toByteArray())+ val truncated = encrypted.copyOf(encrypted.size - 4)++ try {+ decrypt(truncated)+ fail("Expected TRUNCATED")+ } catch (e: BackupException) {+ assertEquals(BackupError.TRUNCATED, e.error)+ }+ }++ @Test+ fun `truncated to header only is rejected`() {+ val encrypted = encrypt("some data".toByteArray())+ val onlyHeader = encrypted.copyOf(BackupFormat.HEADER_BYTES)++ try {+ decrypt(onlyHeader)+ fail("Expected TRUNCATED")+ } catch (e: BackupException) {+ assertEquals(BackupError.TRUNCATED, e.error)+ }+ }++ @Test+ fun `tampered ciphertext is rejected`() {+ val plaintext = ByteArray(smallChunk * 2) { (it * 13).toByte() }+ val encrypted = encrypt(plaintext, smallChunk)++ // Flip a byte in the second chunk's ciphertext (after header + chunk 0)+ val chunk0Total = 4 + smallChunk + BackupFormat.GCM_TAG_BYTES+ val targetByte = BackupFormat.HEADER_BYTES + chunk0Total + 4 + 5+ encrypted[targetByte] = (encrypted[targetByte].toInt() xor 0x01).toByte()++ try {+ decrypt(encrypted)+ fail("Expected TAMPERED")+ } catch (e: BackupException) {+ assertEquals(BackupError.TAMPERED, e.error)+ }+ }++ @Test+ fun `header round-trip preserves all fields`() {+ val plaintext = "x".toByteArray()+ val encrypted = encrypt(plaintext, smallChunk)++ val header = crypto.readHeader(ByteArrayInputStream(encrypted))+ assertEquals(BackupFormat.FORMAT_VERSION, header.formatVersion)+ assertEquals(BackupFormat.KDF_ARGON2ID, header.kdfId)+ assertEquals(smallChunk, header.chunkSize)+ assertEquals(BackupFormat.SALT_BYTES, header.salt.size)+ assertEquals(BackupFormat.NONCE_PREFIX_BYTES, header.noncePrefix.size)+ }++ @Test+ fun `successive backups have different salts`() {+ val plaintext = "x".toByteArray()+ val a = encrypt(plaintext)+ val b = encrypt(plaintext)++ val saltStart = BackupFormat.MAGIC_BYTES + 1 + 1 + BackupFormat.KDF_PARAMS_BYTES+ val saltA = a.sliceArray(saltStart until saltStart + BackupFormat.SALT_BYTES)+ val saltB = b.sliceArray(saltStart until saltStart + BackupFormat.SALT_BYTES)+ assertTrue("salts must differ", !saltA.contentEquals(saltB))+ }++ @Test+ fun `unsupported format version is rejected`() {+ val encrypted = encrypt("hi".toByteArray())+ encrypted[BackupFormat.MAGIC_BYTES] = 99 // formatVersion byte+ try {+ decrypt(encrypted)+ fail("Expected UNSUPPORTED_VERSION")+ } catch (e: BackupException) {+ assertEquals(BackupError.UNSUPPORTED_VERSION, e.error)+ }+ }++ @Test+ fun `unsupported KDF id is rejected`() {+ val encrypted = encrypt("hi".toByteArray())+ encrypted[BackupFormat.MAGIC_BYTES + 1] = BackupFormat.KDF_PBKDF2 // kdfId byte+ try {+ decrypt(encrypted)+ fail("Expected UNSUPPORTED_KDF")+ } catch (e: BackupException) {+ assertEquals(BackupError.UNSUPPORTED_KDF, e.error)+ }+ }++ @Test+ fun `tampered KDF params fails on chunk 0 as wrong password`() {+ val encrypted = encrypt("hi".toByteArray())+ // Flip a byte inside the kdfParams region (memory cost field).+ val kdfStart = BackupFormat.MAGIC_BYTES + 2+ encrypted[kdfStart] = (encrypted[kdfStart].toInt() xor 0x01).toByte()+ try {+ decrypt(encrypted)+ fail("Expected WRONG_PASSWORD or out-of-range param")+ } catch (e: BackupException) {+ // Either Argon2 param validation rejects (TAMPERED via require())+ // or the changed AAD makes chunk 0 fail as WRONG_PASSWORD.+ assertTrue(+ "got ${e.error}",+ e.error == BackupError.WRONG_PASSWORD || e.error == BackupError.TAMPERED+ )+ }+ }++ @Test+ fun `tampered nonce prefix fails on chunk 0`() {+ val encrypted = encrypt("hi".toByteArray())+ // noncePrefix sits after magic + formatVer + kdfId + kdfParams + salt+ val nonceStart = BackupFormat.MAGIC_BYTES + 2 + BackupFormat.KDF_PARAMS_BYTES + BackupFormat.SALT_BYTES+ encrypted[nonceStart] = (encrypted[nonceStart].toInt() xor 0x01).toByte()+ try {+ decrypt(encrypted)+ fail("Expected WRONG_PASSWORD")+ } catch (e: BackupException) {+ assertEquals(BackupError.WRONG_PASSWORD, e.error)+ }+ }++ @Test+ fun `oversized declared chunkSize is rejected`() {+ val encrypted = encrypt("hi".toByteArray())+ // chunkSize sits after magic + formatVer + kdfId + kdfParams + salt + noncePrefix+ val chunkSizeOffset = BackupFormat.MAGIC_BYTES + 2 ++ BackupFormat.KDF_PARAMS_BYTES + BackupFormat.SALT_BYTES ++ BackupFormat.NONCE_PREFIX_BYTES+ // Write 64 MiB (0x04000000) - above MAX_READ_CHUNK_SIZE+ encrypted[chunkSizeOffset] = 0x04+ encrypted[chunkSizeOffset + 1] = 0+ encrypted[chunkSizeOffset + 2] = 0+ encrypted[chunkSizeOffset + 3] = 0+ try {+ decrypt(encrypted)+ fail("Expected TAMPERED")+ } catch (e: BackupException) {+ assertEquals(BackupError.TAMPERED, e.error)+ }+ }++ private fun encrypt(plaintext: ByteArray, chunkSize: Int = BackupFormat.DEFAULT_CHUNK_SIZE): ByteArray {+ val out = ByteArrayOutputStream()+ crypto.encrypt(ByteArrayInputStream(plaintext), out, password, chunkSize)+ return out.toByteArray()+ }++ private fun decrypt(encrypted: ByteArray): ByteArray {+ val out = ByteArrayOutputStream()+ crypto.decrypt(ByteArrayInputStream(encrypted), out, password)+ return out.toByteArray()+ }+}diff --git a/apps/mobile/android/app/src/test/java/com/Colota/backup/BackupRestorerTest.kt b/apps/mobile/android/app/src/test/java/com/Colota/backup/BackupRestorerTest.ktnew file mode 100644index 00000000..e7f40cc8--- /dev/null+++ b/apps/mobile/android/app/src/test/java/com/Colota/backup/BackupRestorerTest.kt@@ -0,0 +1,201 @@+/**+ * Copyright (C) 2026 Max Dietrich+ * Licensed under the GNU AGPLv3. See LICENSE in the project root for details.+ */++package com.Colota.backup++import android.content.ContentValues+import androidx.test.core.app.ApplicationProvider+import com.Colota.data.DatabaseHelper+import com.Colota.util.AppLogger+import com.Colota.util.SecureStorageHelper+import io.mockk.Runs+import io.mockk.every+import io.mockk.just+import io.mockk.mockk+import io.mockk.mockkObject+import io.mockk.slot+import io.mockk.unmockkObject+import io.mockk.verify+import org.junit.After+import org.junit.Assert.assertEquals+import org.junit.Assert.assertTrue+import org.junit.Assert.fail+import org.junit.Before+import org.junit.Test+import org.junit.runner.RunWith+import org.robolectric.RobolectricTestRunner+import java.io.ByteArrayInputStream+import java.io.ByteArrayOutputStream++@RunWith(RobolectricTestRunner::class)+class BackupRestorerTest {++ private lateinit var db: DatabaseHelper+ private lateinit var secureStorage: SecureStorageHelper+ private lateinit var builder: BackupBuilder+ private lateinit var restorer: BackupRestorer++ private val password = "correct horse battery staple".toCharArray()++ @Before+ fun setUp() {+ resetDbSingleton()+ mockkObject(AppLogger)+ every { AppLogger.d(any(), any()) } just Runs+ every { AppLogger.i(any(), any()) } just Runs+ every { AppLogger.w(any(), any()) } just Runs+ every { AppLogger.e(any(), any(), any()) } just Runs++ val context = ApplicationProvider.getApplicationContext<android.content.Context>()+ db = DatabaseHelper.getInstance(context)++ secureStorage = mockk(relaxed = true)+ every { secureStorage.exportPlaintextForBackup() } returns mapOf(+ "auth_type" to "bearer",+ "auth_bearer_token" to "secret-token-99",+ )++ builder = BackupBuilder(context, db, secureStorage)+ restorer = BackupRestorer(context, secureStorage)+ }++ @After+ fun tearDown() {+ DatabaseHelper.getInstance(+ ApplicationProvider.getApplicationContext<android.content.Context>()+ ).close()+ resetDbSingleton()+ unmockkObject(AppLogger)+ }++ @Test+ fun `round-trip restores rows seeded before backup`() {+ seedDatabase(latPrefix = 51.0)+ val backup = backupBytes()++ val context = ApplicationProvider.getApplicationContext<android.content.Context>()+ DatabaseHelper.getInstance(context).writableDatabase+ .delete(DatabaseHelper.TABLE_LOCATIONS, null, null)+ assertEquals(0, countLocations())++ restorer.restore(ByteArrayInputStream(backup), password)++ assertEquals(10, countLocations())+ assertEquals("dark", DatabaseHelper.getInstance(context).getSetting("themeMode"))+ }++ @Test+ fun `restore re-imports secrets via SecureStorageHelper`() {+ seedDatabase(latPrefix = 51.0)+ val backup = backupBytes()++ val captured = slot<Map<String, String>>()+ every { secureStorage.importPlaintextFromBackup(capture(captured)) } just Runs++ restorer.restore(ByteArrayInputStream(backup), password)++ verify { secureStorage.importPlaintextFromBackup(any()) }+ assertEquals("bearer", captured.captured["auth_type"])+ assertEquals("secret-token-99", captured.captured["auth_bearer_token"])+ }++ @Test+ fun `wrong password leaves live database untouched`() {+ seedDatabase(latPrefix = 51.0)+ val originalCount = countLocations()+ val backup = backupBytes()++ try {+ restorer.restore(ByteArrayInputStream(backup), "wrong".toCharArray())+ fail("Expected WRONG_PASSWORD")+ } catch (e: BackupException) {+ assertEquals(BackupError.WRONG_PASSWORD, e.error)+ }++ assertEquals(originalCount, countLocations())+ }++ @Test+ fun `bad magic is rejected before any DB swap`() {+ seedDatabase(latPrefix = 51.0)+ val originalCount = countLocations()+ val backup = backupBytes()+ backup[0] = 'X'.code.toByte()++ try {+ restorer.restore(ByteArrayInputStream(backup), password)+ fail("Expected BAD_MAGIC")+ } catch (e: BackupException) {+ assertEquals(BackupError.BAD_MAGIC, e.error)+ }++ assertEquals(originalCount, countLocations())+ }++ @Test+ fun `restore_temp is cleaned up on success`() {+ seedDatabase(latPrefix = 51.0)+ val backup = backupBytes()++ restorer.restore(ByteArrayInputStream(backup), password)++ val context = ApplicationProvider.getApplicationContext<android.content.Context>()+ val workDir = java.io.File(context.cacheDir, "restore_temp")+ assertTrue("workDir must be removed after restore", !workDir.exists())+ }++ @Test+ fun `restore_temp is cleaned up on wrong password`() {+ seedDatabase(latPrefix = 51.0)+ val backup = backupBytes()++ try {+ restorer.restore(ByteArrayInputStream(backup), "wrong".toCharArray())+ } catch (_: BackupException) {+ // expected+ }++ val context = ApplicationProvider.getApplicationContext<android.content.Context>()+ val workDir = java.io.File(context.cacheDir, "restore_temp")+ assertTrue("workDir must be removed even on failure", !workDir.exists())+ }++ private fun seedDatabase(latPrefix: Double) {+ val sqlite = db.writableDatabase+ for (i in 0..9) {+ val values = ContentValues().apply {+ put("latitude", latPrefix + i * 0.001)+ put("longitude", 13.4 + i * 0.001)+ put("accuracy", 5)+ put("timestamp", System.currentTimeMillis() / 1000 + i)+ put("created_at", System.currentTimeMillis())+ put("sent", 0)+ }+ val id = sqlite.insert(DatabaseHelper.TABLE_LOCATIONS, null, values)+ check(id != -1L) { "seed insert failed at row $i" }+ }+ db.saveSetting("themeMode", "dark")+ }++ private fun backupBytes(): ByteArray {+ return ByteArrayOutputStream().apply {+ builder.build(this, password)+ }.toByteArray()+ }++ private fun countLocations(): Int {+ val context = ApplicationProvider.getApplicationContext<android.content.Context>()+ return DatabaseHelper.getInstance(context).writableDatabase+ .rawQuery("SELECT COUNT(*) FROM ${DatabaseHelper.TABLE_LOCATIONS}", null).use {+ if (it.moveToFirst()) it.getInt(0) else 0+ }+ }++ private fun resetDbSingleton() {+ val field = DatabaseHelper::class.java.getDeclaredField("INSTANCE")+ field.isAccessible = true+ field.set(null, null)+ }+}diff --git a/apps/mobile/android/app/src/test/java/com/Colota/bridge/LocationServiceModuleTest.kt b/apps/mobile/android/app/src/test/java/com/Colota/bridge/LocationServiceModuleTest.ktindex 6d12c027..67507fbe 100644--- a/apps/mobile/android/app/src/test/java/com/Colota/bridge/LocationServiceModuleTest.kt+++ b/apps/mobile/android/app/src/test/java/com/Colota/bridge/LocationServiceModuleTest.kt@@ -53,6 +53,8 @@ class LocationServiceModuleTest {mockkStatic(Arguments::class)every { Arguments.createMap() } returns JavaOnlyMap()+ mockkObject(DatabaseHelper.Companion)+setCompanionField("reactContextRef", WeakReference(mockContext))setCompanionField("isAppInForeground", true)setCompanionField("activeProfileName", null)@@ -62,6 +64,7 @@ class LocationServiceModuleTest {fun tearDown() {unmockkObject(AppLogger)unmockkStatic(Arguments::class)+ unmockkObject(DatabaseHelper.Companion)setCompanionField("reactContextRef", WeakReference<ReactApplicationContext>(null))setCompanionField("isAppInForeground", true)setCompanionField("activeProfileName", null)@@ -494,7 +497,9 @@ class LocationServiceModuleTest {val raw = createModule()val module = spyk(raw, recordPrivateCalls = true)val dbHelper = mockk<DatabaseHelper>(relaxed = true)- setField(module, "dbHelper", dbHelper)+ // Unsafe-allocated module skipped construction; supply the context the dbHelper getter reads.+ setSuperField(module, "mReactApplicationContext", mockContext)+ every { DatabaseHelper.getInstance(any()) } returns dbHelper// Stub private method to avoid real Android service startevery { module["startServiceWithAction"](any<String>()) } returns Unitreturn Pair(module, dbHelper)@@ -532,6 +537,21 @@ class LocationServiceModuleTest {field.set(obj, value)}+ private fun setSuperField(obj: Any, name: String, value: Any?) {+ var clazz: Class<*>? = obj.javaClass+ while (clazz != null) {+ try {+ val field = clazz.getDeclaredField(name)+ field.isAccessible = true+ field.set(obj, value)+ return+ } catch (_: NoSuchFieldException) {+ clazz = clazz.superclass+ }+ }+ throw NoSuchFieldException(name)+ }+private fun getField(obj: Any, name: String): Any? {val field = obj.javaClass.getDeclaredField(name)field.isAccessible = truediff --git a/apps/mobile/src/screens/BackupRestoreScreen.tsx b/apps/mobile/src/screens/BackupRestoreScreen.tsxnew file mode 100644index 00000000..97e14275--- /dev/null+++ b/apps/mobile/src/screens/BackupRestoreScreen.tsx@@ -0,0 +1,472 @@+/**+ * Copyright (C) 2026 Max Dietrich+ * Licensed under the GNU AGPLv3. See LICENSE in the project root for details.+ */++import React, { useEffect, useState } from "react"+import { Modal, ScrollView, View, Text, TextInput, Pressable, StyleSheet } from "react-native"+import { Eye, EyeOff } from "lucide-react-native"+import type { RootScreenProps } from "../types/navigation"+import { useTheme } from "../hooks/useTheme"+import { Button, Card, Container, SectionTitle } from "../components"+import BackupService, {+ MIN_BACKUP_PASSWORD_LENGTH,+ MIN_BACKUP_PASSWORD_BITS,+ type PasswordStrengthResult+} from "../services/BackupService"+import { showAlert, showConfirm, showChoice } from "../services/modalService"+import { logger } from "../utils/logger"+import { fonts } from "../styles/typography"+import { fontSizes } from "@colota/shared"+import type { ThemeColors } from "../types/global"++type Props = RootScreenProps<"Backup & Restore">++const SEGMENT_COUNT = 4++function strengthColor(score: number, colors: ThemeColors): string {+ if (score <= 1) return colors.error+ if (score === 2) return colors.warning+ return colors.success+}++function restoreErrorMessage(e: unknown): string {+ const code = (e as { code?: string }).code+ switch (code) {+ case "E_BACKUP_WRONG_PASSWORD":+ return "Incorrect password, or the backup file is corrupted near the start."+ case "E_BACKUP_BAD_MAGIC":+ return "This file is not a Colota backup."+ case "E_BACKUP_UNSUPPORTED_SCHEMA":+ return "This backup was made with a newer version of Colota. Update the app first."+ case "E_BACKUP_UNSUPPORTED_VERSION":+ case "E_BACKUP_UNSUPPORTED_KDF":+ return "This backup was made with a different version of Colota."+ case "E_BACKUP_INTEGRITY_FAIL":+ return "The backup file is corrupted."+ case "E_BACKUP_TRUNCATED":+ return "The backup file is incomplete."+ case "E_BACKUP_TAMPERED":+ return "The backup file has been modified or is corrupted."+ case "E_BACKUP_MISSING_ENTRY":+ return "The backup file is missing required data."+ case "E_BACKUP_SECRETS_PARTIAL":+ return "Your data was restored, but stored credentials could not be applied. Re-enter them in Connection settings."+ case "E_BUSY":+ return "Another backup or restore is already in progress."+ default:+ return e instanceof Error ? e.message : "Unknown error"+ }+}++type PasswordFieldProps = {+ value: string+ onChangeText: (v: string) => void+ placeholder: string+ visible: boolean+ onToggleVisibility: () => void+ editable: boolean+ colors: ThemeColors+}++function PasswordField({+ value,+ onChangeText,+ placeholder,+ visible,+ onToggleVisibility,+ editable,+ colors+}: PasswordFieldProps) {+ const Icon = visible ? EyeOff : Eye+ return (+ <View style={[styles.inputRow, { borderColor: colors.border, backgroundColor: colors.background }]}>+ <TextInput+ style={[styles.inputField, { color: colors.text }]}+ value={value}+ onChangeText={onChangeText}+ placeholder={placeholder}+ placeholderTextColor={colors.placeholder}+ autoCapitalize="none"+ autoCorrect={false}+ secureTextEntry={!visible}+ editable={editable}+ />+ <Pressable+ onPress={onToggleVisibility}+ hitSlop={8}+ style={styles.eyeButton}+ accessibilityLabel={visible ? "Hide password" : "Show password"}+ >+ <Icon size={20} color={colors.textSecondary} />+ </Pressable>+ </View>+ )+}++function PasswordPromptModal({+ visible,+ filename,+ busy,+ onSubmit,+ onCancel,+ colors+}: {+ visible: boolean+ filename: string+ busy: boolean+ onSubmit: (password: string) => void+ onCancel: () => void+ colors: ThemeColors+}) {+ const [pw, setPw] = useState("")+ const [show, setShow] = useState(false)++ useEffect(() => {+ if (!visible) {+ setPw("")+ setShow(false)+ }+ }, [visible])++ return (+ <Modal+ transparent+ visible={visible}+ animationType="fade"+ statusBarTranslucent+ onRequestClose={busy ? undefined : onCancel}+ >+ <View style={[styles.modalOverlay, { backgroundColor: colors.overlay }]}>+ <View style={[styles.modalCard, { backgroundColor: colors.card, borderColor: colors.border }]}>+ <Text style={[styles.modalTitle, { color: colors.text }]}>Enter password</Text>+ <Text style={[styles.modalSubtitle, { color: colors.textSecondary }]} numberOfLines={1}>+ For {filename}+ </Text>+ <PasswordField+ value={pw}+ onChangeText={setPw}+ placeholder="Backup password"+ visible={show}+ onToggleVisibility={() => setShow((v) => !v)}+ editable={!busy}+ colors={colors}+ />+ <View style={styles.modalButtonsRow}>+ <View style={styles.modalButton}>+ <Button title="Cancel" onPress={onCancel} disabled={busy} variant="secondary" />+ </View>+ <View style={styles.modalButton}>+ <Button+ title={busy ? "Restoring..." : "Restore"}+ onPress={() => pw && onSubmit(pw)}+ disabled={!pw || busy}+ loading={busy}+ variant="danger"+ />+ </View>+ </View>+ </View>+ </View>+ </Modal>+ )+}++export function BackupRestoreScreen({}: Props) {+ const { colors } = useTheme()++ const [backupPassword, setBackupPassword] = useState("")+ const [confirmPassword, setConfirmPassword] = useState("")+ const [showBackupPassword, setShowBackupPassword] = useState(false)+ const [showConfirmPassword, setShowConfirmPassword] = useState(false)+ const [busy, setBusy] = useState<"backup" | "restore" | null>(null)+ const [pendingRestore, setPendingRestore] = useState<{ uri: string; filename: string } | null>(null)++ const [strength, setStrength] = useState<PasswordStrengthResult>({ score: 0, label: "", bits: 0 })+ useEffect(() => {+ let cancelled = false+ BackupService.passwordStrength(backupPassword)+ .then((result) => {+ if (!cancelled) setStrength(result)+ })+ .catch((err) => {+ if (!cancelled) logger.warn("[BackupRestoreScreen] passwordStrength failed", err)+ })+ return () => {+ cancelled = true+ }+ }, [backupPassword])+ const passwordAcceptable = strength.bits >= MIN_BACKUP_PASSWORD_BITS+ const passwordsMatch = backupPassword === confirmPassword+ const showMismatch = confirmPassword.length > 0 && !passwordsMatch+ const canSubmitBackup = passwordAcceptable && passwordsMatch && backupPassword.length > 0++ const onCreateBackup = async () => {+ if (!canSubmitBackup) {+ showAlert("Password not ready", "Both passwords must match. Use a longer or more random password.", "warning")+ return+ }++ const acknowledged = await showConfirm({+ title: "No password recovery",+ message: "If you forget this password, the backup cannot be opened. Store it somewhere safe before continuing.",+ confirmText: "I understand",+ cancelText: "Cancel",+ destructive: true+ })+ if (!acknowledged) return++ const uri = await BackupService.pickBackupDestination()+ if (!uri) return++ setBusy("backup")+ try {+ await BackupService.createBackup(uri, backupPassword)+ setBackupPassword("")+ setConfirmPassword("")+ setShowBackupPassword(false)+ setShowConfirmPassword(false)+ showAlert("Backup created", "Your encrypted backup has been written.", "success")+ } catch (e: unknown) {+ logger.error("[BackupRestoreScreen] backup failed", e)+ const message = e instanceof Error ? e.message : "Unknown error"+ showAlert("Backup failed", message, "error")+ } finally {+ setBusy(null)+ }+ }++ const onChooseBackupFile = async () => {+ const source = await BackupService.pickBackupSource()+ if (!source) return+ setPendingRestore({+ uri: source.uri,+ filename: source.displayName ?? "the selected backup"+ })+ }++ const onRestorePasswordCancel = () => {+ if (busy === "restore") return+ setPendingRestore(null)+ }++ const onRestorePasswordSubmit = async (password: string) => {+ if (!pendingRestore) return+ const { uri } = pendingRestore++ const acknowledged = await showConfirm({+ title: "Replace all data?",+ message: "Restoring will overwrite your current locations, settings and credentials. This cannot be undone.",+ confirmText: "Replace",+ cancelText: "Cancel",+ destructive: true+ })+ if (!acknowledged) return++ setBusy("restore")+ try {+ await BackupService.restoreBackup(uri, password)+ setPendingRestore(null)+ // Block on dismissal; applyRestore reloads the bridge and would wipe an unawaited alert.+ await showChoice({+ title: "Restore complete",+ message: "Your data has been restored. Tracking has been paused; re-enable it from the home screen.",+ variant: "success",+ buttons: [{ text: "Restart app", style: "primary" }]+ })+ await BackupService.applyRestore()+ } catch (e: unknown) {+ logger.error("[BackupRestoreScreen] restore failed", e)+ showAlert("Restore failed", restoreErrorMessage(e), "error")+ setPendingRestore(null)+ } finally {+ setBusy(null)+ }+ }++ const meterColor = strengthColor(strength.score, colors)++ return (+ <Container>+ <ScrollView contentContainerStyle={styles.scrollContent} showsVerticalScrollIndicator={false}>+ <View style={styles.section}>+ <SectionTitle>Encrypted Backup</SectionTitle>+ <Card>+ <Text style={[styles.intro, { color: colors.textSecondary }]}>+ Bundle your locations, settings and credentials into a single encrypted file you can store anywhere.+ </Text>++ <Text style={[styles.fieldLabel, { color: colors.text }]}>Password</Text>+ <PasswordField+ value={backupPassword}+ onChangeText={setBackupPassword}+ placeholder={`At least ${MIN_BACKUP_PASSWORD_LENGTH} characters`}+ visible={showBackupPassword}+ onToggleVisibility={() => setShowBackupPassword((v) => !v)}+ editable={busy === null}+ colors={colors}+ />+ {backupPassword.length > 0 && (+ <View style={styles.strengthRow}>+ <View style={styles.strengthBar}>+ {Array.from({ length: SEGMENT_COUNT }).map((_, i) => (+ <View+ key={i}+ style={[+ styles.strengthSegment,+ {+ backgroundColor: i < strength.score ? meterColor : colors.borderLight+ }+ ]}+ />+ ))}+ </View>+ <Text style={[styles.strengthLabel, { color: meterColor }]}>{strength.label}</Text>+ </View>+ )}++ <Text style={[styles.fieldLabel, { color: colors.text }]}>Confirm password</Text>+ <PasswordField+ value={confirmPassword}+ onChangeText={setConfirmPassword}+ placeholder="Re-enter the same password"+ visible={showConfirmPassword}+ onToggleVisibility={() => setShowConfirmPassword((v) => !v)}+ editable={busy === null}+ colors={colors}+ />+ {showMismatch && <Text style={[styles.errorText, { color: colors.error }]}>Passwords do not match.</Text>}++ <Text style={[styles.hint, { color: colors.textSecondary }]}>+ A random password from a password manager or a long passphrase is safest. Common words and phrases are+ easy to crack. There is no recovery if forgotten.+ </Text>+ <Button+ title={busy === "backup" ? "Creating backup..." : "Create backup"}+ onPress={onCreateBackup}+ disabled={busy !== null || !canSubmitBackup}+ loading={busy === "backup"}+ />+ </Card>+ </View>++ <View style={styles.section}>+ <SectionTitle>Restore from Backup</SectionTitle>+ <Card>+ <Text style={[styles.intro, { color: colors.textSecondary }]}>+ Replace all current data with a previous .colota backup file. You'll be asked for the backup password+ after choosing the file.+ </Text>+ <Button title="Choose backup file" onPress={onChooseBackupFile} disabled={busy !== null} variant="danger" />+ </Card>+ </View>+ </ScrollView>+ <PasswordPromptModal+ visible={pendingRestore !== null}+ filename={pendingRestore?.filename ?? ""}+ busy={busy === "restore"}+ onSubmit={onRestorePasswordSubmit}+ onCancel={onRestorePasswordCancel}+ colors={colors}+ />+ </Container>+ )+}++const styles = StyleSheet.create({+ scrollContent: {+ paddingHorizontal: 16,+ paddingBottom: 40+ },+ section: {+ marginTop: 24+ },+ intro: {+ marginBottom: 12,+ fontSize: 14,+ lineHeight: 20+ },+ fieldLabel: {+ fontSize: 14,+ fontWeight: "500",+ marginBottom: 8+ },+ inputRow: {+ flexDirection: "row",+ alignItems: "center",+ borderWidth: 1,+ borderRadius: 8,+ marginBottom: 8+ },+ inputField: {+ flex: 1,+ paddingHorizontal: 12,+ paddingVertical: 12,+ fontSize: 16+ },+ eyeButton: {+ paddingHorizontal: 12,+ paddingVertical: 12+ },+ strengthRow: {+ flexDirection: "row",+ alignItems: "center",+ marginBottom: 12,+ gap: 8+ },+ strengthBar: {+ flex: 1,+ flexDirection: "row",+ gap: 4+ },+ strengthSegment: {+ flex: 1,+ height: 4,+ borderRadius: 2+ },+ strengthLabel: {+ fontSize: 12,+ fontWeight: "600",+ minWidth: 60,+ textAlign: "right"+ },+ errorText: {+ fontSize: 12,+ marginTop: -4,+ marginBottom: 8+ },+ hint: {+ fontSize: 12,+ lineHeight: 18,+ marginTop: 8,+ marginBottom: 16+ },+ modalOverlay: {+ flex: 1,+ justifyContent: "center",+ paddingHorizontal: 16+ },+ modalCard: {+ padding: 16,+ borderRadius: 12,+ borderWidth: 1+ },+ modalTitle: {+ fontSize: fontSizes.label,+ ...fonts.semiBold,+ marginBottom: 4+ },+ modalSubtitle: {+ fontSize: fontSizes.description,+ ...fonts.regular,+ marginBottom: 16+ },+ modalButtonsRow: {+ flexDirection: "row",+ gap: 12,+ marginTop: 4+ },+ modalButton: {+ flex: 1+ }+})diff --git a/apps/mobile/src/screens/SettingsScreen.tsx b/apps/mobile/src/screens/SettingsScreen.tsxindex e09e2753..030a9c50 100644--- a/apps/mobile/src/screens/SettingsScreen.tsx+++ b/apps/mobile/src/screens/SettingsScreen.tsx@@ -22,6 +22,7 @@ import {Download,Map,ScrollText,+ ShieldCheck,Info,Heart,Clock@@ -198,6 +199,14 @@ export function SettingsScreen({ navigation }: Props) {onPress={() => navigation.navigate("Offline Maps")}/><Divider />+ <ListItem+ testID="nav-backup-restore"+ icon={ShieldCheck}+ label="Backup & Restore"+ sub="Encrypted backup of all your data"+ onPress={() => navigation.navigate("Backup & Restore")}+ />+ <Divider /><ListItemtestID="nav-activity-log"icon={ScrollText}diff --git a/apps/mobile/src/screens/index.ts b/apps/mobile/src/screens/index.tsindex 76b8e53b..614d6180 100644--- a/apps/mobile/src/screens/index.ts+++ b/apps/mobile/src/screens/index.ts@@ -25,3 +25,4 @@ export { TrackingSyncScreen } from "./TrackingSyncScreen"export { SetupImportScreen } from "./SetupImportScreen"export { TripDetailScreen } from "./TripDetailScreen"export { OfflineMapsScreen } from "./OfflineMapsScreen"+export { BackupRestoreScreen } from "./BackupRestoreScreen"diff --git a/apps/mobile/src/services/BackupService.ts b/apps/mobile/src/services/BackupService.tsnew file mode 100644index 00000000..ff44402c--- /dev/null+++ b/apps/mobile/src/services/BackupService.ts@@ -0,0 +1,88 @@+/**+ * Copyright (C) 2026 Max Dietrich+ * Licensed under the GNU AGPLv3. See LICENSE in the project root for details.+ */++import { NativeModules } from "react-native"++const { BackupServiceModule } = NativeModules++export const MIN_BACKUP_PASSWORD_LENGTH = 12+export const MIN_BACKUP_PASSWORD_BITS = 50++type PasswordStrengthScore = 0 | 1 | 2 | 3 | 4++export type PasswordStrengthResult = {+ score: PasswordStrengthScore+ label: string+ bits: number+}++export type BackupSource = {+ uri: string+ displayName: string | null+}++function passwordToCodes(password: string): number[] {+ const codes = new Array<number>(password.length)+ for (let i = 0; i < password.length; i++) codes[i] = password.charCodeAt(i)+ return codes+}++class BackupService {+ private static ensureModule(): void {+ if (!BackupServiceModule) {+ throw new Error("[BackupService] BackupServiceModule not available. Check native linking.")+ }+ }++ static async passwordStrength(password: string): Promise<PasswordStrengthResult> {+ BackupService.ensureModule()+ const codes = passwordToCodes(password)+ try {+ return await BackupServiceModule.passwordStrength(codes)+ } finally {+ codes.fill(0)+ }+ }++ static async pickBackupDestination(): Promise<string | null> {+ BackupService.ensureModule()+ return BackupServiceModule.pickBackupDestination()+ }++ static async pickBackupSource(): Promise<BackupSource | null> {+ BackupService.ensureModule()+ return BackupServiceModule.pickBackupSource()+ }++ // Pass as UTF-16 code units so the Kotlin side never builds a non-wipeable String.+ // The JS string is still uncleanable; this only narrows the native-heap lifetime.+ static async createBackup(uri: string, password: string): Promise<void> {+ BackupService.ensureModule()+ const codes = passwordToCodes(password)+ try {+ await BackupServiceModule.createBackup(uri, codes)+ } finally {+ codes.fill(0)+ }+ }++ static async restoreBackup(uri: string, password: string): Promise<void> {+ BackupService.ensureModule()+ const codes = passwordToCodes(password)+ try {+ await BackupServiceModule.restoreBackup(uri, codes)+ } finally {+ codes.fill(0)+ }+ }++ // RN reload so all modules re-read state from the restored DB.+ static async applyRestore(): Promise<void> {+ BackupService.ensureModule()+ await BackupServiceModule.applyRestore()+ }+}++export default BackupServicediff --git a/apps/mobile/src/types/navigation.ts b/apps/mobile/src/types/navigation.tsindex 214a1d6b..de51006e 100644--- a/apps/mobile/src/types/navigation.ts+++ b/apps/mobile/src/types/navigation.ts@@ -31,6 +31,7 @@ export type RootStackParamList = {"Trip Detail": { trip: Trip }"Offline Maps": undefined"Activity Log": undefined+ "Backup & Restore": undefined}export type RootStackRoute = keyof RootStackParamListdiff --git a/fastlane/metadata/android/en-US/changelogs/38.txt b/fastlane/metadata/android/en-US/changelogs/38.txtindex d2e0f791..7b2738a0 100644--- a/fastlane/metadata/android/en-US/changelogs/38.txt+++ b/fastlane/metadata/android/en-US/changelogs/38.txt@@ -1,3 +1,4 @@+- Encrypted backup and restore: bundle your locations, settings and credentials into a single password-encrypted .colota file you can store anywhere. Restore on the same device or migrate to a new one. There is no password recovery, so use one you won't forget.- mTLS client certificate support: configure a client certificate in the new mTLS Settings screen, either by picking one already installed on the device (key stays in the OS keystore) or by importing a .p12 / .pfx file. Required if your server enforces mutual TLS.- Self-signed / private CA support: import a Trusted Server CA in the same screen for self-hosted servers without publicly-trusted certificates.- Stricter TLS trust (breaking): user-installed CAs from Android Settings -> Encryption & credentials are no longer trusted by Colota. If you relied on one, re-import via the new mTLS Settings screen.diff --git a/fastlane/metadata/android/en-US/full_description.txt b/fastlane/metadata/android/en-US/full_description.txtindex 634b845c..9d4f5dc4 100644--- a/fastlane/metadata/android/en-US/full_description.txt+++ b/fastlane/metadata/android/en-US/full_description.txt@@ -16,7 +16,7 @@ Colota is an open-source GPS tracking app that sends your location to your own s<li><b>Display Settings</b> - Metric or imperial units, 12h or 24h time format. Auto-detected from device locale on first use</li><li><b>App Shortcuts</b> - Long-press the app icon to start or stop tracking directly from the home screen. Compatible with automation apps like Tasker and Samsung Routines</li><li><b>Quick Setup</b> - Configure devices via colota://setup deep links or QR codes</li>-<li><b>Authentication</b> - Basic Auth, Bearer Token or custom headers with AES-256-GCM encryption</li>+<li><b>Authentication</b> - Basic Auth, Bearer Token or custom headers</li><li><b>Dark Mode</b> - Full light and dark theme support</li></ul>