Colota - Android GPS Location tracker
feat: mTLS client certificate support
Max Dietrichc0f15145852b
diff --git a/README.md b/README.mdindex 58e17542..0f20019d 100644--- a/README.md+++ b/README.md@@ -27,7 +27,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.+- **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.- **Dark Mode** - Full light and dark theme support.## Screenshotsdiff --git a/apps/docs/docs/configuration/authentication.md b/apps/docs/docs/configuration/authentication.mdindex c9c1a0ff..a832678f 100644--- a/apps/docs/docs/configuration/authentication.md+++ b/apps/docs/docs/configuration/authentication.md@@ -12,16 +12,21 @@ Colota supports multiple authentication methods, configurable in **Settings > Au## Methods-| Method | Description | Header Sent |-| ------------------ | --------------------------- | ------------------------------- |-| **None** | No authentication (default) | -- |-| **Basic Auth** | Username + password | `Authorization: Basic <base64>` |-| **Bearer Token** | API token / JWT | `Authorization: Bearer <token>` |-| **Custom Headers** | Any key-value pairs | As configured |+| Method | Description | Sent at |+| ---------------------- | ----------------------------------- | ------------------------------- |+| **None** | No authentication (default) | -- |+| **Basic Auth** | Username + password | `Authorization: Basic <base64>` |+| **Bearer Token** | API token / JWT | `Authorization: Bearer <token>` |+| **Custom Headers** | Any key-value pairs | HTTP header |+| **Client Certificate** | PKCS12 (.p12 / .pfx) for mutual TLS | TLS handshake (mTLS) |++mTLS is orthogonal to the HTTP-level methods and can be combined with any of them - a common setup is mTLS at the reverse-proxy layer + Bearer at the application layer. See [mTLS](./mtls) for the dedicated guide.## Credential Storage-All credentials are stored encrypted on-device using Android's `EncryptedSharedPreferences`. Credentials never leave the device except as HTTP headers sent to your configured endpoint.+HTTP credentials (Basic Auth, Bearer tokens, custom headers, imported server CAs) are stored encrypted on-device using Android's `EncryptedSharedPreferences`. Credentials never leave the device except as HTTP headers sent to your configured endpoint.++Client certificate private keys are stored in the OS keystore, kept separate from other app credentials. The PKCS12 password you enter is used once during import and is not saved.## Custom HTTP Headersdiff --git a/apps/docs/docs/configuration/mtls.md b/apps/docs/docs/configuration/mtls.mdnew file mode 100644index 00000000..24fb0f71--- /dev/null+++ b/apps/docs/docs/configuration/mtls.md@@ -0,0 +1,91 @@+---+sidebar_position: 6+---++# Mutual TLS (mTLS)++Authenticate to your server with a client certificate at the TLS handshake, in addition to (or instead of) HTTP-level auth like Bearer or Basic. Useful when your reverse proxy enforces mTLS (e.g. nginx `ssl_verify_client`, Traefik, Cloudflare Access). If your server just needs a Bearer token or Basic Auth, you don't need this.++Configure in **Settings -> Connection -> Authentication & Headers -> Client Certificate (mTLS)**.++## Setup++There are two ways to provide a client certificate. Pick whichever matches your starting point.++### Option A: pick from device certificates (recommended)++If your cert is already installed in Android's KeyChain (via Android Settings -> Encryption & credentials), this is the cleanest path:++1. Open Colota -> Settings -> Connection -> Authentication & Headers -> **Client Certificate (mTLS)**+2. Tap **Pick from device certificates**+3. Android's system dialog appears. Select your cert.+4. The screen now shows the cert's subject, issuer, and expiry date.++Colota only remembers which cert you picked - the cert itself stays where it already was on the phone.++### Option B: import a `.p12` file++If you have a PKCS12 file but the cert isn't installed at the OS level:++1. Move the `.p12` to your phone (any reasonably-secure transport works - syncthing, USB, etc.)+2. Open Colota -> Settings -> Connection -> Authentication & Headers -> **Client Certificate (mTLS)**+3. Tap **Import .p12 / .pfx**+4. Pick the file, enter the password (leave blank if none), tap **Save**+5. The screen now shows the cert's subject, issuer, and expiry date++The next sync request will use this certificate automatically.++The new cert takes effect on the next request - no app restart needed. Same goes if you switch between Option A and Option B later. Colota does not accept PEM client cert + PEM key as two separate files; bundle them into a `.p12` first, or install via Android Settings and use the KeyChain picker. Hostname verification is always on - the server's certificate must match the hostname or IP you connect to.++## Trust model++Colota's HTTPS trust anchors:++1. **System CAs** that ship with Android (Let's Encrypt, DigiCert, ISRG, Google Trust Services, etc.). Always applied.+2. **In-app imported CA** added through the Trusted Server CA section. One slot, trusted only by Colota.++Either anchor accepting the server's chain is enough - the two layers are additive.++User-installed device CAs (from Android Settings -> Encryption & credentials) are **not** honored, so malware or a coerced profile that plants a CA in the device store can't intercept Colota's sync.++### Trusting a private/internal server CA++If your server uses a publicly-trusted certificate (e.g. Let's Encrypt), there's nothing to do here. Otherwise:++- **Import in-app** - mTLS Settings -> **Trusted Server CA** -> Import CA (.crt / .pem). Trust is scoped to Colota; other apps on the phone are unaffected.+- **Or switch to a publicly-trusted cert** - Let's Encrypt is free and works for any public DNS name your server can prove ownership of.++## Testing the setup++In **Connection Settings**, set your endpoint to your `https://...` URL and tap **Test Connection**. Expected: `Connection successful` within a couple of seconds. Failure paths are distinguishable:++| Message | Likely cause | Fix |+| --- | --- | --- |+| `Server certificate is not trusted (self-signed or unknown CA)` | Your server's cert is signed by a CA Colota doesn't trust | Import the CA via mTLS Settings -> Trusted Server CA, or use a publicly-trusted cert |+| `Server requires a client certificate (mTLS) but none is configured` | Server demanded mTLS, Colota didn't send one | Import a `.p12` in the Client Certificate section |+| `Server rejected the client certificate` | Cert reached the server but was rejected | Wrong CA, expired cert, or revoked - check what your reverse proxy expects |+| `Incorrect password for client certificate` | The provided password doesn't unlock the `.p12` | Re-import with the correct password |+| `Hostname not verified` | Server cert is valid but doesn't list the hostname/IP you connected to | Reissue the server cert with a SAN that includes your hostname/IP |++## Lifecycle++### Where the cert lives++Once imported, the cert lives in the OS keystore - not in the app's regular settings, not on the filesystem in plain form and not in any backup.++What this means in practice:++- You don't need to remember the PKCS12 password. It's used during import and then discarded.+- If you picked a cert from the device certificates list, it survives an app reinstall.+- If you imported a `.p12`, uninstalling Colota removes it - re-import after reinstall.+- The Trusted Server CA is a public certificate, so it stays alongside the app's other settings.++### Renewing++Colota shows a warning in mTLS Settings 14 days before `notAfter`. To renew, generate a new `.p12` and tap **Import .p12 / .pfx** again - the new cert replaces the old one, no need to remove first.++If a cert expires before you renew it, sync will fail with `Server rejected the client certificate`. Locations stay queued locally, nothing is lost, until you import a fresh cert.++### Removing++mTLS Settings -> Client Certificate section -> **Remove Certificate**. Same for Trusted Server CA -> **Remove CA**. The next sync request runs without mTLS.diff --git a/apps/docs/docs/configuration/server-settings.md b/apps/docs/docs/configuration/server-settings.mdindex 3ca47554..6033bb51 100644--- a/apps/docs/docs/configuration/server-settings.md+++ b/apps/docs/docs/configuration/server-settings.md@@ -15,7 +15,7 @@ sidebar_position: 3Your server endpoint must accept HTTP or HTTPS requests (POST or GET depending on your HTTP Method setting). HTTPS is required for public endpoints. HTTP is restricted to private/local addresses at the network level - public HTTP endpoints will be blocked at request time.-Self-signed certificates are supported - install your CA certificate on the device via Settings → Security → Encryption & credentials → Install a certificate.+Self-signed and private-CA certificates are supported via three trust paths (system CAs, user-installed device CAs, or an in-app imported CA). Servers that require client-certificate authentication (mTLS) are also supported. See the [mTLS guide](./mtls) for setup.On **Android 17+**, connecting to another device on the local network (everything above except `localhost`) requires the **ACCESS_LOCAL_NETWORK** permission. Colota requests this when you use **Test Connection**. See [Permissions](/docs/development/permissions#local-network-access) for details.diff --git a/apps/docs/docs/development/architecture.md b/apps/docs/docs/development/architecture.mdindex 43c6b85d..f4a56189 100644--- a/apps/docs/docs/development/architecture.md+++ b/apps/docs/docs/development/architecture.md@@ -131,6 +131,20 @@ Orchestrates batch location uploads with:HTTP client. Validates endpoints, enforces HTTPS for public hosts, injects auth headers, caches connectivity checks, and detects unmetered connections, specific SSIDs and VPN status for sync condition filtering.+For mTLS-protected endpoints, builds the `HttpsURLConnection` with a custom `SSLSocketFactory` supplied by `ClientCertSslContextProvider` (per-instance, never `setDefaultSSLSocketFactory()` - the override is scoped to outbound location sync, not the whole process).++### ClientCertSslContextProvider++Builds the cached `SSLSocketFactory` used for mTLS. The key managers are supplied by `DynamicKeyManager` so the cert source can be swapped without rebuilding the SSL context; trust managers come from a `CompositeX509TrustManager` that layers an optional user-imported CA on top of Android's system roots. Includes a lazy migration: legacy PKCS12 + password material in `EncryptedSharedPreferences` (if any) is unwrapped into Android Keystore the first time the provider builds a factory or the Settings UI calls `runMigrationIfNeeded`. Legacy storage is wiped only on permanent failures (bad blob, wrong password, PKCS12-shape errors); transient failures (AndroidKeyStore unavailable, OOM) leave legacy data so the next request can retry.++### DynamicKeyManager++`X509KeyManager` that resolves the active client cert at TLS handshake time from one of two sources: an alias stored in Android's system **KeyChain** (private key stays in the OS / hardware, app never sees the bytes) or a `.p12`-imported entry in **Android Keystore** (key sealed under the app's UID, hardware-backed where available). The resolved alias is cached and invalidated alongside the `SSLSocketFactory` cache, so cert swaps take effect on the next request without an app restart.++### CompositeX509TrustManager++`X509TrustManager` that accepts a server chain if **any** delegate accepts it. Used to layer a user-imported private CA on top of the system trust store without losing system CA validation - additive trust, not pinning.+### GeofenceHelperManages pause zones using the **haversine formula** for distance calculations. Reads geofences directly from SQLite on each lookup.@@ -163,7 +177,7 @@ Centralized constants for condition type strings (`charging`, `android_auto`, `s### SecureStorageHelper-Wraps Android's `EncryptedSharedPreferences` for encrypted credential storage (AES-256-GCM for values, AES-256-SIV for keys). Stores Basic Auth passwords, Bearer tokens, and custom headers.+Wraps 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`.### Other Modules@@ -197,7 +211,8 @@ Wraps Android's `EncryptedSharedPreferences` for encrypted credential storage (A| `TrackingSyncScreen` | GPS interval, distance filter, accuracy threshold and sync strategy preset || `AppearanceScreen` | Light/dark theme, unit system, time format and custom map tile URLs (light and dark) || `ApiSettingsScreen` | Endpoint URL, HTTP method, field mapping with backend templates |-| `AuthSettingsScreen` | Authentication method (None, Basic Auth, Bearer Token) and custom HTTP headers |+| `AuthSettingsScreen` | Authentication method (None, Basic Auth, Bearer Token) and custom HTTP headers, with a link row to mTLS Settings |+| `MtlsSettingsScreen` | Client certificate (PKCS12 import + Android Keystore storage) and Trusted Server CA management || `GeofenceScreen` | Create, edit, and delete pause zones on an interactive map || `GeofenceEditorScreen` | Configure a zone: name, radius, record pause, WiFi pause, motionless pause and timeout, stationary heartbeat || `TrackingProfilesScreen` | List and manage condition-based tracking profiles |diff --git a/apps/docs/docs/faq.md b/apps/docs/docs/faq.mdindex 1f3e1507..4de951d1 100644--- a/apps/docs/docs/faq.md+++ b/apps/docs/docs/faq.md@@ -76,3 +76,13 @@ Colota requires Android 8.0 (API 26) or higher.### Why does Colota ask for "Local network access" permission?On Android 17+, apps need the Local Network Access permission to connect to local network addresses. Colota only requests this when your server is on a private/local IP (e.g. `192.168.x.x`). It is not used for device scanning or discovery, only to reach your self-hosted server. On some Android 16 devices, this may be enforced early via security patches under the "Nearby devices" permission name.++### Does Colota support mutual TLS (mTLS)?++Yes. Import a PKCS12 (`.p12` / `.pfx`) bundle in **Settings -> Connection -> Authentication & Headers -> Client Certificate (mTLS)**. The private key is stored in the OS keystore and the password isn't saved. For self-signed server certificates, import a CA in the same screen so trust is scoped to Colota only - no need to install a CA at the OS level. See the [mTLS guide](/docs/configuration/mtls) for details.++### I was using a CA installed in Android Settings for Colota - does it still work?++No, not anymore. As of this release, Colota only trusts system CAs and an optional CA you import in-app via mTLS Settings - user-installed device CAs are deliberately ignored. If sync starts failing with `Server certificate is not trusted...` after upgrading, you'll need to re-import your CA through the new in-app screen.++The migration is one-time: open Colota -> Settings -> Connection -> Authentication & Headers -> Client Certificate (mTLS) -> Trusted Server CA -> Import CA. The same `.crt` / `.pem` you originally installed in Android Settings works. See [Migrating from earlier behavior](/docs/configuration/mtls#migrating-from-earlier-behavior) for the full walkthrough.diff --git a/apps/docs/docs/guides/troubleshooting.md b/apps/docs/docs/guides/troubleshooting.mdindex 00ea959d..bee53a73 100644--- a/apps/docs/docs/guides/troubleshooting.md+++ b/apps/docs/docs/guides/troubleshooting.md@@ -32,7 +32,22 @@ sidebar_position: 44. Verify network connectivity5. Check the queue count in **Data Management**-**Common causes**: Wrong URL, HTTPS required for public endpoints, expired SSL certificate, incorrect authentication, mismatched field mapping, self-signed certificate (install your CA via Settings → Security → Encryption & credentials), **Sync Condition** restricting uploads to a specific network (Wi-Fi, SSID or VPN), missing local network permission on Android 16+.+**Common causes**: Wrong URL, HTTPS required for public endpoints, expired SSL certificate, incorrect authentication, mismatched field mapping, self-signed / private-CA server cert (see the [mTLS guide](/docs/configuration/mtls) for trust setup), **Sync Condition** restricting uploads to a specific network (Wi-Fi, SSID or VPN), missing local network permission on Android 16+.++### Test Connection error messages++If **Test Connection** fails, the message points at the specific layer that broke:++| Message | What it means | Fix |+| --- | --- | --- |+| `Server certificate is not trusted (self-signed or unknown CA)` | TLS layer: Colota can't validate the server's certificate chain | Import your CA via mTLS Settings -> Trusted Server CA, or use a publicly-trusted cert. User-installed CAs from Android Settings are not honored. |+| `Server requires a client certificate (mTLS) but none is configured` | TLS layer: the server demanded mTLS, Colota didn't present one | Import a `.p12` in mTLS Settings -> Client Certificate |+| `Server rejected the client certificate` | TLS layer: cert was sent but rejected (wrong CA, expired, revoked) | Verify the cert matches what your reverse proxy expects |+| `Incorrect password for client certificate` | Import-time: the password doesn't unlock the `.p12` | Re-import with the correct password |+| `Hostname not verified` | TLS layer: server cert doesn't list the hostname/IP you connected to | Reissue the server cert with a SAN that includes your hostname/IP |+| `Server returned <code>: ...` | HTTP layer: TLS succeeded, but the server returned a 4xx/5xx | Check your auth headers, field mapping, and server logs |+| `Connection timed out` | Network layer: the server didn't respond in time | Check connectivity, firewall, server availability |+| `Local network access denied` | Permission: Android 16+ blocked the connection to a private IP | Grant Local Network Access (Settings -> Apps -> Colota -> Permissions) |## Exporting app logsdiff --git a/apps/docs/docs/security.md b/apps/docs/docs/security.mdindex 677f11e0..9ee8ec7b 100644--- a/apps/docs/docs/security.md+++ b/apps/docs/docs/security.md@@ -8,7 +8,20 @@ An overview of how Colota handles your data at rest, in transit and on-device.## Data in Transit-HTTPS is enforced for all public server endpoints. HTTP is only allowed for private/local network addresses (`192.168.x.x`, `10.x.x.x`, `172.16-31.x.x`, `100.64.x.x`, `localhost`) to support self-hosted setups. Self-signed TLS certificates are supported by installing your CA certificate on the device via Android system settings.+HTTPS is enforced for all public server endpoints. HTTP is only allowed for private/local network addresses (`192.168.x.x`, `10.x.x.x`, `172.16-31.x.x`, `100.64.x.x`, `localhost`) to support self-hosted setups.++### TLS trust anchors++Colota's HTTPS chain validation accepts two trust sources, either of which is sufficient:++1. **System CAs** that ship with Android - the normal public web (Let's Encrypt, DigiCert, etc.)+2. **In-app imported CA** added via Settings -> Authentication & Headers -> Client Certificate (mTLS) -> Trusted Server CA. One slot, trusted only by Colota.++User-installed device CAs (from Android Settings -> Encryption & credentials) are not honored, so malware or a coerced profile that plants a CA in the device store can't intercept Colota's sync. Self-hosted users running a private CA should import it via the in-app path.++### Mutual TLS (mTLS)++For servers that require a client certificate at the TLS handshake (e.g. nginx `ssl_verify_client`, Traefik, Cloudflare Access), Colota supports importing a PKCS12 (`.p12` / `.pfx`) bundle. The private key is stored in the OS keystore and the password you enter during import is not saved. See the [mTLS guide](./configuration/mtls) for setup details.## Credentials at Restdiff --git a/apps/mobile/App.tsx b/apps/mobile/App.tsxindex 80a827e4..a5ed653a 100644--- a/apps/mobile/App.tsx+++ b/apps/mobile/App.tsx@@ -18,6 +18,7 @@ import {SettingsScreen,ApiSettingsScreen,AuthSettingsScreen,+ MtlsSettingsScreen,AutoExportScreen,GeofenceScreen,GeofenceEditorScreen,@@ -66,6 +67,11 @@ const SCREEN_CONFIG: readonly ScreenConfig[] = [component: AuthSettingsScreen,title: "Auth Settings"},+ {+ name: "mTLS Settings",+ component: MtlsSettingsScreen,+ title: "mTLS Settings"+ },{name: "Geofences",component: GeofenceScreen,diff --git a/apps/mobile/android/app/src/main/java/com/colota/bridge/BridgeUtils.kt b/apps/mobile/android/app/src/main/java/com/colota/bridge/BridgeUtils.ktnew file mode 100644index 00000000..411dd89d--- /dev/null+++ b/apps/mobile/android/app/src/main/java/com/colota/bridge/BridgeUtils.kt@@ -0,0 +1,35 @@+/**+ * Copyright (C) 2026 Max Dietrich+ * Licensed under the GNU AGPLv3. See LICENSE in the project root for details.+ */++package com.Colota.bridge++import com.Colota.util.AppLogger+import com.facebook.react.bridge.Promise+import kotlinx.coroutines.CoroutineScope+import kotlinx.coroutines.Dispatchers+import kotlinx.coroutines.launch+import kotlinx.coroutines.withContext++/**+ * Runs [operation] on Dispatchers.IO and resolves/rejects the JS promise.+ * Per-module wrappers usually preserve the [errorCode] and [errorMessage]+ * that callers downstream rely on.+ */+internal fun CoroutineScope.launchForPromise(+ promise: Promise,+ tag: String,+ errorCode: String,+ errorMessage: String,+ operation: suspend () -> Any?,+) {+ launch {+ try {+ promise.resolve(withContext(Dispatchers.IO) { operation() })+ } catch (e: Exception) {+ AppLogger.e(tag, errorMessage, e)+ promise.reject(errorCode, e.message, e)+ }+ }+}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 80135ea5..41d0ca40 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@@ -69,8 +69,8 @@ class LocationServiceModule(reactContext: ReactApplicationContext) :private val moduleScope = CoroutineScope(Dispatchers.IO + SupervisorJob())- // SAF directory picker- private var safPickerPromise: Promise? = null+ // @ReactMethod writes, onActivityResult reads on the main thread - CAS prevents double-pick races.+ private val safPickerPromise = java.util.concurrent.atomic.AtomicReference<Promise?>(null)private val SAF_PICKER_REQUEST = 9002private val chargingReceiver = object : BroadcastReceiver() {@@ -86,16 +86,12 @@ class LocationServiceModule(reactContext: ReactApplicationContext) :private val activityEventListener = object : BaseActivityEventListener() {override fun onActivityResult(activity: Activity, requestCode: Int, resultCode: Int, data: Intent?) {if (requestCode != SAF_PICKER_REQUEST) return- val promise = safPickerPromise ?: return- safPickerPromise = null-+ val promise = safPickerPromise.getAndSet(null) ?: returnif (resultCode != Activity.RESULT_OK || data?.data == null) {promise.resolve(null)return}-val uri = data.data!!- // Persist permission so WorkManager can access it laterval flags = Intent.FLAG_GRANT_READ_URI_PERMISSION or Intent.FLAG_GRANT_WRITE_URI_PERMISSIONreactApplicationContext.contentResolver.takePersistableUriPermission(uri, flags)promise.resolve(uri.toString())@@ -282,16 +278,8 @@ class LocationServiceModule(reactContext: ReactApplicationContext) :/** Runs [operation] on Dispatchers.IO and resolves/rejects the JS promise. */- private fun executeAsync(promise: Promise, operation: suspend () -> Any?) {- moduleScope.launch {- try {- promise.resolve(withContext(Dispatchers.IO) { operation() })- } catch (e: Exception) {- AppLogger.e(TAG, "Database operation failed", e)- promise.reject("DB_ERROR", e.message, e)- }- }- }+ private fun executeAsync(promise: Promise, operation: suspend () -> Any?) =+ moduleScope.launchForPromise(promise, TAG, "DB_ERROR", "Database operation failed", operation)@ReactMethodfun startService(config: ReadableMap, promise: Promise) {@@ -854,12 +842,20 @@ class LocationServiceModule(reactContext: ReactApplicationContext) :promise.reject("E_NO_ACTIVITY", "No current activity")return}- safPickerPromise = promise+ if (!safPickerPromise.compareAndSet(null, promise)) {+ promise.reject("E_PICKER_BUSY", "A picker is already open")+ return+ }val intent = Intent(Intent.ACTION_OPEN_DOCUMENT_TREE).apply {addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION or Intent.FLAG_GRANT_WRITE_URI_PERMISSION)addFlags(Intent.FLAG_GRANT_PERSISTABLE_URI_PERMISSION)}- activity.startActivityForResult(intent, SAF_PICKER_REQUEST)+ try {+ activity.startActivityForResult(intent, SAF_PICKER_REQUEST)+ } catch (e: Exception) {+ safPickerPromise.compareAndSet(promise, null)+ promise.reject("E_PICKER_LAUNCH", e.message ?: "Failed to launch picker", e)+ }}@ReactMethoddiff --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 f94bf87c..f0a41eb6 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@@ -22,6 +22,7 @@ class LocationServicePackage : ReactPackage {override fun createNativeModules(reactContext: ReactApplicationContext): List<NativeModule> {return listOf(LocationServiceModule(reactContext),+ MtlsBridgeModule(reactContext),BuildConfigModule(reactContext))}diff --git a/apps/mobile/android/app/src/main/java/com/colota/bridge/MtlsBridgeModule.kt b/apps/mobile/android/app/src/main/java/com/colota/bridge/MtlsBridgeModule.ktnew file mode 100644index 00000000..40488bd2--- /dev/null+++ b/apps/mobile/android/app/src/main/java/com/colota/bridge/MtlsBridgeModule.kt@@ -0,0 +1,409 @@+/**+ * Copyright (C) 2026 Max Dietrich+ * Licensed under the GNU AGPLv3. See LICENSE in the project root for details.+ */++package com.Colota.bridge++import android.app.Activity+import android.content.Intent+import com.Colota.sync.ApiFormat+import com.Colota.sync.NetworkManager+import com.Colota.sync.tls.ClientCertSslContextProvider+import com.Colota.util.AppLogger+import com.Colota.util.SecureStorageHelper+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 com.facebook.react.bridge.ReactContextBaseJavaModule+import com.facebook.react.bridge.ReactMethod+import com.facebook.react.bridge.ReadableMap+import com.facebook.react.bridge.WritableMap+import kotlinx.coroutines.CoroutineScope+import kotlinx.coroutines.Dispatchers+import kotlinx.coroutines.SupervisorJob+import kotlinx.coroutines.cancel+import kotlinx.coroutines.launch+import kotlinx.coroutines.withContext+import java.util.concurrent.atomic.AtomicReference++/**+ * React Native bridge for mTLS client certificate management.+ *+ * Owns:+ * - PKCS12 import (.p12 / .pfx) via SAF picker -> AndroidKeyStore+ * - System KeyChain alias pick (cert stays in OS keystore)+ * - Trusted Server CA import via SAF picker -> EncryptedSharedPreferences+ * - Test Connection endpoint check that exercises the full TLS path+ *+ * Picker request codes use the 9200-9299 range; the location module owns+ * 9000-9099 and auto-export 9100-9199 (per bridge-module-split conventions).+ */+class MtlsBridgeModule(reactContext: ReactApplicationContext) :+ ReactContextBaseJavaModule(reactContext) {++ private val secureStorage = SecureStorageHelper.getInstance(reactContext)+ private val networkManager = NetworkManager(reactContext)+ private val moduleScope = CoroutineScope(Dispatchers.IO + SupervisorJob())++ // @ReactMethod writes, onActivityResult reads on the main thread - CAS prevents double-pick races.+ private val p12PickerPromise = AtomicReference<Promise?>(null)+ private val serverCaPickerPromise = AtomicReference<Promise?>(null)++ private val activityEventListener = object : BaseActivityEventListener() {+ override fun onActivityResult(activity: Activity, requestCode: Int, resultCode: Int, data: Intent?) {+ when (requestCode) {+ P12_PICKER_REQUEST -> handleFilePickerResult(p12PickerPromise, resultCode, data, "E_P12_READ", ".p12")+ SERVER_CA_PICKER_REQUEST ->+ handleFilePickerResult(serverCaPickerPromise, resultCode, data, "E_CA_READ", "CA")+ }+ }+ }++ /**+ * Resolves the picker's promise with base64 of the picked file's bytes, or+ * null on cancel. Bounded by [P12_MAX_BYTES] to prevent OOM on hostile content providers.+ */+ private fun handleFilePickerResult(+ promiseRef: AtomicReference<Promise?>,+ resultCode: Int,+ data: Intent?,+ errorCode: String,+ label: String,+ ) {+ val promise = promiseRef.getAndSet(null) ?: return+ if (resultCode != Activity.RESULT_OK || data?.data == null) {+ promise.resolve(null)+ return+ }+ try {+ val bytes = reactApplicationContext.contentResolver.openInputStream(data.data!!)?.use { stream ->+ readBoundedBytes(stream, P12_MAX_BYTES)+ } ?: throw java.io.IOException("Could not open file")+ promise.resolve(android.util.Base64.encodeToString(bytes, android.util.Base64.NO_WRAP))+ } catch (e: Exception) {+ AppLogger.e(TAG, "Failed to read picked $label file", e)+ promise.reject(errorCode, e.message ?: "Failed to read file", e)+ }+ }++ init {+ reactContext.addActivityEventListener(activityEventListener)+ }++ override fun getName(): String = "MtlsBridgeModule"++ override fun invalidate() {+ moduleScope.cancel()+ reactApplicationContext.removeActivityEventListener(activityEventListener)+ super.invalidate()+ }++ // ── @ReactMethods: client cert ───────────────────────────────────────++ // Returns the base64 of the picked PKCS12 file. JS collects the password and+ // calls importClientCert next.+ @ReactMethod+ fun pickClientCertFile(promise: Promise) =+ launchFilePicker(promise, p12PickerPromise, P12_PICKER_REQUEST, P12_MIME_TYPES)++ @ReactMethod+ fun importClientCert(b64: String, password: String, promise: Promise) {+ moduleScope.launch {+ // JS-side String is immutable and can't be wiped; the best we can do+ // is zero the CharArray we hand to the keystore.+ val passwordChars = password.toCharArray()+ try {+ val bytes = withContext(Dispatchers.IO) {+ android.util.Base64.decode(b64, android.util.Base64.NO_WRAP)+ }+ val info = withContext(Dispatchers.IO) {+ ClientCertSslContextProvider.importToAndroidKeyStore(bytes, passwordChars)+ }+ // Mutual exclusion: clear any previously chosen KeyChain alias.+ secureStorage.clearKeyChainAlias()+ networkManager.invalidateClientCertCache()+ promise.resolve(buildCertInfoMap(info))+ } catch (e: java.security.UnrecoverableKeyException) {+ promise.reject("E_CERT_PASSWORD", "Incorrect password for client certificate", e)+ } catch (e: java.io.IOException) {+ val msg = e.message ?: ""+ if (msg.contains("password", ignoreCase = true) || msg.contains("mac", ignoreCase = true)) {+ promise.reject("E_CERT_PASSWORD", "Incorrect password for client certificate", e)+ } else {+ promise.reject("E_CERT_INVALID", "Not a valid PKCS12 file: $msg", e)+ }+ } catch (e: Exception) {+ AppLogger.e(TAG, "importClientCert failed", e)+ promise.reject("E_CERT_INVALID", e.message ?: "Failed to import certificate", e)+ } finally {+ java.util.Arrays.fill(passwordChars, ' ')+ }+ }+ }++ @ReactMethod+ fun clearClientCert(promise: Promise) = executeAsync(promise) {+ ClientCertSslContextProvider.deleteAndroidKeyStoreClientCert()+ secureStorage.clearKeyChainAlias()+ networkManager.invalidateClientCertCache()+ true+ }++ @ReactMethod+ fun getClientCertInfo(promise: Promise) = executeAsync(promise) {+ val keychainAlias = secureStorage.getKeyChainAlias()+ val info = if (keychainAlias != null) {+ ClientCertSslContextProvider.getKeyChainCertInfo(reactApplicationContext, keychainAlias)+ } else {+ ClientCertSslContextProvider.getAndroidKeyStoreClientCertInfo()+ }+ if (info == null) {+ Arguments.createMap().apply { putBoolean("configured", false) }+ } else {+ buildCertInfoMap(info).apply {+ putBoolean("configured", true)+ putString("source", if (keychainAlias != null) "keychain" else "p12")+ }+ }+ }++ /**+ * Opens Android's system KeyChain alias picker. If the user picks a cert,+ * persists the alias and returns the leaf cert info. The cert and its+ * private key stay in the OS KeyChain - this app never sees the bytes.+ */+ @ReactMethod+ fun pickKeyChainCert(promise: Promise) {+ val activity = reactApplicationContext.currentActivity+ if (activity == null) {+ promise.reject("E_NO_ACTIVITY", "No current activity")+ return+ }+ android.security.KeyChain.choosePrivateKeyAlias(+ activity,+ { alias ->+ if (alias == null) {+ promise.resolve(null)+ return@choosePrivateKeyAlias+ }+ moduleScope.launch {+ try {+ val info = withContext(Dispatchers.IO) {+ ClientCertSslContextProvider.getKeyChainCertInfo(reactApplicationContext, alias)+ }+ if (info == null) {+ promise.reject("E_KEYCHAIN_ACCESS", "Could not read certificate from KeyChain")+ return@launch+ }+ secureStorage.setKeyChainAlias(alias)+ // Mutual exclusion: drop any previously imported .p12.+ ClientCertSslContextProvider.deleteAndroidKeyStoreClientCert()+ networkManager.invalidateClientCertCache()+ promise.resolve(buildCertInfoMap(info).apply {+ putBoolean("configured", true)+ putString("source", "keychain")+ })+ } catch (e: Exception) {+ AppLogger.e(TAG, "pickKeyChainCert failed", e)+ promise.reject("E_KEYCHAIN_FAIL", e.message ?: "KeyChain selection failed", e)+ }+ }+ },+ null, null, null, -1, null,+ )+ }++ // ── @ReactMethods: trusted server CA ─────────────────────────────────++ // Returns the base64 of the picked CA cert file (PEM or DER).+ @ReactMethod+ fun pickServerCaFile(promise: Promise) =+ launchFilePicker(promise, serverCaPickerPromise, SERVER_CA_PICKER_REQUEST, CA_MIME_TYPES)++ /**+ * Validates the base64-encoded X.509 cert and persists it. The cert is then+ * used as an ADDITIONAL trust anchor (alongside Android's system CAs) for+ * Colota's outbound HTTPS via the composite trust manager.+ */+ @ReactMethod+ fun importServerCa(b64: String, promise: Promise) {+ moduleScope.launch {+ try {+ val bytes = withContext(Dispatchers.IO) {+ android.util.Base64.decode(b64, android.util.Base64.NO_WRAP)+ }+ val info = withContext(Dispatchers.IO) {+ ClientCertSslContextProvider.parseCaInfo(bytes)+ }+ withContext(Dispatchers.IO) {+ secureStorage.setServerCa(bytes)+ }+ networkManager.invalidateClientCertCache()+ promise.resolve(buildCertInfoMap(info))+ } catch (e: Exception) {+ AppLogger.e(TAG, "importServerCa failed", e)+ promise.reject("E_CA_INVALID", "Not a valid X.509 certificate: ${e.message ?: ""}", e)+ }+ }+ }++ @ReactMethod+ fun clearServerCa(promise: Promise) = executeAsync(promise) {+ secureStorage.clearServerCa()+ networkManager.invalidateClientCertCache()+ true+ }++ @ReactMethod+ fun getServerCaInfo(promise: Promise) = executeAsync(promise) {+ val bytes = secureStorage.getServerCaBytes()+ if (bytes == null) {+ Arguments.createMap().apply { putBoolean("configured", false) }+ } else {+ try {+ val info = ClientCertSslContextProvider.parseCaInfo(bytes)+ buildCertInfoMap(info).apply { putBoolean("configured", true) }+ } catch (e: Exception) {+ AppLogger.w(TAG, "Stored server CA could not be parsed: ${e.message}")+ Arguments.createMap().apply {+ putBoolean("configured", true)+ putString("error", e.message ?: "CA unreadable")+ }+ }+ }+ }++ // ── @ReactMethod: test connection ────────────────────────────────────++ // Runs the network/SSL/auth path identically to production sync. The payload+ // shape can differ - production builds payloads natively, this one converts+ // a JS-supplied ReadableMap. Conversion handles all ReadableType variants so+ // nested fields don't blow up the bridge.+ @ReactMethod+ fun testEndpoint(args: ReadableMap, promise: Promise) {+ moduleScope.launch {+ try {+ val endpoint = args.getString("endpoint") ?: ""+ val method = args.getString("method") ?: "POST"+ val apiFormat = ApiFormat.fromWire(args.getString("apiFormat"))+ val payloadMap = args.getMap("payload") ?: Arguments.createMap()+ val customFieldsMap = args.getMap("customFields") ?: Arguments.createMap()++ val payload = payloadMap.toJson()+ val customFields = mutableMapOf<String, String>().apply {+ val it = customFieldsMap.keySetIterator()+ while (it.hasNextKey()) {+ val key = it.nextKey()+ put(key, customFieldsMap.getString(key) ?: "")+ }+ }+ val authHeaders = secureStorage.getAuthHeaders()+ val result = networkManager.testEndpoint(+ payload = payload,+ endpoint = endpoint,+ extraHeaders = authHeaders,+ httpMethod = method,+ apiFormat = apiFormat,+ customFields = customFields,+ )+ promise.resolve(Arguments.createMap().apply {+ putBoolean("ok", result.ok)+ putInt("status", result.httpStatus)+ if (result.errorMessage != null) putString("errorMessage", result.errorMessage)+ })+ } catch (e: Exception) {+ AppLogger.e(TAG, "testEndpoint failed", e)+ promise.reject("E_TEST_ENDPOINT", e.message ?: "Test failed", e)+ }+ }+ }++ // ── Helpers ──────────────────────────────────────────────────────────++ private fun executeAsync(promise: Promise, operation: suspend () -> Any?) =+ moduleScope.launchForPromise(promise, TAG, "E_MTLS", "Operation failed", operation)++ /**+ * Opens an SAF ACTION_OPEN_DOCUMENT picker filtered by [mimeTypes], reserves the+ * promise atomically against double-pick races, and rolls back on launch failure.+ */+ private fun launchFilePicker(+ promise: Promise,+ promiseRef: AtomicReference<Promise?>,+ requestCode: Int,+ mimeTypes: Array<String>,+ ) {+ val activity = reactApplicationContext.currentActivity+ if (activity == null) {+ promise.reject("E_NO_ACTIVITY", "No current activity")+ return+ }+ if (!promiseRef.compareAndSet(null, promise)) {+ promise.reject("E_PICKER_BUSY", "A picker is already open")+ return+ }+ val intent = Intent(Intent.ACTION_OPEN_DOCUMENT).apply {+ addCategory(Intent.CATEGORY_OPENABLE)+ type = "*/*"+ putExtra(Intent.EXTRA_MIME_TYPES, mimeTypes)+ }+ try {+ activity.startActivityForResult(intent, requestCode)+ } catch (e: Exception) {+ promiseRef.compareAndSet(promise, null)+ promise.reject("E_PICKER_LAUNCH", e.message ?: "Failed to launch picker", e)+ }+ }++ private fun buildCertInfoMap(info: ClientCertSslContextProvider.CertInfo): WritableMap =+ Arguments.createMap().apply {+ putString("subject", info.subject)+ putString("issuer", info.issuer)+ putDouble("notBefore", info.notBefore.toDouble())+ putDouble("notAfter", info.notAfter.toDouble())+ }++ /**+ * Reads at most [maxBytes] from [stream] in chunks, throwing if the source+ * exceeds the cap. Avoids letting a malicious or oversized provider hand us+ * gigabytes via InputStream.readBytes().+ */+ private fun readBoundedBytes(stream: java.io.InputStream, maxBytes: Int): ByteArray {+ val baos = java.io.ByteArrayOutputStream()+ val buf = ByteArray(8192)+ var total = 0+ while (true) {+ val n = stream.read(buf)+ if (n == -1) break+ total += n+ if (total > maxBytes) {+ throw java.io.IOException("File too large (over $maxBytes bytes)")+ }+ baos.write(buf, 0, n)+ }+ return baos.toByteArray()+ }++ companion object {+ private const val TAG = "MtlsBridgeModule"+ private const val P12_PICKER_REQUEST = 9200+ private const val SERVER_CA_PICKER_REQUEST = 9201+ private const val P12_MAX_BYTES = 256 * 1024 // 256 KiB cap - real .p12 / .crt files are well under 20 KiB++ private val P12_MIME_TYPES = arrayOf(+ "application/x-pkcs12",+ "application/pkcs12",+ "application/octet-stream",+ "*/*",+ )+ private val CA_MIME_TYPES = arrayOf(+ "application/x-x509-ca-cert",+ "application/pkix-cert",+ "application/x-pem-file",+ "application/octet-stream",+ "*/*",+ )+ }+}diff --git a/apps/mobile/android/app/src/main/java/com/colota/bridge/ReadableJson.kt b/apps/mobile/android/app/src/main/java/com/colota/bridge/ReadableJson.ktnew file mode 100644index 00000000..fe32690e--- /dev/null+++ b/apps/mobile/android/app/src/main/java/com/colota/bridge/ReadableJson.kt@@ -0,0 +1,54 @@+/**+ * Copyright (C) 2026 Max Dietrich+ * Licensed under the GNU AGPLv3. See LICENSE in the project root for details.+ */++package com.Colota.bridge++import com.facebook.react.bridge.ReadableArray+import com.facebook.react.bridge.ReadableMap+import com.facebook.react.bridge.ReadableType+import org.json.JSONArray+import org.json.JSONObject++/**+ * Recursive conversion of React Native [ReadableMap] / [ReadableArray] to+ * [JSONObject] / [JSONArray]. Preserves nested structure, null values, and+ * scalar types - safer than the flat `getString`-as-fallback patterns that+ * silently lose nested data.+ */+fun ReadableMap.toJson(): JSONObject {+ val json = JSONObject()+ val it = keySetIterator()+ while (it.hasNextKey()) {+ val key = it.nextKey()+ json.put(key, readableValue(this, key))+ }+ return json+}++fun ReadableArray.toJson(): JSONArray {+ val json = JSONArray()+ for (i in 0 until size()) {+ json.put(readableValue(this, i))+ }+ return json+}++private fun readableValue(map: ReadableMap, key: String): Any = when (map.getType(key)) {+ ReadableType.Null -> JSONObject.NULL+ ReadableType.Boolean -> map.getBoolean(key)+ ReadableType.Number -> map.getDouble(key)+ ReadableType.String -> map.getString(key) ?: JSONObject.NULL+ ReadableType.Map -> map.getMap(key)?.toJson() ?: JSONObject.NULL+ ReadableType.Array -> map.getArray(key)?.toJson() ?: JSONObject.NULL+}++private fun readableValue(array: ReadableArray, i: Int): Any = when (array.getType(i)) {+ ReadableType.Null -> JSONObject.NULL+ ReadableType.Boolean -> array.getBoolean(i)+ ReadableType.Number -> array.getDouble(i)+ ReadableType.String -> array.getString(i) ?: JSONObject.NULL+ ReadableType.Map -> array.getMap(i)?.toJson() ?: JSONObject.NULL+ ReadableType.Array -> array.getArray(i)?.toJson() ?: JSONObject.NULL+}diff --git a/apps/mobile/android/app/src/main/java/com/colota/sync/NetworkManager.kt b/apps/mobile/android/app/src/main/java/com/colota/sync/NetworkManager.ktindex a9a3667d..b1566f24 100644--- a/apps/mobile/android/app/src/main/java/com/colota/sync/NetworkManager.kt+++ b/apps/mobile/android/app/src/main/java/com/colota/sync/NetworkManager.kt@@ -5,6 +5,7 @@ import android.net.wifi.WifiInfoimport android.net.wifi.WifiManagerimport com.Colota.BuildConfigimport com.Colota.util.AppLogger+import com.Colota.sync.tls.ClientCertSslContextProviderimport com.Colota.util.BatteryStatusimport com.Colota.util.TimedCacheimport android.os.Build@@ -18,9 +19,12 @@ import java.net.HttpURLConnectionimport java.net.URLimport java.net.URLEncoderimport java.nio.charset.StandardCharsets+import java.security.UnrecoverableKeyExceptionimport java.time.Instantimport java.time.ZoneIdimport java.time.format.DateTimeFormatter+import javax.net.ssl.HttpsURLConnection+import javax.net.ssl.SSLHandshakeException/*** Handles all outgoing network communication for the tracking engine.@@ -40,6 +44,16 @@ class NetworkManager(private val context: Context) {@Volatile private var isVpn: Boolean = falseprivate val wifiManager = context.getSystemService(Context.WIFI_SERVICE) as? WifiManager+ // Lazy so existing unit tests that mock Context don't trigger EncryptedSharedPreferences init.+ // Singleton so invalidation propagates between every NetworkManager (foreground service ++ // mTLS bridge module both hold their own NetworkManager).+ private val clientCertProvider by lazy { ClientCertSslContextProvider.getInstance(context) }++ /** Call after a client cert or trusted CA change so the next request picks it up. */+ fun invalidateClientCertCache() {+ clientCertProvider.invalidate()+ }+private val networkCallback = createNetworkCallback()private fun createNetworkCallback(): ConnectivityManager.NetworkCallback {@@ -105,66 +119,14 @@ class NetworkManager(private val context: Context) {extraHeaders: Map<String, String> = emptyMap(),httpMethod: String = "POST",apiFormat: ApiFormat = ApiFormat.FIELD_MAPPED- ): Boolean = withContext(Dispatchers.IO) {- if (endpoint.isBlank()) {- AppLogger.d(TAG, "Empty endpoint provided")- return@withContext false- }-- val resolvedEndpoint = resolveUrlVariables(endpoint, payload)-- val url = try {- URL(resolvedEndpoint)- } catch (e: Exception) {- AppLogger.e(TAG, "Invalid URL: $resolvedEndpoint")- return@withContext false- }-- if (!isValidProtocol(resolvedEndpoint)) {- AppLogger.e(TAG, "Protocol blocked or invalid: $endpoint")- return@withContext false- }-- if (!isNetworkAvailable()) {- AppLogger.d(TAG, "Sync skipped: No internet")- return@withContext false- }-- val transformedPayload = when (apiFormat) {- ApiFormat.TRACCAR_JSON -> buildTraccarJsonPayload(payload)- ApiFormat.OVERLAND_BATCH -> buildOverlandBatchPayload(listOf(payload), emptyMap())- ApiFormat.FIELD_MAPPED -> payload- }-- val isGet = httpMethod.equals("GET", ignoreCase = true)-- val targetUrl = if (isGet) {- val query = buildQueryString(transformedPayload)- val separator = if (url.query != null) "&" else "?"- URL("$resolvedEndpoint$separator$query")- } else {- url- }-- var connection: HttpURLConnection? = null- try {- connection = buildConnection(targetUrl, isGet, extraHeaders)- logRequest(connection, isGet, resolvedEndpoint, targetUrl, transformedPayload)- if (!isGet) writeBody(connection, transformedPayload)- return@withContext readResponse(connection)- } catch (e: java.net.SocketException) {- if (isPrivateHost(url.host ?: "") && e.message?.contains("EPERM") == true) {- AppLogger.e(TAG, "Local network access denied - grant Local Network Access permission", e)- } else {- AppLogger.e(TAG, "Network error: ${e.message}", e)- }- false- } catch (e: Exception) {- AppLogger.e(TAG, "Network error: ${e.message}", e)- false- } finally {- connection?.disconnect()+ ): Boolean {+ val result = runRequest(payload, endpoint, extraHeaders, httpMethod, apiFormat, emptyMap())+ if (result.ok) {+ AppLogger.d(TAG, "Location successfully sent")+ } else if (result.errorMessage != null) {+ AppLogger.e(TAG, result.errorMessage)}+ return result.ok}private fun buildConnection(@@ -182,6 +144,9 @@ class NetworkManager(private val context: Context) {connectTimeout = CONNECTION_TIMEOUTreadTimeout = READ_TIMEOUTuseCaches = false+ if (this is HttpsURLConnection) {+ clientCertProvider.get()?.let { sslSocketFactory = it }+ }}private fun writeBody(connection: HttpURLConnection, payload: JSONObject) {@@ -190,19 +155,6 @@ class NetworkManager(private val context: Context) {connection.outputStream.use { it.write(bodyBytes) }}- private fun readResponse(connection: HttpURLConnection): Boolean {- val responseCode = connection.responseCode- if (responseCode in 200..299) {- AppLogger.d(TAG, "Location successfully sent")- return true- }- val errorBody = try {- connection.errorStream?.bufferedReader()?.use { it.readText() } ?: "No error body"- } catch (_: Exception) { "Could not read error body" }- AppLogger.e(TAG, "${connection.requestMethod} failed: $responseCode - $errorBody")- return false- }-private fun logRequest(connection: HttpURLConnection,isGet: Boolean,@@ -353,6 +305,12 @@ class NetworkManager(private val context: Context) {AppLogger.e(TAG, "Network error: ${e.message}", e)}BatchResult.NetworkError+ } catch (e: SSLHandshakeException) {+ AppLogger.e(TAG, mtlsErrorMessage(e), e)+ BatchResult.NetworkError+ } catch (e: UnrecoverableKeyException) {+ AppLogger.e(TAG, "Client certificate password is incorrect - re-import the .p12", e)+ BatchResult.NetworkError} catch (e: Exception) {AppLogger.e(TAG, "Network error: ${e.message}", e)BatchResult.NetworkError@@ -361,6 +319,119 @@ class NetworkManager(private val context: Context) {}}+ /** Same as [sendToEndpoint] but returns status + error text instead of Boolean. */+ suspend fun testEndpoint(+ payload: JSONObject,+ endpoint: String,+ extraHeaders: Map<String, String> = emptyMap(),+ httpMethod: String = "POST",+ apiFormat: ApiFormat = ApiFormat.FIELD_MAPPED,+ customFields: Map<String, String> = emptyMap(),+ ): TestEndpointResult = runRequest(payload, endpoint, extraHeaders, httpMethod, apiFormat, customFields)++ /**+ * Shared request implementation. Returns a fully-populated [TestEndpointResult];+ * production callers project this to Boolean via [sendToEndpoint], while the+ * Test Connection path exposes it directly via [testEndpoint].+ */+ private suspend fun runRequest(+ payload: JSONObject,+ endpoint: String,+ extraHeaders: Map<String, String>,+ httpMethod: String,+ apiFormat: ApiFormat,+ customFields: Map<String, String>,+ ): TestEndpointResult = withContext(Dispatchers.IO) {+ if (endpoint.isBlank()) {+ return@withContext TestEndpointResult(false, errorMessage = "Endpoint is empty")+ }+ val resolvedEndpoint = resolveUrlVariables(endpoint, payload)+ val url = try {+ URL(resolvedEndpoint)+ } catch (_: Exception) {+ return@withContext TestEndpointResult(false, errorMessage = "Invalid URL: $resolvedEndpoint")+ }+ if (!isValidProtocol(resolvedEndpoint)) {+ return@withContext TestEndpointResult(+ false,+ errorMessage = "HTTPS is required for public endpoints. HTTP is only allowed for private/local addresses."+ )+ }+ if (!isNetworkAvailable()) {+ return@withContext TestEndpointResult(false, errorMessage = "No internet connection")+ }++ val transformedPayload = when (apiFormat) {+ ApiFormat.TRACCAR_JSON -> buildTraccarJsonPayload(payload)+ ApiFormat.OVERLAND_BATCH -> buildOverlandBatchPayload(listOf(payload), customFields)+ ApiFormat.FIELD_MAPPED -> payload+ }+ val isGet = httpMethod.equals("GET", ignoreCase = true)+ val targetUrl = if (isGet) {+ val query = buildQueryString(transformedPayload)+ val separator = if (url.query != null) "&" else "?"+ URL("$resolvedEndpoint$separator$query")+ } else url++ var connection: HttpURLConnection? = null+ try {+ connection = buildConnection(targetUrl, isGet, extraHeaders)+ logRequest(connection, isGet, resolvedEndpoint, targetUrl, transformedPayload)+ if (!isGet) writeBody(connection, transformedPayload)+ val responseCode = connection.responseCode+ if (responseCode in 200..299) {+ TestEndpointResult(true, httpStatus = responseCode)+ } else {+ val errorBody = readErrorBody(connection)+ TestEndpointResult(+ false,+ httpStatus = responseCode,+ errorMessage = "Server returned $responseCode: ${errorBody.take(200)}"+ )+ }+ } catch (e: SSLHandshakeException) {+ TestEndpointResult(false, errorMessage = mtlsErrorMessage(e))+ } catch (e: UnrecoverableKeyException) {+ TestEndpointResult(false, errorMessage = "Client certificate password is incorrect - re-import the .p12")+ } catch (e: java.net.SocketException) {+ val msg = if (isPrivateHost(url.host ?: "") && e.message?.contains("EPERM") == true) {+ "Local network access denied - grant Local Network Access permission"+ } else "Network error: ${e.message}"+ TestEndpointResult(false, errorMessage = msg)+ } catch (e: java.net.SocketTimeoutException) {+ TestEndpointResult(false, errorMessage = "Connection timed out")+ } catch (e: Exception) {+ TestEndpointResult(false, errorMessage = "Connection failed: ${e.message ?: e.javaClass.simpleName}")+ } finally {+ connection?.disconnect()+ }+ }++ // Disambiguates the three TLS failure modes that look similar in logs but+ // need different fixes: untrusted server cert, missing client cert, rejected+ // client cert.+ private fun mtlsErrorMessage(e: SSLHandshakeException): String {+ val detail = (e.message ?: "") + " " + (e.cause?.message ?: "")+ val isServerNotTrusted = detail.contains("Trust anchor", ignoreCase = true) ||+ detail.contains("CertPathValidator", ignoreCase = true) ||+ detail.contains("unable to find valid certification path", ignoreCase = true)+ val isClientRejected = detail.contains("certificate_required", ignoreCase = true) ||+ detail.contains("bad_certificate", ignoreCase = true) ||+ detail.contains("handshake_failure", ignoreCase = true)+ val hasClientCert = clientCertProvider.get() != null++ return when {+ isServerNotTrusted ->+ "Server certificate is not trusted (self-signed or unknown CA). Import the server's CA via mTLS Settings, or use a publicly-trusted certificate."+ isClientRejected && hasClientCert ->+ "Server rejected the client certificate. Common causes: cert signed by wrong CA, cert expired, or cert revoked."+ isClientRejected && !hasClientCert ->+ "Server requires a client certificate (mTLS) but none is configured. Import a .p12 in Auth Settings."+ else ->+ "TLS handshake failed: ${e.message ?: e.javaClass.simpleName}"+ }+ }+private fun readBatchResponse(connection: HttpURLConnection, batchSize: Int): BatchResult {val responseCode = connection.responseCodereturn when (responseCode) {diff --git a/apps/mobile/android/app/src/main/java/com/colota/sync/BatchResult.kt b/apps/mobile/android/app/src/main/java/com/colota/sync/NetworkResults.ktsimilarity index 62%rename from apps/mobile/android/app/src/main/java/com/colota/sync/BatchResult.ktrename to apps/mobile/android/app/src/main/java/com/colota/sync/NetworkResults.ktindex 6f935a1a..9187763d 100644--- a/apps/mobile/android/app/src/main/java/com/colota/sync/BatchResult.kt+++ b/apps/mobile/android/app/src/main/java/com/colota/sync/NetworkResults.kt@@ -8,6 +8,8 @@ package com.Colota.sync/*** Distinguishes 4xx from 5xx so the caller can split-on-4xx (poison row) without* amplifying 5xx outages into N more requests per cycle.+ *+ * Returned by [NetworkManager.sendBatchToEndpoint].*/sealed class BatchResult {object Success : BatchResult()@@ -15,3 +17,13 @@ sealed class BatchResult {data class ServerError(val code: Int) : BatchResult()object NetworkError : BatchResult()}++/**+ * Returned by [NetworkManager.testEndpoint]. Carries enough detail for the+ * Test Connection UI to show a precise error.+ */+data class TestEndpointResult(+ val ok: Boolean,+ val httpStatus: Int = 0,+ val errorMessage: String? = null,+)diff --git a/apps/mobile/android/app/src/main/java/com/colota/sync/tls/ClientCertSslContextProvider.kt b/apps/mobile/android/app/src/main/java/com/colota/sync/tls/ClientCertSslContextProvider.ktnew file mode 100644index 00000000..1c812a4a--- /dev/null+++ b/apps/mobile/android/app/src/main/java/com/colota/sync/tls/ClientCertSslContextProvider.kt@@ -0,0 +1,207 @@+/**+ * Copyright (C) 2026 Max Dietrich+ * Licensed under the GNU AGPLv3. See LICENSE in the project root for details.+ */++package com.Colota.sync.tls++import android.content.Context+import com.Colota.util.AppLogger+import com.Colota.util.SecureStorageHelper+import java.io.ByteArrayInputStream+import java.security.KeyStore+import java.security.cert.CertificateFactory+import java.security.cert.X509Certificate+import javax.net.ssl.KeyManager+import javax.net.ssl.SSLContext+import javax.net.ssl.SSLSocketFactory+import javax.net.ssl.TrustManager+import javax.net.ssl.TrustManagerFactory+import javax.net.ssl.X509TrustManager++/**+ * Builds the cached [SSLSocketFactory] for mTLS-protected endpoints. Client cert+ * comes from [AndroidKeyStore], server CA from [SecureStorageHelper]. Call+ * [invalidate] when either changes.+ *+ * Singleton because the SSL factory cache is process-wide - if both the+ * foreground service's NetworkManager and the bridge module's NetworkManager+ * held separate caches, invalidating one wouldn't propagate to the other and a+ * mid-session cert swap would surface stale state on the un-invalidated path.+ */+class ClientCertSslContextProvider private constructor(context: Context) {++ private val secureStorage = SecureStorageHelper.getInstance(context)+ private val keyManager = DynamicKeyManager(context.applicationContext)++ @Volatile private var cachedFactory: SSLSocketFactory? = null+ @Volatile private var cacheLoaded: Boolean = false++ /** Returns null when neither a client cert nor a server CA is configured. */+ fun get(): SSLSocketFactory? {+ if (cacheLoaded) return cachedFactory+ synchronized(this) {+ if (cacheLoaded) return cachedFactory+ val hasClientCert = hasAnyClientCert()+ val caBytes = secureStorage.getServerCaBytes()+ cachedFactory = if (!hasClientCert && caBytes == null) {+ null+ } else {+ try {+ buildFactoryFromKeyStore(hasClientCert, caBytes)+ } catch (e: Exception) {+ AppLogger.e(TAG, "Failed to build SSL context from stored material", e)+ null+ }+ }+ cacheLoaded = true+ return cachedFactory+ }+ }++ private fun hasAnyClientCert(): Boolean =+ secureStorage.getKeyChainAlias() != null || hasAndroidKeyStoreClientCert()++ private fun buildFactoryFromKeyStore(hasClientCert: Boolean, serverCaBytes: ByteArray?): SSLSocketFactory {+ val keyManagers: Array<KeyManager>? = if (hasClientCert) arrayOf(keyManager) else null+ val trustManagers: Array<TrustManager>? = serverCaBytes?.let { buildTrustManagers(it) }+ val sslContext = SSLContext.getInstance("TLS").apply {+ init(keyManagers, trustManagers, null)+ }+ return sslContext.socketFactory+ }++ fun invalidate() {+ synchronized(this) {+ cachedFactory = null+ cacheLoaded = false+ keyManager.invalidate()+ }+ }++ companion object {+ private const val TAG = "ClientCertSslContextProvider"+ private const val ANDROID_KEYSTORE = "AndroidKeyStore"+ internal const val CLIENT_CERT_ALIAS = "colota_client_cert"++ @Volatile private var INSTANCE: ClientCertSslContextProvider? = null++ @JvmStatic+ fun getInstance(context: Context): ClientCertSslContextProvider =+ INSTANCE ?: synchronized(this) {+ INSTANCE ?: ClientCertSslContextProvider(context.applicationContext).also { INSTANCE = it }+ }++ private fun X509Certificate.toCertInfo() = CertInfo(+ subject = subjectX500Principal.name,+ issuer = issuerX500Principal.name,+ notBefore = notBefore.time,+ notAfter = notAfter.time,+ )++ // Unwraps the PKCS12 and writes the key + chain into AndroidKeyStore.+ // The password is consumed here and never persisted.+ @JvmStatic+ fun importToAndroidKeyStore(pkcs12Bytes: ByteArray, password: CharArray): CertInfo {+ val tmp = KeyStore.getInstance("PKCS12").apply {+ load(ByteArrayInputStream(pkcs12Bytes), password)+ }+ val keyAliases = tmp.aliases().asSequence().filter { tmp.isKeyEntry(it) }.toList()+ if (keyAliases.isEmpty()) {+ throw java.security.KeyStoreException("PKCS12 contains no key entries")+ }+ if (keyAliases.size > 1) {+ AppLogger.w(TAG, "PKCS12 contains ${keyAliases.size} key entries; using first: ${keyAliases.first()}")+ }+ val alias = keyAliases.first()+ val privateKey = tmp.getKey(alias, password) as java.security.PrivateKey+ val chain = tmp.getCertificateChain(alias)+ ?: throw java.security.KeyStoreException("PKCS12 has key entry but no certificate chain")++ val androidKs = KeyStore.getInstance(ANDROID_KEYSTORE).apply { load(null) }+ if (androidKs.containsAlias(CLIENT_CERT_ALIAS)) {+ androidKs.deleteEntry(CLIENT_CERT_ALIAS)+ }+ androidKs.setKeyEntry(CLIENT_CERT_ALIAS, privateKey, null, chain)++ return (chain[0] as X509Certificate).toCertInfo()+ }++ @JvmStatic+ fun hasAndroidKeyStoreClientCert(): Boolean = try {+ KeyStore.getInstance(ANDROID_KEYSTORE).apply { load(null) }.containsAlias(CLIENT_CERT_ALIAS)+ } catch (e: Exception) {+ AppLogger.w(TAG, "AndroidKeyStore unavailable: ${e.message}")+ false+ }++ @JvmStatic+ fun getAndroidKeyStoreClientCertInfo(): CertInfo? = try {+ val ks = KeyStore.getInstance(ANDROID_KEYSTORE).apply { load(null) }+ if (!ks.containsAlias(CLIENT_CERT_ALIAS)) return null+ (ks.getCertificate(CLIENT_CERT_ALIAS) as? X509Certificate)?.toCertInfo()+ } catch (e: Exception) {+ AppLogger.e(TAG, "Failed to read client cert from AndroidKeyStore", e)+ null+ }++ @JvmStatic+ fun deleteAndroidKeyStoreClientCert() {+ try {+ val ks = KeyStore.getInstance(ANDROID_KEYSTORE).apply { load(null) }+ if (ks.containsAlias(CLIENT_CERT_ALIAS)) {+ ks.deleteEntry(CLIENT_CERT_ALIAS)+ }+ } catch (e: Exception) {+ AppLogger.e(TAG, "Failed to delete client cert from AndroidKeyStore", e)+ }+ }++ /**+ * Reads cert info for an alias stored in Android's system KeyChain.+ * Blocks - call from an IO thread.+ */+ @JvmStatic+ fun getKeyChainCertInfo(context: Context, alias: String): CertInfo? = try {+ android.security.KeyChain.getCertificateChain(context, alias)?.firstOrNull()?.toCertInfo()+ } catch (e: Exception) {+ AppLogger.e(TAG, "Failed to read KeyChain cert for alias '$alias'", e)+ null+ }++ @JvmStatic+ fun buildTrustManagers(serverCaBytes: ByteArray): Array<TrustManager> {+ val ca = CertificateFactory.getInstance("X.509")+ .generateCertificate(ByteArrayInputStream(serverCaBytes)) as X509Certificate++ val userKs = KeyStore.getInstance(KeyStore.getDefaultType()).apply {+ load(null, null)+ setCertificateEntry("user-ca", ca)+ }+ val userTmf = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm()).apply {+ init(userKs)+ }+ val systemTmf = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm()).apply {+ init(null as KeyStore?)+ }+ val userTm = userTmf.trustManagers.filterIsInstance<X509TrustManager>().first()+ val systemTm = systemTmf.trustManagers.filterIsInstance<X509TrustManager>().first()+ return arrayOf(CompositeX509TrustManager(listOf(systemTm, userTm)))+ }++ @JvmStatic+ fun parseCaInfo(bytes: ByteArray): CertInfo {+ val cert = CertificateFactory.getInstance("X.509")+ .generateCertificate(ByteArrayInputStream(bytes)) as X509Certificate+ return cert.toCertInfo()+ }++ }++ data class CertInfo(+ val subject: String,+ val issuer: String,+ val notBefore: Long,+ val notAfter: Long,+ )+}diff --git a/apps/mobile/android/app/src/main/java/com/colota/sync/tls/CompositeX509TrustManager.kt b/apps/mobile/android/app/src/main/java/com/colota/sync/tls/CompositeX509TrustManager.ktnew file mode 100644index 00000000..9acb21fe--- /dev/null+++ b/apps/mobile/android/app/src/main/java/com/colota/sync/tls/CompositeX509TrustManager.kt@@ -0,0 +1,40 @@+/**+ * Copyright (C) 2026 Max Dietrich+ * Licensed under the GNU AGPLv3. See LICENSE in the project root for details.+ */++package com.Colota.sync.tls++import java.security.cert.CertificateException+import java.security.cert.X509Certificate+import javax.net.ssl.X509TrustManager++/**+ * Trust manager that accepts a server chain if any [delegates] would accept it.+ * Used to add a user-imported CA on top of the system trust store.+ */+class CompositeX509TrustManager(private val delegates: List<X509TrustManager>) : X509TrustManager {++ override fun checkServerTrusted(chain: Array<out X509Certificate>, authType: String) {+ val errors = mutableListOf<CertificateException>()+ for (tm in delegates) {+ try {+ tm.checkServerTrusted(chain, authType)+ return+ } catch (e: CertificateException) {+ errors += e+ }+ }+ // Re-throw the last delegate's error. ClientCertSslContextProvider.buildTrustManagers+ // orders delegates as [system, user], so the user-CA error is reported last -+ // which is what self-hosted users want to see ("your CA didn't match either").+ throw errors.last()+ }++ override fun checkClientTrusted(chain: Array<out X509Certificate>, authType: String) {+ delegates.first().checkClientTrusted(chain, authType)+ }++ override fun getAcceptedIssuers(): Array<X509Certificate> =+ delegates.flatMap { it.acceptedIssuers.toList() }.toTypedArray()+}diff --git a/apps/mobile/android/app/src/main/java/com/colota/sync/tls/DynamicKeyManager.kt b/apps/mobile/android/app/src/main/java/com/colota/sync/tls/DynamicKeyManager.ktnew file mode 100644index 00000000..fe7372b0--- /dev/null+++ b/apps/mobile/android/app/src/main/java/com/colota/sync/tls/DynamicKeyManager.kt@@ -0,0 +1,132 @@+/**+ * Copyright (C) 2026 Max Dietrich+ * Licensed under the GNU AGPLv3. See LICENSE in the project root for details.+ */++package com.Colota.sync.tls++import android.content.Context+import android.security.KeyChain+import com.Colota.util.AppLogger+import com.Colota.util.SecureStorageHelper+import java.net.Socket+import java.security.KeyStore+import java.security.Principal+import java.security.PrivateKey+import java.security.cert.X509Certificate+import javax.net.ssl.X509KeyManager++/**+ * Resolves the active client cert at TLS handshake time. Supports two sources:+ * - System KeyChain alias (private key stays in OS / hardware, never enters app heap)+ * - AndroidKeyStore entry (.p12 imported via the app)+ *+ * Dynamic resolution means the SSL context doesn't need to be rebuilt when the+ * user swaps certs; only the trust managers (server CA side) require rebuild.+ */+class DynamicKeyManager(private val context: Context) : X509KeyManager {++ private val secureStorage by lazy { SecureStorageHelper.getInstance(context) }++ // Resolved alias is cached so chooseClientAlias doesn't hit EncryptedSharedPreferences+ // on every TLS handshake. Invalidated via [invalidate] when the user changes certs.+ @Volatile private var cachedAlias: String? = null+ @Volatile private var aliasResolved: Boolean = false++ override fun chooseClientAlias(+ keyTypes: Array<String>,+ issuers: Array<Principal>?,+ socket: Socket?,+ ): String? {+ if (aliasResolved) return cachedAlias+ synchronized(this) {+ if (aliasResolved) return cachedAlias+ cachedAlias = resolveAlias()+ aliasResolved = true+ return cachedAlias+ }+ }++ private fun resolveAlias(): String? {+ secureStorage.getKeyChainAlias()?.let { return KEYCHAIN_PREFIX + it }+ if (hasAndroidKeyStoreEntry()) return ClientCertSslContextProvider.CLIENT_CERT_ALIAS+ return null+ }++ override fun getClientAliases(keyType: String, issuers: Array<Principal>?): Array<String>? {+ val alias = chooseClientAlias(arrayOf(keyType), issuers, null) ?: return null+ return arrayOf(alias)+ }++ override fun getCertificateChain(alias: String): Array<X509Certificate>? {+ if (alias.startsWith(KEYCHAIN_PREFIX)) {+ return try {+ KeyChain.getCertificateChain(context, alias.removePrefix(KEYCHAIN_PREFIX))+ } catch (e: Exception) {+ AppLogger.e(TAG, "KeyChain.getCertificateChain failed", e)+ null+ }+ }+ if (alias != ClientCertSslContextProvider.CLIENT_CERT_ALIAS) {+ AppLogger.w(TAG, "Unexpected alias for getCertificateChain: $alias")+ return null+ }+ return try {+ val ks = KeyStore.getInstance(ANDROID_KEYSTORE).apply { load(null) }+ ks.getCertificateChain(alias)?.map { it as X509Certificate }?.toTypedArray()+ } catch (e: Exception) {+ AppLogger.e(TAG, "AndroidKeyStore.getCertificateChain failed", e)+ null+ }+ }++ override fun getPrivateKey(alias: String): PrivateKey? {+ if (alias.startsWith(KEYCHAIN_PREFIX)) {+ return try {+ KeyChain.getPrivateKey(context, alias.removePrefix(KEYCHAIN_PREFIX))+ } catch (e: Exception) {+ AppLogger.e(TAG, "KeyChain.getPrivateKey failed", e)+ null+ }+ }+ if (alias != ClientCertSslContextProvider.CLIENT_CERT_ALIAS) {+ AppLogger.w(TAG, "Unexpected alias for getPrivateKey: $alias")+ return null+ }+ return try {+ val ks = KeyStore.getInstance(ANDROID_KEYSTORE).apply { load(null) }+ ks.getKey(alias, null) as? PrivateKey+ } catch (e: Exception) {+ AppLogger.e(TAG, "AndroidKeyStore.getKey failed", e)+ null+ }+ }++ override fun getServerAliases(keyType: String, issuers: Array<Principal>?): Array<String>? = null++ override fun chooseServerAlias(+ keyType: String,+ issuers: Array<Principal>?,+ socket: Socket?,+ ): String? = null++ fun invalidate() {+ synchronized(this) {+ cachedAlias = null+ aliasResolved = false+ }+ }++ private fun hasAndroidKeyStoreEntry(): Boolean = try {+ KeyStore.getInstance(ANDROID_KEYSTORE).apply { load(null) }+ .containsAlias(ClientCertSslContextProvider.CLIENT_CERT_ALIAS)+ } catch (_: Exception) {+ false+ }++ companion object {+ private const val TAG = "DynamicKeyManager"+ private const val ANDROID_KEYSTORE = "AndroidKeyStore"+ const val KEYCHAIN_PREFIX = "keychain:"+ }+}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 78a3ae41..19d15418 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@@ -27,6 +27,8 @@ class SecureStorageHelper private constructor(context: Context) {const val KEY_PASSWORD = "auth_password"const val KEY_BEARER_TOKEN = "auth_bearer_token"const val KEY_CUSTOM_HEADERS = "custom_headers"+ const val KEY_MTLS_SERVER_CA_B64 = "mtls_server_ca_b64"+ const val KEY_MTLS_KEYCHAIN_ALIAS = "mtls_keychain_alias"@Volatileprivate var INSTANCE: SecureStorageHelper? = null@@ -77,6 +79,33 @@ class SecureStorageHelper private constructor(context: Context) {prefs.edit().remove(key).apply()}+ fun hasServerCa(): Boolean = !getString(KEY_MTLS_SERVER_CA_B64, null).isNullOrBlank()++ fun getServerCaBytes(): ByteArray? =+ getString(KEY_MTLS_SERVER_CA_B64, null)?.takeIf { it.isNotBlank() }?.let {+ try { Base64.decode(it, Base64.NO_WRAP) } catch (_: IllegalArgumentException) { null }+ }++ fun setServerCa(bytes: ByteArray) {+ prefs.edit()+ .putString(KEY_MTLS_SERVER_CA_B64, Base64.encodeToString(bytes, Base64.NO_WRAP))+ .apply()+ }++ fun clearServerCa() {+ prefs.edit().remove(KEY_MTLS_SERVER_CA_B64).apply()+ }++ fun getKeyChainAlias(): String? = getString(KEY_MTLS_KEYCHAIN_ALIAS, null)?.takeIf { it.isNotBlank() }++ fun setKeyChainAlias(alias: String) {+ prefs.edit().putString(KEY_MTLS_KEYCHAIN_ALIAS, alias).apply()+ }++ fun clearKeyChainAlias() {+ prefs.edit().remove(KEY_MTLS_KEYCHAIN_ALIAS).apply()+ }+/*** Builds the full set of auth + custom headers for HTTP requests.*/diff --git a/apps/mobile/android/app/src/main/res/xml/network_security_config.xml b/apps/mobile/android/app/src/main/res/xml/network_security_config.xmlindex 65cffa9d..1e493880 100644--- a/apps/mobile/android/app/src/main/res/xml/network_security_config.xml+++ b/apps/mobile/android/app/src/main/res/xml/network_security_config.xml@@ -8,11 +8,16 @@Actual enforcement happens at the app level:- NetworkManager.isValidProtocol() restricts HTTP to private hosts- settingsValidation.isEndpointAllowed() blocks public HTTP endpoints in the UI++ Trust anchors: system only. User-installed device CAs are deliberately+ NOT honored so a malicious or compromised CA on the device can't MITM+ location sync. Self-hosted users with a private CA should import it via+ the mTLS Settings screen -> Trusted Server CA - that path is+ Colota-scoped and backed by Android Keystore.--><base-config cleartextTrafficPermitted="true"><trust-anchors><certificates src="system" />- <certificates src="user" /></trust-anchors></base-config></network-security-config>\ No newline at end of filediff --git a/apps/mobile/android/app/src/test/java/com/Colota/sync/tls/ClientCertSslContextProviderTest.kt b/apps/mobile/android/app/src/test/java/com/Colota/sync/tls/ClientCertSslContextProviderTest.ktnew file mode 100644index 00000000..4e33d8c4--- /dev/null+++ b/apps/mobile/android/app/src/test/java/com/Colota/sync/tls/ClientCertSslContextProviderTest.kt@@ -0,0 +1,90 @@+package com.Colota.sync.tls++import com.Colota.util.AppLogger+import io.mockk.*+import org.junit.After+import org.junit.Assert.*+import org.junit.Before+import org.junit.Test++/**+ * Tests static helpers on [ClientCertSslContextProvider].+ *+ * The instance methods ([get], [invalidate]) depend on a real Android Context+ * for [SecureStorageHelper], so they're exercised via the bridge integration+ * tests rather than here. The AndroidKeyStore-backed paths likewise need a+ * real Android runtime - covered via the test stack rather than unit tests.+ */+class ClientCertSslContextProviderTest {++ @Before+ fun setUp() {+ 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+ }++ @After+ fun tearDown() = unmockkObject(AppLogger)++ @Test+ fun `parseCaInfo extracts subject and issuer from a PEM-encoded self-signed CA`() {+ val info = ClientCertSslContextProvider.parseCaInfo(VALID_CA_PEM_BYTES)+ assertTrue("Subject was: ${info.subject}", info.subject.contains("colota-test-ca"))+ // Self-signed - issuer matches subject+ assertEquals(info.subject, info.issuer)+ assertTrue("Expected notAfter in future", info.notAfter > System.currentTimeMillis())+ }++ @Test+ fun `buildTrustManagers returns a CompositeX509TrustManager backed by user CA + system`() {+ val tms = ClientCertSslContextProvider.buildTrustManagers(VALID_CA_PEM_BYTES)+ assertEquals(1, tms.size)+ val composite = tms[0]+ assertTrue(composite is CompositeX509TrustManager)+ // Composite includes BOTH user CA and system roots. System trust store+ // has many CAs (DigiCert, ISRG Root, etc.); test fixture adds 1.+ val accepted = (composite as CompositeX509TrustManager).acceptedIssuers+ assertTrue("Expected >1 accepted issuer (user CA + system roots), got ${accepted.size}", accepted.size > 1)+ // User CA subject must be in the accepted list+ assertTrue(+ "Test CA not in accepted issuers",+ accepted.any { it.subjectDN.name.contains("colota-test-ca") }+ )+ }++ companion object {+ /**+ * Self-signed CA PEM, 100-year validity, generated via:+ * openssl genrsa -out ca.key 2048+ * openssl req -x509 -new -key ca.key -days 36500 -out ca.crt \+ * -subj "/CN=colota-test-ca/O=Colota Tests"+ *+ * CertificateFactory accepts both PEM and DER; here we exercise PEM.+ */+ val VALID_CA_PEM_BYTES: ByteArray = (+ "-----BEGIN CERTIFICATE-----\n" ++ "MIIDQzCCAiugAwIBAgIUebnL5/SjKZy8pumffhaPHVy2shkwDQYJKoZIhvcNAQEL\n" ++ "BQAwMDEXMBUGA1UEAwwOY29sb3RhLXRlc3QtY2ExFTATBgNVBAoMDENvbG90YSBU\n" ++ "ZXN0czAgFw0yNjA1MTkxMDEwMzFaGA8yMTI2MDQyNTEwMTAzMVowMDEXMBUGA1UE\n" ++ "AwwOY29sb3RhLXRlc3QtY2ExFTATBgNVBAoMDENvbG90YSBUZXN0czCCASIwDQYJ\n" ++ "KoZIhvcNAQEBBQADggEPADCCAQoCggEBALyRH2cUiHIqqcE1mQO/9BxlrAk/ntr3\n" ++ "G/J3tGpinTS6LZfVqe53j5cRwMWzApHXjfYMbQ6YiGvY2bu3CyQMgZtzG1w1JG2H\n" ++ "fDW7jJlLMzgGsKiQh3R01vus6KLQZySSoqJ/s8K7EwwgFQ6ygMvbXv1IeUk9wUyl\n" ++ "+gTiEdFcPB8J5k0sT6Syab8Ykjaj+m2D/BwkwdxyjOXc498ehNbcladn1ZqwrwOL\n" ++ "ht4g/+qy0VXjQkKPDtld302xCf1bE1ryt8LD/MgVmWutZbjtvtxclEFPlxF6QNk2\n" ++ "VoriulO2DZYEJm0PGv3vIoWijmM9vEjzl5/p0kKd1izuilzSLYbCyG8CAwEAAaNT\n" ++ "MFEwHQYDVR0OBBYEFEXdqd97LSttahNgIXLymzeWgj0FMB8GA1UdIwQYMBaAFEXd\n" ++ "qd97LSttahNgIXLymzeWgj0FMA8GA1UdEwEB/wQFMAMBAf8wDQYJKoZIhvcNAQEL\n" ++ "BQADggEBAFQPPvUSnCIT5f7U/4UczRufwJ7iSYFosBW45NpyPI/hgTafM/Han7qh\n" ++ "N5umCfriNsLbQD+WFf1SgS0tNBWJHHKXZb2/i6coXk74KEIYRXoIaN8j+eWJ65hC\n" ++ "HNdcu2SMXIritxrMFgmoE4tVKRdnYZbS+BNdsuzIqFPBuZ/ebu7pv7BU2lChqYkK\n" ++ "4myHDB9LSJMIauWnGqSd4Il2jtx4S2riNE7Tylja9FxdDyKtKrP4ZnRH4FB9sdth\n" ++ "+7i6xIJdzNB6rOl+09/s2JH7NPDgP80fcx5Zq/qvXg+YrMPJsGIpiOAosJOpPwKI\n" ++ "yBJziS89XwtAI6MZEfj1ajNj9Zid4SY=\n" ++ "-----END CERTIFICATE-----\n"+ ).toByteArray()+ }+}diff --git a/apps/mobile/android/app/src/test/java/com/Colota/sync/tls/CompositeX509TrustManagerTest.kt b/apps/mobile/android/app/src/test/java/com/Colota/sync/tls/CompositeX509TrustManagerTest.ktnew file mode 100644index 00000000..3f4a52ca--- /dev/null+++ b/apps/mobile/android/app/src/test/java/com/Colota/sync/tls/CompositeX509TrustManagerTest.kt@@ -0,0 +1,93 @@+package com.Colota.sync.tls++import io.mockk.*+import org.junit.Assert.*+import org.junit.Test+import java.security.cert.CertificateException+import java.security.cert.X509Certificate+import javax.net.ssl.X509TrustManager++/**+ * Pure-logic tests for [CompositeX509TrustManager]. The "any delegate accepts"+ * semantics matter for the user-CA + system-CA layering, so this exercises:+ * - accept-on-first wins+ * - fall-through when an earlier delegate rejects+ * - re-throw of the LAST error when all reject (not the first)+ * - issuer aggregation+ */+class CompositeX509TrustManagerTest {++ private val chain: Array<X509Certificate> = arrayOf(mockk(relaxed = true))+ private val authType = "RSA"++ @Test+ fun `checkServerTrusted returns when first delegate accepts and skips remaining`() {+ val accepting = mockk<X509TrustManager>(relaxed = true)+ val second = mockk<X509TrustManager>(relaxed = true)+ // accepting.checkServerTrusted does not throw (relaxed mock returns Unit)++ CompositeX509TrustManager(listOf(accepting, second))+ .checkServerTrusted(chain, authType)++ verify(exactly = 1) { accepting.checkServerTrusted(chain, authType) }+ verify(exactly = 0) { second.checkServerTrusted(any(), any()) }+ }++ @Test+ fun `checkServerTrusted falls through when first rejects and later accepts`() {+ val rejecting = mockk<X509TrustManager>()+ every { rejecting.checkServerTrusted(any(), any()) } throws CertificateException("system says no")+ val accepting = mockk<X509TrustManager>(relaxed = true)++ // Should not throw+ CompositeX509TrustManager(listOf(rejecting, accepting))+ .checkServerTrusted(chain, authType)++ verify(exactly = 1) { rejecting.checkServerTrusted(any(), any()) }+ verify(exactly = 1) { accepting.checkServerTrusted(any(), any()) }+ }++ @Test+ fun `checkServerTrusted throws the LAST delegate's error when all reject`() {+ val first = mockk<X509TrustManager>()+ every { first.checkServerTrusted(any(), any()) } throws CertificateException("first")+ val second = mockk<X509TrustManager>()+ every { second.checkServerTrusted(any(), any()) } throws CertificateException("last")++ try {+ CompositeX509TrustManager(listOf(first, second)).checkServerTrusted(chain, authType)+ fail("Expected CertificateException")+ } catch (e: CertificateException) {+ assertEquals("last", e.message)+ }+ }++ @Test+ fun `getAcceptedIssuers concatenates issuers from all delegates`() {+ val issuerA = mockk<X509Certificate>(relaxed = true)+ val issuerB = mockk<X509Certificate>(relaxed = true)+ val issuerC = mockk<X509Certificate>(relaxed = true)++ val first = mockk<X509TrustManager>()+ every { first.acceptedIssuers } returns arrayOf(issuerA, issuerB)+ val second = mockk<X509TrustManager>()+ every { second.acceptedIssuers } returns arrayOf(issuerC)++ val accepted = CompositeX509TrustManager(listOf(first, second)).acceptedIssuers++ assertEquals(3, accepted.size)+ assertTrue(accepted.contentEquals(arrayOf(issuerA, issuerB, issuerC)))+ }++ @Test+ fun `checkClientTrusted delegates to the first delegate only`() {+ val first = mockk<X509TrustManager>(relaxed = true)+ val second = mockk<X509TrustManager>(relaxed = true)++ CompositeX509TrustManager(listOf(first, second))+ .checkClientTrusted(chain, authType)++ verify(exactly = 1) { first.checkClientTrusted(chain, authType) }+ verify(exactly = 0) { second.checkClientTrusted(any(), any()) }+ }+}diff --git a/apps/mobile/android/app/src/test/java/com/Colota/util/SecureStorageHelperTest.kt b/apps/mobile/android/app/src/test/java/com/Colota/util/SecureStorageHelperTest.ktindex d633469b..12f2df64 100644--- a/apps/mobile/android/app/src/test/java/com/Colota/util/SecureStorageHelperTest.kt+++ b/apps/mobile/android/app/src/test/java/com/Colota/util/SecureStorageHelperTest.kt@@ -250,4 +250,108 @@ class SecureStorageHelperTest {assertEquals("auth_bearer_token", SecureStorageHelper.KEY_BEARER_TOKEN)assertEquals("custom_headers", SecureStorageHelper.KEY_CUSTOM_HEADERS)}++ // --- mTLS server CA helpers ---++ @Test+ fun `hasServerCa returns false when no CA stored`() {+ every { prefs.getString("mtls_server_ca_b64", null) } returns null+ assertFalse(helper.hasServerCa())+ }++ @Test+ fun `hasServerCa returns true when CA stored`() {+ every { prefs.getString("mtls_server_ca_b64", null) } returns "AAAA"+ assertTrue(helper.hasServerCa())+ }++ @Test+ fun `getServerCaBytes decodes valid base64`() {+ val raw = byteArrayOf(0x05, 0x06, 0x07, 0x08)+ val encoded = java.util.Base64.getEncoder().encodeToString(raw)+ every { prefs.getString("mtls_server_ca_b64", null) } returns encoded++ mockkStatic(Base64::class)+ every { Base64.decode(encoded, Base64.NO_WRAP) } returns raw++ assertArrayEquals(raw, helper.getServerCaBytes())++ unmockkStatic(Base64::class)+ }++ @Test+ fun `setServerCa persists base64 bytes`() {+ val editor = mockk<SharedPreferences.Editor>(relaxed = true)+ every { prefs.edit() } returns editor+ every { editor.putString(any(), any()) } returns editor++ mockkStatic(Base64::class)+ every { Base64.encodeToString(any(), Base64.NO_WRAP) } answers {+ java.util.Base64.getEncoder().encodeToString(firstArg())+ }++ helper.setServerCa(byteArrayOf(0x0C, 0x0D))++ val expected = java.util.Base64.getEncoder().encodeToString(byteArrayOf(0x0C, 0x0D))+ verify { editor.putString("mtls_server_ca_b64", expected) }+ verify { editor.apply() }++ unmockkStatic(Base64::class)+ }++ @Test+ fun `clearServerCa removes the key`() {+ val editor = mockk<SharedPreferences.Editor>(relaxed = true)+ every { prefs.edit() } returns editor+ every { editor.remove(any()) } returns editor++ helper.clearServerCa()++ verify { editor.remove("mtls_server_ca_b64") }+ verify { editor.apply() }+ }++ // --- KeyChain alias storage ---++ @Test+ fun `getKeyChainAlias returns null when unset`() {+ every { prefs.getString("mtls_keychain_alias", null) } returns null+ assertNull(helper.getKeyChainAlias())+ }++ @Test+ fun `getKeyChainAlias returns null when stored value is blank`() {+ every { prefs.getString("mtls_keychain_alias", null) } returns ""+ assertNull(helper.getKeyChainAlias())+ }++ @Test+ fun `getKeyChainAlias returns the stored alias`() {+ every { prefs.getString("mtls_keychain_alias", null) } returns "colota-cert"+ assertEquals("colota-cert", helper.getKeyChainAlias())+ }++ @Test+ fun `setKeyChainAlias persists the alias string`() {+ val editor = mockk<SharedPreferences.Editor>(relaxed = true)+ every { prefs.edit() } returns editor+ every { editor.putString(any(), any()) } returns editor++ helper.setKeyChainAlias("colota-cert")++ verify { editor.putString("mtls_keychain_alias", "colota-cert") }+ verify { editor.apply() }+ }++ @Test+ fun `clearKeyChainAlias removes the key`() {+ val editor = mockk<SharedPreferences.Editor>(relaxed = true)+ every { prefs.edit() } returns editor+ every { editor.remove(any()) } returns editor++ helper.clearKeyChainAlias()++ verify { editor.remove("mtls_keychain_alias") }+ verify { editor.apply() }+ }}diff --git a/apps/mobile/src/components/features/settings/ConnectionSettings.tsx b/apps/mobile/src/components/features/settings/ConnectionSettings.tsxindex 2cdde300..dba76e6b 100644--- a/apps/mobile/src/components/features/settings/ConnectionSettings.tsx+++ b/apps/mobile/src/components/features/settings/ConnectionSettings.tsx@@ -9,17 +9,12 @@ import { CheckCircle, ChevronRight } from "lucide-react-native"import { Settings, ThemeColors } from "../../../types/global"import NativeLocationService from "../../../services/NativeLocationService"import { isEndpointAllowed } from "../../../utils/settingsValidation"-import {- buildTraccarJsonPayload,- buildOverlandBatchPayload,- isTraccarJsonFormat,- isOverlandFormat-} from "../../../utils/apiPayload"+import { isTraccarJsonFormat, isOverlandFormat } from "../../../utils/apiPayload"import { ensureLocalNetworkPermission } from "../../../services/LocationServicePermission"import { fonts } from "../../../styles/typography"import { SettingRow } from "../../ui/SettingRow"import { useTimeout } from "../../../hooks/useTimeout"-import { CONNECTION_TEST_TIMEOUT, TEST_RESULT_DISPLAY_MS } from "../../../constants"+import { TEST_RESULT_DISPLAY_MS } from "../../../constants"import { logger } from "../../../utils/logger"import { Button, Card, SectionTitle, Divider, FieldMessage } from "../../index"import { showChoice } from "../../../services/modalService"@@ -132,7 +127,6 @@ export function ConnectionSettings({payload[fieldMap.lon] = recentLocation.longitudepayload[fieldMap.acc] = Math.round(recentLocation.accuracy)- // Optional fields with real values from the locationif (fieldMap.alt) payload[fieldMap.alt] = recentLocation.altitude ?? 0if (fieldMap.vel) payload[fieldMap.vel] = recentLocation.speed ?? 0if (fieldMap.batt) payload[fieldMap.batt] = recentLocation.battery ?? 0@@ -140,13 +134,6 @@ export function ConnectionSettings({if (fieldMap.bear) payload[fieldMap.bear] = recentLocation.bearing ?? 0if (fieldMap.tst) payload[fieldMap.tst] = Math.floor(Date.now() / 1000)- const protocolAllowed = await NativeLocationService.isValidEndpointProtocol(endpointInput)- if (!protocolAllowed) {- setTestResponse("HTTPS is required for public endpoints. HTTP is only allowed for private/local addresses.")- setTestError(true)- return- }-const isPrivate = await NativeLocationService.isPrivateEndpoint(endpointInput)if (isPrivate) {const granted = await ensureLocalNetworkPermission()@@ -157,78 +144,36 @@ export function ConnectionSettings({}}- let authHeaders: Record<string, string> = {}- try {- authHeaders = await NativeLocationService.getAuthHeaders()- } catch {- // proceed without auth headers- }-const method = settings.httpMethod ?? "POST"const isTraccarJson = isTraccarJsonFormat(settings.apiTemplate, method)const isOverland = isOverlandFormat(settings.apiTemplate, settings.dawarichMode ?? "single")+ const apiFormat = isTraccarJson ? "traccar_json" : isOverland ? "overland_batch" : ""- let body: object = payload- if (isOverland) {- body = buildOverlandBatchPayload({- latitude: recentLocation.latitude,- longitude: recentLocation.longitude,- accuracy: Math.round(recentLocation.accuracy),- altitude: recentLocation.altitude ?? 0,- speed: recentLocation.speed ?? 0,- course: recentLocation.bearing ?? 0,- batteryLevel: (recentLocation.battery ?? 0) / 100,- batteryState: "unplugged",- deviceId:- settings.customFields.find((f) => f.key === "device_id" || f.key === "tid" || f.key === "id")?.value ??- "colota"- })- } else if (isTraccarJson) {- body = buildTraccarJsonPayload({- latitude: recentLocation.latitude,- longitude: recentLocation.longitude,- accuracy: recentLocation.accuracy,- altitude: recentLocation.altitude ?? 0,- speed: recentLocation.speed ?? 0,- heading: recentLocation.bearing ?? 0,- batteryLevel: (recentLocation.battery ?? 0) / 100,- isCharging: false,- deviceId: settings.customFields.find((f) => f.key === "device_id")?.value ?? "colota"- })+ const customFields: Record<string, string> = {}+ for (const { key, value } of settings.customFields) {+ if (key) customFields[key] = value}- const params = new URLSearchParams(Object.entries(payload).map(([k, v]) => [k, String(v)]))- const url =- method === "GET" ? `${endpointInput}${endpointInput.includes("?") ? "&" : "?"}${params}` : endpointInput- const controller = new AbortController()- timeout.set(() => controller.abort(), CONNECTION_TEST_TIMEOUT)- const response = await fetch(url, {++ const result = await NativeLocationService.testEndpoint({+ endpoint: endpointInput,method,- headers: method === "GET" ? authHeaders : { "Content-Type": "application/json", ...authHeaders },- ...(method === "GET" ? {} : { body: JSON.stringify(body) }),- signal: controller.signal+ apiFormat,+ payload,+ customFields})- timeout.clear()- if (response.ok) {+ if (result.ok) {setTestResponse("Connection successful")onSettingsChange({ ...settings, endpoint: endpointInput })} else {- logger.warn("[ConnectionSettings] Test failed: HTTP", response.status)- setTestResponse(`Server returned ${response.status} ${response.statusText || ""}`.trim())+ logger.warn("[ConnectionSettings] Test failed:", result.status, result.errorMessage)+ setTestResponse(result.errorMessage || `Server returned ${result.status}`)setTestError(true)}} catch (err: any) {- const msg = err.message || ""- let userMessage: string- if (err.name === "AbortError") {- userMessage = `Connection timed out - server did not respond within ${CONNECTION_TEST_TIMEOUT / 1000}s`- } else if (msg.toLowerCase().includes("network request failed")) {- userMessage = "Network request failed - check your URL, connection, and SSL certificate"- } else {- userMessage = `Connection failed: ${msg || "Unknown error"}`- }- logger.warn("[ConnectionSettings] Test failed:", err.name, msg)- setTestResponse(userMessage)+ const msg = err?.message || "Unknown error"+ logger.warn("[ConnectionSettings] Test failed:", err?.name, msg)+ setTestResponse(`Connection failed: ${msg}`)setTestError(true)} finally {setTesting(false)diff --git a/apps/mobile/src/components/features/settings/MtlsSection.tsx b/apps/mobile/src/components/features/settings/MtlsSection.tsxnew file mode 100644index 00000000..f6bf5a64--- /dev/null+++ b/apps/mobile/src/components/features/settings/MtlsSection.tsx@@ -0,0 +1,374 @@+/**+ * Copyright (C) 2026 Max Dietrich+ * Licensed under the GNU AGPLv3. See LICENSE in the project root for details.+ */++import React, { useState, useCallback, useEffect } from "react"+import { Text, StyleSheet, TextInput, View } from "react-native"+import { useTheme } from "../../../hooks/useTheme"+import { fonts, fontSizes } from "../../../styles/typography"+import { SectionTitle, Card, Divider, Button, FieldMessage } from "../../index"+import NativeLocationService from "../../../services/NativeLocationService"+import { ClientCertInfoResult } from "../../../types/global"+import { logger } from "../../../utils/logger"++const EXPIRY_WARNING_DAYS = 14++const CLIENT_CERT_ERR: Record<string, string> = {+ E_CERT_PASSWORD: "Incorrect password",+ E_CERT_INVALID: "Not a valid PKCS12 file"+}+const SERVER_CA_ERR: Record<string, string> = {+ E_CA_READ: "Could not read the selected file. Try a smaller file or pick again.",+ E_CA_INVALID: "Not a valid X.509 certificate. Make sure you're picking the CA cert (PEM or DER)."+}++function errMsg(map: Record<string, string>, err: any, fallback: string): string {+ return map[err?.code] ?? err?.message ?? fallback+}++type ImportState =+ | { kind: "idle" }+ | { kind: "picked"; b64: string; password: string; importing: boolean; error: string | null }++export function MtlsSection() {+ const { colors } = useTheme()+ const [certInfo, setCertInfo] = useState<ClientCertInfoResult | null>(null)+ const [caInfo, setCaInfo] = useState<ClientCertInfoResult | null>(null)+ const [importState, setImportState] = useState<ImportState>({ kind: "idle" })+ const [clientPickError, setClientPickError] = useState<string | null>(null)+ const [caError, setCaError] = useState<string | null>(null)++ const refresh = useCallback(async () => {+ try {+ const [client, ca] = await Promise.all([+ NativeLocationService.getClientCertInfo(),+ NativeLocationService.getServerCaInfo()+ ])+ setCertInfo(client)+ setCaInfo(ca)+ } catch (err) {+ logger.error("[MtlsSection] getClientCertInfo/getServerCaInfo failed:", err)+ setCertInfo({ configured: false })+ setCaInfo({ configured: false })+ }+ }, [])++ useEffect(() => {+ refresh()+ }, [refresh])++ const handlePickServerCa = useCallback(async () => {+ setCaError(null)+ try {+ const b64 = await NativeLocationService.pickServerCaFile()+ if (!b64) return+ await NativeLocationService.importServerCa(b64)+ await refresh()+ } catch (err: any) {+ logger.error("[MtlsSection] importServerCa failed:", err)+ setCaError(errMsg(SERVER_CA_ERR, err, "Could not import the CA"))+ }+ }, [refresh])++ const handleClearServerCa = useCallback(async () => {+ try {+ await NativeLocationService.clearServerCa()+ await refresh()+ } catch (err) {+ logger.error("[MtlsSection] clearServerCa failed:", err)+ }+ }, [refresh])++ const handlePickKeyChain = useCallback(async () => {+ setClientPickError(null)+ try {+ const result = await NativeLocationService.pickKeyChainCert()+ if (!result) return // user cancelled+ await refresh()+ } catch (err: any) {+ logger.error("[MtlsSection] pickKeyChainCert failed:", err)+ setClientPickError(err?.message || "Could not read the selected certificate")+ }+ }, [refresh])++ const handlePickFile = useCallback(async () => {+ setClientPickError(null)+ try {+ const b64 = await NativeLocationService.pickClientCertFile()+ if (!b64) return // user cancelled+ setImportState({ kind: "picked", b64, password: "", importing: false, error: null })+ } catch (err: any) {+ logger.error("[MtlsSection] pick failed:", err)+ setClientPickError(err?.message || "Could not read the selected file")+ }+ }, [])++ const handleImport = useCallback(async () => {+ if (importState.kind !== "picked" || !importState.b64) return+ setImportState({ ...importState, importing: true, error: null })+ try {+ await NativeLocationService.importClientCert(importState.b64, importState.password)+ setImportState({ kind: "idle" })+ await refresh()+ } catch (err: any) {+ setImportState({ ...importState, importing: false, error: errMsg(CLIENT_CERT_ERR, err, "Import failed") })+ }+ }, [importState, refresh])++ const handleCancelImport = useCallback(() => {+ setImportState({ kind: "idle" })+ }, [])++ const handleRemove = useCallback(async () => {+ try {+ await NativeLocationService.clearClientCert()+ await refresh()+ } catch (err) {+ logger.error("[MtlsSection] clear failed:", err)+ }+ }, [refresh])++ if (certInfo === null || caInfo === null) {+ return (+ <View style={styles.section}>+ <SectionTitle>Client Certificate (mTLS)</SectionTitle>+ <Card>+ <Text style={[styles.muted, { color: colors.textSecondary }]}>Loading...</Text>+ </Card>+ </View>+ )+ }++ return (+ <>+ <View style={styles.section}>+ <SectionTitle>Client Certificate (mTLS)</SectionTitle>+ <Card>+ {importState.kind === "picked" ? (+ <View>+ <Text style={[styles.fieldLabel, { color: colors.text }]}>Password (leave empty if none)</Text>+ <TextInput+ style={[+ styles.input,+ {+ borderColor: colors.border,+ color: colors.text,+ backgroundColor: colors.background+ }+ ]}+ value={importState.password}+ onChangeText={(v) => setImportState({ ...importState, password: v, error: null })}+ placeholder="PKCS12 password"+ placeholderTextColor={colors.placeholder}+ autoCapitalize="none"+ autoCorrect={false}+ secureTextEntry+ editable={!importState.importing}+ />+ {importState.error && <FieldMessage variant="error">{importState.error}</FieldMessage>}+ <View style={styles.buttonRow}>+ <Button+ style={styles.flex1}+ onPress={handleImport}+ title={importState.importing ? "Importing..." : "Save"}+ />+ <Button+ variant="secondary"+ title="Cancel"+ onPress={handleCancelImport}+ disabled={importState.importing}+ />+ </View>+ </View>+ ) : certInfo.configured ? (+ <CertCard+ info={certInfo}+ showIssuer+ expiryWarningDays={EXPIRY_WARNING_DAYS}+ removeLabel="Remove Certificate"+ expiredMessage="Certificate has expired. Server will reject connections."+ expiringSoonMessage={(d) => `Certificate expires in ${d} day(s). Renew soon.`}+ errorPrefix="Stored certificate could not be read"+ onRemove={handleRemove}+ onReimport={handlePickFile}+ />+ ) : (+ <View>+ <Text style={[styles.muted, { color: colors.textSecondary }]}>+ No client certificate configured. Required if your server enforces mutual TLS authentication.+ </Text>+ <Button style={styles.importButton} onPress={handlePickKeyChain} title="Pick from device certificates" />+ <FieldMessage>+ Uses a cert already installed in Android (private key stays in the OS keystore).+ </FieldMessage>+ <Button style={styles.importButton} onPress={handlePickFile} title="Import .p12 / .pfx" />+ {clientPickError && <FieldMessage variant="error">{clientPickError}</FieldMessage>}+ </View>+ )}+ </Card>+ </View>++ <View style={styles.section}>+ <SectionTitle>Trusted Server CA</SectionTitle>+ <Card>+ {caInfo.configured ? (+ <CertCard+ info={caInfo}+ showIssuer={false}+ expiryWarningDays={EXPIRY_WARNING_DAYS}+ removeLabel="Remove CA"+ expiredMessage="CA has expired. Server cert validation will fail."+ expiringSoonMessage={(d) => `CA expires in ${d} day(s). Renew soon.`}+ errorPrefix="Stored CA could not be read"+ onRemove={handleClearServerCa}+ onReimport={handlePickServerCa}+ />+ ) : (+ <View>+ <Text style={[styles.muted, { color: colors.textSecondary }]}>+ Only needed if your server uses a private / self-signed CA that public Android trust store doesn't know+ about. Publicly-trusted certs (Let's Encrypt, Cloudflare) work without this.+ </Text>+ <Button style={styles.importButton} onPress={handlePickServerCa} title="Import CA (.crt / .pem)" />+ {caError && <FieldMessage variant="error">{caError}</FieldMessage>}+ </View>+ )}+ </Card>+ </View>+ </>+ )+}++type CertCardProps = {+ info: Extract<ClientCertInfoResult, { configured: true }>+ showIssuer: boolean+ expiryWarningDays: number+ removeLabel: string+ expiredMessage: string+ expiringSoonMessage: (days: number) => string+ errorPrefix: string+ onRemove: () => void+ onReimport: () => void+}++function CertCard({+ info,+ showIssuer,+ expiryWarningDays,+ removeLabel,+ expiredMessage,+ expiringSoonMessage,+ errorPrefix,+ onRemove,+ onReimport+}: CertCardProps) {+ const issuerMissing = showIssuer && !info.issuer+ if (info.error || !info.notAfter || !info.subject || issuerMissing) {+ return (+ <View>+ <FieldMessage variant="error">+ {errorPrefix}: {info.error || "missing fields"}. Re-import to fix.+ </FieldMessage>+ <View style={styles.buttonRow}>+ <Button style={styles.flex1} onPress={onReimport} title="Re-import" />+ <Button variant="danger" title="Remove" onPress={onRemove} />+ </View>+ </View>+ )+ }++ const notAfterDate = new Date(info.notAfter)+ const daysUntilExpiry = Math.floor((info.notAfter - Date.now()) / (1000 * 60 * 60 * 24))+ const expired = daysUntilExpiry < 0+ const expiringSoon = !expired && daysUntilExpiry < expiryWarningDays++ return (+ <View>+ <DetailRow label="Subject" value={shortenDn(info.subject)} />+ {showIssuer && info.issuer && (+ <>+ <Divider />+ <DetailRow label="Issuer" value={shortenDn(info.issuer)} />+ </>+ )}+ <Divider />+ <DetailRow+ label="Expires"+ value={`${notAfterDate.toISOString().slice(0, 10)} (${expired ? "expired" : `in ${daysUntilExpiry}d`})`}+ />+ {expired && <FieldMessage variant="error">{expiredMessage}</FieldMessage>}+ {expiringSoon && <FieldMessage variant="warning">{expiringSoonMessage(daysUntilExpiry)}</FieldMessage>}+ <View style={styles.buttonRow}>+ <Button style={styles.flex1} variant="danger" title={removeLabel} onPress={onRemove} />+ </View>+ </View>+ )+}++function DetailRow({ label, value }: { label: string; value: string }) {+ const { colors } = useTheme()+ return (+ <View style={styles.detailRow}>+ <Text style={[styles.detailLabel, { color: colors.textSecondary }]}>{label}</Text>+ <Text style={[styles.detailValue, { color: colors.text }]} numberOfLines={1} ellipsizeMode="middle">+ {value}+ </Text>+ </View>+ )+}++/**+ * X.500 DNs come back like "CN=foo,O=bar,C=US". Surface CN if present, otherwise+ * the whole thing - users care about identity, not DN parser fidelity.+ */+function shortenDn(dn: string): string {+ const cn = dn.split(",").find((p) => p.trim().toLowerCase().startsWith("cn="))+ return cn ? cn.trim().slice(3) : dn+}++const styles = StyleSheet.create({+ section: {+ marginBottom: 24+ },+ muted: {+ fontSize: 13,+ ...fonts.regular,+ lineHeight: 18+ },+ fieldLabel: {+ fontSize: fontSizes.label,+ ...fonts.semiBold,+ marginBottom: 8+ },+ input: {+ borderWidth: 1.5,+ padding: 14,+ borderRadius: 12,+ fontSize: 15+ },+ importButton: {+ marginTop: 12+ },+ buttonRow: {+ flexDirection: "row",+ gap: 8,+ marginTop: 12,+ alignItems: "center"+ },+ flex1: {+ flex: 1+ },+ detailRow: {+ paddingVertical: 10+ },+ detailLabel: {+ fontSize: 12,+ ...fonts.medium,+ marginBottom: 2+ },+ detailValue: {+ fontSize: 14,+ ...fonts.regular+ }+})diff --git a/apps/mobile/src/components/features/settings/__tests__/ConnectionSettings.test.tsx b/apps/mobile/src/components/features/settings/__tests__/ConnectionSettings.test.tsxindex 870631e9..25780e69 100644--- a/apps/mobile/src/components/features/settings/__tests__/ConnectionSettings.test.tsx+++ b/apps/mobile/src/components/features/settings/__tests__/ConnectionSettings.test.tsx@@ -51,10 +51,8 @@ const mockGetStats = jest.fn().mockResolvedValue({ queued: 0, sent: 0, total: 0,const mockManualFlush = jest.fn().mockResolvedValue(undefined)const mockClearQueue = jest.fn().mockResolvedValue(5)const mockGetMostRecentLocation = jest.fn().mockResolvedValue(null)-const mockGetAuthHeaders = jest.fn().mockResolvedValue({})-const mockIsNetworkAvailable = jest.fn().mockResolvedValue(true)-const mockIsValidEndpointProtocol = jest.fn().mockResolvedValue(true)const mockIsEndpointPrivate = jest.fn().mockResolvedValue(false)+const mockTestEndpoint = jest.fn().mockResolvedValue({ ok: true, status: 200 })jest.mock("../../../../services/NativeLocationService", () => ({__esModule: true,@@ -63,10 +61,8 @@ jest.mock("../../../../services/NativeLocationService", () => ({manualFlush: (...args: any[]) => mockManualFlush(...args),clearQueue: (...args: any[]) => mockClearQueue(...args),getMostRecentLocation: (...args: any[]) => mockGetMostRecentLocation(...args),- getAuthHeaders: (...args: any[]) => mockGetAuthHeaders(...args),- isNetworkAvailable: (...args: any[]) => mockIsNetworkAvailable(...args),- isValidEndpointProtocol: (...args: any[]) => mockIsValidEndpointProtocol(...args),- isPrivateEndpoint: (...args: any[]) => mockIsEndpointPrivate(...args)+ isPrivateEndpoint: (...args: any[]) => mockIsEndpointPrivate(...args),+ testEndpoint: (...args: any[]) => mockTestEndpoint(...args)}}))@@ -327,9 +323,13 @@ describe("ConnectionSettings", () => {bearing: 0}- it("blocks when native protocol check rejects endpoint", async () => {+ it("shows native error message when testEndpoint rejects the protocol", async () => {mockGetMostRecentLocation.mockResolvedValue(location)- mockIsValidEndpointProtocol.mockResolvedValue(false)+ mockTestEndpoint.mockResolvedValue({+ ok: false,+ status: 0,+ errorMessage: "HTTPS is required for public endpoints. HTTP is only allowed for private/local addresses."+ })const { getByText } = renderComponent({}, "http://example.com/api")fireEvent.press(getByText("Test Connection"))@@ -339,15 +339,31 @@ describe("ConnectionSettings", () => {})})- it("allows when native protocol check accepts endpoint", async () => {+ it("shows success message when testEndpoint reports ok", async () => {+ mockGetMostRecentLocation.mockResolvedValue(location)+ mockTestEndpoint.mockResolvedValue({ ok: true, status: 200 })+ const { getByText } = renderComponent({}, "https://example.com/api")++ fireEvent.press(getByText("Test Connection"))++ await waitFor(() => {+ expect(getByText("Connection successful")).toBeTruthy()+ })+ })++ it("surfaces mTLS handshake error from native", async () => {mockGetMostRecentLocation.mockResolvedValue(location)- mockIsValidEndpointProtocol.mockResolvedValue(true)- const { queryByText, getByText } = renderComponent({}, "https://example.com/api")+ mockTestEndpoint.mockResolvedValue({+ ok: false,+ status: 0,+ errorMessage: "TLS handshake failed - server rejected client certificate or cert is expired"+ })+ const { getByText } = renderComponent({}, "https://example.com/api")fireEvent.press(getByText("Test Connection"))await waitFor(() => {- expect(queryByText(/HTTPS is required/)).toBeNull()+ expect(getByText(/TLS handshake failed/)).toBeTruthy()})})})diff --git a/apps/mobile/src/components/features/settings/__tests__/MtlsSection.test.tsx b/apps/mobile/src/components/features/settings/__tests__/MtlsSection.test.tsxnew file mode 100644index 00000000..eecb8b99--- /dev/null+++ b/apps/mobile/src/components/features/settings/__tests__/MtlsSection.test.tsx@@ -0,0 +1,334 @@+import React from "react"+import { render, fireEvent, waitFor } from "@testing-library/react-native"++jest.mock("../../../index", () => {+ const R = require("react")+ const { View, Text, Pressable } = require("react-native")+ return {+ SectionTitle: ({ children }: any) => R.createElement(Text, null, children),+ Card: ({ children }: any) => R.createElement(View, null, children),+ Divider: () => R.createElement(View, null),+ Button: ({ title, onPress, disabled }: any) =>+ R.createElement(+ Pressable,+ { onPress, disabled, accessibilityRole: "button" },+ R.createElement(Text, null, title)+ ),+ FieldMessage: ({ children }: any) => R.createElement(Text, null, children)+ }+})++jest.mock("../../../../hooks/useTheme", () => ({+ useTheme: () => ({+ colors: {+ text: "#000",+ textSecondary: "#666",+ textLight: "#999",+ background: "#fff",+ border: "#ddd",+ placeholder: "#999",+ error: "#f00",+ warning: "#f80",+ success: "#0a0",+ pressedOpacity: 0.7+ }+ })+}))++jest.mock("../../../../utils/logger", () => ({+ logger: { error: jest.fn(), warn: jest.fn(), info: jest.fn(), debug: jest.fn() }+}))++const mockGetClientCertInfo = jest.fn().mockResolvedValue({ configured: false })+const mockGetServerCaInfo = jest.fn().mockResolvedValue({ configured: false })+const mockPickClientCertFile = jest.fn().mockResolvedValue(null)+const mockPickKeyChainCert = jest.fn().mockResolvedValue(null)+const mockImportClientCert = jest.fn().mockResolvedValue({})+const mockClearClientCert = jest.fn().mockResolvedValue(true)+const mockPickServerCaFile = jest.fn().mockResolvedValue(null)+const mockImportServerCa = jest.fn().mockResolvedValue({})+const mockClearServerCa = jest.fn().mockResolvedValue(true)++jest.mock("../../../../services/NativeLocationService", () => ({+ __esModule: true,+ default: {+ getClientCertInfo: (...a: any[]) => mockGetClientCertInfo(...a),+ getServerCaInfo: (...a: any[]) => mockGetServerCaInfo(...a),+ pickClientCertFile: (...a: any[]) => mockPickClientCertFile(...a),+ pickKeyChainCert: (...a: any[]) => mockPickKeyChainCert(...a),+ importClientCert: (...a: any[]) => mockImportClientCert(...a),+ clearClientCert: (...a: any[]) => mockClearClientCert(...a),+ pickServerCaFile: (...a: any[]) => mockPickServerCaFile(...a),+ importServerCa: (...a: any[]) => mockImportServerCa(...a),+ clearServerCa: (...a: any[]) => mockClearServerCa(...a)+ }+}))++import { MtlsSection } from "../MtlsSection"++const ONE_DAY_MS = 24 * 60 * 60 * 1000++describe("MtlsSection", () => {+ beforeEach(() => {+ jest.clearAllMocks()+ mockGetClientCertInfo.mockResolvedValue({ configured: false })+ mockGetServerCaInfo.mockResolvedValue({ configured: false })+ })++ describe("loading + empty states", () => {+ it("shows Loading text before the initial info fetch resolves", () => {+ // Pending promises so refresh() doesn't complete before the render assertion+ mockGetClientCertInfo.mockReturnValue(new Promise(() => {}))+ mockGetServerCaInfo.mockReturnValue(new Promise(() => {}))+ const { getByText } = render(<MtlsSection />)+ expect(getByText("Loading...")).toBeTruthy()+ })++ it("renders both empty-state sections with their action buttons", async () => {+ const { getByText } = render(<MtlsSection />)+ await waitFor(() => {+ expect(getByText("Pick from device certificates")).toBeTruthy()+ expect(getByText("Import .p12 / .pfx")).toBeTruthy()+ expect(getByText("Import CA (.crt / .pem)")).toBeTruthy()+ })+ })+ })++ describe("client cert: KeyChain pick", () => {+ it("refreshes info after a successful KeyChain pick", async () => {+ mockPickKeyChainCert.mockResolvedValueOnce({ configured: true, subject: "CN=picked" })+ mockGetClientCertInfo.mockResolvedValueOnce({ configured: false }).mockResolvedValueOnce({+ configured: true,+ subject: "CN=picked",+ issuer: "CN=Test CA",+ notBefore: Date.now() - ONE_DAY_MS,+ notAfter: Date.now() + 365 * ONE_DAY_MS,+ source: "keychain"+ })++ const { getByText } = render(<MtlsSection />)+ await waitFor(() => expect(getByText("Pick from device certificates")).toBeTruthy())+ fireEvent.press(getByText("Pick from device certificates"))++ await waitFor(() => {+ expect(mockPickKeyChainCert).toHaveBeenCalled()+ expect(mockGetClientCertInfo).toHaveBeenCalledTimes(2)+ })+ })++ it("does not refresh when the user cancels the KeyChain picker", async () => {+ const { getByText } = render(<MtlsSection />)+ await waitFor(() => getByText("Pick from device certificates"))+ fireEvent.press(getByText("Pick from device certificates"))+ await waitFor(() => expect(mockPickKeyChainCert).toHaveBeenCalled())+ // Only the initial info fetch, no second refresh+ expect(mockGetClientCertInfo).toHaveBeenCalledTimes(1)+ })+ })++ describe("client cert: PKCS12 import", () => {+ it("shows password field after picking a .p12 file", async () => {+ mockPickClientCertFile.mockResolvedValueOnce("base64bytes")+ const { getByText, getByPlaceholderText } = render(<MtlsSection />)+ await waitFor(() => getByText("Import .p12 / .pfx"))+ fireEvent.press(getByText("Import .p12 / .pfx"))++ await waitFor(() => {+ expect(getByText("Password (leave empty if none)")).toBeTruthy()+ expect(getByPlaceholderText("PKCS12 password")).toBeTruthy()+ expect(getByText("Save")).toBeTruthy()+ expect(getByText("Cancel")).toBeTruthy()+ })+ })++ it("surfaces wrong-password error inline without persisting state", async () => {+ mockPickClientCertFile.mockResolvedValueOnce("base64bytes")+ mockImportClientCert.mockRejectedValueOnce({ code: "E_CERT_PASSWORD", message: "bad password" })++ const { getByText, getByPlaceholderText } = render(<MtlsSection />)+ await waitFor(() => getByText("Import .p12 / .pfx"))+ fireEvent.press(getByText("Import .p12 / .pfx"))+ await waitFor(() => getByText("Save"))+ fireEvent.changeText(getByPlaceholderText("PKCS12 password"), "wrong")+ fireEvent.press(getByText("Save"))++ await waitFor(() => expect(getByText("Incorrect password")).toBeTruthy())+ // Still in picked state - user can retry without re-picking file+ expect(getByText("Save")).toBeTruthy()+ })++ it("surfaces invalid-PKCS12 error inline", async () => {+ mockPickClientCertFile.mockResolvedValueOnce("base64bytes")+ mockImportClientCert.mockRejectedValueOnce({ code: "E_CERT_INVALID", message: "not pkcs12" })++ const { getByText, getByPlaceholderText } = render(<MtlsSection />)+ await waitFor(() => getByText("Import .p12 / .pfx"))+ fireEvent.press(getByText("Import .p12 / .pfx"))+ await waitFor(() => getByText("Save"))+ fireEvent.changeText(getByPlaceholderText("PKCS12 password"), "any")+ fireEvent.press(getByText("Save"))++ await waitFor(() => expect(getByText("Not a valid PKCS12 file")).toBeTruthy())+ })++ it("Cancel returns to the empty state", async () => {+ mockPickClientCertFile.mockResolvedValueOnce("base64bytes")+ const { getByText, queryByText } = render(<MtlsSection />)+ await waitFor(() => getByText("Import .p12 / .pfx"))+ fireEvent.press(getByText("Import .p12 / .pfx"))+ await waitFor(() => getByText("Save"))++ fireEvent.press(getByText("Cancel"))++ await waitFor(() => {+ expect(queryByText("Save")).toBeNull()+ expect(getByText("Pick from device certificates")).toBeTruthy()+ })+ })+ })++ describe("client cert: configured state", () => {+ it("renders subject, issuer and shows expiry date", async () => {+ const notAfter = Date.now() + 320 * ONE_DAY_MS+ mockGetClientCertInfo.mockResolvedValue({+ configured: true,+ subject: "CN=colota-test-client,O=Colota",+ issuer: "CN=Test CA",+ notBefore: Date.now() - ONE_DAY_MS,+ notAfter,+ source: "p12"+ })++ const { getByText } = render(<MtlsSection />)+ await waitFor(() => {+ // shortenDn strips down to just the CN value+ expect(getByText("colota-test-client")).toBeTruthy()+ expect(getByText("Remove Certificate")).toBeTruthy()+ })+ })++ it("shows the expiring-soon warning when within EXPIRY_WARNING_DAYS", async () => {+ const notAfter = Date.now() + 5 * ONE_DAY_MS+ mockGetClientCertInfo.mockResolvedValue({+ configured: true,+ subject: "CN=expiring",+ issuer: "CN=Test CA",+ notBefore: Date.now() - ONE_DAY_MS,+ notAfter+ })+ const { getByText } = render(<MtlsSection />)+ await waitFor(() => expect(getByText(/Certificate expires in \d+ day/)).toBeTruthy())+ })++ it("shows the expired error when notAfter is in the past", async () => {+ mockGetClientCertInfo.mockResolvedValue({+ configured: true,+ subject: "CN=stale",+ issuer: "CN=Test CA",+ notBefore: Date.now() - 365 * ONE_DAY_MS,+ notAfter: Date.now() - ONE_DAY_MS+ })+ const { getByText } = render(<MtlsSection />)+ await waitFor(() => expect(getByText(/Certificate has expired/)).toBeTruthy())+ })+ })++ describe("server CA section", () => {+ it("renders the empty-state Import CA button + helper text", async () => {+ const { getByText } = render(<MtlsSection />)+ await waitFor(() => {+ expect(getByText("Trusted Server CA")).toBeTruthy()+ expect(getByText("Import CA (.crt / .pem)")).toBeTruthy()+ })+ })++ it("shows friendly error when picker reports file-too-large (E_CA_READ)", async () => {+ mockPickServerCaFile.mockRejectedValueOnce({ code: "E_CA_READ", message: "File too large" })+ const { getByText } = render(<MtlsSection />)+ await waitFor(() => getByText("Import CA (.crt / .pem)"))+ fireEvent.press(getByText("Import CA (.crt / .pem)"))+ await waitFor(() => expect(getByText(/Could not read the selected file/)).toBeTruthy())+ })++ it("shows friendly error when imported file is not a valid X.509", async () => {+ mockPickServerCaFile.mockResolvedValueOnce("notACert")+ mockImportServerCa.mockRejectedValueOnce({ code: "E_CA_INVALID", message: "parse error" })++ const { getByText } = render(<MtlsSection />)+ await waitFor(() => getByText("Import CA (.crt / .pem)"))+ fireEvent.press(getByText("Import CA (.crt / .pem)"))+ await waitFor(() => expect(getByText(/Not a valid X\.509 certificate/)).toBeTruthy())+ })++ it("renders configured state with Remove CA action", async () => {+ mockGetServerCaInfo.mockResolvedValue({+ configured: true,+ subject: "CN=Colota Test CA",+ issuer: "CN=Colota Test CA",+ notBefore: Date.now() - ONE_DAY_MS,+ notAfter: Date.now() + 1000 * ONE_DAY_MS+ })+ const { getByText } = render(<MtlsSection />)+ await waitFor(() => {+ expect(getByText("Colota Test CA")).toBeTruthy()+ expect(getByText("Remove CA")).toBeTruthy()+ })+ })++ it("shows expired CA error when notAfter is in the past", async () => {+ mockGetServerCaInfo.mockResolvedValue({+ configured: true,+ subject: "CN=Old CA",+ issuer: "CN=Old CA",+ notBefore: Date.now() - 730 * ONE_DAY_MS,+ notAfter: Date.now() - ONE_DAY_MS+ })+ const { getByText } = render(<MtlsSection />)+ await waitFor(() => expect(getByText(/CA has expired/)).toBeTruthy())+ })+ })++ describe("remove actions", () => {+ it("clears client cert and refreshes when Remove Certificate is tapped", async () => {+ mockGetClientCertInfo+ .mockResolvedValueOnce({+ configured: true,+ subject: "CN=test",+ issuer: "CN=Test CA",+ notBefore: Date.now() - ONE_DAY_MS,+ notAfter: Date.now() + 365 * ONE_DAY_MS+ })+ .mockResolvedValueOnce({ configured: false })++ const { getByText } = render(<MtlsSection />)+ await waitFor(() => getByText("Remove Certificate"))+ fireEvent.press(getByText("Remove Certificate"))++ await waitFor(() => {+ expect(mockClearClientCert).toHaveBeenCalled()+ expect(mockGetClientCertInfo).toHaveBeenCalledTimes(2)+ })+ })++ it("clears server CA and refreshes when Remove CA is tapped", async () => {+ mockGetServerCaInfo+ .mockResolvedValueOnce({+ configured: true,+ subject: "CN=Test CA",+ issuer: "CN=Test CA",+ notBefore: Date.now() - ONE_DAY_MS,+ notAfter: Date.now() + 365 * ONE_DAY_MS+ })+ .mockResolvedValueOnce({ configured: false })++ const { getByText } = render(<MtlsSection />)+ await waitFor(() => getByText("Remove CA"))+ fireEvent.press(getByText("Remove CA"))++ await waitFor(() => {+ expect(mockClearServerCa).toHaveBeenCalled()+ expect(mockGetServerCaInfo).toHaveBeenCalledTimes(2)+ })+ })+ })+})diff --git a/apps/mobile/src/screens/AuthSettingsScreen.tsx b/apps/mobile/src/screens/AuthSettingsScreen.tsxindex 4e45b134..8058ec60 100644--- a/apps/mobile/src/screens/AuthSettingsScreen.tsx+++ b/apps/mobile/src/screens/AuthSettingsScreen.tsx@@ -5,6 +5,7 @@import React, { useState, useCallback, useEffect, useRef, useMemo } from "react"import { Text, StyleSheet, TextInput, View, ScrollView, Pressable } from "react-native"+import { ChevronRight } from "lucide-react-native"import { AuthConfig, AuthType, DEFAULT_AUTH_CONFIG, ScreenProps } from "../types/global"import { useTheme } from "../hooks/useTheme"import { useAutoSave } from "../hooks/useAutoSave"@@ -26,7 +27,7 @@ type LocalHeader = { key: string; value: string; id: number }/*** Screen for configuring endpoint authentication and custom headers.*/-export function AuthSettingsScreen({}: ScreenProps) {+export function AuthSettingsScreen({ navigation }: ScreenProps) {const { colors } = useTheme()const { restartTracking, settings } = useTracking()@@ -337,6 +338,24 @@ export function AuthSettingsScreen({}: ScreenProps) {</View>)}+ <View style={styles.section}>+ <SectionTitle>Client Certificate</SectionTitle>+ <Card>+ <Pressable+ style={({ pressed }) => [styles.linkRow, pressed && { opacity: colors.pressedOpacity }]}+ onPress={() => navigation.navigate("mTLS Settings")}+ >+ <View style={styles.linkContent}>+ <Text style={[styles.linkLabel, { color: colors.text }]}>Client Certificate (mTLS)</Text>+ <Text style={[styles.linkSub, { color: colors.textSecondary }]}>+ Authenticate to servers that require a client certificate+ </Text>+ </View>+ <ChevronRight size={20} color={colors.textLight} />+ </Pressable>+ </Card>+ </View>+{/* Footer */}<View style={styles.footer}><Text style={[styles.footerText, { color: colors.textLight }]}>@@ -470,5 +489,23 @@ const styles = StyleSheet.create({footerText: {fontSize: 11,textAlign: "center"+ },+ linkRow: {+ flexDirection: "row",+ justifyContent: "space-between",+ alignItems: "center",+ paddingVertical: 12+ },+ linkContent: {+ flex: 1+ },+ linkLabel: {+ fontSize: 16,+ ...fonts.semiBold,+ marginBottom: 2+ },+ linkSub: {+ fontSize: 13,+ ...fonts.regular}})diff --git a/apps/mobile/src/screens/MtlsSettingsScreen.tsx b/apps/mobile/src/screens/MtlsSettingsScreen.tsxnew file mode 100644index 00000000..615e6379--- /dev/null+++ b/apps/mobile/src/screens/MtlsSettingsScreen.tsx@@ -0,0 +1,57 @@+/**+ * Copyright (C) 2026 Max Dietrich+ * Licensed under the GNU AGPLv3. See LICENSE in the project root for details.+ */++import React from "react"+import { Text, StyleSheet, View, ScrollView } from "react-native"+import { ScreenProps } from "../types/global"+import { useTheme } from "../hooks/useTheme"+import { fonts } from "../styles/typography"+import { Container } from "../components"+import { MtlsSection } from "../components/features/settings/MtlsSection"++export function MtlsSettingsScreen({}: ScreenProps) {+ const { colors } = useTheme()++ return (+ <Container>+ <ScrollView+ contentContainerStyle={styles.scrollContent}+ keyboardShouldPersistTaps="handled"+ showsVerticalScrollIndicator={false}+ >+ <View style={styles.header}>+ <Text style={[styles.title, { color: colors.text }]}>Client Certificate (mTLS)</Text>+ <Text style={[styles.subtitle, { color: colors.textSecondary }]}>+ For endpoints behind a reverse proxy that requires mutual TLS authentication+ </Text>+ </View>++ <MtlsSection />+ </ScrollView>+ </Container>+ )+}++const styles = StyleSheet.create({+ scrollContent: {+ paddingHorizontal: 16,+ paddingTop: 16,+ paddingBottom: 40+ },+ header: {+ marginBottom: 20+ },+ title: {+ fontSize: 28,+ ...fonts.bold,+ letterSpacing: -0.5,+ marginBottom: 4+ },+ subtitle: {+ fontSize: 14,+ ...fonts.regular,+ lineHeight: 20+ }+})diff --git a/apps/mobile/src/screens/__tests__/AuthSettingsScreen.test.tsx b/apps/mobile/src/screens/__tests__/AuthSettingsScreen.test.tsxindex c9b058ad..4c8c90ab 100644--- a/apps/mobile/src/screens/__tests__/AuthSettingsScreen.test.tsx+++ b/apps/mobile/src/screens/__tests__/AuthSettingsScreen.test.tsx@@ -66,6 +66,8 @@ jest.mock("../../components", () => {Container: ({ children }: any) => R.createElement(View, null, children),Card: ({ children }: any) => R.createElement(View, null, children),Divider: () => R.createElement(View, null),+ Button: ({ title, onPress }: any) => R.createElement(Pressable, { onPress }, R.createElement(Text, null, title)),+ FieldMessage: ({ children }: any) => R.createElement(Text, null, children),ChipGroup: ({ options, onSelect }: any) =>R.createElement(View,diff --git a/apps/mobile/src/screens/index.ts b/apps/mobile/src/screens/index.tsindex 1ce19168..76b8e53b 100644--- a/apps/mobile/src/screens/index.ts+++ b/apps/mobile/src/screens/index.ts@@ -7,6 +7,7 @@ export { ActivityLogScreen } from "./ActivityLogScreen"export { ApiSettingsScreen } from "./ApiSettingsScreen"export { AutoExportScreen } from "./AutoExportScreen"export { AuthSettingsScreen } from "./AuthSettingsScreen"+export { MtlsSettingsScreen } from "./MtlsSettingsScreen"export { DashboardScreen } from "./DashboardScreen"export { DataManagementScreen } from "./DataManagementScreen"export { ExportDataScreen } from "./ExportDataScreen"diff --git a/apps/mobile/src/services/NativeLocationService.ts b/apps/mobile/src/services/NativeLocationService.tsindex 87e0faa9..fe772d3a 100644--- a/apps/mobile/src/services/NativeLocationService.ts+++ b/apps/mobile/src/services/NativeLocationService.ts@@ -6,16 +6,21 @@import { NativeModules } from "react-native"import {AuthConfig,+ ClientCertInfo,+ ClientCertInfoResult,DailyStat,DatabaseStats,Geofence,+ KeyChainPickResult,+ SavedTrackingProfile,Settings,- TrackingProfile,- SavedTrackingProfile+ TestEndpointArgs,+ TestEndpointResult,+ TrackingProfile} from "../types/global"import { logger } from "../utils/logger"-const { LocationServiceModule, BuildConfigModule } = NativeModules+const { LocationServiceModule, MtlsBridgeModule, BuildConfigModule } = NativeModules/*** Native location service bridge.@@ -854,6 +859,75 @@ class NativeLocationService {this.ensureModule()return LocationServiceModule.getAuthHeaders()}++ // ============================================================================+ // mTLS CLIENT CERTIFICATE (delegates to MtlsBridgeModule)+ // ============================================================================++ private static ensureMtlsModule(): void {+ if (!MtlsBridgeModule) {+ throw new Error("[NativeLocationService] MtlsBridgeModule not available. Check native linking.")+ }+ }++ static async pickClientCertFile(): Promise<string | null> {+ this.ensureMtlsModule()+ return MtlsBridgeModule.pickClientCertFile()+ }++ /**+ * Opens Android's system KeyChain picker. Returns cert info on selection,+ * null on cancel. The private key stays in the OS keystore.+ */+ static async pickKeyChainCert(): Promise<KeyChainPickResult | null> {+ this.ensureMtlsModule()+ return MtlsBridgeModule.pickKeyChainCert()+ }++ /**+ * Rejects with `E_CERT_PASSWORD` on a bad password or `E_CERT_INVALID` on a+ * malformed PKCS12.+ */+ static async importClientCert(b64: string, password: string): Promise<ClientCertInfo> {+ this.ensureMtlsModule()+ return MtlsBridgeModule.importClientCert(b64, password)+ }++ static async clearClientCert(): Promise<boolean> {+ this.ensureMtlsModule()+ return MtlsBridgeModule.clearClientCert()+ }++ static async getClientCertInfo(): Promise<ClientCertInfoResult> {+ this.ensureMtlsModule()+ return MtlsBridgeModule.getClientCertInfo()+ }++ static async testEndpoint(args: TestEndpointArgs): Promise<TestEndpointResult> {+ this.ensureMtlsModule()+ return MtlsBridgeModule.testEndpoint(args)+ }++ static async pickServerCaFile(): Promise<string | null> {+ this.ensureMtlsModule()+ return MtlsBridgeModule.pickServerCaFile()+ }++ /** Rejects with `E_CA_INVALID` if the bytes don't parse as X.509 (PEM or DER). */+ static async importServerCa(b64: string): Promise<ClientCertInfo> {+ this.ensureMtlsModule()+ return MtlsBridgeModule.importServerCa(b64)+ }++ static async clearServerCa(): Promise<boolean> {+ this.ensureMtlsModule()+ return MtlsBridgeModule.clearServerCa()+ }++ static async getServerCaInfo(): Promise<ClientCertInfoResult> {+ this.ensureMtlsModule()+ return MtlsBridgeModule.getServerCaInfo()+ }}export default NativeLocationServicediff --git a/apps/mobile/src/types/global.ts b/apps/mobile/src/types/global.tsindex a05aac14..550ead3c 100644--- a/apps/mobile/src/types/global.ts+++ b/apps/mobile/src/types/global.ts@@ -444,3 +444,36 @@ export interface Trip {distance: number // meterslocationCount: number}++// ============================================================================+// mTLS - client certificate bridge contract+// ============================================================================++export type ClientCertInfo = {+ subject: string+ issuer: string+ notBefore: number+ notAfter: number+}++export type ClientCertSource = "keychain" | "p12"++export type ClientCertInfoResult =+ | { configured: false }+ | ({ configured: true; error?: string; source?: ClientCertSource } & Partial<ClientCertInfo>)++export type KeyChainPickResult = Extract<ClientCertInfoResult, { configured: true }>++export type TestEndpointArgs = {+ endpoint: string+ method: string+ apiFormat?: string+ payload: Record<string, string | number | boolean>+ customFields?: Record<string, string>+}++export type TestEndpointResult = {+ ok: boolean+ status: number+ errorMessage?: string+}diff --git a/apps/mobile/src/types/navigation.ts b/apps/mobile/src/types/navigation.tsindex e9359804..214a1d6b 100644--- a/apps/mobile/src/types/navigation.ts+++ b/apps/mobile/src/types/navigation.ts@@ -16,6 +16,7 @@ export type RootStackParamList = {Appearance: undefined"API Config": undefined"Auth Settings": undefined+ "mTLS Settings": undefinedGeofences: undefined"Geofence Editor": { geofenceId?: number; name?: string; radius?: number; lat?: number; lon?: number } | undefined"Location History": { initialTab?: InspectorTab; initialDate?: string } | undefineddiff --git a/fastlane/metadata/android/en-US/changelogs/38.txt b/fastlane/metadata/android/en-US/changelogs/38.txtnew file mode 100644index 00000000..d2e0f791--- /dev/null+++ b/fastlane/metadata/android/en-US/changelogs/38.txt@@ -0,0 +1,3 @@+- 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.