Skip to content

Colota - Android GPS Location tracker

refactor(connection): one chain from endpoint to certificate (#850)

Max Dietrichc6c69d136659
diff --git a/apps/docs/docs/api-reference.md b/apps/docs/docs/api-reference.md
index 39d6271f..3d0b7a2b 100644
--- a/apps/docs/docs/api-reference.md
+++ b/apps/docs/docs/api-reference.md
@@ -10,7 +10,7 @@ Reference for the HTTP requests Colota sends to your server.
**Method:** `POST` (default) or `GET`
-Configure the HTTP method in **Settings → API Field Mapping → HTTP Method**.
+Configure the HTTP method in **Settings → Connection → Request format → HTTP method**.
### POST (default)
@@ -25,10 +25,7 @@ Additional headers may be included based on your [authentication](/docs/configur
**Body:**
-This is the body for the default field-mapped format. The Traccar POST and Overland templates and
-Dawarich in batch mode, send a different shape entirely. Those formats use fixed field names, so the
-[field mapping](/docs/configuration/field-mapping) does not apply to them and both add a `device_id`
-key. See [API templates](/docs/integrations/api-templates) for the exact bodies.
+This is the body for the default field-mapped format. The Traccar POST and Overland templates and Dawarich in batch mode, send a different shape entirely. Those formats use fixed field names, so the [field mapping](/docs/configuration/field-mapping) does not apply to them and both add a `device_id` key. See [API templates](/docs/integrations/api-templates) for the exact bodies.
```json
{
@@ -82,24 +79,19 @@ When exiting a [pause zone](/docs/guides/geofencing#anchor-points), Colota sends
- `alt`, `vel`, and `bear` are not included
- `batt` and `bs` reflect the current battery state
-A zone [heartbeat](/docs/guides/geofencing) produces the same kind of synthetic point while you are
-still inside the zone: the zone centre, `acc` 0, timestamped when the heartbeat fired. Filter on both
-if you want to tell app-generated points from real fixes.
+A zone [heartbeat](/docs/guides/geofencing) produces the same kind of synthetic point while you are still inside the zone: the zone centre, `acc` 0, timestamped when the heartbeat fired. Filter on both if you want to tell app-generated points from real fixes.
-### Custom Fields
+### Custom fields
-Custom static fields (configured in API Settings) are added to the payload first, then location fields are added. If a custom field has the same name as a location field, the location field overwrites it.
+Custom static fields (configured in Request format) are added to the payload first, then location fields are added. If a custom field has the same name as a location field, the location field overwrites it.
Custom field values are always sent as strings.
## Batch Sync Behavior
-In the default field-mapped format Colota sends **one location per HTTP request**. During batch sync
-up to 10 requests are sent concurrently, processing up to 500 queued locations per sync cycle.
+In the default field-mapped format Colota sends **one location per HTTP request**. During batch sync up to 10 requests are sent concurrently, processing up to 500 queued locations per sync cycle.
-The Overland format, and Dawarich in batch mode, instead send **an array of locations in a single
-request**. Batch size is configurable (1 to 500, default 50) and up to 10 batches are sent per cycle,
-so one cycle can move considerably more than 500 points.
+The Overland format, and Dawarich in batch mode, instead send **an array of locations in a single request**. Batch size is configurable (1 to 500, default 50) and up to 10 batches are sent per cycle, so one cycle can move considerably more than 500 points.
Your server should handle multiple simultaneous POST requests. If you have rate limiting, some requests may fail and be retried.
@@ -147,11 +139,9 @@ Your server only needs to return a 2xx status code. The response body is not rea
| **Any non-2xx response** | Queued for retry |
| **Network timeout** | Retried (10s connection, 10s read timeout) |
-There is no distinction between 4xx and 5xx in retry behavior - all failures are retried indefinitely,
-and failed items stay in the queue until they succeed.
+There is no distinction between 4xx and 5xx in retry behavior - all failures are retried indefinitely, and failed items stay in the queue until they succeed.
-Clearing the queue in **Settings > Data Management** deletes those locations outright, not just their
-place in the queue, so anything not yet sent is lost.
+Clearing the queue in **Settings > Data management** deletes those locations outright, not just their place in the queue, so anything not yet sent is lost.
## Retry Strategy
@@ -165,12 +155,12 @@ Attempt 4: +300s delay (5 minutes)
Attempt 5+: +900s delay (15 minutes)
```
-Failed items stay in the queue indefinitely until they succeed. The queue can be cleared manually in Settings > Data Management if needed.
+Failed items stay in the queue indefinitely until they succeed. The queue can be cleared manually in Settings > Data management if needed.
## Network Requirements
- **HTTPS required** for all public endpoints
-- **HTTP allowed** for private/local addresses - enforced via DNS resolution at both sync time and Test Connection
+- **HTTP allowed** for private/local addresses - enforced via DNS resolution at both sync time and Test connection
- Non-standard ports are supported (e.g., `https://my-server.com:8443/api`)
- Self-signed certificates are supported - see [Server Settings](/docs/configuration/server-settings#endpoint-url) for setup instructions
diff --git a/apps/docs/docs/configuration/authentication.md b/apps/docs/docs/configuration/authentication.md
index 6c50ffad..d6fc8acd 100644
--- a/apps/docs/docs/configuration/authentication.md
+++ b/apps/docs/docs/configuration/authentication.md
@@ -6,37 +6,37 @@ sidebar_position: 5
import ScreenshotGallery from '@site/src/components/ScreenshotGallery'
-Colota supports multiple authentication methods, configurable in **Settings → Connection → Authentication & Headers**.
+Colota supports multiple authentication methods, configurable in **Settings → Connection → Authentication**. The method is a choice of three rows, each saying what it sends, and only the chosen method's fields are shown.
<ScreenshotGallery screenshots={[ { src: "/img/screenshots/Authentication.png", label: "Authentication" }, ]} />
## Methods
-| 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) |
+| Method | Description | Sent at |
+| --- | --- | --- |
+| **None** | No Authorization header; use with a key in the address, a custom header or a client certificate (default) | -- |
+| **Basic auth** | Username and password, encoded, not encrypted; only safe over https | `Authorization: Basic <base64>` |
+| **Bearer token** | API token / JWT | `Authorization: Bearer <token>` |
+| **Custom headers** | Any key-value pairs | HTTP header |
+| **Client certificate** | PKCS12 (.p12 / .pfx) or a device certificate 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.
+Choosing a method removes the credentials stored for the other methods, so picking **None** is how a stored password or token is cleared. A client certificate is orthogonal to the HTTP-level methods and can be combined with any of them - a common setup is mutual TLS at the reverse-proxy layer plus a bearer token at the application layer. It has its own screen, **Settings → Connection → Client certificate**; see [Client certificate](./mtls).
## Credential Storage
-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.
+HTTP credentials (Basic auth, bearer tokens, custom headers, imported server CAs) are stored encrypted on-device using Android's `EncryptedSharedPreferences` and included in encrypted backups. A stored password or token is never shown again: its field stays empty and the note under it says it is set, and typing replaces it. Credentials never leave the device except as HTTP headers sent to your configured endpoint and inside a [setup link](/docs/guides/deep-link-setup) you share, which carries them in the clear.
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 Headers
-Add arbitrary HTTP headers for proxies, API gateways, or services like Cloudflare Access. Each header is a key-value pair sent with every request.
+Add arbitrary HTTP headers for proxies, API gateways, or services like Cloudflare Access. Each header is a name and value pair sent with every request. A value under a name that looks like a credential (authorization, cookie, token, key, secret) is masked while you type. A name already used above is marked on its field, because only the last value is sent.
## Testing with curl
Replicate what Colota sends using curl to test your server:
-**Basic Auth:**
+**Basic auth:**
```bash
curl -X POST https://your-server.com/api/location \
@@ -45,7 +45,7 @@ curl -X POST https://your-server.com/api/location \
-d '{"lat":48.135,"lon":11.582,"acc":12,"vel":0,"batt":85,"bs":2,"tst":1704067200}'
```
-**Bearer Token:**
+**Bearer token:**
```bash
curl -X POST https://your-server.com/api/location \
diff --git a/apps/docs/docs/configuration/field-mapping.md b/apps/docs/docs/configuration/field-mapping.md
index 061f8929..10b44efc 100644
--- a/apps/docs/docs/configuration/field-mapping.md
+++ b/apps/docs/docs/configuration/field-mapping.md
@@ -45,12 +45,12 @@ You can rename any field to match your backend. For example:
}
```
-Configure field names in **Settings → API Field Mapping → Field Mappings**.
+Configure field names in **Settings → Connection → Request format → Field mappings**.
## Custom Static Fields
Add arbitrary key-value pairs that are included in every API payload. For example, adding `_type: "location"` for OwnTracks-compatible backends.
-Configure in **Settings → API Field Mapping → Custom Fields**.
+Configure in **Settings → Connection → Request format → Custom fields**.
**Note:** Custom field values are always sent as strings. Custom fields are added to the payload before location fields - if a custom field key matches a location field key, the location field takes precedence.
diff --git a/apps/docs/docs/configuration/mtls.md b/apps/docs/docs/configuration/mtls.md
index 241030fa..38300efc 100644
--- a/apps/docs/docs/configuration/mtls.md
+++ b/apps/docs/docs/configuration/mtls.md
@@ -2,11 +2,11 @@
sidebar_position: 6
---
-# Mutual TLS (mTLS)
+# Client certificate (mutual TLS)
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)**.
+Configure in **Settings -> Connection -> Client certificate**. The screen opens with the certificate's state (Valid until a date, Expires in N days inside 30 days, Expired, Cannot be read) and where its key lives, then the subject and issuer, then **Replace** and **Remove**.
## Setup
@@ -16,22 +16,22 @@ Two ways to provide a client certificate.
If your cert is already installed in Android's KeyChain (via Android Settings -> Encryption & credentials):
-1. Open Colota -> Settings -> Connection -> Authentication & Headers -> **Client Certificate (mTLS)**
+1. Open Colota -> Settings -> Connection -> **Client certificate**
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.
+4. The screen now reads **Valid** with the expiry date and "device credential store", plus the subject and issuer.
-Colota only remembers which cert you picked - the cert itself stays where it already was on the phone.
+Colota only remembers which cert you picked - the key stays in the device credential store, survives reinstalling Colota and is never backed up.
### 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)**
+2. Open Colota -> Settings -> Connection -> **Client certificate**
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
+4. Pick the file, enter the file password (leave it empty if the file has none), tap **Import**
+5. The screen now reads **Valid** with the expiry date and "imported .p12", plus the subject and issuer. The key moves into the Android Keystore and never leaves the device; it is not backed up, so import again after a restore.
The new cert takes effect on the next sync request - no app restart needed. Same goes if you switch between Option A and Option B later.
@@ -44,7 +44,7 @@ Hostname verification is always on - the server's certificate must match the hos
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.
+2. **In-app imported CA** added through the Trusted server CA card on the same screen. One slot, trusted only by Colota.
Either anchor accepting the server's chain is enough - the two layers are additive.
@@ -54,17 +54,17 @@ User-installed device CAs (from Android Settings -> Encryption & credentials) ar
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.
+- **Import in-app** - Settings -> Connection -> Client certificate -> **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:
+In **Settings -> Connection**, set your endpoint to your `https://...` URL and tap **Test connection**. Expected: **Reachable** with the HTTP status within a couple of seconds. On failure the line reads **Not reachable** and the server's own sentence sits under it:
| 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 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 under Connection -> Client certificate -> Trusted server CA, or use a publicly trusted cert |
+| `Server requires a client certificate (mutual TLS) but none is configured` | Server demanded a client certificate, Colota didn't send one | Add one under Connection -> Client certificate |
| `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 |
@@ -78,8 +78,9 @@ Once imported, the cert lives in the OS keystore - not in the app's regular sett
- 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.
+- The Trusted server CA is a public certificate; it is stored encrypted with the other credentials and included in encrypted backups.
+- A certificate inside 30 days of its expiry reads **Expires in N days** on the card, on the Connection screen's Client certificate row and appended to the sync line, so a failing sync shows its cause.
### Removing
-mTLS Settings -> Client Certificate section -> **Remove Certificate**. Same for Trusted Server CA -> **Remove CA**. The next sync request runs without mTLS.
+Settings -> Connection -> Client certificate -> **Remove**, behind a confirmation that says requests to a server that requires it will fail until you add one again. Same for the Trusted server CA card. **Replace** offers the same two paths as the empty state. The next sync request runs without the removed certificate.
diff --git a/apps/docs/docs/configuration/server-settings.md b/apps/docs/docs/configuration/server-settings.md
index b32e300c..8d28b0e1 100644
--- a/apps/docs/docs/configuration/server-settings.md
+++ b/apps/docs/docs/configuration/server-settings.md
@@ -4,22 +4,24 @@ sidebar_position: 3
# Server Settings
-| Setting | Description | Default | Range |
-| ------------- | -------------------------------------- | --------------- | ----------- |
-| Endpoint | HTTP(S) URL of your server | Empty (offline) | -- |
-| HTTP Method | POST (JSON body) or GET (query params) | POST | POST / GET |
-| Sync Interval | Batch mode interval | Instant (0) | 0s - Custom |
-| Offline Mode | Disable all network activity | Disabled | On/Off |
+Found under **Settings → Connection**. The Server card opens with a line that says what sync is doing now (Synced, Not synced yet, Sync failing with the server's own sentence, No network, No server, Offline mode), then the settings that produced it. The Server details card below it opens Request format, Authentication and Client certificate, each row showing its stored value.
+
+| Setting | Description | Default | Range |
+| --------------- | -------------------------------------- | --------------- | ----------- |
+| Server endpoint | HTTP(S) URL of your server | Empty (offline) | -- |
+| HTTP method | POST (JSON body) or GET (query params) | POST | POST / GET |
+| Sync interval | Batch mode interval | Instant (0) | 0s - Custom |
+| Offline mode | Disable all network activity | Disabled | On/Off |
## Endpoint URL
-Your 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.
+Your server endpoint must accept HTTP or HTTPS requests (POST or GET depending on your HTTP method setting). The field's helper shows the shape the chosen backend template expects. The address is saved when you leave the field, not on every keystroke, and only when it passes: an address without `http://` or `https://` and a host is refused, and plain `http://` to a public host is refused with "http is refused for a public host. Use https." Plain `http://` to a private host (`192.168.x`, `10.x`, `172.16-31.x`, `100.64.x`, `localhost`) is saved with a warning that it is not encrypted, and an address carrying a key in its query string is saved with a warning that the key is stored with settings, not encrypted, and included in setup links.
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.
+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.
-Use the **Test Connection** button in Settings → Connection to verify your server is reachable.
+**Test connection** sits under the field. It sends your latest recorded location to the address with your credentials, so it needs one recorded fix, and it is disabled with the reason until it has one or while the address does not pass. The result stays under the button until the next test or an edit: **Reachable** with the HTTP status and the time, or **Not reachable** with the status or "No response" and the server's own sentence. Test saves nothing itself; the field does, when you leave it.
### Multiple Backends
@@ -49,14 +51,14 @@ This is useful for backends that organize data by date (e.g. S3 with hive partit
## Offline Mode
-Enable **Offline Mode** in Settings to use Colota as a standalone tracker without any server. Locations are recorded and stored locally on-device.
+Enable **Offline mode** under **Settings → Connection** to use Colota as a standalone tracker without any server. Locations are recorded and stored locally on-device.
### Enabling Offline Mode
When you toggle offline mode on with unsent locations still in the queue, a dialog offers several options:
-- **Sync First** - attempt to upload queued locations before switching (only available if an endpoint is configured)
-- **Keep in Queue** - preserve queued locations for later sync when you disable offline mode
+- **Sync first** - attempt to upload queued locations before switching (only available if an endpoint is configured)
+- **Keep in queue** - preserve queued locations for later sync when you disable offline mode
- **Cancel** - abort and stay in online mode
If no locations are queued, offline mode enables immediately.
@@ -67,12 +69,10 @@ The UI simplifies to remove sync-related elements that don't apply:
**Hidden in offline mode:**
-- Server Endpoint and Test Connection
-- Authentication & Headers
-- API Field Mapping
-- Sync Interval, Sync Condition (Any / Wi-Fi / SSID / VPN)
+- Server endpoint, Test connection and the Server details rows (Request format, Authentication, Client certificate); the sync state line and the Offline mode switch stay
+- Sync interval, Sync only on (Any network / Wi-Fi or Ethernet / Specific Wi-Fi network / VPN)
- Queue statistics (Queued / Sent counts)
-- Queue actions (Sync Now, Clear Sent History, Clear Queue)
+- Queue actions (Sync now, Delete queued locations, Delete synced locations)
- Queue info in the tracking notification, which reads "Offline mode" instead
**Still available in offline mode:**
@@ -80,8 +80,8 @@ The UI simplifies to remove sync-related elements that don't apply:
- All tracking parameters (interval, movement threshold, accuracy)
- Tracking profiles and geofences
- Data export (CSV, GeoJSON, GPX, KML) - both manual and auto-export
-- Database statistics (Total locations, Today count, Storage)
-- Data cleanup (Delete All Locations, Delete Old, Optimize Database)
+- Database statistics (Total locations, Storage)
+- Data cleanup (Delete older than, Delete all locations, Compact database)
### Disabling Offline Mode
@@ -101,6 +101,6 @@ Attempt 4: +300s delay (5 minutes)
Attempt 5+: +900s delay (15 minutes)
```
-Failed uploads stay in the queue and are retried indefinitely until they succeed. No data is ever dropped due to failed sync attempts. You can clear the queue manually in Settings > Data Management if needed.
+Failed uploads stay in the queue and are retried indefinitely until they succeed. No data is ever dropped due to failed sync attempts. You can clear the queue manually in Settings > Data management if needed.
The app also auto-syncs when network connectivity is restored.
diff --git a/apps/docs/docs/integrations/api-templates.md b/apps/docs/docs/integrations/api-templates.md
index 23fd802b..9a775da8 100644
--- a/apps/docs/docs/integrations/api-templates.md
+++ b/apps/docs/docs/integrations/api-templates.md
@@ -4,9 +4,9 @@ sidebar_position: 1
# API Templates
-Colota includes built-in templates for popular backends. Select a template in **Settings > API Settings** to auto-configure field mappings and custom fields.
+Colota includes built-in templates for popular backends. Select a template in **Settings > Connection > Request format** to auto-configure field mappings and custom fields.
-| Template | HTTP Method | Bearing Field | Custom Fields | Notes |
+| Template | HTTP method | Bearing Field | Custom fields | Notes |
| --- | --- | --- | --- | --- |
| **Dawarich** | POST | `cog` | `_type: "location"` | OwnTracks single-point format. Optional Batch chip switches to Overland envelope (see [Dawarich integration](./dawarich.md)). |
| **GeoPulse** | POST | `bear` | _(none)_ | Native Colota format |
diff --git a/apps/docs/docs/integrations/custom-backend.md b/apps/docs/docs/integrations/custom-backend.md
index 9ed9ebc8..b53c277a 100644
--- a/apps/docs/docs/integrations/custom-backend.md
+++ b/apps/docs/docs/integrations/custom-backend.md
@@ -15,7 +15,7 @@ Your server needs to:
- Handle `alt`, `vel`, and `bear` fields being absent (they are conditional)
- Handle up to 10 concurrent requests during batch sync
-HTTPS is required for public endpoints. HTTP is restricted to private/local addresses at the network level. Self-signed certificates are supported - see [Server Settings](/docs/configuration/server-settings#endpoint-url). On Android 17+, connecting to local network addresses (not localhost) requires the Local Network Access permission, which Colota requests when you use **Test Connection**.
+HTTPS is required for public endpoints. HTTP is restricted to private/local addresses at the network level. Self-signed certificates are supported - see [Server Settings](/docs/configuration/server-settings#endpoint-url). On Android 17+, connecting to local network addresses (not localhost) requires the Local Network Access permission, which Colota requests when you use **Test connection**.
## Default Payload
@@ -100,7 +100,7 @@ your-domain.com {
## Configuration
-1. Go to **Settings > API Settings**
+1. Go to **Settings > Connection > Request format**
2. Select the **Custom** template (or start from any template and modify)
3. Set your endpoint URL
4. Customize [field mapping](/docs/configuration/field-mapping) to match your API
diff --git a/apps/docs/docs/integrations/dawarich.md b/apps/docs/docs/integrations/dawarich.md
index c3e1d7ab..bccbca69 100644
--- a/apps/docs/docs/integrations/dawarich.md
+++ b/apps/docs/docs/integrations/dawarich.md
@@ -11,7 +11,7 @@ sidebar_position: 2
1. **Install Dawarich** - follow the [Dawarich documentation](https://dawarich.app/docs/intro)
2. **Get your API Key** from Dawarich settings
3. **Configure Colota**:
- - Go to **Settings > API Settings**
+ - Go to **Settings > Connection > Request format**
- Select the **Dawarich** template
- Set your endpoint:
```
@@ -21,7 +21,7 @@ sidebar_position: 2
## Payload Format
-The Dawarich template ships with two modes, picked via a chip in **Settings > API Settings** when the Dawarich template is selected.
+The Dawarich template ships with two modes, picked via a chip in **Settings > Connection > Request format** when the Dawarich template is selected.
### Single point (default)
@@ -71,8 +71,8 @@ Bundles up to N queued points into a single request to `/api/v1/overland/batches
**Endpoint URL**: change the saved endpoint to `https://dawarich.yourdomain.com/api/v1/overland/batches?api_key=YOUR_API_KEY`. The chip only updates the placeholder hint, not your saved endpoint.
-**Batch size**: defaults to 50 points per POST, configurable 1-500 under **Settings > Tracking & Sync > Advanced > Network Settings > Batch Size** (only shown when batch mode is active).
+**Batch size**: defaults to 50 points per POST, configurable 1-500 under **Settings > Tracking & sync > Sync interval > Batch size** (only shown when batch mode is active).
**Requires non-zero sync interval**: batch mode is incompatible with instant sync. Pick a batched preset or set a custom sync interval before enabling. The chip is disabled when sync interval is 0.
-**Device identifier**: your Dawarich server sees this device as the value of the `device_id` custom field, defaulting to `"colota"`. Edit it under **Settings > API Settings > Custom Fields** if you run multiple devices.
+**Device identifier**: your Dawarich server sees this device as the value of the `device_id` custom field, defaulting to `"colota"`. Edit it under **Settings > Connection > Request format > Custom fields** if you run multiple devices.
diff --git a/apps/docs/docs/integrations/geopulse.md b/apps/docs/docs/integrations/geopulse.md
index 538a1095..da625552 100644
--- a/apps/docs/docs/integrations/geopulse.md
+++ b/apps/docs/docs/integrations/geopulse.md
@@ -12,14 +12,14 @@ sidebar_position: 2
2. **Add a Colota location source** in GeoPulse under **Location Sources**
3. **Set a username and password** for the Colota source
4. **Configure Colota**:
- - Go to **Settings > API Settings**
+ - Go to **Settings > Connection > Request format**
- Select the **GeoPulse** template
- Set your endpoint:
```
https://geopulse.yourdomain.com/api/colota
```
- Go to **Settings > Authentication**
- - Enable **Basic Auth** and enter the username and password from step 3
+ - Choose **Basic auth** and enter the username and password from step 3
## Payload Format
diff --git a/apps/docs/docs/integrations/home-assistant.md b/apps/docs/docs/integrations/home-assistant.md
index 5e76445d..2c0d2285 100644
--- a/apps/docs/docs/integrations/home-assistant.md
+++ b/apps/docs/docs/integrations/home-assistant.md
@@ -34,7 +34,7 @@ Colota has a dedicated Home Assistant integration that receives location updates
### 3. Configure the Colota app
-1. Go to **Settings > API Settings**
+1. Go to **Settings > Connection > Request format**
2. Paste the webhook URL as the endpoint
3. No authentication is needed - the webhook URL acts as the secret
diff --git a/apps/docs/docs/integrations/overland.md b/apps/docs/docs/integrations/overland.md
index 09e00e00..e9647f6e 100644
--- a/apps/docs/docs/integrations/overland.md
+++ b/apps/docs/docs/integrations/overland.md
@@ -8,13 +8,13 @@ Colota is a drop-in Android client for the [Overland](https://github.com/aaronpk
## Setup
-1. **Pick the Overland template** in **Settings > API Settings**
+1. **Pick the Overland template** in **Settings > Connection > Request format**
2. **Set your endpoint** to your Overland-compatible server's batch URL, e.g.:
```
https://overland.yourdomain.com/
```
Some implementations use a path like `/api/v1/overland/batches`. Check your server's docs.
-3. **Choose a batched sync preset** (Balanced or Power Saver). Instant sync is not supported because Overland is a batch-only protocol.
+3. **Choose a batched sync preset** (Balanced or Power saver). Instant sync is not supported because Overland is a batch-only protocol.
4. **Set a `device_id`** in custom fields if you want to override the default `"colota"`.
## Payload Format
@@ -49,7 +49,7 @@ Each upload is a single POST containing one or more locations as GeoJSON Feature
## Configuration
-**Batch size**: defaults to 50 points per POST, configurable 1-500 under **Settings > Tracking & Sync > Advanced > Network Settings > Batch Size**. Larger bundles mean fewer round trips but bigger payloads on flaky networks.
+**Batch size**: defaults to 50 points per POST, configurable 1-500 under **Settings > Tracking & sync > Sync interval > Batch size**. Larger bundles mean fewer round trips but bigger payloads on flaky networks.
**HTTP method**: POST only. The Overland protocol does not support GET; the option is hidden when this template is selected.
@@ -57,7 +57,7 @@ Each upload is a single POST containing one or more locations as GeoJSON Feature
## Device Identifier
-Your server sees this device as the value of the `device_id` custom field, defaulting to `"colota"`. Edit it under **Settings > API Settings > Custom Fields** if you run multiple devices. If you previously set `tid` (OwnTracks) or `id` (Traccar) as a custom field, that value is reused so you don't have to reconfigure.
+Your server sees this device as the value of the `device_id` custom field, defaulting to `"colota"`. Edit it under **Settings > Connection > Request format > Custom fields** if you run multiple devices. If you previously set `tid` (OwnTracks) or `id` (Traccar) as a custom field, that value is reused so you don't have to reconfigure.
## Dawarich Users
diff --git a/apps/docs/docs/integrations/owntracks.md b/apps/docs/docs/integrations/owntracks.md
index aa08c624..ac6d5f5d 100644
--- a/apps/docs/docs/integrations/owntracks.md
+++ b/apps/docs/docs/integrations/owntracks.md
@@ -10,10 +10,10 @@ sidebar_position: 3
1. **Install OwnTracks Recorder** - follow the [OwnTracks documentation](https://owntracks.org/booklet/)
2. **Configure Colota**:
- - Go to **Settings > API Settings**
+ - Go to **Settings > Connection > Request format**
- Select the **OwnTracks** template
- Set your endpoint URL, e.g. `https://owntracks.yourdomain.com/pub`
- - If your Recorder uses HTTP Basic Auth, configure it in **Settings > Authentication & Headers**
+ - If your Recorder uses HTTP Basic Auth, configure it in **Settings > Connection > Authentication**
## Payload Format
diff --git a/apps/docs/docs/integrations/phonetrack.md b/apps/docs/docs/integrations/phonetrack.md
index 40c8d9a6..84a7bc96 100644
--- a/apps/docs/docs/integrations/phonetrack.md
+++ b/apps/docs/docs/integrations/phonetrack.md
@@ -15,7 +15,7 @@ sidebar_position: 5
https://nextcloud.yourdomain.com/apps/phonetrack/log/owntracks/SESSION_TOKEN/DEVICE_NAME
```
4. **Configure Colota**:
- - Go to **Settings > API Settings**
+ - Go to **Settings > Connection > Request format**
- Select the **OwnTracks** template
- Paste the URL as your endpoint
diff --git a/apps/docs/docs/integrations/reitti.md b/apps/docs/docs/integrations/reitti.md
index 463bb658..1d9c664b 100644
--- a/apps/docs/docs/integrations/reitti.md
+++ b/apps/docs/docs/integrations/reitti.md
@@ -10,7 +10,7 @@ sidebar_position: 4
1. **Install Reitti** - follow the [Reitti documentation](https://www.dedicatedcode.com/projects/reitti/)
2. **Configure Colota**:
- - Go to **Settings > API Settings**
+ - Go to **Settings > Connection > Request format**
- Select the **Reitti** template
- Set your endpoint URL, e.g. `https://reitti.yourdomain.com/api/location`
diff --git a/apps/docs/docs/integrations/traccar.md b/apps/docs/docs/integrations/traccar.md
index 970d0efa..99f4342f 100644
--- a/apps/docs/docs/integrations/traccar.md
+++ b/apps/docs/docs/integrations/traccar.md
@@ -17,7 +17,7 @@ sidebar_position: 6
## Setup in Colota
-1. Go to **Settings > API Settings**
+1. Go to **Settings > Connection > Request format**
2. Select the **Traccar** template
3. Choose your HTTP method:
- **GET** - OsmAnd protocol, compatible with all Traccar versions
@@ -36,7 +36,7 @@ Traccar identifies devices by a unique identifier. Add a custom field with key `
| GET | `id` query parameter | custom field `id` |
| POST | `device_id` in JSON body | custom field `id` (or `device_id` if set, otherwise `colota`) |
-The current value is visible in the example payload on the API Settings screen.
+The current value is visible in the example payload on the Request format screen.
In Traccar, open **Settings > Devices**, create a new device, and set the **Identifier** to the same value Colota is sending.
diff --git a/apps/mobile/App.tsx b/apps/mobile/App.tsx
index 97fabbe2..7a9f184b 100644
--- a/apps/mobile/App.tsx
+++ b/apps/mobile/App.tsx
@@ -20,6 +20,7 @@ import {
DashboardScreen,
SettingsScreen,
ApiSettingsScreen,
+ BackendTemplateScreen,
AuthSettingsScreen,
MtlsSettingsScreen,
AutoExportScreen,
@@ -67,19 +68,24 @@ const SCREEN_CONFIG: readonly ScreenConfig[] = [
title: "Settings"
},
{
- name: "API Config",
+ name: "Request Format",
component: ApiSettingsScreen,
- title: "API Config"
+ title: "Request format"
+ },
+ {
+ name: "Backend Template",
+ component: BackendTemplateScreen,
+ title: "Backend template"
},
{
name: "Auth Settings",
component: AuthSettingsScreen,
- title: "Auth Settings"
+ title: "Authentication"
},
{
name: "mTLS Settings",
component: MtlsSettingsScreen,
- title: "mTLS Settings"
+ title: "Client certificate"
},
{
name: "Geofences",
diff --git a/apps/mobile/src/components/features/settings/ConnectionSettings.tsx b/apps/mobile/src/components/features/settings/ConnectionSettings.tsx
index 5cc2e34c..f3880061 100644
--- a/apps/mobile/src/components/features/settings/ConnectionSettings.tsx
+++ b/apps/mobile/src/components/features/settings/ConnectionSettings.tsx
@@ -3,71 +3,128 @@
* Licensed under the GNU AGPLv3. See LICENSE in the project root for details.
*/
-import React, { useState, useCallback, useEffect, useRef } from "react"
-import { Text, StyleSheet, TextInput, Switch, View, Pressable } from "react-native"
-import { CheckCircle, ChevronRight } from "lucide-react-native"
-import { Settings, ThemeColors } from "../../../types/global"
+import React, { useState, useCallback, useEffect } from "react"
+import { Text, StyleSheet, View, ActivityIndicator, Keyboard } from "react-native"
+import {
+ Braces,
+ CircleAlert,
+ CircleCheckBig,
+ CircleDashed,
+ Cloud,
+ CloudOff,
+ KeyRound,
+ Radio,
+ ShieldCheck,
+ WifiOff,
+ type LucideIcon
+} from "lucide-react-native"
+import { Settings } from "../../../types/global"
+import type { ScreenProps } from "../../../types/global"
import NativeLocationService from "../../../services/NativeLocationService"
-import { isEndpointAllowed } from "../../../utils/settingsValidation"
+import { endpointCarriesKey, endpointExample, isEndpointAllowed } from "../../../utils/settingsValidation"
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 { TEST_RESULT_DISPLAY_MS } from "../../../constants"
+import { fontSizes, fonts, lineHeights } from "../../../styles/typography"
+import { useTheme } from "../../../hooks/useTheme"
+import { space } from "../../../constants"
import { logger } from "../../../utils/logger"
-import { Button, Card, SectionTitle, Divider, FieldMessage } from "../../index"
+import { formatTime } from "../../../utils/geo"
+import type { ServerIcon, ServerState, ServerTone } from "../../../utils/serverState"
+import {
+ Button,
+ Card,
+ Divider,
+ FieldMessage,
+ ListItem,
+ SectionTitle,
+ SettingRow,
+ StateLine,
+ TextField,
+ Toggle
+} from "../../index"
import { showChoice } from "../../../services/modalService"
interface ConnectionSettingsProps {
settings: Settings
- endpointInput: string
- onEndpointInputChange: (value: string) => void
- onSettingsChange: (newSettings: Settings) => void
- colors: ThemeColors
- navigation: any
+ /** State only; the immediate save follows through `onSettingsChange`. */
+ onSettingsLocal: (next: Settings) => void
+ onSettingsChange: (next: Settings) => void
+ server: ServerState
+ /** A recorded fix exists, which Test connection sends. */
+ hasFix: boolean
+ requestSummary: string
+ authSummary: string
+ certificateSummary: string
+ navigation: ScreenProps["navigation"]
}
+type Validation = { error?: string; warnings: string[] }
+type TestState = { kind: "testing" } | { kind: "done"; ok: boolean; status: number; at: number; message?: string }
+
+const SERVER_ICONS: Record<ServerIcon, LucideIcon> = {
+ cloudOff: CloudOff,
+ cloud: Cloud,
+ wifiOff: WifiOff,
+ alert: CircleAlert,
+ dashed: CircleDashed,
+ check: CircleCheckBig
+}
+
+const SCHEME_ERROR = "Starts with http:// or https:// and names a host."
+const PUBLIC_HTTP_ERROR = "http is refused for a public host. Use https."
+const PRIVATE_HTTP_WARNING = "Not encrypted: plain http on a private host."
+const KEY_WARNING =
+ "This address carries a key. It is stored with settings, not encrypted, and included in setup links. Use a header where the server allows it."
+
export function ConnectionSettings({
settings,
- endpointInput,
- onEndpointInputChange,
+ onSettingsLocal,
onSettingsChange,
- colors,
+ server,
+ hasFix,
+ requestSummary,
+ authSummary,
+ certificateSummary,
navigation
}: ConnectionSettingsProps) {
- const [testing, setTesting] = useState(false)
- const [testResponse, setTestResponse] = useState<string | null>(null)
- const [testError, setTestError] = useState(false)
- const [endpointPrivate, setEndpointPrivate] = useState(false)
- const timeout = useTimeout()
- const pendingCheck = useRef(0)
+ const { colors } = useTheme()
+ const [draft, setDraft] = useState(settings.endpoint)
+ const [validation, setValidation] = useState<Validation>({ warnings: [] })
+ const [test, setTest] = useState<TestState | null>(null)
useEffect(() => {
- if (!endpointInput || !endpointInput.startsWith("http://")) {
- setEndpointPrivate(false)
- return
- }
- const id = ++pendingCheck.current
- NativeLocationService.isPrivateEndpoint(endpointInput).then((isPrivate) => {
- if (id === pendingCheck.current) setEndpointPrivate(isPrivate)
- })
- }, [endpointInput])
+ setDraft(settings.endpoint)
+ }, [settings.endpoint])
+
+ const tone = (t: ServerTone) =>
+ t === "success"
+ ? colors.success
+ : t === "error"
+ ? colors.error
+ : t === "warning"
+ ? colors.warning
+ : t === "light"
+ ? colors.textLight
+ : colors.textSecondary
const handleOfflineModeChange = useCallback(
async (enabled: boolean) => {
+ const apply = (next: Settings) => {
+ onSettingsLocal(next)
+ onSettingsChange(next)
+ }
if (enabled) {
try {
const stats = await NativeLocationService.getStats()
if (stats.queued > 0) {
const hasEndpoint = !!settings.endpoint
const buttons = [
- ...(hasEndpoint ? [{ text: "Sync First", style: "primary" as const }] : []),
- { text: "Keep in Queue", style: "secondary" as const },
+ ...(hasEndpoint ? [{ text: "Sync first", style: "primary" as const }] : []),
+ { text: "Keep in queue", style: "secondary" as const },
{ text: "Cancel", style: "secondary" as const }
]
const choice = await showChoice({
- title: "Unsent Locations",
+ title: "Unsent locations",
message: `You have ${stats.queued} locations waiting to sync. What would you like to do?`,
buttons
})
@@ -80,9 +137,9 @@ export function ConnectionSettings({
} catch {
// sync may fail, proceed to offline anyway
}
- onSettingsChange({ ...settings, isOfflineMode: true })
+ apply({ ...settings, isOfflineMode: true })
} else if (action === "keep") {
- onSettingsChange({ ...settings, isOfflineMode: true })
+ apply({ ...settings, isOfflineMode: true })
}
return
}
@@ -90,22 +147,65 @@ export function ConnectionSettings({
// stats fetch failed, proceed normally
}
}
- onSettingsChange({ ...settings, isOfflineMode: enabled })
+ apply({ ...settings, isOfflineMode: enabled })
},
- [settings, onSettingsChange]
+ [settings, onSettingsLocal, onSettingsChange]
)
+ const handleDraftChange = (text: string) => {
+ setDraft(text)
+ setValidation({ warnings: [] })
+ setTest(null)
+ }
+
+ /** Validates the draft, stores it when it passes and returns whether it did. Runs on blur and before a test. */
+ const commitDraft = useCallback(async (): Promise<boolean> => {
+ const text = draft.trim()
+ const store = (warnings: string[]) => {
+ setValidation({ warnings })
+ if (text !== settings.endpoint) {
+ const next = { ...settings, endpoint: text }
+ onSettingsLocal(next)
+ onSettingsChange(next)
+ }
+ return true
+ }
+ if (text === "") return store([])
+ if (!isEndpointAllowed(text)) {
+ setValidation({ error: SCHEME_ERROR, warnings: [] })
+ return false
+ }
+ const warnings = endpointCarriesKey(text) ? [KEY_WARNING] : []
+ if (text.startsWith("http://")) {
+ const isPrivate = await NativeLocationService.isPrivateEndpoint(text)
+ if (!isPrivate) {
+ setValidation({ error: PUBLIC_HTTP_ERROR, warnings: [] })
+ return false
+ }
+ return store([PRIVATE_HTTP_WARNING, ...warnings])
+ }
+ return store(warnings)
+ }, [draft, settings, onSettingsLocal, onSettingsChange])
+
+ const draftPasses = draft.trim() !== "" && isEndpointAllowed(draft.trim()) && !validation.error
+ const testBlocker = !draft.trim()
+ ? "Enter a server endpoint to test."
+ : !draftPasses
+ ? "Fix the address above to test."
+ : !hasFix
+ ? "Needs one recorded location to send. Start tracking first."
+ : null
+
const handleTestEndpoint = useCallback(async () => {
- if (!endpointInput) return
- setTesting(true)
- setTestResponse(null)
- setTestError(false)
+ Keyboard.dismiss()
+ if (testBlocker || !(await commitDraft())) return
+ const endpoint = draft.trim()
+ setTest({ kind: "testing" })
try {
const recentLocation = await NativeLocationService.getMostRecentLocation()
if (!recentLocation) {
- setTestResponse("No location data yet. Start tracking to collect a test point, then try again.")
- setTestError(true)
+ setTest({ kind: "done", ok: false, status: 0, at: Date.now(), message: "No recorded location to send." })
return
}
@@ -117,7 +217,6 @@ export function ConnectionSettings({
if (key) payload[key] = value
}
- // Core location fields
payload[fieldMap.lat] = recentLocation.latitude
payload[fieldMap.lon] = recentLocation.longitude
payload[fieldMap.acc] = Math.round(recentLocation.accuracy)
@@ -129,12 +228,17 @@ export function ConnectionSettings({
if (fieldMap.bear) payload[fieldMap.bear] = recentLocation.bearing ?? 0
if (fieldMap.tst) payload[fieldMap.tst] = Math.floor(Date.now() / 1000)
- const isPrivate = await NativeLocationService.isPrivateEndpoint(endpointInput)
+ const isPrivate = await NativeLocationService.isPrivateEndpoint(endpoint)
if (isPrivate) {
const granted = await ensureLocalNetworkPermission()
if (!granted) {
- setTestResponse("Local network permission required to reach this server")
- setTestError(true)
+ setTest({
+ kind: "done",
+ ok: false,
+ status: 0,
+ at: Date.now(),
+ message: "Local network permission required to reach this server"
+ })
return
}
}
@@ -149,231 +253,170 @@ export function ConnectionSettings({
if (key) customFields[key] = value
}
- const result = await NativeLocationService.testEndpoint({
- endpoint: endpointInput,
- method,
- apiFormat,
- payload,
- customFields
+ const result = await NativeLocationService.testEndpoint({ endpoint, method, apiFormat, payload, customFields })
+ if (!result.ok) logger.warn("[ConnectionSettings] Test failed:", result.status, result.errorMessage)
+ setTest({
+ kind: "done",
+ ok: result.ok,
+ status: result.status,
+ at: Date.now(),
+ message: result.ok ? undefined : result.errorMessage || `Server returned ${result.status}`
})
-
- if (result.ok) {
- setTestResponse("Connection successful")
- onSettingsChange({ ...settings, endpoint: endpointInput })
- } else {
- 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 || "Unknown error"
logger.warn("[ConnectionSettings] Test failed:", err?.name, msg)
- setTestResponse(`Connection failed: ${msg}`)
- setTestError(true)
- } finally {
- setTesting(false)
- timeout.set(() => setTestResponse(null), TEST_RESULT_DISPLAY_MS)
+ setTest({ kind: "done", ok: false, status: 0, at: Date.now(), message: `Connection failed: ${msg}` })
}
- }, [endpointInput, settings, onSettingsChange, timeout])
+ }, [testBlocker, commitDraft, draft, settings])
+
+ const example = endpointExample(settings.apiTemplate, settings.dawarichMode)
+ const helper = `Example: ${example}. https for public hosts, http only on a private host (192.168.x, 10.x, 172.16-31.x, 100.64.x, localhost). %DATE, %YEAR, %MONTH, %DAY and %TIMESTAMP expand when sending.`
+ const ServerGlyph = SERVER_ICONS[server.icon]
return (
- <View style={styles.section}>
- <SectionTitle>Connection</SectionTitle>
- <Card>
- <SettingRow label="Offline Mode" hint="Save locally, no network sync">
- <Switch
+ <View>
+ <Text style={[styles.intro, { color: colors.textSecondary }]}>
+ Where locations are sent and how the server knows it is you. Changes apply at once.
+ </Text>
+
+ <SectionTitle>Server</SectionTitle>
+ <Card rows>
+ <StateLine
+ icon={ServerGlyph}
+ iconColor={tone(server.tone)}
+ label={server.word}
+ caption={server.caption}
+ testID="server-state"
+ />
+ <Divider tight />
+ <SettingRow
+ label="Offline mode"
+ hint="On: locations stay on this device and nothing is sent. Off: they sync to the server below."
+ >
+ <Toggle
+ accessibilityLabel="Offline mode"
value={settings.isOfflineMode}
onValueChange={handleOfflineModeChange}
- trackColor={{
- false: colors.border,
- true: colors.primary + "80"
- }}
- thumbColor={settings.isOfflineMode ? colors.primary : colors.border}
/>
</SettingRow>
+ {/* A standalone tracker never sends, so the server and its details leave the screen with the toggle. */}
{!settings.isOfflineMode && (
<>
- <Divider />
+ <Divider tight />
- <View style={styles.inputGroup}>
- <View style={styles.inputHeader}>
- <Text style={[styles.inputLabel, { color: colors.text }]}>Server Endpoint</Text>
- {endpointInput && (
- <View
- style={[
- styles.protocolBadge,
- {
- backgroundColor: endpointInput.startsWith("https://")
- ? colors.success + "20"
- : colors.warning + "20"
- }
- ]}
- >
- <Text
- style={[
- styles.protocolText,
- {
- color: endpointInput.startsWith("https://") ? colors.success : colors.warning
- }
- ]}
- >
- {endpointInput.startsWith("https://") ? "HTTPS" : "HTTP"}
- </Text>
- </View>
- )}
+ <View style={styles.block}>
+ <View>
+ <TextField
+ label="Server endpoint"
+ testID="endpoint-input"
+ mono
+ value={draft}
+ onChangeText={handleDraftChange}
+ onBlur={() => {
+ commitDraft()
+ }}
+ placeholder={example}
+ autoCapitalize="none"
+ autoCorrect={false}
+ keyboardType="url"
+ error={validation.error}
+ />
+ {!validation.error && <FieldMessage>{helper}</FieldMessage>}
+ {validation.warnings.map((warning) => (
+ <FieldMessage key={warning} variant="warning">
+ {warning}
+ </FieldMessage>
+ ))}
</View>
- <TextInput
- style={[
- styles.input,
- {
- borderColor: colors.border,
- color: colors.text,
- backgroundColor: colors.background
- }
- ]}
- value={endpointInput}
- onChangeText={onEndpointInputChange}
- placeholder="https://your-server.com/api/locations"
- placeholderTextColor={colors.placeholder}
- autoCapitalize="none"
- autoCorrect={false}
- keyboardType="url"
- />
-
- {!endpointInput && (
- <FieldMessage variant="warning">No server configured. Locations are saved locally</FieldMessage>
- )}
+ <View>
+ <Button
+ icon={Radio}
+ title="Test connection"
+ onPress={handleTestEndpoint}
+ disabled={testBlocker !== null}
+ loading={test?.kind === "testing"}
+ testID="test-connection-btn"
+ />
+ <FieldMessage>
+ {testBlocker ?? "Sends your latest recorded location to this endpoint with your credentials."}
+ </FieldMessage>
+ </View>
- {endpointInput.startsWith("http://") && !endpointPrivate && (
- <FieldMessage variant="warning">HTTP only allowed for private IPs / localhost</FieldMessage>
+ {test?.kind === "testing" && (
+ <StateLine
+ icon={<ActivityIndicator size="small" color={colors.textLight} />}
+ iconColor={colors.textLight}
+ label="Testing"
+ caption="Sending your latest location"
+ testID="test-result"
+ />
)}
-
- {endpointInput.includes("%") && (
- <FieldMessage>Variables: %DATE, %YEAR, %MONTH, %DAY, %TIMESTAMP</FieldMessage>
+ {test?.kind === "done" && (
+ <View>
+ <StateLine
+ icon={test.ok ? CircleCheckBig : CircleAlert}
+ iconColor={test.ok ? colors.success : colors.error}
+ label={test.ok ? "Reachable" : "Not reachable"}
+ caption={`${test.status > 0 ? `HTTP ${test.status}` : "No response"} · ${formatTime(Math.floor(test.at / 1000))}`}
+ testID="test-result"
+ />
+ {!test.ok && test.message ? <FieldMessage variant="error">{test.message}</FieldMessage> : null}
+ </View>
)}
</View>
-
- <Button
- style={[
- styles.testButton,
- (!endpointInput || !isEndpointAllowed(endpointInput)) && styles.disabledButton
- ]}
- onPress={() => {
- if (!endpointInput || !isEndpointAllowed(endpointInput)) return
- handleTestEndpoint()
- }}
- title={testing ? "Testing..." : "Test Connection"}
- />
-
- {testResponse && (
- <View
- style={[
- styles.responseBox,
- {
- borderColor: testError ? colors.error : colors.success,
- backgroundColor: (testError ? colors.error : colors.success) + "15"
- }
- ]}
- >
- {!testError && <CheckCircle size={16} color={colors.success} />}
- <Text style={[styles.responseText, { color: testError ? colors.error : colors.success }]}>
- {testResponse}
- </Text>
- </View>
- )}
-
- <Divider />
-
- <Pressable
- style={({ pressed }) => [styles.linkRow, pressed && { opacity: colors.pressedOpacity }]}
- onPress={() => navigation.navigate("Auth Settings")}
- >
- <View style={styles.linkContent}>
- <Text style={[styles.linkLabel, { color: colors.text }]}>Authentication & Headers</Text>
- <Text style={[styles.linkSub, { color: colors.textSecondary }]}>
- Basic auth, bearer tokens, custom headers
- </Text>
- </View>
- <ChevronRight size={20} color={colors.textLight} />
- </Pressable>
</>
)}
</Card>
+
+ {!settings.isOfflineMode && (
+ <>
+ <SectionTitle style={styles.groupTop}>Server details</SectionTitle>
+ <Card rows>
+ <ListItem
+ testID="nav-request-format"
+ icon={Braces}
+ label="Request format"
+ sub={requestSummary}
+ onPress={() => navigation.navigate("Request Format")}
+ />
+ <Divider tight inset />
+ <ListItem
+ testID="nav-auth-settings"
+ icon={KeyRound}
+ label="Authentication"
+ sub={authSummary}
+ onPress={() => navigation.navigate("Auth Settings")}
+ />
+ <Divider tight inset />
+ <ListItem
+ testID="nav-mtls-settings"
+ icon={ShieldCheck}
+ label="Client certificate"
+ sub={certificateSummary}
+ onPress={() => navigation.navigate("mTLS Settings")}
+ />
+ </Card>
+ </>
+ )}
</View>
)
}
const styles = StyleSheet.create({
- section: {
- marginBottom: 24
- },
- inputGroup: {
- marginBottom: 12
- },
- inputHeader: {
- flexDirection: "row",
- justifyContent: "space-between",
- alignItems: "center",
- marginBottom: 10
- },
- inputLabel: {
- fontSize: 15,
- ...fonts.semiBold
- },
- protocolBadge: {
- paddingHorizontal: 10,
- paddingVertical: 4,
- borderRadius: 12
- },
- protocolText: {
- fontSize: 11,
- ...fonts.bold
- },
- input: {
- borderWidth: 1.5,
- padding: 16,
- borderRadius: 12,
- fontSize: 15,
- ...fonts.regular
- },
- testButton: {
- marginTop: 12
- },
- disabledButton: {
- opacity: 0.5
- },
- responseBox: {
- marginTop: 12,
- padding: 14,
- borderWidth: 1.5,
- borderRadius: 12,
- flexDirection: "row",
- alignItems: "center",
- justifyContent: "center",
- gap: 8
- },
- responseText: {
- fontSize: 14,
- ...fonts.semiBold
- },
- linkRow: {
- flexDirection: "row",
- justifyContent: "space-between",
- alignItems: "center",
- paddingVertical: 12
- },
- linkContent: {
- flex: 1
+ intro: {
+ fontSize: fontSizes.body,
+ ...fonts.regular,
+ lineHeight: lineHeights.body,
+ marginBottom: space.lg
},
- linkLabel: {
- fontSize: 16,
- ...fonts.semiBold,
- marginBottom: 2
+ groupTop: {
+ marginTop: space.xl
},
- linkSub: {
- fontSize: 13,
- ...fonts.regular
+ block: {
+ paddingTop: space.lg,
+ paddingBottom: space.lg,
+ gap: space.lg
}
})
diff --git a/apps/mobile/src/components/features/settings/MtlsSection.tsx b/apps/mobile/src/components/features/settings/MtlsSection.tsx
index 3959ca3c..0d33ac86 100644
--- a/apps/mobile/src/components/features/settings/MtlsSection.tsx
+++ b/apps/mobile/src/components/features/settings/MtlsSection.tsx
@@ -4,15 +4,17 @@
*/
import React, { useState, useCallback, useEffect } from "react"
-import { Text, StyleSheet, TextInput, View } from "react-native"
+import { Text, StyleSheet, View, ActivityIndicator } from "react-native"
+import { CircleAlert, ShieldCheck, TriangleAlert, type LucideIcon } from "lucide-react-native"
import { useTheme } from "../../../hooks/useTheme"
-import { fonts, fontSizes } from "../../../styles/typography"
-import { SectionTitle, Card, Divider, Button, FieldMessage } from "../../index"
+import { fonts, fontSizes, lineHeights } from "../../../styles/typography"
+import { SectionTitle, Card, Divider, Button, FieldMessage, TextField, StateLine, StatRow } from "../../index"
import NativeLocationService from "../../../services/NativeLocationService"
+import { showChoice, showConfirm } from "../../../services/modalService"
import { ClientCertInfoResult } from "../../../types/global"
+import { describeCertificate, type CertificateState } from "../../../utils/certificateState"
import { logger } from "../../../utils/logger"
-
-const EXPIRY_WARNING_DAYS = 14
+import { space } from "../../../constants"
const CLIENT_CERT_ERR: Record<string, string> = {
E_CERT_PASSWORD: "Incorrect password",
@@ -30,6 +32,10 @@ function errMsg(map: Record<string, string>, err: any, fallback: string): string
type ImportState =
{ kind: "idle" } | { kind: "picked"; b64: string; password: string; importing: boolean; error: string | null }
+const PICK_LINE = "Key stays in the device credential store, survives reinstalling Colota, never backed up."
+const IMPORT_LINE =
+ "Key moves into the Android Keystore and never leaves the device. The file password is used once and discarded. Not backed up, import again after a restore."
+
export function MtlsSection() {
const { colors } = useTheme()
const [certInfo, setCertInfo] = useState<ClientCertInfoResult | null>(null)
@@ -71,6 +77,13 @@ export function MtlsSection() {
}, [refresh])
const handleClearServerCa = useCallback(async () => {
+ const confirmed = await showConfirm({
+ title: "Remove trusted CA?",
+ message: "Connections to a server signed by it will fail until you import it again.",
+ confirmText: "Remove",
+ destructive: true
+ })
+ if (!confirmed) return
try {
await NativeLocationService.clearServerCa()
await refresh()
@@ -83,7 +96,7 @@ export function MtlsSection() {
setClientPickError(null)
try {
const result = await NativeLocationService.pickKeyChainCert()
- if (!result) return // user cancelled
+ if (!result) return
await refresh()
} catch (err: any) {
logger.error("[MtlsSection] pickKeyChainCert failed:", err)
@@ -95,7 +108,7 @@ export function MtlsSection() {
setClientPickError(null)
try {
const b64 = await NativeLocationService.pickClientCertFile()
- if (!b64) return // user cancelled
+ if (!b64) return
setImportState({ kind: "picked", b64, password: "", importing: false, error: null })
} catch (err: any) {
logger.error("[MtlsSection] pick failed:", err)
@@ -115,11 +128,28 @@ export function MtlsSection() {
}
}, [importState, refresh])
- const handleCancelImport = useCallback(() => {
- setImportState({ kind: "idle" })
- }, [])
+ const handleReplace = useCallback(async () => {
+ const choice = await showChoice({
+ title: "Replace certificate",
+ message: "The current certificate is replaced as soon as the new one is read.",
+ buttons: [
+ { text: "Pick from device", style: "primary" },
+ { text: "Import .p12", style: "secondary" },
+ { text: "Cancel", style: "secondary" }
+ ]
+ })
+ if (choice === 0) handlePickKeyChain()
+ else if (choice === 1) handlePickFile()
+ }, [handlePickKeyChain, handlePickFile])
const handleRemove = useCallback(async () => {
+ const confirmed = await showConfirm({
+ title: "Remove client certificate?",
+ message: "Requests to a server that requires it will fail until you add one again.",
+ confirmText: "Remove",
+ destructive: true
+ })
+ if (!confirmed) return
try {
await NativeLocationService.clearClientCert()
await refresh()
@@ -130,190 +160,153 @@ export function MtlsSection() {
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 style={styles.loading}>
+ <ActivityIndicator size="large" color={colors.primary} />
</View>
)
}
return (
<>
- <View style={styles.section}>
- <SectionTitle>Client Certificate (mTLS)</SectionTitle>
- <Card>
- {importState.kind === "picked" ? (
+ <SectionTitle>Client certificate</SectionTitle>
+ <Card rows>
+ {importState.kind === "picked" ? (
+ <View style={styles.block}>
<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
- }
- ]}
+ <TextField
+ label="File password"
+ testID="p12-password"
value={importState.password}
onChangeText={(v) => setImportState({ ...importState, password: v, error: null })}
- placeholder="PKCS12 password"
- placeholderTextColor={colors.placeholder}
+ placeholder="Leave empty if the file has none"
autoCapitalize="none"
autoCorrect={false}
- secureTextEntry
- editable={!importState.importing}
+ secure
+ disabled={importState.importing}
+ error={importState.error ?? undefined}
/>
- {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>
+ {!importState.error && (
+ <FieldMessage>
+ Used once to unwrap the key, then discarded. Leave empty if the file has none.
+ </FieldMessage>
+ )}
+ </View>
+ <View style={styles.buttonRow}>
+ <Button style={styles.flex1} onPress={handleImport} title="Import" loading={importState.importing} />
+ <Button
+ variant="ghost"
+ title="Cancel"
+ onPress={() => setImportState({ kind: "idle" })}
+ disabled={importState.importing}
+ />
+ </View>
+ </View>
+ ) : certInfo.configured ? (
+ <CertificateCard
+ state={describeCertificate(certInfo)}
+ subject={certInfo.subject}
+ issuer={certInfo.issuer}
+ onReplace={handleReplace}
+ onRemove={handleRemove}
+ removeTestID="remove-cert-btn"
+ />
+ ) : (
+ <View style={styles.block}>
+ <Text style={[styles.description, { color: colors.textSecondary }]}>
+ None. Only for a server that asks for one.
+ </Text>
+ <View>
+ <Button variant="secondary" onPress={handlePickKeyChain} title="Pick from device certificates" />
+ <FieldMessage>{PICK_LINE}</FieldMessage>
</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" />
+ <Button variant="secondary" onPress={handlePickFile} title="Import .p12 / .pfx" />
+ <FieldMessage>{IMPORT_LINE}</FieldMessage>
{clientPickError && <FieldMessage variant="error">{clientPickError}</FieldMessage>}
</View>
- )}
- </Card>
- </View>
+ </View>
+ )}
+ </Card>
- <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}
- />
- ) : (
+ <SectionTitle style={styles.groupTop}>Trusted server CA</SectionTitle>
+ <Card rows>
+ {caInfo.configured ? (
+ <CertificateCard
+ state={describeCertificate(caInfo, undefined, "server certificate checks will fail")}
+ subject={caInfo.subject}
+ onReplace={handlePickServerCa}
+ onRemove={handleClearServerCa}
+ removeTestID="remove-ca-btn"
+ />
+ ) : (
+ <View style={styles.block}>
+ <Text style={[styles.description, { color: colors.textSecondary }]}>
+ None. Public CAs such as Let's Encrypt work without it. Add one only for a private or self-signed CA.
+ Certificates you installed on the device are not used.
+ </Text>
<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)" />
+ <Button variant="secondary" onPress={handlePickServerCa} title="Import CA (.crt / .pem)" />
+ <FieldMessage>Encrypted on this device and included in encrypted backups.</FieldMessage>
{caError && <FieldMessage variant="error">{caError}</FieldMessage>}
</View>
- )}
- </Card>
- </View>
+ </View>
+ )}
+ </Card>
</>
)
}
-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
+const STATE_ICONS: Record<CertificateState["state"], LucideIcon> = {
+ none: ShieldCheck,
+ valid: ShieldCheck,
+ expiring: TriangleAlert,
+ expired: CircleAlert,
+ unreadable: CircleAlert
}
-function CertCard({
- info,
- showIssuer,
- expiryWarningDays,
- removeLabel,
- expiredMessage,
- expiringSoonMessage,
- errorPrefix,
+function CertificateCard({
+ state,
+ subject,
+ issuer,
+ onReplace,
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
-
+ removeTestID
+}: {
+ state: CertificateState
+ subject?: string
+ issuer?: string
+ onReplace: () => void
+ onRemove: () => void
+ removeTestID: string
+}) {
+ const { colors } = useTheme()
+ const tone =
+ state.state === "valid"
+ ? colors.success
+ : state.state === "expiring"
+ ? colors.warning
+ : state.state === "none"
+ ? colors.textSecondary
+ : colors.error
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`})`}
+ <>
+ <StateLine
+ icon={STATE_ICONS[state.state]}
+ iconColor={tone}
+ label={state.word}
+ caption={state.caption}
+ testID="certificate-state"
/>
- {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} />
+ <Divider tight />
+ <View style={styles.details}>
+ {subject ? <StatRow label="Subject" value={shortenDn(subject)} /> : null}
+ {issuer ? <StatRow label="Issuer" value={shortenDn(issuer)} /> : null}
+ <View style={styles.buttonRow}>
+ <Button style={styles.flex1} variant="ghost" title="Replace" onPress={onReplace} />
+ <Button style={styles.flex1} variant="danger" title="Remove" onPress={onRemove} testID={removeTestID} />
+ </View>
</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>
+ </>
)
}
@@ -327,47 +320,34 @@ function shortenDn(dn: string): string {
}
const styles = StyleSheet.create({
- section: {
- marginBottom: 24
+ loading: {
+ flex: 1,
+ justifyContent: "center",
+ alignItems: "center"
},
- muted: {
- fontSize: 13,
- ...fonts.regular,
- lineHeight: 18
+ groupTop: {
+ marginTop: space.xl
},
- fieldLabel: {
- fontSize: fontSizes.label,
- ...fonts.semiBold,
- marginBottom: 8
+ block: {
+ paddingTop: space.lg,
+ paddingBottom: space.lg,
+ gap: space.lg
},
- input: {
- borderWidth: 1.5,
- padding: 14,
- borderRadius: 12,
- fontSize: 15
+ details: {
+ paddingTop: space.md,
+ paddingBottom: space.lg
},
- importButton: {
- marginTop: 12
+ description: {
+ fontSize: fontSizes.description,
+ ...fonts.regular,
+ lineHeight: lineHeights.description
},
buttonRow: {
flexDirection: "row",
- gap: 8,
- marginTop: 12,
+ gap: space.md,
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.tsx
index 1173429b..940adb5a 100644
--- a/apps/mobile/src/components/features/settings/__tests__/ConnectionSettings.test.tsx
+++ b/apps/mobile/src/components/features/settings/__tests__/ConnectionSettings.test.tsx
@@ -1,32 +1,32 @@
import React from "react"
import { render, fireEvent, waitFor } from "@testing-library/react-native"
import { DEFAULT_SETTINGS, Settings } from "../../../../types/global"
+import type { ServerState } from "../../../../utils/serverState"
jest.mock("../../../index", () => {
const R = require("react")
const { View, Text, Pressable } = require("react-native")
return {
+ ListItem: require("../../../../testing/componentStubs").ListItemStub,
+ TextField: require("../../../../testing/componentStubs").TextFieldStub,
+ Toggle: function (props: any) {
+ return require("react").createElement(require("react-native").Switch, {
+ testID: props.testID,
+ value: props.value,
+ onValueChange: props.onValueChange,
+ disabled: props.disabled,
+ accessibilityLabel: props.accessibilityLabel
+ })
+ },
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 }, R.createElement(Text, null, title)),
- SettingRow: ({ label, hint, children }: any) =>
+ Button: ({ title, onPress, disabled, loading, testID }: any) =>
R.createElement(
- View,
- null,
- R.createElement(Text, null, label),
- hint && R.createElement(Text, null, hint),
- children
+ Pressable,
+ { onPress, disabled, testID, accessibilityRole: "button", accessibilityState: { disabled, busy: loading } },
+ R.createElement(Text, null, title)
),
- FieldMessage: ({ children }: any) => R.createElement(Text, null, children)
- }
-})
-
-jest.mock("../../../ui/SettingRow", () => {
- const R = require("react")
- const { View, Text } = require("react-native")
- return {
SettingRow: ({ label, hint, children }: any) =>
R.createElement(
View,
@@ -34,22 +34,15 @@ jest.mock("../../../ui/SettingRow", () => {
R.createElement(Text, null, label),
hint && R.createElement(Text, null, hint),
children
- )
- }
-})
-
-jest.mock("lucide-react-native", () => {
- const R = require("react")
- const { View } = require("react-native")
- return {
- CheckCircle: () => R.createElement(View, null),
- ChevronRight: () => R.createElement(View, null)
+ ),
+ StateLine: ({ label, caption, testID }: any) =>
+ R.createElement(View, { testID }, R.createElement(Text, null, label), R.createElement(Text, null, caption)),
+ FieldMessage: ({ children }: any) => R.createElement(Text, null, children)
}
})
const mockGetStats = jest.fn().mockResolvedValue({ queued: 0, sent: 0, total: 0, today: 0, databaseSizeMB: 0 })
const mockManualFlush = jest.fn().mockResolvedValue(undefined)
-const mockClearQueue = jest.fn().mockResolvedValue(5)
const mockGetMostRecentLocation = jest.fn().mockResolvedValue(null)
const mockIsEndpointPrivate = jest.fn().mockResolvedValue(false)
const mockTestEndpoint = jest.fn().mockResolvedValue({ ok: true, status: 200 })
@@ -59,7 +52,6 @@ jest.mock("../../../../services/NativeLocationService", () => ({
default: {
getStats: (...args: any[]) => mockGetStats(...args),
manualFlush: (...args: any[]) => mockManualFlush(...args),
- clearQueue: (...args: any[]) => mockClearQueue(...args),
getMostRecentLocation: (...args: any[]) => mockGetMostRecentLocation(...args),
isPrivateEndpoint: (...args: any[]) => mockIsEndpointPrivate(...args),
testEndpoint: (...args: any[]) => mockTestEndpoint(...args)
@@ -71,16 +63,12 @@ jest.mock("../../../../services/modalService", () => ({
showChoice: (...args: any[]) => mockShowChoice(...args)
}))
-jest.mock("../../../../utils/settingsValidation", () => ({
- isEndpointAllowed: () => true
-}))
-
jest.mock("../../../../services/LocationServicePermission", () => ({
ensureLocalNetworkPermission: jest.fn().mockResolvedValue(true)
}))
-jest.mock("../../../../hooks/useTimeout", () => ({
- useTimeout: () => ({ set: jest.fn(), clear: jest.fn() })
+jest.mock("../../../../hooks/useTheme", () => ({
+ useTheme: () => ({ colors: require("@colota/shared").lightColors })
}))
jest.mock("../../../../utils/logger", () => ({
@@ -89,268 +77,281 @@ jest.mock("../../../../utils/logger", () => ({
import { ConnectionSettings } from "../ConnectionSettings"
-const mockColors = {
- primary: "#0d9488",
- primaryDark: "#115E59",
- text: "#000",
- textSecondary: "#6b7280",
- textLight: "#9ca3af",
- background: "#fff",
- border: "#e5e7eb",
- success: "#22c55e",
- warning: "#f59e0b",
- error: "#ef4444",
- placeholder: "#9ca3af",
- card: "#fff"
-} as any
-
-const mockNavigation = { navigate: jest.fn() }
+const synced: ServerState = {
+ icon: "check",
+ tone: "success",
+ word: "Synced",
+ caption: "Last sync 14:02 · queue empty",
+ rowSub: "example.com"
+}
+const location = { latitude: 52.5, longitude: 13.4, accuracy: 10, altitude: 50, speed: 0, battery: 80 }
+const mockNavigation = { navigate: jest.fn() } as any
describe("ConnectionSettings", () => {
- let mockOnSettingsChange: jest.Mock
+ let onSettingsLocal: jest.Mock
+ let onSettingsChange: jest.Mock
beforeEach(() => {
jest.clearAllMocks()
- mockOnSettingsChange = jest.fn()
+ onSettingsLocal = jest.fn()
+ onSettingsChange = jest.fn()
+ mockGetMostRecentLocation.mockResolvedValue(location)
+ mockIsEndpointPrivate.mockResolvedValue(false)
+ mockTestEndpoint.mockResolvedValue({ ok: true, status: 200 })
})
- function renderComponent(overrides?: Partial<Settings>, endpointInput = "https://example.com/api/locations") {
- const settings = { ...DEFAULT_SETTINGS, ...overrides }
+ function renderComponent(
+ overrides?: Partial<Settings>,
+ props: Partial<React.ComponentProps<typeof ConnectionSettings>> = {}
+ ) {
+ const settings = { ...DEFAULT_SETTINGS, endpoint: "https://example.com/api", ...overrides }
return render(
<ConnectionSettings
settings={settings}
- endpointInput={endpointInput}
- onEndpointInputChange={jest.fn()}
- onSettingsChange={mockOnSettingsChange}
- colors={mockColors}
+ onSettingsLocal={onSettingsLocal}
+ onSettingsChange={onSettingsChange}
+ server={synced}
+ hasFix
+ requestSummary="Traccar · GET"
+ authSummary="Bearer token"
+ certificateSummary="Not set"
navigation={mockNavigation}
+ {...props}
/>
)
}
- it("renders Connection section title", () => {
- const { getByText } = renderComponent()
-
- expect(getByText("Connection")).toBeTruthy()
- })
+ const endpointField = (api: ReturnType<typeof render>) => api.getByTestId("endpoint-input")
- it("shows Offline Mode toggle", () => {
- const { getByText } = renderComponent()
+ describe("the server card", () => {
+ it("opens with what sync is doing now, then the configuration that produced it", () => {
+ const { getByTestId, getByText } = renderComponent()
- expect(getByText("Offline Mode")).toBeTruthy()
- expect(getByText("Save locally, no network sync")).toBeTruthy()
- })
+ expect(getByTestId("server-state")).toBeTruthy()
+ expect(getByText("Synced")).toBeTruthy()
+ expect(getByText("Last sync 14:02 · queue empty")).toBeTruthy()
+ expect(getByText("Offline mode")).toBeTruthy()
+ expect(getByText("Server endpoint")).toBeTruthy()
+ })
- describe("online mode", () => {
- it("shows Server Endpoint input", () => {
- const { getByText } = renderComponent()
+ it("drops the server and its details under offline mode, since a standalone tracker never sends", () => {
+ const { getByText, queryByTestId, queryByText } = renderComponent({ isOfflineMode: true })
- expect(getByText("Server Endpoint")).toBeTruthy()
+ expect(getByText("Synced")).toBeTruthy()
+ expect(getByText("Offline mode")).toBeTruthy()
+ expect(queryByTestId("endpoint-input")).toBeNull()
+ expect(queryByTestId("test-connection-btn")).toBeNull()
+ expect(queryByText("Server details")).toBeNull()
+ expect(queryByTestId("nav-auth-settings")).toBeNull()
})
- it("shows Test Connection button", () => {
- const { getByText } = renderComponent()
+ it("shows the template's endpoint shape as the persistent helper", () => {
+ const { getByText } = renderComponent({ apiTemplate: "traccar" })
- expect(getByText("Test Connection")).toBeTruthy()
+ expect(getByText(/^Example: http:\/\/192\.168\.1\.10:5055\./)).toBeTruthy()
})
- it("shows Authentication & Headers link", () => {
- const { getByText } = renderComponent()
-
- expect(getByText("Authentication & Headers")).toBeTruthy()
+ it("lists the three server details as rows whose sub is the stored value", () => {
+ const { getByText, getByTestId } = renderComponent()
+
+ expect(getByText("Traccar · GET")).toBeTruthy()
+ expect(getByText("Bearer token")).toBeTruthy()
+ expect(getByText("Not set")).toBeTruthy()
+ fireEvent.press(getByTestId("nav-request-format"))
+ fireEvent.press(getByTestId("nav-auth-settings"))
+ fireEvent.press(getByTestId("nav-mtls-settings"))
+ expect(mockNavigation.navigate.mock.calls.map((c: any[]) => c[0])).toEqual([
+ "Request Format",
+ "Auth Settings",
+ "mTLS Settings"
+ ])
})
+ })
+
+ describe("the endpoint field", () => {
+ it("never saves on a keystroke, since every save restarts the service", () => {
+ const api = renderComponent()
- it("shows HTTPS badge for https endpoint", () => {
- const { getByText } = renderComponent({}, "https://example.com/api/locations")
+ fireEvent.changeText(endpointField(api), "https://exam")
- expect(getByText("HTTPS")).toBeTruthy()
+ expect(onSettingsChange).not.toHaveBeenCalled()
})
- it("shows HTTP badge for http endpoint", () => {
- const { getByText } = renderComponent({}, "http://192.168.1.1/api/locations")
+ it("stores a passing address on blur, local state first, then the immediate save", async () => {
+ const api = renderComponent()
+
+ fireEvent.changeText(endpointField(api), "https://tracks.example.org/api")
+ fireEvent(endpointField(api), "blur")
- expect(getByText("HTTP")).toBeTruthy()
+ await waitFor(() =>
+ expect(onSettingsChange).toHaveBeenCalledWith(
+ expect.objectContaining({ endpoint: "https://tracks.example.org/api" })
+ )
+ )
+ expect(onSettingsLocal.mock.invocationCallOrder[0]).toBeLessThan(onSettingsChange.mock.invocationCallOrder[0])
})
- })
- describe("offline mode", () => {
- it("hides Server Endpoint input", () => {
- const { queryByText } = renderComponent({ isOfflineMode: true })
+ it("refuses plain http to a public host with an error and stores nothing", async () => {
+ const api = renderComponent()
- expect(queryByText("Server Endpoint")).toBeNull()
+ fireEvent.changeText(endpointField(api), "http://example.com/api")
+ fireEvent(endpointField(api), "blur")
+
+ expect(await api.findByText("http is refused for a public host. Use https.")).toBeTruthy()
+ expect(onSettingsChange).not.toHaveBeenCalled()
+ expect(api.getByTestId("test-connection-btn").props.accessibilityState.disabled).toBe(true)
})
- it("hides Test Connection button", () => {
- const { queryByText } = renderComponent({ isOfflineMode: true })
+ it("stores plain http to a private host and says it is not encrypted", async () => {
+ mockIsEndpointPrivate.mockResolvedValue(true)
+ const api = renderComponent()
+
+ fireEvent.changeText(endpointField(api), "http://192.168.1.10:5055")
+ fireEvent(endpointField(api), "blur")
- expect(queryByText("Test Connection")).toBeNull()
+ expect(await api.findByText("Not encrypted: plain http on a private host.")).toBeTruthy()
+ expect(onSettingsChange).toHaveBeenCalledWith(expect.objectContaining({ endpoint: "http://192.168.1.10:5055" }))
})
- it("hides Authentication & Headers link", () => {
- const { queryByText } = renderComponent({ isOfflineMode: true })
+ it("warns when the address carries a key, because settings store it in the clear", async () => {
+ const api = renderComponent()
+
+ fireEvent.changeText(endpointField(api), "https://d.example/api?api_key=abc")
+ fireEvent(endpointField(api), "blur")
- expect(queryByText("Authentication & Headers")).toBeNull()
+ expect(await api.findByText(/^This address carries a key\./)).toBeTruthy()
+ expect(onSettingsChange).toHaveBeenCalled()
})
- })
- describe("offline mode toggle with queue", () => {
- it("enables offline mode directly when queue is empty", async () => {
- mockGetStats.mockResolvedValue({ queued: 0, sent: 0, total: 0, today: 0, databaseSizeMB: 0 })
- const { getAllByRole } = renderComponent()
+ it("names the scheme rule when the text is not an address", async () => {
+ const api = renderComponent()
- const toggle = getAllByRole("switch")[0]
- fireEvent(toggle, "valueChange", true)
+ fireEvent.changeText(endpointField(api), "tracks.example.org")
+ fireEvent(endpointField(api), "blur")
- await waitFor(() => {
- expect(mockOnSettingsChange).toHaveBeenCalledWith(expect.objectContaining({ isOfflineMode: true }))
- })
+ expect(await api.findByText("Starts with http:// or https:// and names a host.")).toBeTruthy()
+ expect(onSettingsChange).not.toHaveBeenCalled()
})
- it("shows choice dialog when queue has items", async () => {
- mockGetStats.mockResolvedValue({ queued: 10, sent: 50, total: 60, today: 5, databaseSizeMB: 1 })
- mockShowChoice.mockResolvedValue(2) // Cancel
- const { getAllByRole } = renderComponent({ endpoint: "https://example.com/api" })
+ it("stores an emptied field, since clearing the server is a deliberate delete", async () => {
+ const api = renderComponent()
- const toggle = getAllByRole("switch")[0]
- fireEvent(toggle, "valueChange", true)
+ fireEvent.changeText(endpointField(api), "")
+ fireEvent(endpointField(api), "blur")
- await waitFor(() => {
- expect(mockShowChoice).toHaveBeenCalledWith(
- expect.objectContaining({
- title: "Unsent Locations",
- message: expect.stringContaining("10 locations")
- })
- )
- })
+ await waitFor(() => expect(onSettingsChange).toHaveBeenCalledWith(expect.objectContaining({ endpoint: "" })))
+ expect(api.getByText("Enter a server endpoint to test.")).toBeTruthy()
})
+ })
- it("syncs first then enables offline when Sync First chosen", async () => {
- mockGetStats.mockResolvedValue({ queued: 10, sent: 50, total: 60, today: 5, databaseSizeMB: 1 })
- mockShowChoice.mockResolvedValue(0) // Sync First (with endpoint)
- const { getAllByRole } = renderComponent({ endpoint: "https://example.com/api" })
+ describe("test connection", () => {
+ it("is disabled with the reason while nothing has been recorded", () => {
+ const { getByText, getByTestId } = renderComponent({}, { hasFix: false })
- const toggle = getAllByRole("switch")[0]
- fireEvent(toggle, "valueChange", true)
+ expect(getByTestId("test-connection-btn").props.accessibilityState.disabled).toBe(true)
+ expect(getByText("Needs one recorded location to send. Start tracking first.")).toBeTruthy()
+ })
- await waitFor(() => {
- expect(mockManualFlush).toHaveBeenCalled()
- expect(mockOnSettingsChange).toHaveBeenCalledWith(expect.objectContaining({ isOfflineMode: true }))
- })
+ it("says what it sends while enabled", () => {
+ const { getByText } = renderComponent()
+
+ expect(getByText("Sends your latest recorded location to this endpoint with your credentials.")).toBeTruthy()
})
- it("keeps queue and enables offline when Keep chosen", async () => {
- mockGetStats.mockResolvedValue({ queued: 10, sent: 50, total: 60, today: 5, databaseSizeMB: 1 })
- mockShowChoice.mockResolvedValue(1) // Keep in Queue (with endpoint)
- const { getAllByRole } = renderComponent({ endpoint: "https://example.com/api" })
+ it("reports Reachable with the code and the time, and persists nothing itself", async () => {
+ const api = renderComponent()
- const toggle = getAllByRole("switch")[0]
- fireEvent(toggle, "valueChange", true)
+ fireEvent.press(api.getByTestId("test-connection-btn"))
- await waitFor(() => {
- expect(mockManualFlush).not.toHaveBeenCalled()
- expect(mockClearQueue).not.toHaveBeenCalled()
- expect(mockOnSettingsChange).toHaveBeenCalledWith(expect.objectContaining({ isOfflineMode: true }))
- })
+ expect(await api.findByText("Reachable")).toBeTruthy()
+ expect(api.getByText(/^HTTP 200 · /)).toBeTruthy()
+ expect(mockTestEndpoint).toHaveBeenCalledWith(expect.objectContaining({ endpoint: "https://example.com/api" }))
+ expect(onSettingsChange).not.toHaveBeenCalled()
})
- it("does not enable offline when Cancel chosen", async () => {
- mockGetStats.mockResolvedValue({ queued: 10, sent: 50, total: 60, today: 5, databaseSizeMB: 1 })
- mockShowChoice.mockResolvedValue(2) // Cancel (with endpoint)
- const { getAllByRole } = renderComponent({ endpoint: "https://example.com/api" })
+ it("reports Not reachable with the server's own sentence, which stays until the next edit", async () => {
+ mockTestEndpoint.mockResolvedValue({
+ ok: false,
+ status: 0,
+ errorMessage: "Server certificate is not trusted (self-signed or unknown CA)."
+ })
+ const api = renderComponent()
- const toggle = getAllByRole("switch")[0]
- fireEvent(toggle, "valueChange", true)
+ fireEvent.press(api.getByTestId("test-connection-btn"))
- await waitFor(() => {
- expect(mockShowChoice).toHaveBeenCalled()
- })
- expect(mockOnSettingsChange).not.toHaveBeenCalled()
+ expect(await api.findByText("Not reachable")).toBeTruthy()
+ expect(api.getByText(/^No response · /)).toBeTruthy()
+ expect(api.getByText(/Server certificate is not trusted/)).toBeTruthy()
+
+ fireEvent.changeText(endpointField(api), "https://example.com/api/v2")
+ expect(api.queryByText("Not reachable")).toBeNull()
})
- it("disables offline mode directly without dialog", async () => {
- const { getAllByRole } = renderComponent({ isOfflineMode: true })
+ it("falls back to the status code when the server sends no sentence", async () => {
+ mockTestEndpoint.mockResolvedValue({ ok: false, status: 401 })
+ const api = renderComponent()
- const toggle = getAllByRole("switch")[0]
- fireEvent(toggle, "valueChange", false)
+ fireEvent.press(api.getByTestId("test-connection-btn"))
- await waitFor(() => {
- expect(mockOnSettingsChange).toHaveBeenCalledWith(expect.objectContaining({ isOfflineMode: false }))
- })
- expect(mockShowChoice).not.toHaveBeenCalled()
+ expect(await api.findByText("Server returned 401")).toBeTruthy()
+ expect(api.getByText(/^HTTP 401 · /)).toBeTruthy()
})
+ })
- it("omits Sync First button when no endpoint configured", async () => {
- mockGetStats.mockResolvedValue({ queued: 5, sent: 0, total: 5, today: 5, databaseSizeMB: 0.1 })
- mockShowChoice.mockResolvedValue(0) // Keep in Queue (no endpoint, so index 0 = keep)
- const { getAllByRole } = renderComponent({ endpoint: "" }, "")
+ describe("offline mode toggle with queue", () => {
+ const toggle = (api: ReturnType<typeof render>) => api.getAllByRole("switch")[0]
- const toggle = getAllByRole("switch")[0]
- fireEvent(toggle, "valueChange", true)
+ it("enables offline mode directly when queue is empty, local state first", async () => {
+ mockGetStats.mockResolvedValue({ queued: 0, sent: 0, total: 0, today: 0, databaseSizeMB: 0 })
+ const api = renderComponent()
- await waitFor(() => {
- expect(mockShowChoice).toHaveBeenCalledWith(
- expect.objectContaining({
- buttons: expect.not.arrayContaining([expect.objectContaining({ text: "Sync First" })])
- })
- )
- })
+ fireEvent(toggle(api), "valueChange", true)
+
+ await waitFor(() =>
+ expect(onSettingsChange).toHaveBeenCalledWith(expect.objectContaining({ isOfflineMode: true }))
+ )
+ expect(onSettingsLocal).toHaveBeenCalledWith(expect.objectContaining({ isOfflineMode: true }))
})
- })
- describe("test connection HTTPS enforcement", () => {
- const location = {
- latitude: 52.5,
- longitude: 13.4,
- accuracy: 10,
- altitude: 50,
- speed: 0,
- battery: 80,
- batteryStatus: 2,
- bearing: 0
- }
-
- it("shows native error message when testEndpoint rejects the protocol", async () => {
- mockGetMostRecentLocation.mockResolvedValue(location)
- 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")
+ it("asks about unsent locations and syncs first when told to", async () => {
+ mockGetStats.mockResolvedValue({ queued: 10, sent: 50, total: 60, today: 5, databaseSizeMB: 1 })
+ mockShowChoice.mockResolvedValue(0)
+ const api = renderComponent()
- fireEvent.press(getByText("Test Connection"))
+ fireEvent(toggle(api), "valueChange", true)
- await waitFor(() => {
- expect(getByText(/HTTPS is required for public endpoints/)).toBeTruthy()
- })
+ await waitFor(() => expect(mockManualFlush).toHaveBeenCalled())
+ expect(mockShowChoice).toHaveBeenCalledWith(
+ expect.objectContaining({ title: "Unsent locations", message: expect.stringContaining("10 locations") })
+ )
+ expect(onSettingsChange).toHaveBeenCalledWith(expect.objectContaining({ isOfflineMode: true }))
})
- 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")
+ it("does not enable offline when Cancel is chosen", async () => {
+ mockGetStats.mockResolvedValue({ queued: 10, sent: 50, total: 60, today: 5, databaseSizeMB: 1 })
+ mockShowChoice.mockResolvedValue(2)
+ const api = renderComponent()
- fireEvent.press(getByText("Test Connection"))
+ fireEvent(toggle(api), "valueChange", true)
- await waitFor(() => {
- expect(getByText("Connection successful")).toBeTruthy()
- })
+ await waitFor(() => expect(mockShowChoice).toHaveBeenCalled())
+ expect(onSettingsChange).not.toHaveBeenCalled()
})
- it("surfaces mTLS handshake error from native", async () => {
- mockGetMostRecentLocation.mockResolvedValue(location)
- 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")
+ it("omits Sync first when no endpoint is configured", async () => {
+ mockGetStats.mockResolvedValue({ queued: 5, sent: 0, total: 5, today: 5, databaseSizeMB: 0.1 })
+ mockShowChoice.mockResolvedValue(0)
+ const api = renderComponent({ endpoint: "" })
- fireEvent.press(getByText("Test Connection"))
+ fireEvent(toggle(api), "valueChange", true)
- await waitFor(() => {
- expect(getByText(/TLS handshake failed/)).toBeTruthy()
- })
+ await waitFor(() =>
+ expect(mockShowChoice).toHaveBeenCalledWith(
+ expect.objectContaining({
+ buttons: expect.not.arrayContaining([expect.objectContaining({ text: "Sync first" })])
+ })
+ )
+ )
})
})
})
diff --git a/apps/mobile/src/components/features/settings/__tests__/MtlsSection.test.tsx b/apps/mobile/src/components/features/settings/__tests__/MtlsSection.test.tsx
index eecb8b99..4efd4e36 100644
--- a/apps/mobile/src/components/features/settings/__tests__/MtlsSection.test.tsx
+++ b/apps/mobile/src/components/features/settings/__tests__/MtlsSection.test.tsx
@@ -1,44 +1,45 @@
import React from "react"
import { render, fireEvent, waitFor } from "@testing-library/react-native"
+import { ActivityIndicator } from "react-native"
+import { CERT_EXPIRY_WARNING_DAYS } from "../../../../constants"
jest.mock("../../../index", () => {
const R = require("react")
const { View, Text, Pressable } = require("react-native")
return {
+ TextField: require("../../../../testing/componentStubs").TextFieldStub,
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) =>
+ Button: ({ title, onPress, disabled, testID }: any) =>
R.createElement(
Pressable,
- { onPress, disabled, accessibilityRole: "button" },
+ { onPress, disabled, testID, accessibilityRole: "button" },
R.createElement(Text, null, title)
),
- FieldMessage: ({ children }: any) => R.createElement(Text, null, children)
+ FieldMessage: ({ children }: any) => R.createElement(Text, null, children),
+ StateLine: ({ label, caption, testID }: any) =>
+ R.createElement(View, { testID }, R.createElement(Text, null, label), R.createElement(Text, null, caption)),
+ StatRow: ({ label, value }: any) =>
+ R.createElement(View, null, R.createElement(Text, null, label), R.createElement(Text, null, value))
}
})
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
- }
- })
+ useTheme: () => ({ colors: require("@colota/shared").lightColors })
}))
jest.mock("../../../../utils/logger", () => ({
logger: { error: jest.fn(), warn: jest.fn(), info: jest.fn(), debug: jest.fn() }
}))
+const mockShowConfirm = jest.fn().mockResolvedValue(true)
+const mockShowChoice = jest.fn().mockResolvedValue(2)
+jest.mock("../../../../services/modalService", () => ({
+ showConfirm: (...a: any[]) => mockShowConfirm(...a),
+ showChoice: (...a: any[]) => mockShowChoice(...a)
+}))
+
const mockGetClientCertInfo = jest.fn().mockResolvedValue({ configured: false })
const mockGetServerCaInfo = jest.fn().mockResolvedValue({ configured: false })
const mockPickClientCertFile = jest.fn().mockResolvedValue(null)
@@ -67,268 +68,204 @@ jest.mock("../../../../services/NativeLocationService", () => ({
import { MtlsSection } from "../MtlsSection"
const ONE_DAY_MS = 24 * 60 * 60 * 1000
+const loaded = (daysLeft: number, extra: Record<string, unknown> = {}) => ({
+ configured: true,
+ subject: "CN=colota-test-client,O=Colota",
+ issuer: "CN=Test CA",
+ notBefore: Date.now() - ONE_DAY_MS,
+ notAfter: Date.now() + daysLeft * ONE_DAY_MS + 60_000,
+ ...extra
+})
describe("MtlsSection", () => {
beforeEach(() => {
jest.clearAllMocks()
mockGetClientCertInfo.mockResolvedValue({ configured: false })
mockGetServerCaInfo.mockResolvedValue({ configured: false })
+ mockShowConfirm.mockResolvedValue(true)
+ mockShowChoice.mockResolvedValue(2)
})
- 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
+ describe("loading and empty", () => {
+ it("spins before the first read resolves, never the word", () => {
mockGetClientCertInfo.mockReturnValue(new Promise(() => {}))
mockGetServerCaInfo.mockReturnValue(new Promise(() => {}))
- const { getByText } = render(<MtlsSection />)
- expect(getByText("Loading...")).toBeTruthy()
+ const { UNSAFE_getByType, queryByText } = render(<MtlsSection />)
+ expect(UNSAFE_getByType(ActivityIndicator)).toBeTruthy()
+ expect(queryByText("Loading...")).toBeNull()
+ })
+
+ it("offers the two paths as equals, each with its custody line", async () => {
+ const { findByText, getByText } = render(<MtlsSection />)
+
+ expect(await findByText("Pick from device certificates")).toBeTruthy()
+ expect(
+ getByText("Key stays in the device credential store, survives reinstalling Colota, never backed up.")
+ ).toBeTruthy()
+ expect(getByText("Import .p12 / .pfx")).toBeTruthy()
+ expect(getByText(/^Key moves into the Android Keystore/)).toBeTruthy()
+ expect(getByText("None. Only for a server that asks for one.")).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()
- })
+ it("says when a CA is needed at all and where it lives", async () => {
+ const { findByText, getByText } = render(<MtlsSection />)
+
+ expect(await findByText("Import CA (.crt / .pem)")).toBeTruthy()
+ expect(getByText(/^None\. Public CAs such as Let's Encrypt work without it\./)).toBeTruthy()
+ expect(getByText("Encrypted on this device and included in encrypted backups.")).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)
- })
+ mockGetClientCertInfo
+ .mockResolvedValueOnce({ configured: false })
+ .mockResolvedValueOnce(loaded(365, { source: "keychain" }))
+
+ const { findByText } = render(<MtlsSection />)
+ fireEvent.press(await findByText("Pick from device certificates"))
+
+ await waitFor(() => 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"))
+ const { findByText } = render(<MtlsSection />)
+ fireEvent.press(await findByText("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" })
+ describe("client cert: .p12 import", () => {
+ it("asks for the file password after a pick and says the password is used once", async () => {
+ mockPickClientCertFile.mockResolvedValueOnce("BASE64")
+ const { findByText, getByText } = render(<MtlsSection />)
- 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"))
+ fireEvent.press(await findByText("Import .p12 / .pfx"))
- await waitFor(() => expect(getByText("Incorrect password")).toBeTruthy())
- // Still in picked state - user can retry without re-picking file
- expect(getByText("Save")).toBeTruthy()
+ expect(await findByText("File password")).toBeTruthy()
+ expect(getByText("Used once to unwrap the key, then discarded. Leave empty if the file has none.")).toBeTruthy()
+ expect(getByText("Import")).toBeTruthy()
+ expect(getByText("Cancel")).toBeTruthy()
})
- it("surfaces invalid-PKCS12 error inline", async () => {
- mockPickClientCertFile.mockResolvedValueOnce("base64bytes")
- mockImportClientCert.mockRejectedValueOnce({ code: "E_CERT_INVALID", message: "not pkcs12" })
+ it("surfaces a wrong password on the field and keeps the form", async () => {
+ mockPickClientCertFile.mockResolvedValueOnce("BASE64")
+ mockImportClientCert.mockRejectedValueOnce({ code: "E_CERT_PASSWORD" })
+ const { findByText, getByText } = render(<MtlsSection />)
- 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"))
+ fireEvent.press(await findByText("Import .p12 / .pfx"))
+ fireEvent.press(await findByText("Import"))
- await waitFor(() => expect(getByText("Not a valid PKCS12 file")).toBeTruthy())
+ expect(await findByText("Incorrect password")).toBeTruthy()
+ expect(getByText("File password")).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()
- })
- })
- })
+ mockPickClientCertFile.mockResolvedValueOnce("BASE64")
+ const { findByText, queryByText } = render(<MtlsSection />)
- 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()
- })
- })
+ fireEvent.press(await findByText("Import .p12 / .pfx"))
+ fireEvent.press(await findByText("Cancel"))
- 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())
+ await waitFor(() => expect(queryByText("File password")).toBeNull())
+ expect(await findByText("Pick from device certificates")).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()
- })
+ describe("client cert: loaded", () => {
+ it("opens with the certificate's state and origin, then subject and issuer as ledger rows", async () => {
+ mockGetClientCertInfo.mockResolvedValue(loaded(320, { source: "keychain" }))
+ const { findByText, getByText } = render(<MtlsSection />)
+
+ expect(await findByText("Valid")).toBeTruthy()
+ expect(getByText(/^Until .* · device credential store$/)).toBeTruthy()
+ expect(getByText("colota-test-client")).toBeTruthy()
+ expect(getByText("Test CA")).toBeTruthy()
+ expect(getByText("Replace")).toBeTruthy()
+ expect(getByText("Remove")).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("warns inside the window as a word, never a fill", async () => {
+ mockGetClientCertInfo.mockResolvedValue(loaded(5, { source: "p12" }))
+ const { findByText } = render(<MtlsSection />)
+
+ expect(await findByText("Expires in 5 days")).toBeTruthy()
+ expect(CERT_EXPIRY_WARNING_DAYS).toBe(30)
})
- 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" })
+ it("says what an expired certificate will do", async () => {
+ mockGetClientCertInfo.mockResolvedValue(loaded(-1))
+ const { findByText, getByText } = render(<MtlsSection />)
- 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())
+ expect(await findByText("Expired")).toBeTruthy()
+ expect(getByText(/the server will refuse it$/)).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("removes only after the confirm that says what will fail", async () => {
+ mockGetClientCertInfo.mockResolvedValue(loaded(320))
+ mockShowConfirm.mockResolvedValueOnce(false)
+ const { findByTestId } = render(<MtlsSection />)
+
+ fireEvent.press(await findByTestId("remove-cert-btn"))
+ await waitFor(() =>
+ expect(mockShowConfirm).toHaveBeenCalledWith(
+ expect.objectContaining({ title: "Remove client certificate?", destructive: true })
+ )
+ )
+ expect(mockClearClientCert).not.toHaveBeenCalled()
+
+ mockShowConfirm.mockResolvedValueOnce(true)
+ fireEvent.press(await findByTestId("remove-cert-btn"))
+ await waitFor(() => expect(mockClearClientCert).toHaveBeenCalled())
+ expect(mockGetClientCertInfo).toHaveBeenCalledTimes(2)
})
- 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())
+ it("Replace offers the same two paths and runs the chosen one", async () => {
+ mockGetClientCertInfo.mockResolvedValue(loaded(320))
+ mockShowChoice.mockResolvedValueOnce(1)
+ mockPickClientCertFile.mockResolvedValueOnce("BASE64")
+ const { findByText } = render(<MtlsSection />)
+
+ fireEvent.press(await findByText("Replace"))
+
+ await waitFor(() =>
+ expect(mockShowChoice).toHaveBeenCalledWith(expect.objectContaining({ title: "Replace certificate" }))
+ )
+ expect(await findByText("File password")).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 })
+ describe("trusted server CA", () => {
+ it("shows friendly errors from the picker and the parser", async () => {
+ mockPickServerCaFile.mockResolvedValueOnce("BASE64")
+ mockImportServerCa.mockRejectedValueOnce({ code: "E_CA_INVALID" })
+ const { findByText } = render(<MtlsSection />)
- const { getByText } = render(<MtlsSection />)
- await waitFor(() => getByText("Remove Certificate"))
- fireEvent.press(getByText("Remove Certificate"))
+ fireEvent.press(await findByText("Import CA (.crt / .pem)"))
- await waitFor(() => {
- expect(mockClearClientCert).toHaveBeenCalled()
- expect(mockGetClientCertInfo).toHaveBeenCalledTimes(2)
- })
+ expect(await findByText(/^Not a valid X\.509 certificate/)).toBeTruthy()
})
- 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 })
+ it("reads Valid when loaded and removes only after the confirm", async () => {
+ mockGetServerCaInfo.mockResolvedValue(loaded(900))
+ const { findByTestId, getByText } = render(<MtlsSection />)
+
+ fireEvent.press(await findByTestId("remove-ca-btn"))
+
+ await waitFor(() =>
+ expect(mockShowConfirm).toHaveBeenCalledWith(expect.objectContaining({ title: "Remove trusted CA?" }))
+ )
+ await waitFor(() => expect(mockClearServerCa).toHaveBeenCalled())
+ expect(getByText("Valid")).toBeTruthy()
+ })
- const { getByText } = render(<MtlsSection />)
- await waitFor(() => getByText("Remove CA"))
- fireEvent.press(getByText("Remove CA"))
+ it("names the consequence of an expired CA", async () => {
+ mockGetServerCaInfo.mockResolvedValue(loaded(-2))
+ const { findByText } = render(<MtlsSection />)
- await waitFor(() => {
- expect(mockClearServerCa).toHaveBeenCalled()
- expect(mockGetServerCaInfo).toHaveBeenCalledTimes(2)
- })
+ expect(await findByText(/server certificate checks will fail$/)).toBeTruthy()
})
})
})
diff --git a/apps/mobile/src/screens/ApiSettingsScreen.tsx b/apps/mobile/src/screens/ApiSettingsScreen.tsx
index e39993e3..9fd67a92 100644
--- a/apps/mobile/src/screens/ApiSettingsScreen.tsx
+++ b/apps/mobile/src/screens/ApiSettingsScreen.tsx
@@ -3,12 +3,12 @@
* Licensed under the GNU AGPLv3. See LICENSE in the project root for details.
*/
-import { useState, useCallback, useMemo, useRef } from "react"
-import { Text, StyleSheet, TextInput, View, ScrollView, Pressable } from "react-native"
+import { useState, useCallback, useEffect, useMemo, useRef } from "react"
+import { Text, StyleSheet, View, ScrollView, Pressable } from "react-native"
+import { RotateCcw, X } from "lucide-react-native"
import {
FieldMap,
DEFAULT_FIELD_MAP,
- ScreenProps,
CustomField,
ApiTemplateName,
API_TEMPLATES,
@@ -20,8 +20,20 @@ import { useAutoSave } from "../hooks/useAutoSave"
import { useTimeout } from "../hooks/useTimeout"
import { useTracking } from "../contexts/TrackingProvider"
import NativeLocationService from "../services/NativeLocationService"
-import { fonts } from "../styles/typography"
-import { SectionTitle, FloatingSaveIndicator, Container, Divider, ChipGroup } from "../components"
+import { fontSizes, fonts, lineHeights, type } from "../styles/typography"
+import type { RootScreenProps } from "../types/navigation"
+import {
+ SectionTitle,
+ FloatingSaveIndicator,
+ Container,
+ Divider,
+ Card,
+ ListItem,
+ RadioRow,
+ Button,
+ TextField,
+ IconButton
+} from "../components"
import { findDuplicates } from "../utils/settingsValidation"
import {
buildTraccarJsonPayload,
@@ -29,6 +41,8 @@ import {
isTraccarJsonFormat,
isOverlandFormat
} from "../utils/apiPayload"
+import { HIT_SLOP_LG, space, STATE_LAYER_ALPHA } from "../constants"
+import { radius } from "@colota/shared"
type LocalCustomField = CustomField & { id: number }
@@ -45,22 +59,9 @@ const FIELD_DESCRIPTIONS: Record<keyof FieldMap, string> = {
bear: "Direction of travel (0-360°)"
}
-const TEMPLATE_OPTIONS: { value: ApiTemplateName; label: string }[] = [
- { value: "custom", label: "Custom" },
- ...Object.entries(API_TEMPLATES).map(([key, tmpl]) => ({
- value: key as ApiTemplateName,
- label: tmpl.label
- }))
-]
-
-const HTTP_METHOD_OPTIONS: { value: HttpMethod; label: string }[] = [
- { value: "POST", label: "POST" },
- { value: "GET", label: "GET" }
-]
-
-const DAWARICH_MODE_OPTIONS: { value: DawarichMode; label: string }[] = [
- { value: "single", label: "Single point" },
- { value: "batch", label: "Batch" }
+const HTTP_METHOD_OPTIONS: { value: HttpMethod; label: string; sub: string }[] = [
+ { value: "POST", label: "POST", sub: "Sends the fields as a JSON body" },
+ { value: "GET", label: "GET", sub: "Sends the fields as URL query parameters" }
]
/**
@@ -81,7 +82,7 @@ function getReferenceCustomFields(template: ApiTemplateName): CustomField[] {
* Screen for configuring API field name mappings, backend templates,
* and custom static fields.
*/
-export function ApiSettingsScreen({}: ScreenProps) {
+export function ApiSettingsScreen({ navigation, route }: RootScreenProps<"Request Format">) {
const { settings, setSettings, restartTracking } = useTracking()
const { colors } = useTheme()
@@ -100,8 +101,15 @@ export function ApiSettingsScreen({}: ScreenProps) {
const isGetMethod = localHttpMethod === "GET"
const showDawarichChip = localTemplate === "dawarich"
const batchDisabled = isInstantSync || isGetMethod
+ const batchDisabledReason = isInstantSync ? "Needs a sync interval above Instant" : "Needs the POST method, not GET"
const copiedTimeout = useTimeout()
- const { saving, saveSuccess, debouncedSaveAndRestart, immediateSaveAndRestart } = useAutoSave()
+ const {
+ saving,
+ message: saveMessage,
+ isError: saveIsError,
+ debouncedSaveAndRestart,
+ immediateSaveAndRestart
+ } = useAutoSave()
const referenceFieldMap = getReferenceFieldMap(localTemplate)
@@ -330,6 +338,15 @@ export function ApiSettingsScreen({}: ScreenProps) {
[localFieldMap, localCustomFields, localHttpMethod, localDawarichMode, saveImmediately]
)
+ // The picker hands its choice back through the route. Clearing the param afterwards stops the
+ // effect re-applying it on every later render of this screen.
+ const incomingTemplate = route.params?.template
+ useEffect(() => {
+ if (!incomingTemplate) return
+ if (incomingTemplate !== localTemplate) handleTemplateChange(incomingTemplate)
+ navigation.setParams({ template: undefined })
+ }, [incomingTemplate, localTemplate, handleTemplateChange, navigation])
+
/**
* Handles field value changes with auto-save.
* Switching to "custom" template if a known template was selected.
@@ -462,9 +479,7 @@ export function ApiSettingsScreen({}: ScreenProps) {
return (
<Container>
<ScrollView contentContainerStyle={styles.scrollContent} keyboardShouldPersistTaps="handled">
- {/* Header */}
<View style={styles.header}>
- <Text style={[styles.title, { color: colors.text }]}>API Field Mapping</Text>
<Text style={[styles.subtitle, { color: colors.textSecondary }]}>
Customize field names sent to your server
</Text>
@@ -472,83 +487,88 @@ export function ApiSettingsScreen({}: ScreenProps) {
{/* Template Selector */}
<View style={styles.section}>
- <SectionTitle>BACKEND TEMPLATE</SectionTitle>
- <ChipGroup
- options={TEMPLATE_OPTIONS}
- selected={localTemplate}
- onSelect={handleTemplateChange}
- colors={colors}
- />
- {localTemplate !== "custom" && (
- <Text style={[styles.templateHint, { color: colors.textSecondary }]}>
- {API_TEMPLATES[localTemplate].description}
- </Text>
- )}
+ <SectionTitle>Backend template</SectionTitle>
+ <Card rows>
+ <ListItem
+ testID="nav-backend-template"
+ label={localTemplate === "custom" ? "Custom" : API_TEMPLATES[localTemplate].label}
+ sub={
+ localTemplate === "custom"
+ ? "Your own field names, mapped by hand"
+ : API_TEMPLATES[localTemplate].description
+ }
+ onPress={() => navigation.navigate("Backend Template", { selected: localTemplate })}
+ />
+ </Card>
</View>
{/* HTTP Method Selector */}
{/* Overland template is POST-only by spec; no need to expose the choice */}
{localTemplate !== "overland" && (
<View style={styles.section}>
- <SectionTitle>HTTP METHOD</SectionTitle>
- <ChipGroup
- options={HTTP_METHOD_OPTIONS}
- selected={localHttpMethod}
- onSelect={handleHttpMethodChange}
- colors={colors}
- />
- {localHttpMethod === "GET" && (
- <Text style={[styles.templateHint, { color: colors.textSecondary }]}>
- Fields sent as URL query parameters instead of JSON body
- </Text>
- )}
+ <SectionTitle>HTTP method</SectionTitle>
+ <View accessibilityRole="radiogroup" style={styles.radioGroup}>
+ {HTTP_METHOD_OPTIONS.map(({ value, label, sub }) => (
+ <RadioRow
+ key={value}
+ testID={`http-method-${value.toLowerCase()}`}
+ label={label}
+ sub={sub}
+ selected={localHttpMethod === value}
+ onPress={() => handleHttpMethodChange(value)}
+ />
+ ))}
+ </View>
</View>
)}
{/* Dawarich Mode Selector (Dawarich template only) */}
{showDawarichChip && (
<View style={styles.section}>
- <SectionTitle>DAWARICH MODE</SectionTitle>
- <ChipGroup
- options={DAWARICH_MODE_OPTIONS}
- selected={localDawarichMode}
- onSelect={handleDawarichModeChange}
- colors={colors}
- disabled={batchDisabled ? new Set<DawarichMode>(["batch"]) : undefined}
- />
+ <SectionTitle>Dawarich mode</SectionTitle>
+ <View accessibilityRole="radiogroup" style={styles.radioGroup}>
+ <RadioRow
+ testID="dawarich-mode-single"
+ label="Single point"
+ sub="Sends one request per location"
+ selected={localDawarichMode === "single"}
+ onPress={() => handleDawarichModeChange("single")}
+ />
+ <RadioRow
+ testID="dawarich-mode-batch"
+ label="Batch"
+ sub={batchDisabled ? batchDisabledReason : "Sends queued locations in one request"}
+ disabled={batchDisabled}
+ selected={localDawarichMode === "batch"}
+ onPress={() => handleDawarichModeChange("batch")}
+ />
+ </View>
<Text style={[styles.templateHint, { color: colors.textSecondary }]}>
{localDawarichMode === "batch"
- ? "Endpoint: /api/v1/overland/batches?api_key=YOUR_API_KEY"
- : "Endpoint: /api/v1/owntracks/points?api_key=YOUR_API_KEY"}
+ ? `Endpoint: ${API_TEMPLATES.dawarich.batchEndpointExample}`
+ : `Endpoint: ${API_TEMPLATES.dawarich.endpointExample}`}
</Text>
- {isInstantSync && (
- <Text style={[styles.templateHint, { color: colors.textSecondary }]}>
- Batch mode requires a non-zero sync interval. Switch to a batched preset to enable it.
- </Text>
- )}
- {isGetMethod && !isInstantSync && (
- <Text style={[styles.templateHint, { color: colors.textSecondary }]}>
- Batch mode requires POST. Switch HTTP method to POST to enable batch.
- </Text>
- )}
</View>
)}
{/* Field Mapping Section */}
<View style={styles.fieldsSection}>
<View style={styles.sectionHeader}>
- <SectionTitle>FIELD MAPPINGS</SectionTitle>
+ <SectionTitle>Field mappings</SectionTitle>
{hasModifications && (
<Pressable
onPress={handleResetAll}
- style={({ pressed }) => [styles.resetAllButton, pressed && { opacity: colors.pressedOpacity }]}
+ hitSlop={HIT_SLOP_LG}
+ accessibilityRole="button"
+ android_ripple={{ color: colors.primaryDark + STATE_LAYER_ALPHA, borderless: true }}
+ style={styles.resetAllButton}
>
- <Text style={[styles.resetAllText, { color: colors.primaryDark }]}>RESET ALL</Text>
+ <Text style={[styles.resetAllText, { color: colors.primaryDark }]}>Reset all</Text>
</Pressable>
)}
</View>
- <View style={[styles.fieldsCard, { backgroundColor: colors.card, borderColor: colors.border }]}>
+ <View style={[styles.fieldsCard, { backgroundColor: colors.card }]}>
{(Object.keys(DEFAULT_FIELD_MAP) as Array<keyof FieldMap>).map((key, index) => {
const isFieldModified = modifiedFields.has(key)
const fieldValue = localFieldMap[key]?.trim()
@@ -575,37 +595,25 @@ export function ApiSettingsScreen({}: ScreenProps) {
{/* Right: Value input */}
<View style={styles.valueColumn}>
<View style={styles.inputRow}>
- <TextInput
- style={[
- styles.fieldInput,
- {
- borderColor: isDuplicate
- ? colors.error
- : isFieldModified
- ? colors.primary
- : colors.border,
- color: colors.text,
- backgroundColor: colors.background
- }
- ]}
+ <TextField
+ accessibilityLabel={key}
+ testID={`field-${key}`}
+ style={styles.fieldInput}
+ mono
+ error={isDuplicate}
value={localFieldMap[key]}
onChangeText={(text) => handleFieldChange(key, text)}
placeholder={referenceFieldMap[key]}
- placeholderTextColor={colors.placeholder}
autoCapitalize="none"
autoCorrect={false}
/>
{isFieldModified && (
- <Pressable
+ <IconButton
+ icon={RotateCcw}
+ testID={`reset-${key}`}
+ accessibilityLabel={`Reset ${key} to the default`}
onPress={() => handleResetField(key)}
- style={({ pressed }) => [
- styles.resetButton,
- { backgroundColor: colors.border },
- pressed && { opacity: colors.pressedOpacity }
- ]}
- >
- <Text style={[styles.resetIcon, { color: colors.textSecondary }]}>↺</Text>
- </Pressable>
+ />
)}
</View>
</View>
@@ -621,10 +629,10 @@ export function ApiSettingsScreen({}: ScreenProps) {
{/* Custom Fields Section */}
<View style={styles.fieldsSection}>
<View style={styles.sectionHeader}>
- <SectionTitle>CUSTOM FIELDS</SectionTitle>
+ <SectionTitle>Custom fields</SectionTitle>
</View>
- <View style={[styles.fieldsCard, { backgroundColor: colors.card, borderColor: colors.border }]}>
+ <View style={[styles.fieldsCard, { backgroundColor: colors.card }]}>
{localCustomFields.length === 0 ? (
<Text style={[styles.emptyHint, { color: colors.textSecondary }]}>
No custom fields. Add static key-value pairs to include in every payload.
@@ -635,48 +643,36 @@ export function ApiSettingsScreen({}: ScreenProps) {
return (
<View key={field.id}>
<View style={styles.customFieldRow}>
- <TextInput
- style={[
- styles.customFieldInput,
- {
- borderColor: isDuplicate ? colors.error : colors.border,
- color: colors.text,
- backgroundColor: colors.background
- }
- ]}
+ <TextField
+ accessibilityLabel="Custom field key"
+ testID={`custom-key-${field.id}`}
+ style={styles.customFieldInput}
+ mono
+ error={isDuplicate}
value={field.key}
onChangeText={(text) => handleCustomFieldChange(field.id, "key", text)}
placeholder="Key"
- placeholderTextColor={colors.placeholder}
autoCapitalize="none"
autoCorrect={false}
/>
- <TextInput
- style={[
- styles.customFieldInput,
- {
- borderColor: colors.border,
- color: colors.text,
- backgroundColor: colors.background
- }
- ]}
+ <TextField
+ accessibilityLabel="Custom field value"
+ testID={`custom-value-${field.id}`}
+ style={styles.customFieldInput}
+ mono
value={field.value}
onChangeText={(text) => handleCustomFieldChange(field.id, "value", text)}
placeholder="Value"
- placeholderTextColor={colors.placeholder}
autoCapitalize="none"
autoCorrect={false}
/>
- <Pressable
+ <IconButton
+ icon={X}
+ tone="danger"
+ testID={`remove-custom-${field.id}`}
+ accessibilityLabel="Remove this custom field"
onPress={() => handleRemoveCustomField(field.id)}
- style={({ pressed }) => [
- styles.removeButton,
- { backgroundColor: colors.error + "15" },
- pressed && { opacity: colors.pressedOpacity }
- ]}
- >
- <Text style={[styles.removeButtonText, { color: colors.error }]}>X</Text>
- </Pressable>
+ />
</View>
{index < localCustomFields.length - 1 && <Divider />}
</View>
@@ -684,16 +680,7 @@ export function ApiSettingsScreen({}: ScreenProps) {
})
)}
- <Pressable
- onPress={handleAddCustomField}
- style={({ pressed }) => [
- styles.addButton,
- { borderColor: colors.border },
- pressed && { opacity: colors.pressedOpacity }
- ]}
- >
- <Text style={[styles.addButtonText, { color: colors.primaryDark }]}>+ Add Field</Text>
- </Pressable>
+ <Button title="+ Add Field" onPress={handleAddCustomField} variant="secondary" />
</View>
</View>
@@ -710,7 +697,7 @@ export function ApiSettingsScreen({}: ScreenProps) {
{/* Example payload preview */}
<View style={styles.exampleSection}>
- <SectionTitle>{localHttpMethod === "GET" ? "EXAMPLE REQUEST" : "EXAMPLE PAYLOAD"}</SectionTitle>
+ <SectionTitle>{localHttpMethod === "GET" ? "Example request" : "Example payload"}</SectionTitle>
<View
style={[
styles.exampleCard,
@@ -723,10 +710,13 @@ export function ApiSettingsScreen({}: ScreenProps) {
<Text style={[styles.exampleCode, { color: colors.textSecondary }]}>{examplePayload}</Text>
<Pressable
onPress={handleCopyPayload}
- style={({ pressed }) => [styles.copyButton, pressed && { opacity: colors.pressedOpacity }]}
+ hitSlop={HIT_SLOP_LG}
+ accessibilityRole="button"
+ android_ripple={{ color: colors.primaryDark + STATE_LAYER_ALPHA, borderless: true }}
+ style={styles.copyButton}
>
<Text style={[styles.copyButtonText, { color: copied ? colors.success : colors.primaryDark }]}>
- {copied ? "COPIED!" : "COPY"}
+ {copied ? "Copied!" : "Copy"}
</Text>
</Pressable>
</View>
@@ -741,39 +731,39 @@ export function ApiSettingsScreen({}: ScreenProps) {
</ScrollView>
{/* Floating Save Indicator */}
- <FloatingSaveIndicator saving={saving} success={saveSuccess} colors={colors} />
+ <FloatingSaveIndicator saving={saving} message={saveMessage} isError={saveIsError} />
</Container>
)
}
const styles = StyleSheet.create({
scrollContent: {
- paddingHorizontal: 16,
- paddingBottom: 40
+ paddingHorizontal: space.lg,
+ paddingBottom: space.xxl
},
header: {
- marginTop: 20,
- marginBottom: 20
- },
- title: {
- fontSize: 28,
- ...fonts.bold,
- letterSpacing: -0.5,
- marginBottom: 4
+ marginTop: space.xl,
+ marginBottom: space.xl
},
subtitle: {
- fontSize: 14,
- lineHeight: 20
+ fontSize: fontSizes.body,
+ lineHeight: lineHeights.body
},
section: {
- marginBottom: 24
+ marginBottom: space.xl
+ },
+ // Every control pays its own top padding, so the gap under a SectionTitle has to be measured to the
+ // text rather than to the box. A chip pays space.sm and lands at 20; a row pays space.lg and would
+ // land at 28. Pulling up space.sm puts the row text at 20 too, with the ripple still clear of the title.
+ radioGroup: {
+ marginTop: -space.sm
},
templateHint: {
- fontSize: 12,
- marginTop: 8
+ fontSize: fontSizes.caption,
+ marginTop: space.sm
},
fieldsSection: {
- marginBottom: 20
+ marginBottom: space.xl
},
sectionHeader: {
flexDirection: "row",
@@ -781,23 +771,21 @@ const styles = StyleSheet.create({
alignItems: "center"
},
resetAllButton: {
- paddingVertical: 4,
- paddingHorizontal: 8
+ paddingVertical: space.xs,
+ paddingHorizontal: space.sm
},
resetAllText: {
- fontSize: 11,
- ...fonts.bold,
- letterSpacing: 0.5
+ fontSize: fontSizes.label,
+ ...fonts.semiBold
},
fieldsCard: {
- padding: 12,
- borderRadius: 10,
- borderWidth: 1
+ padding: space.md,
+ borderRadius: radius.md
},
fieldRow: {
flexDirection: "row",
- paddingVertical: 10,
- gap: 12
+ paddingVertical: space.md,
+ gap: space.md
},
keyColumn: {
flex: 1,
@@ -806,27 +794,25 @@ const styles = StyleSheet.create({
keyHeader: {
flexDirection: "row",
alignItems: "center",
- gap: 6,
- marginBottom: 2
+ gap: space.sm,
+ marginBottom: space.xxs
},
fieldLabel: {
- fontSize: 13,
- ...fonts.bold,
- letterSpacing: 0.5
+ fontSize: fontSizes.description,
+ ...fonts.bold
},
modifiedBadge: {
- paddingHorizontal: 6,
- paddingVertical: 2,
- borderRadius: 4
+ paddingHorizontal: space.sm,
+ paddingVertical: space.xxs,
+ borderRadius: radius.xs
},
modifiedText: {
- fontSize: 9,
- ...fonts.bold,
- letterSpacing: 0.3
+ fontSize: fontSizes.micro,
+ ...fonts.bold
},
fieldDescription: {
- fontSize: 11,
- lineHeight: 15
+ fontSize: fontSizes.small,
+ lineHeight: lineHeights.small
},
valueColumn: {
flex: 1,
@@ -835,111 +821,61 @@ const styles = StyleSheet.create({
inputRow: {
flexDirection: "row",
alignItems: "center",
- gap: 6
+ gap: space.sm
},
fieldInput: {
- flex: 1,
- borderWidth: 1.5,
- paddingHorizontal: 10,
- paddingVertical: 8,
- borderRadius: 8,
- fontSize: 14,
- fontFamily: "monospace"
- },
- resetButton: {
- width: 32,
- height: 32,
- borderRadius: 16,
- justifyContent: "center",
- alignItems: "center"
- },
- resetIcon: {
- fontSize: 18,
- ...fonts.semiBold
+ flex: 1
},
customFieldRow: {
flexDirection: "row",
alignItems: "center",
- gap: 8,
- paddingVertical: 8
+ gap: space.sm,
+ paddingVertical: space.sm
},
customFieldInput: {
- flex: 1,
- borderWidth: 1.5,
- paddingHorizontal: 10,
- paddingVertical: 8,
- borderRadius: 8,
- fontSize: 14,
- fontFamily: "monospace"
- },
- removeButton: {
- width: 32,
- height: 32,
- borderRadius: 16,
- justifyContent: "center",
- alignItems: "center"
- },
- removeButtonText: {
- fontSize: 13,
- ...fonts.bold
- },
- addButton: {
- paddingVertical: 12,
- alignItems: "center",
- borderRadius: 10,
- borderWidth: 1.5,
- borderStyle: "dashed",
- marginTop: 8
- },
- addButtonText: {
- fontSize: 14,
- ...fonts.semiBold
+ flex: 1
},
emptyHint: {
- fontSize: 13,
+ fontSize: fontSizes.description,
textAlign: "center",
- paddingVertical: 8
+ paddingVertical: space.sm
},
warningBanner: {
- padding: 12,
- borderRadius: 8,
+ padding: space.md,
+ borderRadius: radius.sm,
borderWidth: 1,
- marginBottom: 20
+ marginBottom: space.xl
},
warningText: {
- fontSize: 12,
- lineHeight: 18
+ fontSize: fontSizes.caption,
+ lineHeight: lineHeights.caption
},
exampleSection: {
- marginBottom: 20
+ marginBottom: space.xl
},
copyButton: {
alignSelf: "flex-end",
- paddingVertical: 4,
- paddingHorizontal: 2,
- marginTop: 8
+ paddingVertical: space.xs,
+ paddingHorizontal: space.sm,
+ marginTop: space.sm
},
copyButtonText: {
- fontSize: 11,
- ...fonts.bold,
- letterSpacing: 0.5
+ fontSize: fontSizes.label,
+ ...fonts.semiBold
},
exampleCard: {
- padding: 14,
- borderRadius: 8,
- borderWidth: 1
+ padding: space.lg,
+ borderRadius: radius.sm
},
exampleCode: {
- fontSize: 12,
- fontFamily: "monospace",
- lineHeight: 18
+ ...type.mono
},
footer: {
- paddingVertical: 16,
+ paddingVertical: space.lg,
alignItems: "center"
},
footerText: {
- fontSize: 11,
+ fontSize: fontSizes.small,
textAlign: "center"
}
})
diff --git a/apps/mobile/src/screens/AuthSettingsScreen.tsx b/apps/mobile/src/screens/AuthSettingsScreen.tsx
index 8058ec60..b775dc55 100644
--- a/apps/mobile/src/screens/AuthSettingsScreen.tsx
+++ b/apps/mobile/src/screens/AuthSettingsScreen.tsx
@@ -3,44 +3,85 @@
* Licensed under the GNU AGPLv3. See LICENSE in the project root for details.
*/
-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 React, { useState, useCallback, useEffect, useRef } from "react"
+import { Text, StyleSheet, View, ScrollView, ActivityIndicator } from "react-native"
+import { X } from "lucide-react-native"
import { AuthConfig, AuthType, DEFAULT_AUTH_CONFIG, ScreenProps } from "../types/global"
import { useTheme } from "../hooks/useTheme"
import { useAutoSave } from "../hooks/useAutoSave"
import { useTracking } from "../contexts/TrackingProvider"
-import { fonts, fontSizes } from "../styles/typography"
-import { SectionTitle, FloatingSaveIndicator, Container, Card, Divider, ChipGroup } from "../components"
+import { fonts, fontSizes, lineHeights } from "../styles/typography"
+import {
+ SectionTitle,
+ FloatingSaveIndicator,
+ Container,
+ Card,
+ Divider,
+ RadioRow,
+ Button,
+ TextField,
+ FieldMessage,
+ IconButton
+} from "../components"
import NativeLocationService from "../services/NativeLocationService"
import { logger } from "../utils/logger"
-import { findDuplicates } from "../utils/settingsValidation"
+import { size, space } from "../constants"
-const AUTH_TYPE_OPTIONS: { value: AuthType; label: string }[] = [
- { value: "none", label: "None" },
- { value: "basic", label: "Basic Auth" },
- { value: "bearer", label: "Bearer Token" }
+const METHODS: { value: AuthType; label: string; sub: string }[] = [
+ {
+ value: "none",
+ label: "None",
+ sub: "No Authorization header. Use with a key in the address, a custom header or a client certificate."
+ },
+ {
+ value: "basic",
+ label: "Basic auth",
+ sub: "Sends Authorization: Basic with the username and password encoded, not encrypted. Only safe over https."
+ },
+ { value: "bearer", label: "Bearer token", sub: "Sends Authorization: Bearer with the token." }
]
+const SECRET_SET = "Set · encrypted on this device, in encrypted backups. Type to replace."
+const SECRET_UNSET = "Not set · encrypted once saved."
+const DUPLICATE_HEADER = "Also used above. Only the last value is sent."
+const SENSITIVE_HEADER = /authorization|cookie|token|key|secret/i
+
type LocalHeader = { key: string; value: string; id: number }
-/**
- * Screen for configuring endpoint authentication and custom headers.
- */
-export function AuthSettingsScreen({ navigation }: ScreenProps) {
+/** A method owns its credentials: choosing one drops the others', so a never-echoed secret can still be cleared. */
+export function withMethod(config: AuthConfig, authType: AuthType): AuthConfig {
+ return {
+ ...config,
+ authType,
+ username: authType === "basic" ? config.username : "",
+ password: authType === "basic" ? config.password : "",
+ bearerToken: authType === "bearer" ? config.bearerToken : ""
+ }
+}
+
+export function AuthSettingsScreen({}: ScreenProps) {
const { colors } = useTheme()
const { restartTracking, settings } = useTracking()
const [config, setConfig] = useState<AuthConfig>(DEFAULT_AUTH_CONFIG)
+ const configRef = useRef(config)
+ configRef.current = config
const [loading, setLoading] = useState(true)
- const { saving, saveSuccess, debouncedSaveAndRestart, immediateSaveAndRestart } = useAutoSave()
+ const [passwordDraft, setPasswordDraft] = useState("")
+ const [tokenDraft, setTokenDraft] = useState("")
+ const {
+ saving,
+ message: saveMessage,
+ isError: saveIsError,
+ debouncedSaveAndRestart,
+ immediateSaveAndRestart
+ } = useAutoSave()
const nextIdRef = useRef(0)
const assignId = () => nextIdRef.current++
const [localHeaders, setLocalHeaders] = useState<LocalHeader[]>([])
- // Load config on mount
useEffect(() => {
;(async () => {
try {
@@ -55,96 +96,82 @@ export function AuthSettingsScreen({ navigation }: ScreenProps) {
})()
}, [])
- /** Detect duplicate header keys */
- const duplicateKeys = useMemo(() => {
- const keys = localHeaders.map((h) => h.key.trim()).filter(Boolean)
- return findDuplicates(keys)
- }, [localHeaders])
-
- /** Convert local headers array to Record for saving */
- const headersToRecord = useCallback((headers: LocalHeader[]): Record<string, string> => {
+ const headersToRecord = (headers: LocalHeader[]): Record<string, string> => {
const record: Record<string, string> = {}
for (const h of headers) {
const k = h.key.trim()
if (k) record[k] = h.value.trim()
}
return record
- }, [])
+ }
- const debouncedSave = useCallback(
- (newConfig: AuthConfig) => {
- debouncedSaveAndRestart(
+ const saveNow = useCallback(
+ (next: AuthConfig) => {
+ setConfig(next)
+ immediateSaveAndRestart(
async () => {
- await NativeLocationService.saveAuthConfig(newConfig)
+ await NativeLocationService.saveAuthConfig(next)
},
() => restartTracking(settings)
)
},
- [debouncedSaveAndRestart, restartTracking, settings]
+ [immediateSaveAndRestart, restartTracking, settings]
)
- const updateConfig = useCallback(
+ const saveSoon = useCallback(
(partial: Partial<AuthConfig>) => {
- const next = { ...config, ...partial }
+ const next = { ...configRef.current, ...partial }
setConfig(next)
- debouncedSave(next)
- },
- [config, debouncedSave]
- )
-
- const handleAuthTypeChange = useCallback(
- (authType: AuthType) => {
- const next = { ...config, authType }
- setConfig(next)
- immediateSaveAndRestart(
+ debouncedSaveAndRestart(
async () => {
await NativeLocationService.saveAuthConfig(next)
},
() => restartTracking(settings)
)
},
- [config, immediateSaveAndRestart, restartTracking, settings]
+ [debouncedSaveAndRestart, restartTracking, settings]
)
- const addHeader = useCallback(() => {
- setLocalHeaders((prev) => [...prev, { key: "", value: "", id: assignId() }])
- }, [])
+ const handleMethod = (authType: AuthType) => {
+ if (authType === config.authType) return
+ setPasswordDraft("")
+ setTokenDraft("")
+ saveNow(withMethod(config, authType))
+ }
- const updateHeaderField = useCallback(
- (id: number, field: "key" | "value", text: string) => {
- const next = localHeaders.map((h) => (h.id === id ? { ...h, [field]: text } : h))
- setLocalHeaders(next)
- updateConfig({ customHeaders: headersToRecord(next) })
- },
- [localHeaders, updateConfig, headersToRecord]
- )
+ const handleSecret = (key: "password" | "bearerToken", text: string) => {
+ if (key === "password") setPasswordDraft(text)
+ else setTokenDraft(text)
+ // An empty draft keeps the stored value; choosing another method is how a secret is cleared.
+ if (text !== "") saveSoon({ [key]: text })
+ }
- const removeHeader = useCallback(
- (id: number) => {
- const next = localHeaders.filter((h) => h.id !== id)
- setLocalHeaders(next)
- const nextConfig = { ...config, customHeaders: headersToRecord(next) }
- setConfig(nextConfig)
- immediateSaveAndRestart(
- async () => {
- await NativeLocationService.saveAuthConfig(nextConfig)
- },
- () => restartTracking(settings)
- )
- },
- [localHeaders, config, headersToRecord, immediateSaveAndRestart, restartTracking, settings]
- )
+ const addHeader = () => setLocalHeaders((prev) => [...prev, { key: "", value: "", id: assignId() }])
+
+ const updateHeaderField = (id: number, field: "key" | "value", text: string) => {
+ const next = localHeaders.map((h) => (h.id === id ? { ...h, [field]: text } : h))
+ setLocalHeaders(next)
+ saveSoon({ customHeaders: headersToRecord(next) })
+ }
+
+ const removeHeader = (id: number) => {
+ const next = localHeaders.filter((h) => h.id !== id)
+ setLocalHeaders(next)
+ saveNow({ ...configRef.current, customHeaders: headersToRecord(next) })
+ }
if (loading) {
return (
<Container>
<View style={styles.loadingContainer}>
- <Text style={[styles.loadingText, { color: colors.textSecondary }]}>Loading...</Text>
+ <ActivityIndicator size="large" color={colors.primary} />
</View>
</Container>
)
}
+ const secretHint = (stored: string) => (stored !== "" ? SECRET_SET : SECRET_UNSET)
+
return (
<Container>
<ScrollView
@@ -152,360 +179,191 @@ export function AuthSettingsScreen({ navigation }: ScreenProps) {
keyboardShouldPersistTaps="handled"
showsVerticalScrollIndicator={false}
>
- {/* Header */}
- <View style={styles.header}>
- <Text style={[styles.title, { color: colors.text }]}>Authentication & Headers</Text>
- <Text style={[styles.subtitle, { color: colors.textSecondary }]}>Secure your endpoint connection</Text>
- </View>
-
- {/* Authentication Section */}
- <View style={styles.section}>
- <SectionTitle>Authentication</SectionTitle>
- <Card>
- <ChipGroup
- options={AUTH_TYPE_OPTIONS}
- selected={config.authType}
- onSelect={handleAuthTypeChange}
- colors={colors}
- />
-
- {/* Basic Auth fields */}
- {config.authType === "basic" && (
- <>
- <Divider />
- <View style={styles.fieldGroup}>
- <Text style={[styles.fieldLabel, { color: colors.text }]}>Username</Text>
- <TextInput
- style={[
- styles.input,
- {
- borderColor: colors.border,
- color: colors.text,
- backgroundColor: colors.background
- }
- ]}
- value={config.username}
- onChangeText={(v) => updateConfig({ username: v })}
- placeholder="Username"
- placeholderTextColor={colors.placeholder}
- autoCapitalize="none"
- autoCorrect={false}
- />
-
- <Text style={[styles.fieldLabel, styles.fieldLabelSpaced, { color: colors.text }]}>Password</Text>
- <TextInput
- style={[
- styles.input,
- {
- borderColor: colors.border,
- color: colors.text,
- backgroundColor: colors.background
- }
- ]}
- value={config.password}
- onChangeText={(v) => updateConfig({ password: v })}
- placeholder="Password"
- placeholderTextColor={colors.placeholder}
- autoCapitalize="none"
- autoCorrect={false}
- secureTextEntry
- />
- </View>
- </>
- )}
-
- {/* Bearer Token field */}
- {config.authType === "bearer" && (
- <>
- <Divider />
- <View style={styles.fieldGroup}>
- <Text style={[styles.fieldLabel, { color: colors.text }]}>Token</Text>
- <TextInput
- style={[
- styles.input,
- styles.tokenInput,
- {
- borderColor: colors.border,
- color: colors.text,
- backgroundColor: colors.background
- }
- ]}
- value={config.bearerToken}
- onChangeText={(v) => updateConfig({ bearerToken: v })}
- placeholder="Bearer token"
- placeholderTextColor={colors.placeholder}
- autoCapitalize="none"
- autoCorrect={false}
- multiline
- textAlignVertical="top"
- />
- </View>
- </>
- )}
- </Card>
- </View>
+ <Text style={[styles.intro, { color: colors.textSecondary }]}>
+ How each request proves who it is from. Stored encrypted on this device and in encrypted backups. A setup link
+ you share carries it in the clear.
+ </Text>
- {/* Custom Headers Section */}
- <View style={styles.section}>
- <SectionTitle>Custom Headers</SectionTitle>
- <Card>
- {localHeaders.length === 0 ? (
- <Text style={[styles.emptyHint, { color: colors.textSecondary }]}>No custom headers configured</Text>
- ) : (
- localHeaders.map((header, index) => {
- const isDuplicate = header.key.trim() !== "" && duplicateKeys.has(header.key.trim())
- return (
- <View key={header.id}>
- {index > 0 && <Divider />}
- <View style={styles.headerRow}>
- <View style={styles.headerInputs}>
- <TextInput
- style={[
- styles.headerInput,
- {
- borderColor: isDuplicate ? colors.error : colors.border,
- color: colors.text,
- backgroundColor: colors.background
- }
- ]}
- value={header.key}
- onChangeText={(v) => updateHeaderField(header.id, "key", v)}
- placeholder="Header name"
- placeholderTextColor={colors.placeholder}
- autoCapitalize="none"
- autoCorrect={false}
- />
- <TextInput
- style={[
- styles.headerInput,
- {
- borderColor: colors.border,
- color: colors.text,
- backgroundColor: colors.background
- }
- ]}
- value={header.value}
- onChangeText={(v) => updateHeaderField(header.id, "value", v)}
- placeholder="Value"
- placeholderTextColor={colors.placeholder}
- autoCapitalize="none"
- autoCorrect={false}
- />
- </View>
- <Pressable
- onPress={() => removeHeader(header.id)}
- style={({ pressed }) => [
- styles.removeButton,
- { backgroundColor: colors.error + "15" },
- pressed && { opacity: colors.pressedOpacity }
- ]}
- >
- <Text style={[styles.removeButtonText, { color: colors.error }]}>X</Text>
- </Pressable>
+ <SectionTitle>Method</SectionTitle>
+ <Card rows>
+ <View accessibilityRole="radiogroup" style={styles.group}>
+ {METHODS.map(({ value, label, sub }) => (
+ <React.Fragment key={value}>
+ <RadioRow
+ testID={`auth-${value}`}
+ label={label}
+ sub={sub}
+ selected={config.authType === value}
+ onPress={() => handleMethod(value)}
+ />
+ {value === "basic" && config.authType === "basic" && (
+ <View style={styles.reveal}>
+ <TextField
+ label="Username"
+ testID="basic-username"
+ value={config.username}
+ onChangeText={(v) => saveSoon({ username: v })}
+ placeholder="Username"
+ autoCapitalize="none"
+ autoCorrect={false}
+ autoComplete="username"
+ />
+ <View>
+ <TextField
+ label="Password"
+ testID="basic-password"
+ value={passwordDraft}
+ onChangeText={(v) => handleSecret("password", v)}
+ placeholder="Password"
+ autoCapitalize="none"
+ autoCorrect={false}
+ autoComplete="password"
+ secure
+ />
+ <FieldMessage>{secretHint(config.password)}</FieldMessage>
</View>
</View>
- )
- })
- )}
-
- {localHeaders.length > 0 && <Divider />}
-
- <Pressable
- style={({ pressed }) => [
- styles.addButton,
- { borderColor: colors.primary },
- pressed && { opacity: colors.pressedOpacity }
- ]}
- onPress={addHeader}
- >
- <Text style={[styles.addButtonText, { color: colors.primaryDark }]}>+ Add Header</Text>
- </Pressable>
-
- <Text style={[styles.hint, { color: colors.textSecondary }]}>
- e.g., CF-Access-Client-Id for Cloudflare Access
- </Text>
- </Card>
- </View>
+ )}
+ {value === "bearer" && config.authType === "bearer" && (
+ <View style={styles.reveal}>
+ <View>
+ <TextField
+ label="Token"
+ testID="bearer-token"
+ mono
+ value={tokenDraft}
+ onChangeText={(v) => handleSecret("bearerToken", v)}
+ placeholder="Paste the token"
+ autoCapitalize="none"
+ autoCorrect={false}
+ autoComplete="off"
+ importantForAutofill="no"
+ secure
+ />
+ <FieldMessage>{secretHint(config.bearerToken)}</FieldMessage>
+ </View>
+ </View>
+ )}
+ </React.Fragment>
+ ))}
+ </View>
+ <Divider tight />
+ <View style={styles.footer}>
+ <FieldMessage>Choosing a method removes the credentials stored for the others.</FieldMessage>
+ </View>
+ </Card>
- {/* Duplicate key warning */}
- {duplicateKeys.size > 0 && (
- <View
- style={[styles.warningBanner, { backgroundColor: colors.error + "15", borderColor: colors.error + "40" }]}
- >
- <Text style={[styles.warningText, { color: colors.error }]}>
- Duplicate header names: {[...duplicateKeys].join(", ")}. Only the last value will be sent.
+ <SectionTitle style={styles.groupTop}>Custom headers</SectionTitle>
+ <Card rows>
+ {localHeaders.length === 0 ? (
+ <Text style={[styles.description, { color: colors.textSecondary }]}>
+ None. A custom header is sent with every request.
</Text>
+ ) : (
+ localHeaders.map((header, index) => {
+ const name = header.key.trim()
+ const isDuplicate = name !== "" && localHeaders.slice(0, index).some((h) => h.key.trim() === name)
+ return (
+ <View key={header.id}>
+ {index > 0 && <Divider tight />}
+ <View style={styles.headerRow}>
+ <View style={styles.headerInputs}>
+ <TextField
+ accessibilityLabel="Header name"
+ testID={`header-key-${header.id}`}
+ mono
+ error={isDuplicate ? DUPLICATE_HEADER : undefined}
+ value={header.key}
+ onChangeText={(v) => updateHeaderField(header.id, "key", v)}
+ placeholder="Name"
+ autoCapitalize="none"
+ autoCorrect={false}
+ />
+ <TextField
+ accessibilityLabel="Header value"
+ testID={`header-value-${header.id}`}
+ value={header.value}
+ onChangeText={(v) => updateHeaderField(header.id, "value", v)}
+ placeholder="Value"
+ autoCapitalize="none"
+ autoCorrect={false}
+ secure={SENSITIVE_HEADER.test(name)}
+ />
+ </View>
+ <IconButton
+ icon={X}
+ tone="danger"
+ testID={`remove-header-${header.id}`}
+ accessibilityLabel={name ? `Remove header ${name}` : "Remove header"}
+ onPress={() => removeHeader(header.id)}
+ />
+ </View>
+ </View>
+ )
+ })
+ )}
+ <Divider tight />
+ <View style={styles.footer}>
+ <Button title="+ Add header" onPress={addHeader} variant="secondary" testID="add-header-btn" />
+ <FieldMessage>Example: CF-Access-Client-Id for Cloudflare Access.</FieldMessage>
</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 }]}>
- Credentials and headers are stored encrypted on device
- </Text>
- </View>
+ </Card>
</ScrollView>
- <FloatingSaveIndicator saving={saving} success={saveSuccess} colors={colors} />
+ <FloatingSaveIndicator saving={saving} message={saveMessage} isError={saveIsError} />
</Container>
)
}
const styles = StyleSheet.create({
scrollContent: {
- paddingHorizontal: 16,
- paddingTop: 16,
- paddingBottom: 40
+ paddingHorizontal: space.lg,
+ paddingTop: space.lg,
+ paddingBottom: space.xxl
},
loadingContainer: {
flex: 1,
justifyContent: "center",
alignItems: "center"
},
- loadingText: {
- fontSize: 15,
- ...fonts.regular
- },
- header: {
- marginBottom: 20
- },
- title: {
- fontSize: 28,
- ...fonts.bold,
- letterSpacing: -0.5,
- marginBottom: 4
- },
- subtitle: {
- fontSize: 14,
+ intro: {
+ fontSize: fontSizes.body,
...fonts.regular,
- lineHeight: 20
- },
- section: {
- marginBottom: 24
- },
- fieldGroup: {
- marginTop: 4
+ lineHeight: lineHeights.body,
+ marginBottom: space.lg
},
- fieldLabel: {
- fontSize: fontSizes.label,
- ...fonts.semiBold,
- marginBottom: 8
+ group: {
+ marginTop: -space.sm
},
- fieldLabelSpaced: {
- marginTop: 14
+ groupTop: {
+ marginTop: space.xl
},
- input: {
- borderWidth: 1.5,
- padding: 14,
- borderRadius: 12,
- fontSize: 15
+ // The row above already pays space.lg below it; the fields' gap is the rhythm to the next row.
+ reveal: {
+ paddingLeft: size.iconColumn,
+ marginTop: -space.xs,
+ paddingBottom: space.lg,
+ gap: space.lg
},
- tokenInput: {
- minHeight: 80,
- fontFamily: "monospace",
- fontSize: 13
+ footer: {
+ paddingTop: space.xs,
+ paddingBottom: space.lg
},
- emptyHint: {
- fontSize: 14,
- textAlign: "center",
- paddingVertical: 8
+ description: {
+ fontSize: fontSizes.description,
+ ...fonts.regular,
+ lineHeight: lineHeights.description,
+ paddingTop: space.lg,
+ paddingBottom: space.md
},
headerRow: {
flexDirection: "row",
alignItems: "center",
- gap: 8,
- paddingVertical: 8
+ gap: space.sm,
+ paddingVertical: space.md
},
headerInputs: {
flex: 1,
- gap: 8
- },
- headerInput: {
- borderWidth: 1.5,
- padding: 12,
- borderRadius: 10,
- fontSize: 14
- },
- removeButton: {
- width: 36,
- height: 36,
- borderRadius: 18,
- justifyContent: "center",
- alignItems: "center"
- },
- removeButtonText: {
- fontSize: 14,
- ...fonts.bold
- },
- addButton: {
- paddingVertical: 14,
- alignItems: "center",
- borderRadius: 12,
- borderWidth: 1.5,
- borderStyle: "dashed",
- marginTop: 4
- },
- addButtonText: {
- fontSize: 15,
- ...fonts.semiBold
- },
- hint: {
- fontSize: 12,
- marginTop: 10,
- textAlign: "center"
- },
- warningBanner: {
- padding: 12,
- borderRadius: 8,
- borderWidth: 1,
- marginBottom: 20
- },
- warningText: {
- fontSize: 12,
- lineHeight: 18
- },
- footer: {
- paddingVertical: 16,
- alignItems: "center"
- },
- 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
+ gap: space.sm
}
})
diff --git a/apps/mobile/src/screens/BackendTemplateScreen.tsx b/apps/mobile/src/screens/BackendTemplateScreen.tsx
new file mode 100644
index 00000000..f26494ea
--- /dev/null
+++ b/apps/mobile/src/screens/BackendTemplateScreen.tsx
@@ -0,0 +1,67 @@
+/**
+ * Copyright (C) 2026 Max Dietrich
+ * Licensed under the GNU AGPLv3. See LICENSE in the project root for details.
+ */
+
+import React, { useCallback } from "react"
+import { View, ScrollView, StyleSheet } from "react-native"
+import { Card, Container, RadioRow } from "../components"
+import { API_TEMPLATES, ApiTemplateName } from "../types/global"
+import { space } from "../constants"
+import type { RootScreenProps } from "../types/navigation"
+
+type TemplateOption = { value: ApiTemplateName; label: string; description: string }
+
+/**
+ * Eight options, each needing a sentence, is past the point where inline radio rows fit a form
+ * screen: it measures around 580dp. Android puts that behind a row on the parent screen, the way
+ * Settings does for Default browser or Digital assistant app.
+ */
+const OPTIONS: TemplateOption[] = [
+ { value: "custom", label: "Custom", description: "Your own field names, mapped by hand" },
+ ...Object.entries(API_TEMPLATES).map(([key, template]) => ({
+ value: key as ApiTemplateName,
+ label: template.label,
+ description: template.description
+ }))
+]
+
+export function BackendTemplateScreen({ navigation, route }: RootScreenProps<"Backend Template">) {
+ const selected = route.params.selected
+
+ const choose = useCallback(
+ (value: ApiTemplateName) => {
+ navigation.popTo("Request Format", { template: value }, { merge: true })
+ },
+ [navigation]
+ )
+
+ return (
+ <Container>
+ <ScrollView contentContainerStyle={styles.scrollContent}>
+ <Card rows>
+ <View accessibilityRole="radiogroup">
+ {OPTIONS.map((option) => (
+ <RadioRow
+ key={option.value}
+ testID={`template-${option.value}`}
+ label={option.label}
+ sub={option.description}
+ selected={selected === option.value}
+ onPress={() => choose(option.value)}
+ />
+ ))}
+ </View>
+ </Card>
+ </ScrollView>
+ </Container>
+ )
+}
+
+const styles = StyleSheet.create({
+ scrollContent: {
+ paddingHorizontal: space.lg,
+ paddingTop: space.lg,
+ paddingBottom: space.xxl
+ }
+})
diff --git a/apps/mobile/src/screens/ConnectionScreen.tsx b/apps/mobile/src/screens/ConnectionScreen.tsx
index ed8da034..af5a3c7b 100644
--- a/apps/mobile/src/screens/ConnectionScreen.tsx
+++ b/apps/mobile/src/screens/ConnectionScreen.tsx
@@ -3,26 +3,73 @@
* Licensed under the GNU AGPLv3. See LICENSE in the project root for details.
*/
-import React, { useState, useCallback, useEffect } from "react"
-import { StyleSheet, ScrollView } from "react-native"
-import { ScreenProps, Settings } from "../types/global"
-import { useTheme } from "../hooks/useTheme"
+import React, { useState, useCallback } from "react"
+import { StyleSheet, ScrollView, DeviceEventEmitter } from "react-native"
+import { useFocusEffect } from "@react-navigation/native"
+import { API_TEMPLATES, AuthConfig, ClientCertInfoResult, DatabaseStats, ScreenProps, Settings } from "../types/global"
import { useAutoSave } from "../hooks/useAutoSave"
import { useTracking } from "../contexts/TrackingProvider"
import { FloatingSaveIndicator } from "../components/ui/FloatingSaveIndicator"
import { Container } from "../components"
import { ConnectionSettings } from "../components/features/settings/ConnectionSettings"
+import NativeLocationService from "../services/NativeLocationService"
+import { describeServer } from "../utils/serverState"
+import { describeCertificate } from "../utils/certificateState"
+import { logger } from "../utils/logger"
+import { space } from "../constants"
+
+const AUTH_WORDS = { none: "None", basic: "Basic auth", bearer: "Bearer token" } as const
+
+export function authSummary(auth: AuthConfig | null): string {
+ if (!auth) return ""
+ const headers = Object.keys(auth.customHeaders).length
+ return headers > 0
+ ? `${AUTH_WORDS[auth.authType]} · ${headers} ${headers === 1 ? "header" : "headers"}`
+ : AUTH_WORDS[auth.authType]
+}
export function ConnectionScreen({ navigation }: ScreenProps) {
- const { settings, setSettings, restartTracking } = useTracking()
- const { colors } = useTheme()
- const { saving, saveSuccess, immediateSaveAndRestart } = useAutoSave()
+ const { settings, setSettings, updateSettingsLocal, restartTracking } = useTracking()
+ const { saving, message: saveMessage, isError: saveIsError, immediateSaveAndRestart } = useAutoSave()
- const [endpointInput, setEndpointInput] = useState(settings.endpoint || "")
+ const [stats, setStats] = useState<DatabaseStats | null>(null)
+ const [deviceOnline, setDeviceOnline] = useState(true)
+ const [hasFix, setHasFix] = useState(false)
+ const [auth, setAuth] = useState<AuthConfig | null>(null)
+ const [certInfo, setCertInfo] = useState<ClientCertInfoResult | null>(null)
- useEffect(() => {
- setEndpointInput(settings.endpoint || "")
- }, [settings.endpoint])
+ useFocusEffect(
+ useCallback(() => {
+ let cancelled = false
+ const refresh = async () => {
+ try {
+ const [nextStats, online, fix, nextAuth, cert] = await Promise.all([
+ NativeLocationService.getStats(),
+ NativeLocationService.isNetworkAvailable(),
+ NativeLocationService.getMostRecentLocation(),
+ NativeLocationService.getAuthConfig(),
+ NativeLocationService.getClientCertInfo()
+ ])
+ if (cancelled) return
+ setStats(nextStats)
+ setDeviceOnline(online)
+ setHasFix(fix !== null)
+ setAuth(nextAuth)
+ setCertInfo(cert)
+ } catch (err) {
+ logger.error("[ConnectionScreen] Failed to read the server state:", err)
+ }
+ }
+ refresh()
+ const subs = ["onSyncProgress", "onSyncError", "onLocationUpdate"].map((event) =>
+ DeviceEventEmitter.addListener(event, refresh)
+ )
+ return () => {
+ cancelled = true
+ subs.forEach((sub) => sub.remove())
+ }
+ }, [])
+ )
const handleImmediateSave = useCallback(
(newSettings: Settings) => {
@@ -34,6 +81,20 @@ export function ConnectionScreen({ navigation }: ScreenProps) {
[setSettings, immediateSaveAndRestart, restartTracking]
)
+ const certificate = describeCertificate(certInfo)
+ const server = describeServer({
+ offline: settings.isOfflineMode,
+ endpoint: settings.endpoint,
+ deviceOnline,
+ queued: stats?.queued ?? 0,
+ today: stats?.today ?? 0,
+ lastSyncTime: stats?.lastSyncTime ?? 0,
+ lastSyncError: stats?.lastSyncError ?? "",
+ certificate
+ })
+ const template = settings.apiTemplate === "custom" ? "Custom" : API_TEMPLATES[settings.apiTemplate].label
+ const requestSummary = `${template} · ${settings.httpMethod ?? "POST"}`
+
return (
<Container>
<ScrollView
@@ -43,23 +104,26 @@ export function ConnectionScreen({ navigation }: ScreenProps) {
>
<ConnectionSettings
settings={settings}
- endpointInput={endpointInput}
- onEndpointInputChange={setEndpointInput}
+ onSettingsLocal={updateSettingsLocal}
onSettingsChange={handleImmediateSave}
- colors={colors}
+ server={server}
+ hasFix={hasFix}
+ requestSummary={requestSummary}
+ authSummary={authSummary(auth)}
+ certificateSummary={certificate.rowSub}
navigation={navigation}
/>
</ScrollView>
- <FloatingSaveIndicator saving={saving} success={saveSuccess} colors={colors} />
+ <FloatingSaveIndicator saving={saving} message={saveMessage} isError={saveIsError} />
</Container>
)
}
const styles = StyleSheet.create({
scrollContent: {
- paddingHorizontal: 16,
- paddingTop: 16,
- paddingBottom: 16
+ paddingHorizontal: space.lg,
+ paddingTop: space.lg,
+ paddingBottom: space.xxl
}
})
diff --git a/apps/mobile/src/screens/DashboardScreen.tsx b/apps/mobile/src/screens/DashboardScreen.tsx
index 01d27b5b..15b5dec9 100644
--- a/apps/mobile/src/screens/DashboardScreen.tsx
+++ b/apps/mobile/src/screens/DashboardScreen.tsx
@@ -255,7 +255,7 @@ export function DashboardScreen({ navigation }: ScreenProps) {
onStartTracking={handleStart}
onNavigateToConnection={() => navigation.navigate("Connection")}
onNavigateToTrackingSync={() => navigation.navigate("Tracking & Sync")}
- onNavigateToApiConfig={() => navigation.navigate("API Config")}
+ onNavigateToApiConfig={() => navigation.navigate("Request Format")}
/>
)}
diff --git a/apps/mobile/src/screens/MtlsSettingsScreen.tsx b/apps/mobile/src/screens/MtlsSettingsScreen.tsx
index 615e6379..2202a727 100644
--- a/apps/mobile/src/screens/MtlsSettingsScreen.tsx
+++ b/apps/mobile/src/screens/MtlsSettingsScreen.tsx
@@ -7,9 +7,10 @@ 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 { fontSizes, fonts, lineHeights } from "../styles/typography"
import { Container } from "../components"
import { MtlsSection } from "../components/features/settings/MtlsSection"
+import { space } from "../constants"
export function MtlsSettingsScreen({}: ScreenProps) {
const { colors } = useTheme()
@@ -22,9 +23,9 @@ export function MtlsSettingsScreen({}: ScreenProps) {
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
+ For a server or reverse proxy that requires mutual TLS. Not needed for tokens or passwords. The private key
+ never leaves this device.
</Text>
</View>
@@ -36,22 +37,16 @@ export function MtlsSettingsScreen({}: ScreenProps) {
const styles = StyleSheet.create({
scrollContent: {
- paddingHorizontal: 16,
- paddingTop: 16,
- paddingBottom: 40
+ paddingHorizontal: space.lg,
+ paddingTop: space.lg,
+ paddingBottom: space.xxl
},
header: {
- marginBottom: 20
- },
- title: {
- fontSize: 28,
- ...fonts.bold,
- letterSpacing: -0.5,
- marginBottom: 4
+ marginBottom: space.lg
},
subtitle: {
- fontSize: 14,
+ fontSize: fontSizes.body,
...fonts.regular,
- lineHeight: 20
+ lineHeight: lineHeights.body
}
})
diff --git a/apps/mobile/src/screens/SettingsScreen.tsx b/apps/mobile/src/screens/SettingsScreen.tsx
index 520b3f5c..16201d4f 100644
--- a/apps/mobile/src/screens/SettingsScreen.tsx
+++ b/apps/mobile/src/screens/SettingsScreen.tsx
@@ -138,7 +138,7 @@ export function SettingsScreen({ navigation }: Props) {
icon={Braces}
label="API Field Mapping"
sub={apiSummary}
- onPress={() => navigation.navigate("API Config")}
+ onPress={() => navigation.navigate("Request Format")}
/>
</>
)}
diff --git a/apps/mobile/src/screens/__tests__/ApiSettingsScreen.test.tsx b/apps/mobile/src/screens/__tests__/ApiSettingsScreen.test.tsx
index 58169e3c..ffeab359 100644
--- a/apps/mobile/src/screens/__tests__/ApiSettingsScreen.test.tsx
+++ b/apps/mobile/src/screens/__tests__/ApiSettingsScreen.test.tsx
@@ -61,10 +61,49 @@ jest.mock("../../components", () => {
const R = require("react")
const { View, Text, Pressable } = require("react-native")
return {
+ IconButton: require("../../testing/componentStubs").IconButtonStub,
+ TextField: require("../../testing/componentStubs").TextFieldStub,
+ Button: function (props: any) {
+ return require("react").createElement(
+ require("react-native").Pressable,
+ { testID: props.testID, onPress: props.onPress, disabled: props.disabled, accessibilityRole: "button" },
+ require("react").createElement(require("react-native").Text, null, props.title)
+ )
+ },
+ Toggle: function (props: any) {
+ return require("react").createElement(require("react-native").Switch, {
+ testID: props.testID,
+ value: props.value,
+ onValueChange: props.onValueChange,
+ disabled: props.disabled,
+ accessibilityLabel: props.accessibilityLabel
+ })
+ },
SectionTitle: ({ children }: any) => R.createElement(Text, null, children),
FloatingSaveIndicator: () => null,
Container: ({ children }: any) => R.createElement(View, null, children),
Divider: () => R.createElement(View, null),
+ Card: ({ children }: any) => R.createElement(View, null, children),
+ ListItem: ({ testID, label, sub, onPress }: any) =>
+ R.createElement(
+ Pressable,
+ { testID, onPress, accessibilityRole: "button" },
+ R.createElement(Text, null, label),
+ sub ? R.createElement(Text, null, sub) : null
+ ),
+ RadioRow: ({ testID, label, sub, selected, disabled, onPress }: any) =>
+ R.createElement(
+ Pressable,
+ {
+ testID,
+ onPress,
+ disabled,
+ accessibilityRole: "radio",
+ accessibilityState: { checked: selected, disabled }
+ },
+ R.createElement(Text, null, label),
+ sub ? R.createElement(Text, null, sub) : null
+ ),
ChipGroup: ({ options, selected, onSelect }: any) =>
R.createElement(
View,
@@ -82,6 +121,8 @@ jest.mock("../../components", () => {
import { ApiSettingsScreen } from "../ApiSettingsScreen"
+const mockNavigation = { navigate: jest.fn(), setOptions: jest.fn(), goBack: jest.fn(), setParams: jest.fn() }
+
describe("ApiSettingsScreen", () => {
beforeEach(() => {
jest.clearAllMocks()
@@ -92,25 +133,36 @@ describe("ApiSettingsScreen", () => {
if (settingsOverride) {
mockSettings = { ...DEFAULT_SETTINGS, ...settingsOverride }
}
- return render(<ApiSettingsScreen navigation={{} as any} />)
+ return render(<ApiSettingsScreen navigation={mockNavigation as any} route={{ params: {} } as any} />)
+ }
+
+ /** The picker screen hands its choice back through the route, which is the only way in now. */
+ function renderWithTemplate(template: string, settingsOverride?: Partial<Settings>) {
+ if (settingsOverride) {
+ mockSettings = { ...DEFAULT_SETTINGS, ...settingsOverride }
+ }
+ return render(<ApiSettingsScreen navigation={mockNavigation as any} route={{ params: { template } } as any} />)
}
describe("template switching", () => {
- it("renders all template options", () => {
- const { getByText, getAllByText } = renderScreen()
+ it("names the current template on a row instead of listing eight chips", () => {
+ const { getByTestId, getByText } = renderWithTemplate("dawarich")
- expect(getAllByText(/Custom/).length).toBeGreaterThan(0)
+ expect(getByTestId("nav-backend-template")).toBeTruthy()
expect(getByText("Dawarich")).toBeTruthy()
- expect(getByText("OwnTracks")).toBeTruthy()
- expect(getByText(/PhoneTrack/)).toBeTruthy()
- expect(getByText("Reitti")).toBeTruthy()
- expect(getByText("Traccar")).toBeTruthy()
+ expect(getByText(API_TEMPLATES.dawarich.description)).toBeTruthy()
})
- it("selecting Dawarich template applies its field map", () => {
- const { getByText, getByDisplayValue } = renderScreen()
+ it("opens the picker rather than switching in place", () => {
+ const { getByTestId } = renderScreen()
- fireEvent.press(getByText("Dawarich"))
+ fireEvent.press(getByTestId("nav-backend-template"))
+
+ expect(mockNavigation.navigate).toHaveBeenCalledWith("Backend Template", { selected: "custom" })
+ })
+
+ it("selecting Dawarich template applies its field map", () => {
+ const { getByDisplayValue } = renderWithTemplate("dawarich")
// Dawarich uses "cog" for bearing
expect(getByDisplayValue("cog")).toBeTruthy()
@@ -120,9 +172,7 @@ describe("ApiSettingsScreen", () => {
})
it("selecting OwnTracks template applies its custom fields", () => {
- const { getByText, getByDisplayValue } = renderScreen()
-
- fireEvent.press(getByText("OwnTracks"))
+ const { getByDisplayValue } = renderWithTemplate("owntracks")
// OwnTracks has _type and tid custom fields
expect(getByDisplayValue("_type")).toBeTruthy()
@@ -132,9 +182,7 @@ describe("ApiSettingsScreen", () => {
})
it("selecting PhoneTrack template applies its unique field names", () => {
- const { getByText, getByDisplayValue } = renderScreen()
-
- fireEvent.press(getByText(/PhoneTrack/))
+ const { getByDisplayValue } = renderWithTemplate("phonetrack")
// PhoneTrack uses different field names
expect(getByDisplayValue("speed")).toBeTruthy() // vel -> speed
@@ -144,33 +192,22 @@ describe("ApiSettingsScreen", () => {
})
it("switching template triggers immediate save", () => {
- const { getByText } = renderScreen()
-
- fireEvent.press(getByText("Traccar"))
+ renderWithTemplate("traccar")
expect(mockImmediateSaveAndRestart).toHaveBeenCalled()
})
it("switching back to Custom preserves current field map", () => {
- const { getByText, getByDisplayValue } = renderScreen()
-
- // First switch to PhoneTrack
- fireEvent.press(getByText(/PhoneTrack/))
+ const { getByDisplayValue, rerender } = renderWithTemplate("phonetrack")
expect(getByDisplayValue("speed")).toBeTruthy()
// Switch to Custom - field map stays as PhoneTrack's
- fireEvent.press(getByText("Custom"))
+ rerender(
+ <ApiSettingsScreen navigation={mockNavigation as any} route={{ params: { template: "custom" } } as any} />
+ )
expect(getByDisplayValue("speed")).toBeTruthy()
})
- it("shows template description for non-custom templates", () => {
- const { getByText } = renderScreen()
-
- fireEvent.press(getByText("Dawarich"))
-
- expect(getByText(API_TEMPLATES.dawarich.description)).toBeTruthy()
- })
-
it("editing a field auto-switches template to Custom", () => {
const { getByText, getByDisplayValue, queryByText } = renderScreen({
apiTemplate: "dawarich",
@@ -199,12 +236,11 @@ describe("ApiSettingsScreen", () => {
expect(getByText(/GET/)).toBeTruthy()
})
- it("switching to GET shows query parameter hint", () => {
+ it("states what each method does without one being picked, which the chips could not", () => {
const { getByText } = renderScreen()
- fireEvent.press(getByText(/^GET$/))
-
- expect(getByText("Fields sent as URL query parameters instead of JSON body")).toBeTruthy()
+ expect(getByText("Sends the fields as a JSON body")).toBeTruthy()
+ expect(getByText("Sends the fields as URL query parameters")).toBeTruthy()
})
it("switching method triggers immediate save", () => {
@@ -215,12 +251,14 @@ describe("ApiSettingsScreen", () => {
expect(mockImmediateSaveAndRestart).toHaveBeenCalled()
})
- it("example payload changes format for GET method", () => {
- const { getByText } = renderScreen()
+ it("calls the example a request under GET, because a GET carries no payload", () => {
+ const { getByText, getByTestId } = renderScreen()
- fireEvent.press(getByText(/^GET$/))
+ expect(getByText("Example payload")).toBeTruthy()
+
+ fireEvent.press(getByTestId("http-method-get"))
- expect(getByText("EXAMPLE REQUEST")).toBeTruthy()
+ expect(getByText("Example request")).toBeTruthy()
})
})
@@ -235,13 +273,15 @@ describe("ApiSettingsScreen", () => {
expect(getByText("Modified")).toBeTruthy()
})
- it("shows RESET ALL button when any field is modified", () => {
- const { getByText, getByDisplayValue } = renderScreen()
+ it("offers Reset all as a button once a field is modified", () => {
+ // The heading's action was a bare Pressable, so a screen reader announced the words with
+ // no role and nothing said it was pressable.
+ const { getByRole, getByDisplayValue } = renderScreen()
const latInput = getByDisplayValue("lat")
fireEvent.changeText(latInput, "latitude")
- expect(getByText("RESET ALL")).toBeTruthy()
+ expect(getByRole("button", { name: "Reset all" })).toBeTruthy()
})
})
@@ -264,10 +304,34 @@ describe("ApiSettingsScreen", () => {
})
describe("copy payload", () => {
- it("renders the COPY button", () => {
- const { getByText } = renderScreen()
+ it("offers the payload copy as a button, in sentence case", () => {
+ // A bare Pressable with no role: TalkBack announced the word and nothing else. COPY was
+ // also the last caps label left after the sentence-case sweep.
+ const { getByRole } = renderScreen()
+
+ expect(getByRole("button", { name: "Copy" })).toBeTruthy()
+ })
+ })
+
+ describe("dawarich mode", () => {
+ it("says on the row itself why batch cannot be picked, rather than in a line under the group", () => {
+ const { getByText } = renderWithTemplate("dawarich", { syncInterval: 0 })
+
+ expect(getByText("Needs a sync interval above Instant")).toBeTruthy()
+ })
+
+ it("names the other blocker when the method is the thing in the way", () => {
+ const { getByText, getByTestId } = renderWithTemplate("dawarich", { syncInterval: 300 })
+
+ fireEvent.press(getByTestId("http-method-get"))
+
+ expect(getByText("Needs the POST method, not GET")).toBeTruthy()
+ })
+
+ it("marks the blocked option disabled instead of only dimming it", () => {
+ const { getByTestId } = renderWithTemplate("dawarich", { syncInterval: 0 })
- expect(getByText("COPY")).toBeTruthy()
+ expect(getByTestId("dawarich-mode-batch").props.accessibilityState.disabled).toBe(true)
})
})
})
diff --git a/apps/mobile/src/screens/__tests__/AuthSettingsScreen.test.tsx b/apps/mobile/src/screens/__tests__/AuthSettingsScreen.test.tsx
index 4c8c90ab..35ded032 100644
--- a/apps/mobile/src/screens/__tests__/AuthSettingsScreen.test.tsx
+++ b/apps/mobile/src/screens/__tests__/AuthSettingsScreen.test.tsx
@@ -1,9 +1,8 @@
import React from "react"
import { render, fireEvent, waitFor } from "@testing-library/react-native"
+import { ActivityIndicator } from "react-native"
import { DEFAULT_AUTH_CONFIG, AuthConfig } from "../../types/global"
-// --- Mocks ---
-
let mockAuthConfig: AuthConfig = { ...DEFAULT_AUTH_CONFIG }
const mockSaveAuthConfig = jest.fn().mockResolvedValue(undefined)
const mockGetAuthConfig = jest.fn(() => Promise.resolve(mockAuthConfig))
@@ -26,23 +25,7 @@ jest.mock("../../contexts/TrackingProvider", () => ({
}))
jest.mock("../../hooks/useTheme", () => ({
- useTheme: () => ({
- colors: {
- primary: "#0d9488",
- primaryDark: "#115E59",
- border: "#e5e7eb",
- text: "#000",
- textSecondary: "#6b7280",
- textLight: "#9ca3af",
- background: "#fff",
- info: "#3b82f6",
- success: "#22c55e",
- error: "#ef4444",
- card: "#fff",
- placeholder: "#9ca3af",
- textOnPrimary: "#fff"
- }
- })
+ useTheme: () => ({ colors: require("@colota/shared").lightColors })
}))
const mockDebouncedSaveAndRestart = jest.fn()
@@ -51,7 +34,8 @@ const mockImmediateSaveAndRestart = jest.fn()
jest.mock("../../hooks/useAutoSave", () => ({
useAutoSave: () => ({
saving: false,
- saveSuccess: false,
+ message: null,
+ isError: false,
debouncedSaveAndRestart: mockDebouncedSaveAndRestart,
immediateSaveAndRestart: mockImmediateSaveAndRestart
})
@@ -61,25 +45,23 @@ jest.mock("../../components", () => {
const R = require("react")
const { View, Text, Pressable } = require("react-native")
return {
+ IconButton: require("../../testing/componentStubs").IconButtonStub,
+ TextField: require("../../testing/componentStubs").TextFieldStub,
+ RadioRow: ({ testID, label, sub, selected, onPress }: any) =>
+ R.createElement(
+ Pressable,
+ { testID, onPress, accessibilityRole: "radio", accessibilityState: { checked: selected } },
+ R.createElement(Text, null, label),
+ sub ? R.createElement(Text, null, sub) : null
+ ),
SectionTitle: ({ children }: any) => R.createElement(Text, null, children),
FloatingSaveIndicator: () => null,
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,
- null,
- options.map((opt: any) =>
- R.createElement(
- Pressable,
- { key: opt.value, onPress: () => onSelect(opt.value) },
- R.createElement(Text, null, opt.label)
- )
- )
- )
+ Button: ({ title, onPress, testID }: any) =>
+ R.createElement(Pressable, { onPress, testID }, R.createElement(Text, null, title)),
+ FieldMessage: ({ children }: any) => R.createElement(Text, null, children)
}
})
@@ -87,7 +69,18 @@ jest.mock("../../utils/logger", () => ({
logger: { error: jest.fn(), info: jest.fn(), debug: jest.fn() }
}))
-import { AuthSettingsScreen } from "../AuthSettingsScreen"
+import { AuthSettingsScreen, withMethod } from "../AuthSettingsScreen"
+
+const lastImmediateConfig = async () => {
+ const [saveFn] = mockImmediateSaveAndRestart.mock.calls.at(-1)
+ await saveFn()
+ return mockSaveAuthConfig.mock.calls.at(-1)[0] as AuthConfig
+}
+const lastDebouncedConfig = async () => {
+ const [saveFn] = mockDebouncedSaveAndRestart.mock.calls.at(-1)
+ await saveFn()
+ return mockSaveAuthConfig.mock.calls.at(-1)[0] as AuthConfig
+}
describe("AuthSettingsScreen", () => {
beforeEach(() => {
@@ -99,240 +92,157 @@ describe("AuthSettingsScreen", () => {
return render(<AuthSettingsScreen navigation={{} as any} />)
}
- describe("loading state", () => {
- it("shows loading text while fetching config", () => {
- // Keep the promise pending
- mockGetAuthConfig.mockReturnValueOnce(new Promise(() => {}))
- const { getByText } = renderScreen()
-
- expect(getByText("Loading...")).toBeTruthy()
- })
-
- it("shows content after config is loaded", async () => {
- const { getByText } = renderScreen()
+ it("spins while the config loads, never the word", () => {
+ mockGetAuthConfig.mockReturnValueOnce(new Promise(() => {}))
+ const { UNSAFE_getByType, queryByText } = renderScreen()
- await waitFor(() => {
- expect(getByText("Authentication & Headers")).toBeTruthy()
- })
- })
+ expect(UNSAFE_getByType(ActivityIndicator)).toBeTruthy()
+ expect(queryByText("Loading...")).toBeNull()
})
- describe("auth type changes", () => {
- it("renders all three auth type options", async () => {
- const { getByText } = renderScreen()
-
- await waitFor(() => {
- expect(getByText("None")).toBeTruthy()
- })
- expect(getByText("Basic Auth")).toBeTruthy()
- expect(getByText("Bearer Token")).toBeTruthy()
- })
-
- it("defaults to None with no credential fields visible", async () => {
- const { queryByText, getByText } = renderScreen()
-
- await waitFor(() => {
- expect(getByText("None")).toBeTruthy()
- })
+ describe("method", () => {
+ it("is a radio group whose rows say what each sends, with only the chosen method's fields", async () => {
+ const { getByTestId, getByText, queryByText } = renderScreen()
+ await waitFor(() => expect(getByTestId("auth-none").props.accessibilityState.checked).toBe(true))
+ expect(
+ getByText(
+ "Sends Authorization: Basic with the username and password encoded, not encrypted. Only safe over https."
+ )
+ ).toBeTruthy()
+ expect(getByText("Sends Authorization: Bearer with the token.")).toBeTruthy()
expect(queryByText("Username")).toBeNull()
- expect(queryByText("Password")).toBeNull()
expect(queryByText("Token")).toBeNull()
- })
-
- it("switching to Basic Auth shows username and password fields", async () => {
- const { getByText } = renderScreen()
-
- await waitFor(() => {
- expect(getByText("None")).toBeTruthy()
- })
-
- fireEvent.press(getByText("Basic Auth"))
+ fireEvent.press(getByTestId("auth-basic"))
expect(getByText("Username")).toBeTruthy()
expect(getByText("Password")).toBeTruthy()
- })
-
- it("switching to Bearer Token shows token field", async () => {
- const { getByText } = renderScreen()
- await waitFor(() => {
- expect(getByText("None")).toBeTruthy()
- })
-
- fireEvent.press(getByText("Bearer Token"))
-
- expect(getByText("Token")).toBeTruthy()
- })
-
- it("switching from Basic Auth to Bearer hides username/password, shows token", async () => {
- const { getByText, queryByText } = renderScreen()
-
- await waitFor(() => {
- expect(getByText("None")).toBeTruthy()
- })
-
- fireEvent.press(getByText("Basic Auth"))
- expect(getByText("Username")).toBeTruthy()
-
- fireEvent.press(getByText("Bearer Token"))
+ fireEvent.press(getByTestId("auth-bearer"))
expect(queryByText("Username")).toBeNull()
- expect(queryByText("Password")).toBeNull()
expect(getByText("Token")).toBeTruthy()
})
- it("switching from Bearer to None hides token field", async () => {
- const { getByText, queryByText } = renderScreen()
+ it("saves a method at once and drops the credentials of the others, so a never-shown secret can be cleared", async () => {
+ mockAuthConfig = { ...DEFAULT_AUTH_CONFIG, authType: "basic", username: "max", password: "hunter2" }
+ const { getByTestId } = renderScreen()
+ await waitFor(() => expect(getByTestId("auth-basic").props.accessibilityState.checked).toBe(true))
+
+ fireEvent.press(getByTestId("auth-bearer"))
- await waitFor(() => {
- expect(getByText("None")).toBeTruthy()
+ expect(await lastImmediateConfig()).toMatchObject({
+ authType: "bearer",
+ username: "",
+ password: "",
+ bearerToken: ""
+ })
+ expect(withMethod({ ...DEFAULT_AUTH_CONFIG, bearerToken: "t", username: "u" }, "none")).toMatchObject({
+ bearerToken: "",
+ username: ""
})
+ })
- fireEvent.press(getByText("Bearer Token"))
- expect(getByText("Token")).toBeTruthy()
+ it("names the storage on the card, not in a footer paragraph", async () => {
+ const { findByText } = renderScreen()
- fireEvent.press(getByText("None"))
- expect(queryByText("Token")).toBeNull()
+ expect(await findByText("Choosing a method removes the credentials stored for the others.")).toBeTruthy()
+ expect(await findByText(/Stored encrypted on this device and in encrypted backups/)).toBeTruthy()
})
+ })
- it("auth type change triggers immediate save", async () => {
- const { getByText } = renderScreen()
-
- await waitFor(() => {
- expect(getByText("None")).toBeTruthy()
- })
+ describe("secrets", () => {
+ it("never echoes a stored secret: the field is empty and the note says it is set", async () => {
+ mockAuthConfig = { ...DEFAULT_AUTH_CONFIG, authType: "bearer", bearerToken: "my-secret-token" }
+ const { getByTestId, getByText, queryByDisplayValue } = renderScreen()
- fireEvent.press(getByText("Basic Auth"))
+ await waitFor(() => expect(getByTestId("bearer-token")).toBeTruthy())
- expect(mockImmediateSaveAndRestart).toHaveBeenCalled()
+ expect(queryByDisplayValue("my-secret-token")).toBeNull()
+ expect(getByText("Set · encrypted on this device, in encrypted backups. Type to replace.")).toBeTruthy()
})
- it("loads saved Basic Auth config and shows fields", async () => {
- mockAuthConfig = {
- ...DEFAULT_AUTH_CONFIG,
- authType: "basic",
- username: "testuser",
- password: "testpass"
- }
+ it("says when nothing is stored yet", async () => {
+ mockAuthConfig = { ...DEFAULT_AUTH_CONFIG, authType: "basic", username: "max" }
+ const { findByText, getByDisplayValue } = renderScreen()
- const { getByText, getByDisplayValue } = renderScreen()
-
- await waitFor(() => {
- expect(getByText("Username")).toBeTruthy()
- })
-
- expect(getByDisplayValue("testuser")).toBeTruthy()
- expect(getByDisplayValue("testpass")).toBeTruthy()
+ expect(await findByText("Not set · encrypted once saved.")).toBeTruthy()
+ expect(getByDisplayValue("max")).toBeTruthy()
})
- it("loads saved Bearer config and shows field", async () => {
- mockAuthConfig = {
- ...DEFAULT_AUTH_CONFIG,
- authType: "bearer",
- bearerToken: "my-secret-token"
- }
-
- const { getByText, getByDisplayValue } = renderScreen()
+ it("replaces the stored value when typed and keeps it when the draft is cleared", async () => {
+ mockAuthConfig = { ...DEFAULT_AUTH_CONFIG, authType: "bearer", bearerToken: "old" }
+ const { getByTestId } = renderScreen()
+ await waitFor(() => expect(getByTestId("bearer-token")).toBeTruthy())
- await waitFor(() => {
- expect(getByText("Token")).toBeTruthy()
- })
+ fireEvent.changeText(getByTestId("bearer-token"), "new-token")
+ expect((await lastDebouncedConfig()).bearerToken).toBe("new-token")
- expect(getByDisplayValue("my-secret-token")).toBeTruthy()
+ mockDebouncedSaveAndRestart.mockClear()
+ fireEvent.changeText(getByTestId("bearer-token"), "")
+ expect(mockDebouncedSaveAndRestart).not.toHaveBeenCalled()
})
- it("typing in username triggers debounced save", async () => {
- const { getByText, getByPlaceholderText } = renderScreen()
-
- await waitFor(() => {
- expect(getByText("None")).toBeTruthy()
- })
-
- fireEvent.press(getByText("Basic Auth"))
+ it("carries a first edit into a second one typed inside the debounce", async () => {
+ mockAuthConfig = { ...DEFAULT_AUTH_CONFIG, authType: "basic" }
+ const { getByTestId } = renderScreen()
+ await waitFor(() => expect(getByTestId("basic-username")).toBeTruthy())
- const usernameInput = getByPlaceholderText("Username")
- fireEvent.changeText(usernameInput, "newuser")
+ fireEvent.changeText(getByTestId("basic-username"), "max")
+ fireEvent.changeText(getByTestId("basic-password"), "hunter2")
- expect(mockDebouncedSaveAndRestart).toHaveBeenCalled()
+ expect(await lastDebouncedConfig()).toMatchObject({ username: "max", password: "hunter2" })
})
})
describe("custom headers", () => {
- it("shows empty state when no headers configured", async () => {
- const { getByText } = renderScreen()
+ it("says none are set and what a header does", async () => {
+ const { findByText } = renderScreen()
- await waitFor(() => {
- expect(getByText("No custom headers configured")).toBeTruthy()
- })
+ expect(await findByText("None. A custom header is sent with every request.")).toBeTruthy()
})
- it("adds a header row when + Add Header is pressed", async () => {
- const { getByText, getAllByPlaceholderText } = renderScreen()
+ it("adds a row and saves it once a name exists", async () => {
+ const { getByTestId, getAllByPlaceholderText, findByTestId } = renderScreen()
- await waitFor(() => {
- expect(getByText("+ Add Header")).toBeTruthy()
- })
+ fireEvent.press(await findByTestId("add-header-btn"))
+ expect(getAllByPlaceholderText("Name")).toHaveLength(1)
- fireEvent.press(getByText("+ Add Header"))
+ fireEvent.changeText(getAllByPlaceholderText("Name")[0], "CF-Access-Client-Id")
+ fireEvent.changeText(getAllByPlaceholderText("Value")[0], "abc")
- expect(getAllByPlaceholderText("Header name")).toHaveLength(1)
- expect(getAllByPlaceholderText("Value")).toHaveLength(1)
+ expect((await lastDebouncedConfig()).customHeaders).toEqual({ "CF-Access-Client-Id": "abc" })
+ expect(getByTestId("add-header-btn")).toBeTruthy()
})
- it("loads saved custom headers", async () => {
- mockAuthConfig = {
- ...DEFAULT_AUTH_CONFIG,
- customHeaders: { "CF-Access-Client-Id": "abc123" }
- }
-
- const { getByDisplayValue } = renderScreen()
-
- await waitFor(() => {
- expect(getByDisplayValue("CF-Access-Client-Id")).toBeTruthy()
- })
+ it("loads saved headers with their values, since a name and value pair must be auditable", async () => {
+ mockAuthConfig = { ...DEFAULT_AUTH_CONFIG, customHeaders: { "CF-Access-Client-Id": "abc123" } }
+ const { findByDisplayValue, getByDisplayValue } = renderScreen()
+ expect(await findByDisplayValue("CF-Access-Client-Id")).toBeTruthy()
expect(getByDisplayValue("abc123")).toBeTruthy()
})
- it("removes a header when X is pressed", async () => {
- mockAuthConfig = {
- ...DEFAULT_AUTH_CONFIG,
- customHeaders: { "X-Custom": "val" }
- }
-
- const { getByDisplayValue, getByText, queryByDisplayValue } = renderScreen()
-
- await waitFor(() => {
- expect(getByDisplayValue("X-Custom")).toBeTruthy()
- })
+ it("removes a header at once, named for a screen reader", async () => {
+ mockAuthConfig = { ...DEFAULT_AUTH_CONFIG, customHeaders: { "X-Custom": "val" } }
+ const { findByLabelText, queryByDisplayValue } = renderScreen()
- fireEvent.press(getByText("X"))
+ fireEvent.press(await findByLabelText("Remove header X-Custom"))
expect(queryByDisplayValue("X-Custom")).toBeNull()
- expect(mockImmediateSaveAndRestart).toHaveBeenCalled()
+ expect((await lastImmediateConfig()).customHeaders).toEqual({})
})
- it("shows duplicate key warning when header names collide", async () => {
- mockAuthConfig = {
- ...DEFAULT_AUTH_CONFIG,
- customHeaders: { "X-One": "a" }
- }
+ it("marks a duplicate name on its own field instead of a banner", async () => {
+ mockAuthConfig = { ...DEFAULT_AUTH_CONFIG, customHeaders: { "X-One": "a" } }
+ const { findByTestId, getAllByPlaceholderText, queryByText, getByText } = renderScreen()
- const { getByText, getAllByPlaceholderText, queryByText } = renderScreen()
+ fireEvent.press(await findByTestId("add-header-btn"))
+ expect(queryByText("Also used above. Only the last value is sent.")).toBeNull()
- await waitFor(() => {
- expect(getByText("+ Add Header")).toBeTruthy()
- })
+ fireEvent.changeText(getAllByPlaceholderText("Name")[1], "X-One")
- // No warning initially
+ expect(getByText("Also used above. Only the last value is sent.")).toBeTruthy()
expect(queryByText(/Duplicate header names/)).toBeNull()
-
- // Add second header and type same key
- fireEvent.press(getByText("+ Add Header"))
- const nameInputs = getAllByPlaceholderText("Header name")
- fireEvent.changeText(nameInputs[1], "X-One")
-
- expect(getByText(/Duplicate header names/)).toBeTruthy()
})
})
})
diff --git a/apps/mobile/src/screens/__tests__/BackendTemplateScreen.test.tsx b/apps/mobile/src/screens/__tests__/BackendTemplateScreen.test.tsx
new file mode 100644
index 00000000..41ae8b91
--- /dev/null
+++ b/apps/mobile/src/screens/__tests__/BackendTemplateScreen.test.tsx
@@ -0,0 +1,65 @@
+import React from "react"
+import { render, fireEvent } from "@testing-library/react-native"
+
+jest.mock("../../components", () => {
+ const R = require("react")
+ const { View, Text, Pressable } = require("react-native")
+ return {
+ Container: ({ children }: any) => R.createElement(View, null, children),
+ Card: ({ children }: any) => R.createElement(View, null, children),
+ RadioRow: ({ testID, label, sub, selected, onPress }: any) =>
+ R.createElement(
+ Pressable,
+ { testID, onPress, accessibilityRole: "radio", accessibilityState: { checked: selected } },
+ R.createElement(Text, null, label),
+ sub ? R.createElement(Text, null, sub) : null
+ )
+ }
+})
+
+import { BackendTemplateScreen } from "../BackendTemplateScreen"
+import { API_TEMPLATES } from "../../types/global"
+
+describe("BackendTemplateScreen", () => {
+ const mockPopTo = jest.fn()
+ const navigation = { popTo: mockPopTo }
+
+ beforeEach(() => {
+ jest.clearAllMocks()
+ })
+
+ function renderScreen(selected = "custom") {
+ return render(<BackendTemplateScreen navigation={navigation as any} route={{ params: { selected } } as any} />)
+ }
+
+ it("describes every template on its own row, which is why this is a screen and not a menu", () => {
+ const { getByText } = renderScreen()
+
+ Object.values(API_TEMPLATES).forEach((template) => {
+ expect(getByText(template.label)).toBeTruthy()
+ expect(getByText(template.description)).toBeTruthy()
+ })
+ })
+
+ it("offers Custom alongside the templates, because it is a choice and not an absence", () => {
+ const { getByTestId, getByText } = renderScreen()
+
+ expect(getByTestId("template-custom")).toBeTruthy()
+ expect(getByText("Your own field names, mapped by hand")).toBeTruthy()
+ })
+
+ it("marks the incoming selection so you can see what you are on", () => {
+ const { getByTestId } = renderScreen("traccar")
+
+ expect(getByTestId("template-traccar").props.accessibilityState.checked).toBe(true)
+ expect(getByTestId("template-custom").props.accessibilityState.checked).toBe(false)
+ })
+
+ it("hands the choice back and returns, rather than pushing another copy of the parent", () => {
+ const { getByTestId } = renderScreen()
+
+ fireEvent.press(getByTestId("template-dawarich"))
+
+ expect(mockPopTo).toHaveBeenCalledWith("Request Format", { template: "dawarich" }, { merge: true })
+ })
+})
diff --git a/apps/mobile/src/screens/__tests__/ConnectionScreen.test.tsx b/apps/mobile/src/screens/__tests__/ConnectionScreen.test.tsx
new file mode 100644
index 00000000..64921393
--- /dev/null
+++ b/apps/mobile/src/screens/__tests__/ConnectionScreen.test.tsx
@@ -0,0 +1,158 @@
+import React from "react"
+import { render, fireEvent, waitFor } from "@testing-library/react-native"
+import { DEFAULT_AUTH_CONFIG } from "../../types/global"
+
+let mockSettings = { ...require("../../types/global").DEFAULT_SETTINGS, endpoint: "https://tracks.example.org/api" }
+const mockSetSettings = jest.fn()
+const mockUpdateSettingsLocal = jest.fn()
+const mockRestartTracking = jest.fn()
+
+jest.mock("../../contexts/TrackingProvider", () => ({
+ useTracking: () => ({
+ settings: mockSettings,
+ setSettings: mockSetSettings,
+ updateSettingsLocal: mockUpdateSettingsLocal,
+ restartTracking: mockRestartTracking
+ })
+}))
+
+const mockImmediateSaveAndRestart = jest.fn()
+jest.mock("../../hooks/useAutoSave", () => ({
+ useAutoSave: () => ({
+ saving: false,
+ message: null,
+ isError: false,
+ debouncedSaveAndRestart: jest.fn(),
+ immediateSaveAndRestart: mockImmediateSaveAndRestart
+ })
+}))
+
+const mockGetStats = jest.fn()
+const mockIsNetworkAvailable = jest.fn()
+const mockGetMostRecentLocation = jest.fn()
+const mockGetAuthConfig = jest.fn()
+const mockGetClientCertInfo = jest.fn()
+jest.mock("../../services/NativeLocationService", () => ({
+ __esModule: true,
+ default: {
+ getStats: (...a: unknown[]) => mockGetStats(...a),
+ isNetworkAvailable: (...a: unknown[]) => mockIsNetworkAvailable(...a),
+ getMostRecentLocation: (...a: unknown[]) => mockGetMostRecentLocation(...a),
+ getAuthConfig: (...a: unknown[]) => mockGetAuthConfig(...a),
+ getClientCertInfo: (...a: unknown[]) => mockGetClientCertInfo(...a)
+ }
+}))
+
+jest.mock("@react-navigation/native", () => ({
+ useFocusEffect: (cb: () => (() => void) | void) => {
+ const R = require("react")
+ R.useEffect(() => {
+ const cleanup = cb()
+ return typeof cleanup === "function" ? cleanup : undefined
+ }, [cb])
+ }
+}))
+
+jest.mock("../../utils/logger", () => ({ logger: { error: jest.fn() } }))
+
+jest.mock("../../components", () => {
+ const R = require("react")
+ const { View } = require("react-native")
+ return { Container: ({ children }: any) => R.createElement(View, null, children) }
+})
+
+jest.mock("../../components/ui/FloatingSaveIndicator", () => ({ FloatingSaveIndicator: () => null }))
+
+jest.mock("../../components/features/settings/ConnectionSettings", () => {
+ const R = require("react")
+ const { View, Text, Pressable } = require("react-native")
+ return {
+ ConnectionSettings: (props: any) =>
+ R.createElement(
+ View,
+ null,
+ R.createElement(Text, null, `word:${props.server.word}`),
+ R.createElement(Text, null, `caption:${props.server.caption}`),
+ R.createElement(Text, null, `fix:${props.hasFix}`),
+ R.createElement(Text, null, `request:${props.requestSummary}`),
+ R.createElement(Text, null, `auth:${props.authSummary}`),
+ R.createElement(Text, null, `cert:${props.certificateSummary}`),
+ R.createElement(Pressable, {
+ testID: "save",
+ onPress: () => {
+ const next = { ...props.settings, endpoint: "https://new.example/api" }
+ props.onSettingsLocal(next)
+ props.onSettingsChange(next)
+ }
+ })
+ )
+ }
+})
+
+import { ConnectionScreen, authSummary } from "../ConnectionScreen"
+
+const mockProps = { navigation: { navigate: jest.fn() } as any, route: { params: undefined } as any }
+
+beforeEach(() => {
+ jest.clearAllMocks()
+ mockSettings = { ...require("../../types/global").DEFAULT_SETTINGS, endpoint: "https://tracks.example.org/api" }
+ mockGetStats.mockResolvedValue({
+ queued: 38,
+ sent: 400,
+ total: 438,
+ today: 5,
+ databaseSizeMB: 1,
+ lastSyncTime: 0,
+ lastSyncError: "HTTP 401 Unauthorized"
+ })
+ mockIsNetworkAvailable.mockResolvedValue(true)
+ mockGetMostRecentLocation.mockResolvedValue({ latitude: 1, longitude: 2 })
+ mockGetAuthConfig.mockResolvedValue({ ...DEFAULT_AUTH_CONFIG, authType: "bearer", customHeaders: { A: "1", B: "2" } })
+ mockGetClientCertInfo.mockResolvedValue({ configured: false })
+})
+
+describe("ConnectionScreen", () => {
+ it("reads the server state on focus and hands the card what sync is doing now", async () => {
+ const { findByText, getByText } = render(<ConnectionScreen {...mockProps} />)
+
+ expect(await findByText("word:Sync failing")).toBeTruthy()
+ expect(getByText("caption:HTTP 401 Unauthorized · 38 queued · last success never")).toBeTruthy()
+ expect(getByText("fix:true")).toBeTruthy()
+ })
+
+ it("prints each detail row's stored value as its sub", async () => {
+ mockSettings = { ...mockSettings, apiTemplate: "traccar", httpMethod: "GET" }
+ const { findByText, getByText } = render(<ConnectionScreen {...mockProps} />)
+
+ expect(await findByText("auth:Bearer token · 2 headers")).toBeTruthy()
+ expect(getByText("request:Traccar · GET")).toBeTruthy()
+ expect(getByText("cert:Not set")).toBeTruthy()
+ })
+
+ it("wires a change to local state then the immediate save that restarts tracking", async () => {
+ const { getByTestId, findByText } = render(<ConnectionScreen {...mockProps} />)
+ await findByText("fix:true")
+
+ fireEvent.press(getByTestId("save"))
+
+ expect(mockUpdateSettingsLocal).toHaveBeenCalledWith(
+ expect.objectContaining({ endpoint: "https://new.example/api" })
+ )
+ await waitFor(() => expect(mockImmediateSaveAndRestart).toHaveBeenCalledTimes(1))
+ const [save, restart] = mockImmediateSaveAndRestart.mock.calls[0]
+ save()
+ restart()
+ expect(mockSetSettings).toHaveBeenCalledWith(expect.objectContaining({ endpoint: "https://new.example/api" }))
+ expect(mockRestartTracking).toHaveBeenCalledWith(expect.objectContaining({ endpoint: "https://new.example/api" }))
+ })
+})
+
+describe("authSummary", () => {
+ it("names the method and counts headers only when there are some", () => {
+ expect(authSummary({ ...DEFAULT_AUTH_CONFIG })).toBe("None")
+ expect(authSummary({ ...DEFAULT_AUTH_CONFIG, authType: "basic", customHeaders: { A: "1" } })).toBe(
+ "Basic auth · 1 header"
+ )
+ expect(authSummary(null)).toBe("")
+ })
+})
diff --git a/apps/mobile/src/screens/__tests__/SettingsScreen.test.tsx b/apps/mobile/src/screens/__tests__/SettingsScreen.test.tsx
index beed0441..a0e1d5be 100644
--- a/apps/mobile/src/screens/__tests__/SettingsScreen.test.tsx
+++ b/apps/mobile/src/screens/__tests__/SettingsScreen.test.tsx
@@ -198,7 +198,7 @@ describe("SettingsScreen", () => {
fireEvent.press(getByText("API Field Mapping"))
- expect(mockNavigate).toHaveBeenCalledWith("API Config")
+ expect(mockNavigate).toHaveBeenCalledWith("Request Format")
})
// --- Offline mode ---
diff --git a/apps/mobile/src/screens/index.ts b/apps/mobile/src/screens/index.ts
index 4e833fad..073a6971 100644
--- a/apps/mobile/src/screens/index.ts
+++ b/apps/mobile/src/screens/index.ts
@@ -28,3 +28,4 @@ export { ShareSetupScreen } from "./ShareSetupScreen"
export { TripDetailScreen } from "./TripDetailScreen"
export { OfflineMapsScreen } from "./OfflineMapsScreen"
export { BackupRestoreScreen } from "./BackupRestoreScreen"
+export { BackendTemplateScreen } from "./BackendTemplateScreen"
diff --git a/apps/mobile/src/types/navigation.ts b/apps/mobile/src/types/navigation.ts
index 4dd35441..5558d558 100644
--- a/apps/mobile/src/types/navigation.ts
+++ b/apps/mobile/src/types/navigation.ts
@@ -1,3 +1,4 @@
+import type { ApiTemplateName } from "./global"
/**
* Copyright (C) 2026 Max Dietrich
* Licensed under the GNU AGPLv3. See LICENSE in the project root for details.
@@ -14,7 +15,8 @@ export type RootStackParamList = {
Connection: undefined
"Tracking & Sync": undefined
Appearance: undefined
- "API Config": undefined
+ "Request Format": { template?: ApiTemplateName } | undefined
+ "Backend Template": { selected: ApiTemplateName }
"Auth Settings": undefined
"mTLS Settings": undefined
Geofences: undefined