diff --git a/native-android/README.md b/native-android/README.md index a4e00f2..025d31f 100644 --- a/native-android/README.md +++ b/native-android/README.md @@ -7,7 +7,8 @@ contacts, messages and settings. This is a standalone experiment next to the team app in `OffGridCH/app`. It has no remote. -- Package `ch.offgrid.android`, minSdk 26, target/compile SDK 35, version 0.1.0 +- Package `ch.offgrid.android`, minSdk 26, target/compile SDK 35, version 0.1.0-lab3 (versionCode 2), + written against the lab firmware image 0.2.0-lab.3 and the team stack `feature/mesh-direct` - Specs followed: `OffGridCH/firmware/docs/offgrid-link.md` (link), `offgrid-protocol.md` (radio protocol, crypto test vectors), designs in `offgrid-landing/design/*.png` @@ -29,7 +30,24 @@ POSTHOG_KEY=phc_... | APK | Path | Use | |---|---|---| | Debug | `app/build/outputs/apk/debug/app-debug.apk` | Development: test menu, simulated contacts, debug pairing buttons | -| Release-style | `app/build/outputs/apk/release/app-release.apk` | Demos: no test menu, no debug buttons. Signed with the SDK debug key (`CN=Android Debug`), so it installs without a keystore. A real release key is an open decision; none was created. | +| Release | `app/build/outputs/apk/release/app-release.apk` (signed) or `app-release-unsigned.apk` | Download from the landing page: no test menu, no debug buttons, no TCP bridge, no forced codec. Signed only with the release key below; without it the APK is unsigned, never signed with the debug key. | + +Release signing reads four values from Gradle properties (`-P…` or `~/.gradle/gradle.properties`) or +environment variables of the same names; no key or password is in this repository: + +```sh +OFFGRID_RELEASE_STORE_FILE=/path/to/offgrid-release.jks +OFFGRID_RELEASE_STORE_PASSWORD=… +OFFGRID_RELEASE_KEY_ALIAS=offgrid +OFFGRID_RELEASE_KEY_PASSWORD=… +./gradlew assembleRelease +``` + +When only some of them are set, or the keystore file does not exist, the build stops with the missing names. + +The lab test APK for phones with a lab board is the debug build with `OFFGRID_TEXT_CODEC=ogz1` and +without `OFFGRID_TCP_LINK` in `local.properties`: it switches a lab image to OGZ1 with `lab.set` after +unlocking and counts bytes with the codec, and it uses USB, not the TCP bridge. ## Install @@ -37,8 +55,8 @@ POSTHOG_KEY=phc_... then Developer options, USB debugging) and connect it, or start an emulator. 2. Check that it shows up: `adb devices`. 3. Install or update: `adb install -r app/build/outputs/apk/debug/app-debug.apk` - (or the release-style APK). Debug and release-style builds share the package name and the - signing key, so one replaces the other and keeps the data. + (or the signed release APK). Debug and release builds share the package name but not the + signing key: switching between them needs an uninstall, which deletes the app's data. 4. Without adb: copy the APK to the phone and open it in the file manager; Android asks once to allow installs from that app. @@ -47,16 +65,20 @@ A long press on the antenna picture in "Antenne verbinden" switches a debug buil simulated antenna on a phone as well. Unit tests cover line framing and the 2048-byte limit, the request/response/event codec and -client (timeouts, parse errors without id, unplugging), the simulated antenna end to end -(provision, pair, send, deliver, wrong token), the crypto test vectors from the protocol spec -(fingerprint, node ids, token wrap), message and name limits, backup encryption, geo +client (timeouts, parse errors without id, unplugging, float RSSI), the simulated antenna end to +end (provision, pair, send, deliver, wrong token) and its lab.3 behaviour (random refs, waiting, +`recent`, cancel, authenticated factory reset, OGZ1), the crypto test vectors from the protocol +spec (fingerprint, node ids, token wrap) and vectors for the unlock and reset wrap computed with +Python `cryptography` from the firmware's `Security::unwrap` (`tools/wrap_vectors.py`), the +outbox reconciliation, the antenna session against the simulator (wrong phone, rate limit, +auto-lock, factory reset, backup token), message and name limits, backup encryption, geo formatting and analytics. ## Architecture | Package | Content | |---|---| -| `link` | `Link` interface, `LineFramer`, `LinkCodec`, `LinkClient` (ids, max 4 in flight, timeouts, events) | +| `link` | `Link` interface, `LineFramer`, `LinkCodec`, `LinkClient` (ids, one request in flight, timeouts, events) | | `link/usb` | `UsbSerialLink` on usb-serial-for-android (CP210x, CH34x, ESP32-S3 CDC), permission request | | `link/sim` | `SimulatedHeltec`, an in-process antenna that speaks the same JSON Lines, with virtual peers | | `crypto` | X25519/HKDF/AES-GCM token wrap, fingerprint, Keystore-backed unlock token | @@ -150,7 +172,30 @@ next try. - **Keys stay on the antenna.** The phone holds only an unlock token derived from a Keystore key (`HMAC(K_phone, "og-unlock-v1" || device_id)`), wrapped per session with X25519 + HKDF + - AES-GCM as link spec 6 describes. Every `sec.*` call uses a fresh `sys.hello` session. + AES-GCM as link spec 6 describes (label `og-unlock-wrap-v1`, salt the 16-byte session nonce, + AAD the 6-byte device_id, envelope iv || ciphertext || tag = 60 bytes). Every `sec.*` call uses a + fresh `sys.hello` session; a session that expired or a state that changed in between gets one + more try. `E_UNLOCK_FAILED`, `E_RATE_LIMITED`, `E_NO_SESSION` and `E_INTERNAL` each have their + own text on "Antenne verbinden", other codes are shown with the code, and the reason of an + auto-lock (`sec.state`) is shown until the antenna is open again. +- **"Alle Daten löschen" erases the antenna** with `sys.factory_reset` (`method: "app"`, token + wrapped with the label `og-reset-wrap-v1`, link spec 6.11). The phone's data is only deleted + when the antenna confirmed; afterwards the app sets the empty antenna up again for this phone. + Without an antenna only the phone is cleared and the dialog says that the antenna keeps its + contacts. +- **Reflashed or reset antenna:** a known antenna that reports `unprovisioned` is provisioned + again. The token is derived each time, so nothing stored has to be replaced; a token from a + backup import for that antenna is dropped. Contacts the antenna no longer lists become + "Neu koppeln" (slot detached, history kept) with a banner on the contact list; pairing the same + key again reuses the row. +- **Delivery state survives reconnects.** A `msg_ref` is only valid within one boot of one antenna, + and `msg.status` events are lost while the phone is away. Each accepted message stores the link + session its ref belongs to; events only update messages of the current session. After every + connect (antenna ready, contacts synced) the app compares its open messages with `msg.pending`: + still queued takes over the antenna state, an entry in `recent` (lab.3) applies its final state, + and anything else becomes "Nicht zugestellt" (reason `lost`) with "Erneut senden". The app never + resends on its own. The lab image's `waiting` state shows a clock and "Wartet auf " + instead of a check mark. See `domain/OutboxReconciler.kt`. - **Pairing is mutual QR.** Both phones scan each other (`pair.begin`/`pair.complete`). The contact stays "pending" until the first delivered message; the app sends a small ping after pairing so the firmware can activate it. @@ -172,8 +217,6 @@ next try. "Diese Antennen-Firmware kennt noch keine Gruppen." - **Composer placeholder** uses the contact's display name ("Nachricht an Anna Meier"), as the screens skill says. `Chat.png` shows only the first name, `chat-standort.png` the full name. -- **Firmware reset:** contacts the antenna no longer lists become "pending" (slot detached) - instead of being deleted, so history stays and the user can pair again. ## Firmware status @@ -183,12 +226,13 @@ image (`lab_radio`) and what only a second board can show. It is kept by the age ## Missing for a real antenna -- Firmware: real token authentication, identity and contacts that survive a reboot, real LoRa - delivery in the team image, the reaction fix (`JsonObjectConst`), a boot animation that does - not block `setup()`, and `group.*` if groups stay in scope. -- App: a test on a physical phone with a Heltec (only the emulator was used so far), battery use - of the background receive service, a release signing key, and a decision on the 83-byte - versus 153-character conflict. +- Firmware: `group.*` if groups stay in scope. Real token authentication, persistent contacts and + real delivery come with the team stack `feature/mesh-direct` and the lab image 0.2.0-lab.3; the + app's side of them was checked against the firmware source, independent vectors and the + simulator, not on a board. +- App: a test on a physical phone with a lab.3 board (security, factory reset, reconnect + reconciliation), battery use of the background receive service, and a + decision on the 83-byte versus 153-character conflict. ## Screenshots diff --git a/native-android/STATUS.md b/native-android/STATUS.md index 03fd38d..cab6de0 100644 --- a/native-android/STATUS.md +++ b/native-android/STATUS.md @@ -4,12 +4,22 @@ Snapshot for the 02:00 team sync on 2026-10-24. The branch builds and passes `./gradlew testDebugUnitTest lint assembleDebug assembleRelease` (lint: 0 errors). APKs: - Debug: `app/build/outputs/apk/debug/app-debug.apk` -- Release-style, signed with the SDK debug key: `app/build/outputs/apk/release/app-release.apk` +- Release 0.2.0 (versionCode 3): `app/build/outputs/apk/release/app-release.apk` when the release key is + configured (README, Build), else `app-release-unsigned.apk`; never signed with the debug key. Install with `adb install -r `; details in the [README](README.md). Everything runs against the simulated antenna on the emulator; a real Heltec is the hardware agent's lane on `main`, which is merged in (last merge: `1b19e72`, OGZ1 text codec). +## Lab.3 adaptation (0.1.0-lab3) + +The app follows the lab image 0.2.0-lab.3 and the team stack `feature/mesh-direct`: real token checks +with their own error texts, the authenticated factory reset behind «Alle Daten löschen», reflashed +boards set up again with their contacts marked «Neu koppeln», and the lost-message fix (waiting state +«Wartet auf », reconnect reconciliation with `msg.pending`, «Nicht zugestellt» instead of a +permanent «gesendet»). Database version 2. Checked against the firmware source, independent vectors and +the simulator only; see [`docs/hardware.md`](docs/hardware.md), "App against lab.3". + ## Done - **Shared components** match the HTML designs and animate their state changes: buttons, @@ -64,5 +74,5 @@ which is merged in (last merge: `1b19e72`, OGZ1 text codec). contact list header is not in `Kontakte.png`. 4. **Composer placeholder.** `Chat.png` shows "Nachricht an Anna", `chat-standort.png` "Nachricht an Anna Meier". The app follows the screens skill (display name). -5. **Release key.** The release-style APK is signed with the debug key; a store release needs a - real key. +5. **Release key.** The build signs releases with a key from `OFFGRID_RELEASE_*` Gradle properties or + environment variables; the keystore itself is created and kept outside the repository. diff --git a/native-android/app/build.gradle.kts b/native-android/app/build.gradle.kts index d17d1e6..05fe036 100644 --- a/native-android/app/build.gradle.kts +++ b/native-android/app/build.gradle.kts @@ -1,5 +1,20 @@ import java.util.Properties +/** + * Release signing from Gradle properties (`-POFFGRID_RELEASE_STORE_FILE=…`, or `~/.gradle/gradle.properties`) or + * environment variables of the same names. No key lives in this repository. Without any of them the release APK + * is built unsigned (`app-release-unsigned.apk`); it is never signed with the debug key. + */ +val releaseSigningNames = listOf( + "OFFGRID_RELEASE_STORE_FILE", "OFFGRID_RELEASE_STORE_PASSWORD", "OFFGRID_RELEASE_KEY_ALIAS", "OFFGRID_RELEASE_KEY_PASSWORD", +) +val releaseSigning: Map = releaseSigningNames.mapNotNull { name -> + (providers.gradleProperty(name).orNull ?: providers.environmentVariable(name).orNull)?.takeIf { it.isNotBlank() }?.let { name to it } +}.toMap() +if (releaseSigning.isNotEmpty() && releaseSigning.size < releaseSigningNames.size) { + throw GradleException("Release signing is incomplete, missing: ${(releaseSigningNames - releaseSigning.keys).joinToString()}") +} + plugins { alias(libs.plugins.android.application) alias(libs.plugins.kotlin.android) @@ -16,8 +31,9 @@ android { applicationId = "ch.offgrid.android" minSdk = 26 targetSdk = 35 - versionCode = 1 - versionName = "0.1.0" + // 3: database version 3 (delivery details), Nils' 0.3.0 contract and the lab.3 settings. + versionCode = 3 + versionName = "0.2.0" // PostHog project key from the untracked local.properties (`POSTHOG_KEY=phc_...`). Empty means // analytics is a no-op, which is the default for every checkout. @@ -35,12 +51,26 @@ android { buildConfigField("String", "TEXT_CODEC", "\"$textCodec\"") } + signingConfigs { + if (releaseSigning.isNotEmpty()) { + create("release") { + val store = file(releaseSigning.getValue("OFFGRID_RELEASE_STORE_FILE")) + if (!store.isFile) throw GradleException("OFFGRID_RELEASE_STORE_FILE does not exist: $store") + storeFile = store + storePassword = releaseSigning.getValue("OFFGRID_RELEASE_STORE_PASSWORD") + keyAlias = releaseSigning.getValue("OFFGRID_RELEASE_KEY_ALIAS") + keyPassword = releaseSigning.getValue("OFFGRID_RELEASE_KEY_PASSWORD") + } + } + } + buildTypes { release { + // Debug-only bridges: no TCP link to a dev machine and no forced TEXT codec in a release. buildConfigField("String", "TCP_LINK", "\"\"") - // Release-style APK for demos, signed with the SDK debug key so it installs without a - // keystore. A real release key is an open decision; no key was created. - signingConfig = signingConfigs.getByName("debug") + buildConfigField("String", "TEXT_CODEC", "\"\"") + // Unsigned when the release key is not configured (see releaseSigning above), never the debug key. + signingConfig = if (releaseSigning.isNotEmpty()) signingConfigs.getByName("release") else null isMinifyEnabled = false proguardFiles(getDefaultProguardFile("proguard-android-optimize.txt"), "proguard-rules.pro") } @@ -98,5 +128,7 @@ dependencies { debugImplementation(libs.androidx.compose.ui.tooling) testImplementation(libs.junit) + // Runs the Room migration SQL on a plain SQLite database; Room's MigrationTestHelper needs a device. + testImplementation(libs.sqlite.jdbc) testImplementation(libs.kotlinx.coroutines.test) } diff --git a/native-android/app/schemas/ch.offgrid.android.data.OffGridDatabase/2.json b/native-android/app/schemas/ch.offgrid.android.data.OffGridDatabase/2.json new file mode 100644 index 0000000..8213111 --- /dev/null +++ b/native-android/app/schemas/ch.offgrid.android.data.OffGridDatabase/2.json @@ -0,0 +1,387 @@ +{ + "formatVersion": 1, + "database": { + "version": 2, + "identityHash": "8c689f2eaf21359b191114f8724946a2", + "entities": [ + { + "tableName": "contacts", + "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, `deviceId` TEXT NOT NULL, `deviceContactId` INTEGER NOT NULL, `displayName` TEXT NOT NULL, `firstName` TEXT, `lastName` TEXT, `nodeId` TEXT NOT NULL, `publicKey` TEXT NOT NULL, `fingerprint` TEXT NOT NULL, `state` TEXT NOT NULL, `lastRssi` INTEGER, `lastSnr` REAL, `lastSeenAt` INTEGER, `createdAt` INTEGER NOT NULL)", + "fields": [ + { + "fieldPath": "id", + "columnName": "id", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "deviceId", + "columnName": "deviceId", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "deviceContactId", + "columnName": "deviceContactId", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "displayName", + "columnName": "displayName", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "firstName", + "columnName": "firstName", + "affinity": "TEXT", + "notNull": false + }, + { + "fieldPath": "lastName", + "columnName": "lastName", + "affinity": "TEXT", + "notNull": false + }, + { + "fieldPath": "nodeId", + "columnName": "nodeId", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "publicKey", + "columnName": "publicKey", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "fingerprint", + "columnName": "fingerprint", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "state", + "columnName": "state", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "lastRssi", + "columnName": "lastRssi", + "affinity": "INTEGER", + "notNull": false + }, + { + "fieldPath": "lastSnr", + "columnName": "lastSnr", + "affinity": "REAL", + "notNull": false + }, + { + "fieldPath": "lastSeenAt", + "columnName": "lastSeenAt", + "affinity": "INTEGER", + "notNull": false + }, + { + "fieldPath": "createdAt", + "columnName": "createdAt", + "affinity": "INTEGER", + "notNull": true + } + ], + "primaryKey": { + "autoGenerate": true, + "columnNames": [ + "id" + ] + }, + "indices": [ + { + "name": "index_contacts_publicKey", + "unique": true, + "columnNames": [ + "publicKey" + ], + "orders": [], + "createSql": "CREATE UNIQUE INDEX IF NOT EXISTS `index_contacts_publicKey` ON `${TABLE_NAME}` (`publicKey`)" + } + ], + "foreignKeys": [] + }, + { + "tableName": "messages", + "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, `contactId` INTEGER, `groupId` INTEGER, `direction` TEXT NOT NULL, `kind` TEXT NOT NULL, `text` TEXT NOT NULL, `lat` REAL, `lon` REAL, `accuracyM` INTEGER, `ageS` INTEGER, `status` INTEGER NOT NULL, `failReason` TEXT, `msgRef` INTEGER, `refSession` TEXT, `ctr` INTEGER, `senderContactId` INTEGER, `senderName` TEXT, `rssi` INTEGER, `peerReaction` TEXT, `sentAt` INTEGER NOT NULL, `readAt` INTEGER)", + "fields": [ + { + "fieldPath": "id", + "columnName": "id", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "contactId", + "columnName": "contactId", + "affinity": "INTEGER", + "notNull": false + }, + { + "fieldPath": "groupId", + "columnName": "groupId", + "affinity": "INTEGER", + "notNull": false + }, + { + "fieldPath": "direction", + "columnName": "direction", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "kind", + "columnName": "kind", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "text", + "columnName": "text", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "lat", + "columnName": "lat", + "affinity": "REAL", + "notNull": false + }, + { + "fieldPath": "lon", + "columnName": "lon", + "affinity": "REAL", + "notNull": false + }, + { + "fieldPath": "accuracyM", + "columnName": "accuracyM", + "affinity": "INTEGER", + "notNull": false + }, + { + "fieldPath": "ageS", + "columnName": "ageS", + "affinity": "INTEGER", + "notNull": false + }, + { + "fieldPath": "status", + "columnName": "status", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "failReason", + "columnName": "failReason", + "affinity": "TEXT", + "notNull": false + }, + { + "fieldPath": "msgRef", + "columnName": "msgRef", + "affinity": "INTEGER", + "notNull": false + }, + { + "fieldPath": "refSession", + "columnName": "refSession", + "affinity": "TEXT", + "notNull": false + }, + { + "fieldPath": "ctr", + "columnName": "ctr", + "affinity": "INTEGER", + "notNull": false + }, + { + "fieldPath": "senderContactId", + "columnName": "senderContactId", + "affinity": "INTEGER", + "notNull": false + }, + { + "fieldPath": "senderName", + "columnName": "senderName", + "affinity": "TEXT", + "notNull": false + }, + { + "fieldPath": "rssi", + "columnName": "rssi", + "affinity": "INTEGER", + "notNull": false + }, + { + "fieldPath": "peerReaction", + "columnName": "peerReaction", + "affinity": "TEXT", + "notNull": false + }, + { + "fieldPath": "sentAt", + "columnName": "sentAt", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "readAt", + "columnName": "readAt", + "affinity": "INTEGER", + "notNull": false + } + ], + "primaryKey": { + "autoGenerate": true, + "columnNames": [ + "id" + ] + }, + "indices": [ + { + "name": "index_messages_contactId", + "unique": false, + "columnNames": [ + "contactId" + ], + "orders": [], + "createSql": "CREATE INDEX IF NOT EXISTS `index_messages_contactId` ON `${TABLE_NAME}` (`contactId`)" + }, + { + "name": "index_messages_groupId", + "unique": false, + "columnNames": [ + "groupId" + ], + "orders": [], + "createSql": "CREATE INDEX IF NOT EXISTS `index_messages_groupId` ON `${TABLE_NAME}` (`groupId`)" + }, + { + "name": "index_messages_msgRef", + "unique": false, + "columnNames": [ + "msgRef" + ], + "orders": [], + "createSql": "CREATE INDEX IF NOT EXISTS `index_messages_msgRef` ON `${TABLE_NAME}` (`msgRef`)" + } + ], + "foreignKeys": [] + }, + { + "tableName": "groups", + "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, `deviceId` TEXT NOT NULL, `deviceGroupId` INTEGER NOT NULL, `name` TEXT NOT NULL, `createdAt` INTEGER NOT NULL)", + "fields": [ + { + "fieldPath": "id", + "columnName": "id", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "deviceId", + "columnName": "deviceId", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "deviceGroupId", + "columnName": "deviceGroupId", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "name", + "columnName": "name", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "createdAt", + "columnName": "createdAt", + "affinity": "INTEGER", + "notNull": true + } + ], + "primaryKey": { + "autoGenerate": true, + "columnNames": [ + "id" + ] + }, + "indices": [], + "foreignKeys": [] + }, + { + "tableName": "group_members", + "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`groupId` INTEGER NOT NULL, `contactId` INTEGER NOT NULL, PRIMARY KEY(`groupId`, `contactId`))", + "fields": [ + { + "fieldPath": "groupId", + "columnName": "groupId", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "contactId", + "columnName": "contactId", + "affinity": "INTEGER", + "notNull": true + } + ], + "primaryKey": { + "autoGenerate": false, + "columnNames": [ + "groupId", + "contactId" + ] + }, + "indices": [], + "foreignKeys": [] + }, + { + "tableName": "settings", + "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`key` TEXT NOT NULL, `value` TEXT NOT NULL, PRIMARY KEY(`key`))", + "fields": [ + { + "fieldPath": "key", + "columnName": "key", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "value", + "columnName": "value", + "affinity": "TEXT", + "notNull": true + } + ], + "primaryKey": { + "autoGenerate": false, + "columnNames": [ + "key" + ] + }, + "indices": [], + "foreignKeys": [] + } + ], + "views": [], + "setupQueries": [ + "CREATE TABLE IF NOT EXISTS room_master_table (id INTEGER PRIMARY KEY,identity_hash TEXT)", + "INSERT OR REPLACE INTO room_master_table (id,identity_hash) VALUES(42, '8c689f2eaf21359b191114f8724946a2')" + ] + } +} \ No newline at end of file diff --git a/native-android/app/schemas/ch.offgrid.android.data.OffGridDatabase/3.json b/native-android/app/schemas/ch.offgrid.android.data.OffGridDatabase/3.json new file mode 100644 index 0000000..f34c401 --- /dev/null +++ b/native-android/app/schemas/ch.offgrid.android.data.OffGridDatabase/3.json @@ -0,0 +1,442 @@ +{ + "formatVersion": 1, + "database": { + "version": 3, + "identityHash": "00ec6e90ac9e32447a07523760fd98e5", + "entities": [ + { + "tableName": "contacts", + "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, `deviceId` TEXT NOT NULL, `deviceContactId` INTEGER NOT NULL, `displayName` TEXT NOT NULL, `firstName` TEXT, `lastName` TEXT, `nodeId` TEXT NOT NULL, `publicKey` TEXT NOT NULL, `fingerprint` TEXT NOT NULL, `state` TEXT NOT NULL, `lastRssi` INTEGER, `lastSnr` REAL, `lastSeenAt` INTEGER, `createdAt` INTEGER NOT NULL)", + "fields": [ + { + "fieldPath": "id", + "columnName": "id", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "deviceId", + "columnName": "deviceId", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "deviceContactId", + "columnName": "deviceContactId", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "displayName", + "columnName": "displayName", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "firstName", + "columnName": "firstName", + "affinity": "TEXT", + "notNull": false + }, + { + "fieldPath": "lastName", + "columnName": "lastName", + "affinity": "TEXT", + "notNull": false + }, + { + "fieldPath": "nodeId", + "columnName": "nodeId", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "publicKey", + "columnName": "publicKey", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "fingerprint", + "columnName": "fingerprint", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "state", + "columnName": "state", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "lastRssi", + "columnName": "lastRssi", + "affinity": "INTEGER", + "notNull": false + }, + { + "fieldPath": "lastSnr", + "columnName": "lastSnr", + "affinity": "REAL", + "notNull": false + }, + { + "fieldPath": "lastSeenAt", + "columnName": "lastSeenAt", + "affinity": "INTEGER", + "notNull": false + }, + { + "fieldPath": "createdAt", + "columnName": "createdAt", + "affinity": "INTEGER", + "notNull": true + } + ], + "primaryKey": { + "autoGenerate": true, + "columnNames": [ + "id" + ] + }, + "indices": [ + { + "name": "index_contacts_publicKey", + "unique": true, + "columnNames": [ + "publicKey" + ], + "orders": [], + "createSql": "CREATE UNIQUE INDEX IF NOT EXISTS `index_contacts_publicKey` ON `${TABLE_NAME}` (`publicKey`)" + } + ], + "foreignKeys": [] + }, + { + "tableName": "messages", + "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, `contactId` INTEGER, `groupId` INTEGER, `direction` TEXT NOT NULL, `kind` TEXT NOT NULL, `text` TEXT NOT NULL, `lat` REAL, `lon` REAL, `accuracyM` INTEGER, `ageS` INTEGER, `status` INTEGER NOT NULL, `failReason` TEXT, `msgRef` INTEGER, `refSession` TEXT, `ctr` INTEGER, `senderContactId` INTEGER, `senderName` TEXT, `rssi` INTEGER, `snr` REAL, `hops` INTEGER, `retry` INTEGER, `rttMs` INTEGER, `compressed` INTEGER, `bytesOnAir` INTEGER, `airtimeMs` INTEGER, `deviceState` TEXT, `deliveredOffline` INTEGER NOT NULL DEFAULT 0, `peerReaction` TEXT, `sentAt` INTEGER NOT NULL, `readAt` INTEGER)", + "fields": [ + { + "fieldPath": "id", + "columnName": "id", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "contactId", + "columnName": "contactId", + "affinity": "INTEGER", + "notNull": false + }, + { + "fieldPath": "groupId", + "columnName": "groupId", + "affinity": "INTEGER", + "notNull": false + }, + { + "fieldPath": "direction", + "columnName": "direction", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "kind", + "columnName": "kind", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "text", + "columnName": "text", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "lat", + "columnName": "lat", + "affinity": "REAL", + "notNull": false + }, + { + "fieldPath": "lon", + "columnName": "lon", + "affinity": "REAL", + "notNull": false + }, + { + "fieldPath": "accuracyM", + "columnName": "accuracyM", + "affinity": "INTEGER", + "notNull": false + }, + { + "fieldPath": "ageS", + "columnName": "ageS", + "affinity": "INTEGER", + "notNull": false + }, + { + "fieldPath": "status", + "columnName": "status", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "failReason", + "columnName": "failReason", + "affinity": "TEXT", + "notNull": false + }, + { + "fieldPath": "msgRef", + "columnName": "msgRef", + "affinity": "INTEGER", + "notNull": false + }, + { + "fieldPath": "refSession", + "columnName": "refSession", + "affinity": "TEXT", + "notNull": false + }, + { + "fieldPath": "ctr", + "columnName": "ctr", + "affinity": "INTEGER", + "notNull": false + }, + { + "fieldPath": "senderContactId", + "columnName": "senderContactId", + "affinity": "INTEGER", + "notNull": false + }, + { + "fieldPath": "senderName", + "columnName": "senderName", + "affinity": "TEXT", + "notNull": false + }, + { + "fieldPath": "rssi", + "columnName": "rssi", + "affinity": "INTEGER", + "notNull": false + }, + { + "fieldPath": "snr", + "columnName": "snr", + "affinity": "REAL", + "notNull": false + }, + { + "fieldPath": "hops", + "columnName": "hops", + "affinity": "INTEGER", + "notNull": false + }, + { + "fieldPath": "retry", + "columnName": "retry", + "affinity": "INTEGER", + "notNull": false + }, + { + "fieldPath": "rttMs", + "columnName": "rttMs", + "affinity": "INTEGER", + "notNull": false + }, + { + "fieldPath": "compressed", + "columnName": "compressed", + "affinity": "INTEGER", + "notNull": false + }, + { + "fieldPath": "bytesOnAir", + "columnName": "bytesOnAir", + "affinity": "INTEGER", + "notNull": false + }, + { + "fieldPath": "airtimeMs", + "columnName": "airtimeMs", + "affinity": "INTEGER", + "notNull": false + }, + { + "fieldPath": "deviceState", + "columnName": "deviceState", + "affinity": "TEXT", + "notNull": false + }, + { + "fieldPath": "deliveredOffline", + "columnName": "deliveredOffline", + "affinity": "INTEGER", + "notNull": true, + "defaultValue": "0" + }, + { + "fieldPath": "peerReaction", + "columnName": "peerReaction", + "affinity": "TEXT", + "notNull": false + }, + { + "fieldPath": "sentAt", + "columnName": "sentAt", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "readAt", + "columnName": "readAt", + "affinity": "INTEGER", + "notNull": false + } + ], + "primaryKey": { + "autoGenerate": true, + "columnNames": [ + "id" + ] + }, + "indices": [ + { + "name": "index_messages_contactId", + "unique": false, + "columnNames": [ + "contactId" + ], + "orders": [], + "createSql": "CREATE INDEX IF NOT EXISTS `index_messages_contactId` ON `${TABLE_NAME}` (`contactId`)" + }, + { + "name": "index_messages_groupId", + "unique": false, + "columnNames": [ + "groupId" + ], + "orders": [], + "createSql": "CREATE INDEX IF NOT EXISTS `index_messages_groupId` ON `${TABLE_NAME}` (`groupId`)" + }, + { + "name": "index_messages_msgRef", + "unique": false, + "columnNames": [ + "msgRef" + ], + "orders": [], + "createSql": "CREATE INDEX IF NOT EXISTS `index_messages_msgRef` ON `${TABLE_NAME}` (`msgRef`)" + } + ], + "foreignKeys": [] + }, + { + "tableName": "groups", + "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, `deviceId` TEXT NOT NULL, `deviceGroupId` INTEGER NOT NULL, `name` TEXT NOT NULL, `createdAt` INTEGER NOT NULL)", + "fields": [ + { + "fieldPath": "id", + "columnName": "id", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "deviceId", + "columnName": "deviceId", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "deviceGroupId", + "columnName": "deviceGroupId", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "name", + "columnName": "name", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "createdAt", + "columnName": "createdAt", + "affinity": "INTEGER", + "notNull": true + } + ], + "primaryKey": { + "autoGenerate": true, + "columnNames": [ + "id" + ] + }, + "indices": [], + "foreignKeys": [] + }, + { + "tableName": "group_members", + "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`groupId` INTEGER NOT NULL, `contactId` INTEGER NOT NULL, PRIMARY KEY(`groupId`, `contactId`))", + "fields": [ + { + "fieldPath": "groupId", + "columnName": "groupId", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "contactId", + "columnName": "contactId", + "affinity": "INTEGER", + "notNull": true + } + ], + "primaryKey": { + "autoGenerate": false, + "columnNames": [ + "groupId", + "contactId" + ] + }, + "indices": [], + "foreignKeys": [] + }, + { + "tableName": "settings", + "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`key` TEXT NOT NULL, `value` TEXT NOT NULL, PRIMARY KEY(`key`))", + "fields": [ + { + "fieldPath": "key", + "columnName": "key", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "value", + "columnName": "value", + "affinity": "TEXT", + "notNull": true + } + ], + "primaryKey": { + "autoGenerate": false, + "columnNames": [ + "key" + ] + }, + "indices": [], + "foreignKeys": [] + } + ], + "views": [], + "setupQueries": [ + "CREATE TABLE IF NOT EXISTS room_master_table (id INTEGER PRIMARY KEY,identity_hash TEXT)", + "INSERT OR REPLACE INTO room_master_table (id,identity_hash) VALUES(42, '00ec6e90ac9e32447a07523760fd98e5')" + ] + } +} \ No newline at end of file diff --git a/native-android/app/schemas/ch.offgrid.android.data.OffGridDatabase/4.json b/native-android/app/schemas/ch.offgrid.android.data.OffGridDatabase/4.json new file mode 100644 index 0000000..1f253af --- /dev/null +++ b/native-android/app/schemas/ch.offgrid.android.data.OffGridDatabase/4.json @@ -0,0 +1,506 @@ +{ + "formatVersion": 1, + "database": { + "version": 4, + "identityHash": "a50e3c28fda5fff39bf71e81eb5e079a", + "entities": [ + { + "tableName": "contacts", + "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, `deviceId` TEXT NOT NULL, `deviceContactId` INTEGER NOT NULL, `displayName` TEXT NOT NULL, `firstName` TEXT, `lastName` TEXT, `nodeId` TEXT NOT NULL, `publicKey` TEXT NOT NULL, `fingerprint` TEXT NOT NULL, `state` TEXT NOT NULL, `lastRssi` INTEGER, `lastSnr` REAL, `lastSeenAt` INTEGER, `createdAt` INTEGER NOT NULL)", + "fields": [ + { + "fieldPath": "id", + "columnName": "id", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "deviceId", + "columnName": "deviceId", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "deviceContactId", + "columnName": "deviceContactId", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "displayName", + "columnName": "displayName", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "firstName", + "columnName": "firstName", + "affinity": "TEXT", + "notNull": false + }, + { + "fieldPath": "lastName", + "columnName": "lastName", + "affinity": "TEXT", + "notNull": false + }, + { + "fieldPath": "nodeId", + "columnName": "nodeId", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "publicKey", + "columnName": "publicKey", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "fingerprint", + "columnName": "fingerprint", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "state", + "columnName": "state", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "lastRssi", + "columnName": "lastRssi", + "affinity": "INTEGER", + "notNull": false + }, + { + "fieldPath": "lastSnr", + "columnName": "lastSnr", + "affinity": "REAL", + "notNull": false + }, + { + "fieldPath": "lastSeenAt", + "columnName": "lastSeenAt", + "affinity": "INTEGER", + "notNull": false + }, + { + "fieldPath": "createdAt", + "columnName": "createdAt", + "affinity": "INTEGER", + "notNull": true + } + ], + "primaryKey": { + "autoGenerate": true, + "columnNames": [ + "id" + ] + }, + "indices": [ + { + "name": "index_contacts_publicKey", + "unique": true, + "columnNames": [ + "publicKey" + ], + "orders": [], + "createSql": "CREATE UNIQUE INDEX IF NOT EXISTS `index_contacts_publicKey` ON `${TABLE_NAME}` (`publicKey`)" + } + ], + "foreignKeys": [] + }, + { + "tableName": "messages", + "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, `contactId` INTEGER, `groupId` INTEGER, `direction` TEXT NOT NULL, `kind` TEXT NOT NULL, `text` TEXT NOT NULL, `lat` REAL, `lon` REAL, `accuracyM` INTEGER, `ageS` INTEGER, `status` INTEGER NOT NULL, `failReason` TEXT, `msgRef` INTEGER, `refSession` TEXT, `ctr` INTEGER, `senderContactId` INTEGER, `senderName` TEXT, `senderNodeId` TEXT, `rssi` INTEGER, `snr` REAL, `hops` INTEGER, `retry` INTEGER, `rttMs` INTEGER, `compressed` INTEGER, `bytesOnAir` INTEGER, `airtimeMs` INTEGER, `deviceState` TEXT, `deliveredOffline` INTEGER NOT NULL DEFAULT 0, `peerReaction` TEXT, `sentAt` INTEGER NOT NULL, `readAt` INTEGER)", + "fields": [ + { + "fieldPath": "id", + "columnName": "id", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "contactId", + "columnName": "contactId", + "affinity": "INTEGER", + "notNull": false + }, + { + "fieldPath": "groupId", + "columnName": "groupId", + "affinity": "INTEGER", + "notNull": false + }, + { + "fieldPath": "direction", + "columnName": "direction", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "kind", + "columnName": "kind", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "text", + "columnName": "text", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "lat", + "columnName": "lat", + "affinity": "REAL", + "notNull": false + }, + { + "fieldPath": "lon", + "columnName": "lon", + "affinity": "REAL", + "notNull": false + }, + { + "fieldPath": "accuracyM", + "columnName": "accuracyM", + "affinity": "INTEGER", + "notNull": false + }, + { + "fieldPath": "ageS", + "columnName": "ageS", + "affinity": "INTEGER", + "notNull": false + }, + { + "fieldPath": "status", + "columnName": "status", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "failReason", + "columnName": "failReason", + "affinity": "TEXT", + "notNull": false + }, + { + "fieldPath": "msgRef", + "columnName": "msgRef", + "affinity": "INTEGER", + "notNull": false + }, + { + "fieldPath": "refSession", + "columnName": "refSession", + "affinity": "TEXT", + "notNull": false + }, + { + "fieldPath": "ctr", + "columnName": "ctr", + "affinity": "INTEGER", + "notNull": false + }, + { + "fieldPath": "senderContactId", + "columnName": "senderContactId", + "affinity": "INTEGER", + "notNull": false + }, + { + "fieldPath": "senderName", + "columnName": "senderName", + "affinity": "TEXT", + "notNull": false + }, + { + "fieldPath": "senderNodeId", + "columnName": "senderNodeId", + "affinity": "TEXT", + "notNull": false + }, + { + "fieldPath": "rssi", + "columnName": "rssi", + "affinity": "INTEGER", + "notNull": false + }, + { + "fieldPath": "snr", + "columnName": "snr", + "affinity": "REAL", + "notNull": false + }, + { + "fieldPath": "hops", + "columnName": "hops", + "affinity": "INTEGER", + "notNull": false + }, + { + "fieldPath": "retry", + "columnName": "retry", + "affinity": "INTEGER", + "notNull": false + }, + { + "fieldPath": "rttMs", + "columnName": "rttMs", + "affinity": "INTEGER", + "notNull": false + }, + { + "fieldPath": "compressed", + "columnName": "compressed", + "affinity": "INTEGER", + "notNull": false + }, + { + "fieldPath": "bytesOnAir", + "columnName": "bytesOnAir", + "affinity": "INTEGER", + "notNull": false + }, + { + "fieldPath": "airtimeMs", + "columnName": "airtimeMs", + "affinity": "INTEGER", + "notNull": false + }, + { + "fieldPath": "deviceState", + "columnName": "deviceState", + "affinity": "TEXT", + "notNull": false + }, + { + "fieldPath": "deliveredOffline", + "columnName": "deliveredOffline", + "affinity": "INTEGER", + "notNull": true, + "defaultValue": "0" + }, + { + "fieldPath": "peerReaction", + "columnName": "peerReaction", + "affinity": "TEXT", + "notNull": false + }, + { + "fieldPath": "sentAt", + "columnName": "sentAt", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "readAt", + "columnName": "readAt", + "affinity": "INTEGER", + "notNull": false + } + ], + "primaryKey": { + "autoGenerate": true, + "columnNames": [ + "id" + ] + }, + "indices": [ + { + "name": "index_messages_contactId", + "unique": false, + "columnNames": [ + "contactId" + ], + "orders": [], + "createSql": "CREATE INDEX IF NOT EXISTS `index_messages_contactId` ON `${TABLE_NAME}` (`contactId`)" + }, + { + "name": "index_messages_groupId", + "unique": false, + "columnNames": [ + "groupId" + ], + "orders": [], + "createSql": "CREATE INDEX IF NOT EXISTS `index_messages_groupId` ON `${TABLE_NAME}` (`groupId`)" + }, + { + "name": "index_messages_msgRef", + "unique": false, + "columnNames": [ + "msgRef" + ], + "orders": [], + "createSql": "CREATE INDEX IF NOT EXISTS `index_messages_msgRef` ON `${TABLE_NAME}` (`msgRef`)" + } + ], + "foreignKeys": [] + }, + { + "tableName": "groups", + "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, `deviceId` TEXT NOT NULL, `deviceGroupId` INTEGER NOT NULL, `name` TEXT NOT NULL, `createdAt` INTEGER NOT NULL, `gid` TEXT NOT NULL DEFAULT '', `epoch` INTEGER NOT NULL DEFAULT 1, `owner` INTEGER NOT NULL DEFAULT 1)", + "fields": [ + { + "fieldPath": "id", + "columnName": "id", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "deviceId", + "columnName": "deviceId", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "deviceGroupId", + "columnName": "deviceGroupId", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "name", + "columnName": "name", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "createdAt", + "columnName": "createdAt", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "gid", + "columnName": "gid", + "affinity": "TEXT", + "notNull": true, + "defaultValue": "''" + }, + { + "fieldPath": "epoch", + "columnName": "epoch", + "affinity": "INTEGER", + "notNull": true, + "defaultValue": "1" + }, + { + "fieldPath": "owner", + "columnName": "owner", + "affinity": "INTEGER", + "notNull": true, + "defaultValue": "1" + } + ], + "primaryKey": { + "autoGenerate": true, + "columnNames": [ + "id" + ] + }, + "indices": [], + "foreignKeys": [] + }, + { + "tableName": "group_members", + "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`groupId` INTEGER NOT NULL, `member` INTEGER NOT NULL, `contactId` INTEGER, `nodeId` TEXT NOT NULL, `keyState` TEXT NOT NULL DEFAULT 'none', `syncRef` INTEGER, `syncSession` TEXT, `syncReason` TEXT, PRIMARY KEY(`groupId`, `member`))", + "fields": [ + { + "fieldPath": "groupId", + "columnName": "groupId", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "member", + "columnName": "member", + "affinity": "INTEGER", + "notNull": true + }, + { + "fieldPath": "contactId", + "columnName": "contactId", + "affinity": "INTEGER", + "notNull": false + }, + { + "fieldPath": "nodeId", + "columnName": "nodeId", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "keyState", + "columnName": "keyState", + "affinity": "TEXT", + "notNull": true, + "defaultValue": "'none'" + }, + { + "fieldPath": "syncRef", + "columnName": "syncRef", + "affinity": "INTEGER", + "notNull": false + }, + { + "fieldPath": "syncSession", + "columnName": "syncSession", + "affinity": "TEXT", + "notNull": false + }, + { + "fieldPath": "syncReason", + "columnName": "syncReason", + "affinity": "TEXT", + "notNull": false + } + ], + "primaryKey": { + "autoGenerate": false, + "columnNames": [ + "groupId", + "member" + ] + }, + "indices": [], + "foreignKeys": [] + }, + { + "tableName": "settings", + "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`key` TEXT NOT NULL, `value` TEXT NOT NULL, PRIMARY KEY(`key`))", + "fields": [ + { + "fieldPath": "key", + "columnName": "key", + "affinity": "TEXT", + "notNull": true + }, + { + "fieldPath": "value", + "columnName": "value", + "affinity": "TEXT", + "notNull": true + } + ], + "primaryKey": { + "autoGenerate": false, + "columnNames": [ + "key" + ] + }, + "indices": [], + "foreignKeys": [] + } + ], + "views": [], + "setupQueries": [ + "CREATE TABLE IF NOT EXISTS room_master_table (id INTEGER PRIMARY KEY,identity_hash TEXT)", + "INSERT OR REPLACE INTO room_master_table (id,identity_hash) VALUES(42, 'a50e3c28fda5fff39bf71e81eb5e079a')" + ] + } +} \ No newline at end of file diff --git a/native-android/app/src/main/java/ch/offgrid/android/AppContainer.kt b/native-android/app/src/main/java/ch/offgrid/android/AppContainer.kt index 8a8edae..cad5382 100644 --- a/native-android/app/src/main/java/ch/offgrid/android/AppContainer.kt +++ b/native-android/app/src/main/java/ch/offgrid/android/AppContainer.kt @@ -8,6 +8,9 @@ import android.util.Log import androidx.room.Room import ch.offgrid.android.analytics.Analytics import ch.offgrid.android.crypto.KeystoreUnlockTokenSource +import ch.offgrid.android.data.MIGRATION_1_2 +import ch.offgrid.android.data.MIGRATION_2_3 +import ch.offgrid.android.data.MIGRATION_3_4 import ch.offgrid.android.data.OffGridDatabase import ch.offgrid.android.domain.AntennaManager import ch.offgrid.android.domain.BackupService @@ -29,15 +32,19 @@ import kotlinx.coroutines.flow.MutableStateFlow import kotlinx.coroutines.flow.StateFlow import kotlinx.coroutines.flow.asStateFlow import kotlinx.coroutines.flow.combine +import kotlinx.coroutines.flow.map import kotlinx.coroutines.launch import kotlinx.coroutines.runBlocking +import kotlinx.serialization.json.JsonObject import java.io.File import java.util.UUID /** Manual dependency container; one per process. */ class AppContainer(private val context: Context) { val scope = CoroutineScope(SupervisorJob() + Dispatchers.Default) - val db: OffGridDatabase = Room.databaseBuilder(context, OffGridDatabase::class.java, "offgrid.db").build() + val db: OffGridDatabase = Room.databaseBuilder(context, OffGridDatabase::class.java, "offgrid.db") + .addMigrations(MIGRATION_1_2, MIGRATION_2_3, MIGRATION_3_4) + .build() val settings = Settings(db.settings(), scope) val simDevice = SimulatedHeltec(SimFlashStore(File(context.filesDir, "sim-heltec.json")), scope) @@ -66,11 +73,14 @@ class AppContainer(private val context: Context) { ?: UUID.randomUUID().toString().also { analyticsPrefs.edit().putString(ANALYTICS_ID, it).apply() } }) val notifier = MessageNotifier(context, db) - val messaging = Messaging(db, antenna, scope, onIncoming = { message -> + val messaging = Messaging(db, antenna, scope, settings, onIncoming = { message -> vibrate() scope.launch { notifier.onIncoming(message) } }, track = analytics::track) - val pairing = Pairing(antenna, messaging, db, scope, track = analytics::track) + val pairing = Pairing(antenna, object : Pairing.Store { + override suspend fun save(deviceId: String, contact: JsonObject) = messaging.upsertFromDevice(deviceId, contact, keepName = false) + override fun contactState(contactId: Long) = db.contacts().observe(contactId).map { it?.state } + }, scope, track = analytics::track) val location = LocationService(context) { _linkKind.value == LinkKind.SIMULATED } val backup = BackupService(db, settings, antenna) diff --git a/native-android/app/src/main/java/ch/offgrid/android/crypto/UnlockToken.kt b/native-android/app/src/main/java/ch/offgrid/android/crypto/UnlockToken.kt index 0f1884b..a2aa3ef 100644 --- a/native-android/app/src/main/java/ch/offgrid/android/crypto/UnlockToken.kt +++ b/native-android/app/src/main/java/ch/offgrid/android/crypto/UnlockToken.kt @@ -41,19 +41,34 @@ class FixedKeyUnlockTokenSource(private val kPhone: ByteArray) : UnlockTokenSour override fun token(deviceId: ByteArray): ByteArray = OgCrypto.hmacSha256(kPhone, TOKEN_LABEL, deviceId) } -/** The wrapped token envelope sent with `sec.provision`, `sec.unlock` and `sec.rotate_token`. */ +/** The wrapped token envelope sent with `sec.provision`, `sec.unlock`, `sec.rotate_token` and `sys.factory_reset`. */ data class WrappedToken(val appEphPub: ByteArray, val wrapped: ByteArray) /** - * Link spec 6.5: + * What a wrapped token authorizes. The HKDF label differs, so an envelope made for one purpose never + * verifies for the other (link spec 6.11: "a normal unlock envelope cannot authorize reset"). + */ +enum class WrapPurpose(label: String) { + /** `sec.provision`, `sec.unlock`, `sec.rotate_token`. */ + UNLOCK("og-unlock-wrap-v1"), + + /** `sys.factory_reset` with `method: "app"`. */ + RESET("og-reset-wrap-v1"), + ; + + val label: ByteArray = label.toByteArray(Charsets.US_ASCII) +} + +/** + * Link spec 6.5 and 6.11, byte for byte as `Security::unwrap` on the firmware reads it: * ``` * shared = X25519(app_eph_private, device_eph_public) - * wrap_key = HKDF-SHA256(ikm = shared, salt = nonce, info = "og-unlock-wrap-v1" || device_id_bytes, L = 32) - * wrapped = iv (12 B) || AES-256-GCM(wrap_key, iv, token, aad = device_id_bytes) = 60 bytes + * wrap_key = HKDF-SHA256(ikm = shared, salt = nonce (16 B), info = label || device_id_bytes (6 B), L = 32) + * wrapped = iv (12 B) || AES-256-GCM(wrap_key, iv, token (32 B), aad = device_id_bytes) = 60 bytes * ``` + * `label` is `og-unlock-wrap-v1` or `og-reset-wrap-v1` ([WrapPurpose]). */ object TokenWrap { - private val WRAP_LABEL = "og-unlock-wrap-v1".toByteArray(Charsets.US_ASCII) const val WRAPPED_SIZE = 60 fun wrap( @@ -61,23 +76,34 @@ object TokenWrap { deviceId: ByteArray, deviceEphPub: ByteArray, nonce: ByteArray, + purpose: WrapPurpose = WrapPurpose.UNLOCK, appEphPrivate: ByteArray = OgCrypto.x25519PrivateKey(), iv: ByteArray = OgCrypto.randomBytes(12), ): WrappedToken { + require(token.size == 32) { "unlock token must be 32 bytes" } + require(deviceId.size == 6) { "device_id must be 6 bytes" } + require(nonce.size == 16) { "session nonce must be 16 bytes" } val shared = OgCrypto.x25519Shared(appEphPrivate, deviceEphPub) - val key = wrapKey(shared, nonce, deviceId) + val key = wrapKey(shared, nonce, deviceId, purpose) val sealed = OgCrypto.aesGcmEncrypt(key, iv, token, aad = deviceId) return WrappedToken(OgCrypto.x25519PublicKey(appEphPrivate), iv + sealed) } - /** Device side, used by the simulator. Throws when the envelope does not verify. */ - fun unwrap(wrapped: ByteArray, deviceId: ByteArray, deviceEphPrivate: ByteArray, appEphPub: ByteArray, nonce: ByteArray): ByteArray { + /** Device side, used by the simulator. Throws when the envelope does not verify for [purpose]. */ + fun unwrap( + wrapped: ByteArray, + deviceId: ByteArray, + deviceEphPrivate: ByteArray, + appEphPub: ByteArray, + nonce: ByteArray, + purpose: WrapPurpose = WrapPurpose.UNLOCK, + ): ByteArray { require(wrapped.size == WRAPPED_SIZE) { "wrapped token must be $WRAPPED_SIZE bytes" } val shared = OgCrypto.x25519Shared(deviceEphPrivate, appEphPub) - val key = wrapKey(shared, nonce, deviceId) + val key = wrapKey(shared, nonce, deviceId, purpose) return OgCrypto.aesGcmDecrypt(key, wrapped.copyOfRange(0, 12), wrapped.copyOfRange(12, wrapped.size), aad = deviceId) } - private fun wrapKey(shared: ByteArray, nonce: ByteArray, deviceId: ByteArray): ByteArray = - OgCrypto.hkdfSha256(shared, nonce, WRAP_LABEL + deviceId, 32) + private fun wrapKey(shared: ByteArray, nonce: ByteArray, deviceId: ByteArray, purpose: WrapPurpose): ByteArray = + OgCrypto.hkdfSha256(shared, nonce, purpose.label + deviceId, 32) } diff --git a/native-android/app/src/main/java/ch/offgrid/android/data/Daos.kt b/native-android/app/src/main/java/ch/offgrid/android/data/Daos.kt index 62c8e12..c8f429e 100644 --- a/native-android/app/src/main/java/ch/offgrid/android/data/Daos.kt +++ b/native-android/app/src/main/java/ch/offgrid/android/data/Daos.kt @@ -75,8 +75,13 @@ interface MessageDao { @Query("SELECT COUNT(*) FROM messages") fun observeCount(): Flow - @Query("SELECT * FROM messages WHERE msgRef = :ref AND status IN (1, 2) ORDER BY id DESC LIMIT 1") - suspend fun byMsgRef(ref: Int): MessageEntity? + /** The open message the antenna knows as [ref] in the current link [session] (statuses 1, 2 and 5). */ + @Query("SELECT * FROM messages WHERE msgRef = :ref AND refSession = :session AND status IN (1, 2, 5) ORDER BY id DESC LIMIT 1") + suspend fun byMsgRef(ref: Int, session: String): MessageEntity? + + /** Outgoing messages the antenna had and that have no final state yet. */ + @Query("SELECT * FROM messages WHERE direction = 'out' AND msgRef IS NOT NULL AND status IN (1, 2, 5) ORDER BY id") + suspend fun openOutgoing(): List @Query("SELECT * FROM messages WHERE status = 0 AND direction = 'out' ORDER BY sentAt, id") suspend fun localQueue(): List @@ -102,16 +107,12 @@ interface MessageDao { @Query("UPDATE messages SET readAt = :at WHERE groupId = :groupId AND direction = 'in' AND readAt IS NULL") suspend fun markGroupRead(groupId: Long, at: Long) - /** Link spec 7.5: after a device reboot every unfinished message is gone from its queue. */ - @Query("UPDATE messages SET status = 4, failReason = 'reboot', msgRef = NULL WHERE status = 1") - suspend fun failDeviceQueued() - - @Query("UPDATE messages SET msgRef = NULL WHERE msgRef IS NOT NULL") - suspend fun clearRefs() - @Query("DELETE FROM messages WHERE contactId = :contactId") suspend fun deleteForContact(contactId: Long) + @Query("DELETE FROM messages WHERE groupId = :groupId") + suspend fun deleteForGroup(groupId: Long) + @Query("SELECT * FROM messages") suspend fun all(): List } @@ -124,17 +125,57 @@ interface GroupDao { @Query("SELECT * FROM groups WHERE id = :id") fun observe(id: Long): Flow + @Query("SELECT * FROM groups WHERE id = :id") + suspend fun byId(id: Long): GroupEntity? + @Query("SELECT * FROM groups WHERE deviceId = :deviceId AND deviceGroupId = :groupId") suspend fun byDeviceGroup(deviceId: String, groupId: Int): GroupEntity? @Query("SELECT * FROM group_members") fun observeMembers(): Flow> + @Query("SELECT * FROM group_members WHERE groupId = :groupId ORDER BY member") + suspend fun membersOf(groupId: Long): List + @Insert suspend fun insert(group: GroupEntity): Long - @Insert(onConflict = OnConflictStrategy.IGNORE) - suspend fun insertMembers(members: List) + @Update + suspend fun update(group: GroupEntity) + + @Insert(onConflict = OnConflictStrategy.REPLACE) + suspend fun putMembers(members: List) + + @Update + suspend fun updateMember(member: GroupMemberEntity) + + @Query("DELETE FROM group_members WHERE groupId = :groupId") + suspend fun deleteMembers(groupId: Long) + + @Query("DELETE FROM groups WHERE id = :id") + suspend fun delete(id: Long) + + /** Replaces the member list of a group in one step, so a reader never sees a half-written list. */ + @Transaction + suspend fun replaceMembers(groupId: Long, members: List) { + deleteMembers(groupId) + putMembers(members) + } + + /** The member whose open `group.sync` the antenna knows as [ref] in the current link [session]. */ + @Query("SELECT * FROM group_members WHERE syncRef = :ref AND syncSession = :session AND keyState = 'pending'") + suspend fun bySyncRef(ref: Int, session: String): GroupMemberEntity? + + /** Syncs the antenna accepted that have no final state yet, of the groups held on [deviceId]. */ + @Query( + """SELECT m.* FROM group_members m JOIN groups g ON g.id = m.groupId + WHERE m.keyState = 'pending' AND m.syncRef IS NOT NULL AND g.deviceId = :deviceId ORDER BY m.groupId, m.member""", + ) + suspend fun openSyncs(deviceId: String): List + + /** Syncs that still have to be handed to the antenna, oldest group first. */ + @Query("SELECT * FROM group_members WHERE keyState = 'queued' ORDER BY groupId, member") + suspend fun queuedSyncs(): List @Query("SELECT * FROM groups") suspend fun all(): List @@ -210,7 +251,7 @@ interface MaintenanceDao { @Database( entities = [ContactEntity::class, MessageEntity::class, GroupEntity::class, GroupMemberEntity::class, SettingEntity::class], - version = 1, + version = 4, exportSchema = true, ) abstract class OffGridDatabase : RoomDatabase() { diff --git a/native-android/app/src/main/java/ch/offgrid/android/data/Entities.kt b/native-android/app/src/main/java/ch/offgrid/android/data/Entities.kt index 39ae98f..5c361da 100644 --- a/native-android/app/src/main/java/ch/offgrid/android/data/Entities.kt +++ b/native-android/app/src/main/java/ch/offgrid/android/data/Entities.kt @@ -1,5 +1,6 @@ package ch.offgrid.android.data +import androidx.room.ColumnInfo import androidx.room.Entity import androidx.room.Index import androidx.room.PrimaryKey @@ -45,8 +46,17 @@ object MessageStatus { /** End-to-end ACK verified ("zugestellt"). */ const val DELIVERED = 3 - /** Gave up ("Nicht gesendet"). */ + /** + * Gave up: "Nicht zugestellt" when the antenna had the message (reason from `msg.status`, or `lost` + * when it vanished from the antenna's queue), "Nicht gesendet" when the antenna refused it (error code). + */ const val FAILED = 4 + + /** + * Lab image: no ACK after all retries, the antenna keeps it and sends it again when the contact is + * heard, for up to 30 minutes ("Wartet auf …", `msg.status` state `waiting`). + */ + const val WAITING = 5 } @Serializable @@ -70,14 +80,44 @@ data class MessageEntity( val ageS: Int? = null, val status: Int, val failReason: String? = null, - /** Device handle from `msg.send`, unique since the device booted. Cleared on `sys.boot`. */ + /** + * Device handle from `msg.send`, unique only within one boot of the antenna. Set while the antenna + * has the message and cleared when it reached a final state. + */ val msgRef: Int? = null, + /** + * `/` of the app's link session in which [msgRef] was last confirmed. `msg.status` + * events only match messages of the current session; a reconnect re-confirms refs with `msg.pending`. + */ + val refSession: String? = null, /** Counter of the message within the conversation direction, used to match reactions. */ val ctr: Int? = null, - /** Group messages: who wrote it. */ + /** Group messages: who wrote it. [senderContactId] is null when the antenna holds no contact for the sender. */ val senderContactId: Long? = null, val senderName: String? = null, + /** Group messages: NodeID of the sender (`group.received.node_id`), the only identity of a non-contact. */ + val senderNodeId: String? = null, val rssi: Int? = null, + /** SNR in dB of a received message (`msg.received.snr`). */ + val snr: Double? = null, + /** Hops the ACK of a delivery reported, or the hops a received message took (0 = direct). */ + val hops: Int? = null, + /** RETRY of the received copy, or the retries the antenna needed for an outgoing message. */ + val retry: Int? = null, + /** Time from handing over to the authenticated ACK (`msg.status.rtt_ms`), waits and retries included. */ + val rttMs: Int? = null, + /** Lab image: the TEXT body went on air OGZ1-compressed. Null when the firmware does not say. */ + val compressed: Boolean? = null, + val bytesOnAir: Int? = null, + val airtimeMs: Int? = null, + /** Last state the antenna reported (`queued`, `sent`, `relayed`, `retrying`, `waiting`, …). */ + val deviceState: String? = null, + /** + * The delivery was not reported while the phone was connected; the reconciliation found it in + * `msg.pending.recent` afterwards ("zugestellt, während offline"). + */ + @ColumnInfo(defaultValue = "0") + val deliveredOffline: Boolean = false, /** * Reaction shown under this message: on our own messages the peer's, on the peer's messages * the one we sent. The column name predates the second case; renaming it would need a migration. @@ -88,22 +128,66 @@ data class MessageEntity( ) /** - * A group chat. Groups are a proposed link extension (`group.*`, see README), because protocol and - * link v1 put group chats out of scope. + * A group chat (link spec 6, "Groups"). The antenna holds the key and the member list; the app keeps the + * slot number plus display data and history. A group joined from another phone has [owner] false. */ @Serializable @Entity(tableName = "groups") data class GroupEntity( @PrimaryKey(autoGenerate = true) val id: Long = 0, val deviceId: String, + /** `group_id` slot (1 to 8) on that Heltec, or 0 once the antenna no longer holds the group. */ val deviceGroupId: Int, val name: String, val createdAt: Long, + /** 8 hex digits, the same on every member; empty for groups from before database version 4. */ + @ColumnInfo(defaultValue = "''") + val gid: String = "", + /** Counts every member change (1 to 255); a sync of an older epoch is worthless. */ + @ColumnInfo(defaultValue = "1") + val epoch: Int = 1, + /** Only the owner adds and removes members and hands out the key. */ + @ColumnInfo(defaultValue = "1") + val owner: Boolean = true, ) +/** Where the group key stands for one member (`group.sync` is an acknowledged direct message). */ +object KeyState { + /** Nothing to deliver: this phone is not the owner, or the group predates database version 4. */ + const val NONE = "none" + + /** Waiting to be handed to the antenna ("ausstehend"). */ + const val QUEUED = "queued" + + /** The antenna has the sync and waits for the member's ACK ("ausstehend"). */ + const val PENDING = "pending" + + /** The member acknowledged the key ("zugestellt"). */ + const val DELIVERED = "delivered" + + /** The sync ended without an ACK ("fehlgeschlagen"); [GroupMemberEntity.syncReason] says why. */ + const val FAILED = "failed" +} + +/** + * A member of a group other than this phone. [member] is the index in the group (the owner is 0); the + * contact is null for a member the antenna has no contact for, who is then only known by [nodeId]. + */ @Serializable -@Entity(tableName = "group_members", primaryKeys = ["groupId", "contactId"]) -data class GroupMemberEntity(val groupId: Long, val contactId: Long) +@Entity(tableName = "group_members", primaryKeys = ["groupId", "member"]) +data class GroupMemberEntity( + val groupId: Long, + val member: Int = 0, + val contactId: Long? = null, + val nodeId: String = "", + @ColumnInfo(defaultValue = "'none'") + val keyState: String = KeyState.NONE, + /** `msg_ref` of the open `group.sync`, with the link session it was confirmed in (see `OutboxReconciler`). */ + val syncRef: Int? = null, + val syncSession: String? = null, + /** Why the sync failed: a `msg.status` reason, an error code or `lost`. */ + val syncReason: String? = null, +) @Entity(tableName = "settings") data class SettingEntity(@PrimaryKey val key: String, val value: String) diff --git a/native-android/app/src/main/java/ch/offgrid/android/data/Migrations.kt b/native-android/app/src/main/java/ch/offgrid/android/data/Migrations.kt new file mode 100644 index 0000000..5931d8c --- /dev/null +++ b/native-android/app/src/main/java/ch/offgrid/android/data/Migrations.kt @@ -0,0 +1,62 @@ +package ch.offgrid.android.data + +import androidx.room.migration.Migration +import androidx.sqlite.db.SupportSQLiteDatabase + +/** + * 1 to 2: `messages.refSession` for the reconnect reconciliation (see `OutboxReconciler`). + * + * Version 1 cleared the refs of sent messages whenever the antenna restarted, which left them at + * "gesendet" for good although nobody knew whether they arrived. Those direct messages become + * "Nicht zugestellt" (reason `lost`) so they can be sent again. Group messages keep "gesendet": without + * an end-to-end ACK that is their final state. + */ +val MIGRATION_1_2 = object : Migration(1, 2) { + override fun migrate(db: SupportSQLiteDatabase) { + db.execSQL("ALTER TABLE messages ADD COLUMN refSession TEXT") + db.execSQL( + "UPDATE messages SET status = 4, failReason = 'lost' " + + "WHERE direction = 'out' AND groupId IS NULL AND msgRef IS NULL AND status IN (1, 2)", + ) + } +} + +/** 2 to 3: delivery and signal details per message for the details sheet, and "zugestellt, während offline". */ +val MIGRATION_2_3 = object : Migration(2, 3) { + override fun migrate(db: SupportSQLiteDatabase) { + listOf("snr REAL", "hops INTEGER", "retry INTEGER", "rttMs INTEGER", "compressed INTEGER", "bytesOnAir INTEGER", + "airtimeMs INTEGER", "deviceState TEXT", "deliveredOffline INTEGER NOT NULL DEFAULT 0") + .forEach { db.execSQL("ALTER TABLE messages ADD COLUMN $it") } + } +} + +/** + * The statements of [MIGRATION_3_4], separate so a unit test can run them on a plain SQLite database. + * + * Groups follow the firmware's `group.*` API (link spec 6): a group has a `gid`, an `epoch` and an owner, + * a member is identified by its index and NodeID and may have no contact, and the key state of every + * member is kept for the owner's `group.sync`. The old `group_members` table had (groupId, contactId) as its + * key, so it is rebuilt; the old members get consecutive indexes 1, 2, ... in contact order. Groups from + * version 3 were made with the earlier proposal for the API and are all owned by this phone. + */ +val MIGRATION_3_4_SQL = listOf( + "ALTER TABLE groups ADD COLUMN gid TEXT NOT NULL DEFAULT ''", + "ALTER TABLE groups ADD COLUMN epoch INTEGER NOT NULL DEFAULT 1", + "ALTER TABLE groups ADD COLUMN owner INTEGER NOT NULL DEFAULT 1", + "ALTER TABLE messages ADD COLUMN senderNodeId TEXT", + "CREATE TABLE IF NOT EXISTS group_members_v4 (`groupId` INTEGER NOT NULL, `member` INTEGER NOT NULL, `contactId` INTEGER, " + + "`nodeId` TEXT NOT NULL, `keyState` TEXT NOT NULL DEFAULT 'none', `syncRef` INTEGER, `syncSession` TEXT, `syncReason` TEXT, " + + "PRIMARY KEY(`groupId`, `member`))", + "INSERT INTO group_members_v4 (groupId, member, contactId, nodeId) " + + "SELECT m.groupId, (SELECT COUNT(*) FROM group_members o WHERE o.groupId = m.groupId AND o.contactId <= m.contactId), " + + "m.contactId, COALESCE((SELECT c.nodeId FROM contacts c WHERE c.id = m.contactId), '') FROM group_members m", + "DROP TABLE group_members", + "ALTER TABLE group_members_v4 RENAME TO group_members", +) + +/** 3 to 4: groups on the firmware's `group.*` API. */ +val MIGRATION_3_4 = object : Migration(3, 4) { + override fun migrate(db: SupportSQLiteDatabase) { + MIGRATION_3_4_SQL.forEach(db::execSQL) + } +} diff --git a/native-android/app/src/main/java/ch/offgrid/android/domain/AntennaManager.kt b/native-android/app/src/main/java/ch/offgrid/android/domain/AntennaManager.kt index 8bb3e87..e063022 100644 --- a/native-android/app/src/main/java/ch/offgrid/android/domain/AntennaManager.kt +++ b/native-android/app/src/main/java/ch/offgrid/android/domain/AntennaManager.kt @@ -4,6 +4,7 @@ import ch.offgrid.android.BuildConfig import ch.offgrid.android.crypto.OgCrypto import ch.offgrid.android.crypto.TokenWrap import ch.offgrid.android.crypto.UnlockTokenSource +import ch.offgrid.android.crypto.WrapPurpose import ch.offgrid.android.link.Incoming import ch.offgrid.android.link.Link import ch.offgrid.android.link.LinkClient @@ -19,6 +20,7 @@ import ch.offgrid.android.link.double import ch.offgrid.android.link.int import ch.offgrid.android.link.obj import ch.offgrid.android.link.str +import kotlinx.coroutines.CompletableDeferred import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.Job import kotlinx.coroutines.cancelAndJoin @@ -30,34 +32,163 @@ import kotlinx.coroutines.flow.update import kotlinx.coroutines.launch import kotlinx.coroutines.sync.Mutex import kotlinx.coroutines.sync.withLock +import kotlinx.coroutines.withTimeoutOrNull +import kotlinx.serialization.json.JsonArray import kotlinx.serialization.json.JsonObject +import kotlinx.serialization.json.JsonPrimitive import kotlinx.serialization.json.buildJsonObject +import kotlinx.serialization.json.contentOrNull import kotlinx.serialization.json.put enum class AntennaPhase { DISCONNECTED, SEARCHING, DEVICE_FOUND, CONNECTING, READY, ERROR } -/** UI error codes, texts in the screen spec ("Fehlertexte"). */ -enum class AntennaError { NO_DEVICE, PERMISSION_DENIED, OPEN_FAILED, NO_INFO, PROTO_MISMATCH, LOST, UNLOCK_FAILED } +/** What a [AntennaPhase.CONNECTING] session is doing, shown under "Verbindung wird aufgebaut". */ +enum class AntennaActivity { + /** `sys.hello` is being retried while the antenna boots. */ + HELLO, + + /** The antenna has no vault (`unprovisioned`): `sec.provision` sets it up for this phone. */ + PROVISIONING, + + /** The antenna is `locked`: `sec.unlock` with this phone's token. */ + UNLOCKING, + + /** It locked itself while connected (heartbeat timeout, restart, error): unlock again. */ + RELOCKING, + + /** `sys.factory_reset` was accepted; waiting for the restart and setting it up again. */ + RESETTING, +} + +/** UI error codes, texts in the screen spec ("Fehlertexte") and `AntennaError.text()`. */ +enum class AntennaError { + NO_DEVICE, PERMISSION_DENIED, OPEN_FAILED, NO_INFO, PROTO_MISMATCH, LOST, + + /** `E_UNLOCK_FAILED`: the antenna's vault belongs to another phone's token. */ + UNLOCK_FAILED, + + /** `E_RATE_LIMITED`: too many failed unlock or reset attempts, the antenna waits (2 s doubling, at most 60 s). */ + RATE_LIMITED, + + /** `E_NO_SESSION` twice in a row: the `sys.hello` session expired or was used up. */ + NO_SESSION, + + /** `E_INTERNAL` during unlock: the antenna could not read or write its vault. */ + VAULT_ERROR, + + /** `sys.hello.mock` is true: an old image without real authentication (link spec 14, item 2). */ + MOCK_FIRMWARE, + + /** The link is open but three heartbeats in a row got no answer. */ + UNRESPONSIVE, + + /** Any other error code; [AntennaState.errorCode] has it. */ + REJECTED, +} + +/** A `sec.state` "locked" event: why and when (wall clock of the phone). */ +data class LockEvent(val reason: String, val at: Long) + +/** + * What the antenna says about groups in `sys.hello` (link spec 6, "Groups"): `features` lists `"groups"` and + * `limits` carries the slots, the members per group (the owner included) and the text size. Firmware without + * the feature has no `group.*` commands, so the app shows no groups for it. + */ +data class GroupSupport( + val maxGroups: Int = DEFAULT_MAX_GROUPS, + val maxMembers: Int = DEFAULT_MAX_MEMBERS, + val maxTextBytes: Int = MessageLimits.DEFAULT_MAX_TEXT_BYTES, +) { + /** Others a group of this phone can take: the app's cap [MessageLimits.MAX_GROUP_MEMBERS], less if the antenna allows fewer. */ + val maxOtherMembers: Int get() = minOf(MessageLimits.MAX_GROUP_MEMBERS, maxMembers - 1) + + companion object { + const val FEATURE = "groups" + const val DEFAULT_MAX_GROUPS = 8 + const val DEFAULT_MAX_MEMBERS = 16 + + /** Null when [hello] does not list the feature. */ + fun parse(hello: JsonObject): GroupSupport? { + val listed = (hello["features"] as? JsonArray)?.any { (it as? JsonPrimitive)?.contentOrNull == FEATURE } == true + if (!listed) return null + val limits = hello.obj("limits") + return GroupSupport( + maxGroups = limits?.int("max_groups") ?: DEFAULT_MAX_GROUPS, + maxMembers = limits?.int("max_group_members") ?: DEFAULT_MAX_MEMBERS, + maxTextBytes = limits?.int("max_group_text_bytes") ?: MessageLimits.DEFAULT_MAX_TEXT_BYTES, + ) + } + } +} data class AntennaState( val phase: AntennaPhase = AntennaPhase.DISCONNECTED, val kind: LinkKind = LinkKind.SIMULATED, val deviceLabel: String? = null, val fwVersion: String? = null, - val freqMhz: Double? = null, + /** `fw.build` from `sys.hello` (compiler build date on the firmware). */ + val fwBuild: String? = null, val deviceId: String? = null, val nodeId: String? = null, + /** Name of the antenna's own identity (`id.get`). */ + val deviceName: String? = null, val maxTextBytes: Int = MessageLimits.DEFAULT_MAX_TEXT_BYTES, /** TEXT codec of a lab radio image (`sys.hello.text_codec`); the team firmware always sends raw UTF-8. */ val textCodec: String = MessageLimits.CODEC_RAW, /** UTF-8 input the antenna accepts; above [maxTextBytes] only with a codec (`limits.max_text_input_bytes`). */ val maxTextInputBytes: Int = MessageLimits.DEFAULT_MAX_TEXT_BYTES, + /** Null for firmware without the `groups` feature (`sys.hello.features`). */ + val groups: GroupSupport? = null, val error: AntennaError? = null, + /** The link error code behind [error], for the note on the connect screen. */ + val errorCode: String? = null, + /** Reason of the last `sec.state` "locked" (`heartbeat_timeout`, `lock`, `error`, …) until the antenna is open again. */ + val lockReason: String? = null, + /** Device state from the last `sys.hello` or `sec.state`: `unprovisioned`, `locked` or `unlocked`. */ + val deviceState: String? = null, + val activity: AntennaActivity? = null, + /** `sys.hello.lab_radio`: our lab image with `lab.*`, OGZ1, `waiting` and `recent`. */ + val labRadio: Boolean = false, + /** `sys.hello.radio_diagnostics`: the team's diagnostics profile. */ + val radioDiagnostics: Boolean = false, + val radio: RadioConfig? = null, + val mesh: MeshConfig? = null, + val lab: LabConfig? = null, + /** `sys.status.radio.running` after unlocking; RF can fail independently of the vault (link spec 4). */ + val radioRunning: Boolean? = null, + /** `sys.status.radio.last_error` (RadioLib code), when not 0. */ + val radioError: Int? = null, + /** `sys.status.storage.vault_status`: `ready`, `missing`, `corrupt`, … */ + val vaultStatus: String? = null, + /** `sys.status.queue.dropped_events`: events the antenna could not hand to the phone since it booted. */ + val droppedEvents: Int? = null, + val secureBoot: Boolean? = null, + val flashEncryption: Boolean? = null, + /** `sec.get_policy.lock_timeout_s`: the antenna locks after this long without a command (0 = never). */ + val lockTimeoutS: Int? = null, + /** + * With [AntennaError.RATE_LIMITED]: phone time when the antenna accepts the next attempt. The firmware does + * not report it, so this is the app's estimate of `Security::failure`; the session retries on its own then. + */ + val retryAt: Long? = null, + /** The last time the antenna locked itself or was locked, kept after it was opened again. */ + val lastLock: LockEvent? = null, + /** Code of the last unsolicited `error` event (storage, RF, lost events). */ + val lastDeviceError: String? = null, + /** + * Counts the times this app opened a locked or empty vault. A change means the antenna's RAM state (pairing + * session, refs) is new; reconnecting to an antenna that stayed unlocked keeps it. + */ + val unlockCount: Int = 0, ) { val ready: Boolean get() = phase == AntennaPhase.READY + val freqMhz: Double? get() = radio?.freqMhz val busy: Boolean get() = phase == AntennaPhase.SEARCHING || phase == AntennaPhase.DEVICE_FOUND || phase == AntennaPhase.CONNECTING } +/** Outcome of [AntennaManager.factoryReset]. */ +enum class ResetResult { DONE, NOT_CONNECTED, WRONG_PHONE, RATE_LIMITED, UNSUPPORTED, FAILED } + /** Receives device events and the "ready" signal; implemented by [Messaging]. */ interface AntennaListener { suspend fun onReady(antenna: AntennaManager, deviceId: String) @@ -65,9 +196,31 @@ interface AntennaListener { suspend fun onDeviceRebooted() } +/** Opening the vault failed for a reason the user has to see. */ +private class UnlockFailure(val error: AntennaError, val code: String?) : Exception(code ?: error.name) + /** - * Owns the connection to the antenna: open the link, `sys.hello`, provision or unlock the vault - * with the Keystore token, heartbeat every 5 s, and re-unlock after a reboot or auto-lock. + * The firmware's authentication backoff (`Security::failure`): from the third failure in a row it refuses every + * attempt for 2 s, doubling up to 60 s, and success clears it. `E_RATE_LIMITED` carries no remaining time, so the + * app estimates it from its own failures; failures by another phone are unknown to it, so each further + * `E_RATE_LIMITED` doubles the guess from 2 s instead. + */ +object AuthBackoff { + const val MAX_MS = 60_000L + + fun delayAfter(failures: Int): Long = if (failures < 3) 0 else minOf(MAX_MS, 2_000L shl (failures - 3).coerceAtMost(5)) + + /** When the antenna accepts the next attempt, seen at [now] after [rateLimited] `E_RATE_LIMITED` answers in a row. */ + fun retryAt(now: Long, failures: Int, lastFailureAt: Long, rateLimited: Int): Long { + val known = lastFailureAt + delayAfter(failures) + return if (known > now) known else now + minOf(MAX_MS, 2_000L shl (rateLimited - 1).coerceIn(0, 5)) + } +} + +/** + * Owns the connection to the antenna (link spec 2, 3 and 14): open the link, `sys.hello`, provision or unlock + * the vault with the Keystore token, heartbeat every second, notice auto-locks and restarts and unlock again, + * and keep what the antenna reports about itself (firmware, radio, mesh, lab settings) in [state]. */ class AntennaManager( private val scope: CoroutineScope, @@ -75,6 +228,7 @@ class AntennaManager( private val tokenSource: UnlockTokenSource, private val settings: Settings, private val log: (String) -> Unit = {}, + private val now: () -> Long = System::currentTimeMillis, ) { private val _state = MutableStateFlow(AntennaState()) val state: StateFlow = _state.asStateFlow() @@ -82,11 +236,23 @@ class AntennaManager( lateinit var listener: AntennaListener private var sessionJob: Job? = null + private var retryJob: Job? = null private var client: LinkClient? = null private val unlockMutex = Mutex() + private val relockMutex = Mutex() + + /** Authentication failures of this app in a row (`E_UNLOCK_FAILED`), for the [AuthBackoff] estimate. */ + private var authFailures = 0 + private var lastAuthFailureAt = 0L + private var rateLimitedInRow = 0 + + /** Set while a factory reset runs: its lock and restart are expected and must not trigger a re-unlock. */ + @Volatile + private var resetBoot: CompletableDeferred? = null fun connect() { if (state.value.busy || state.value.ready) return + retryJob?.cancel() val previous = sessionJob sessionJob = scope.launch { previous?.cancelAndJoin() @@ -95,22 +261,33 @@ class AntennaManager( } fun disconnect() { + retryJob?.cancel() sessionJob?.cancel() client?.close() client = null - _state.update { it.copy(phase = AntennaPhase.DISCONNECTED, error = null) } + _state.update { it.copy(phase = AntennaPhase.DISCONNECTED, error = null, errorCode = null, activity = null, retryAt = null) } } - /** Sends a command on the open link. Throws [LinkClosedException] when the antenna is not ready. */ + /** + * Sends a command on the open link. Throws [LinkClosedException] when the antenna is not ready. An `E_LOCKED` + * answer while the app thinks it is open means a `sec.state` event was lost: the vault is opened again. + */ suspend fun call(cmd: String, args: JsonObject? = null): JsonObject { val c = client ?: throw LinkClosedException() if (!state.value.ready && !cmd.startsWith("sys.")) throw LinkClosedException() - return c.call(cmd, args) + try { + return c.call(cmd, args) + } catch (e: LinkCommandException) { + if (e.error.code in LOCKED_CODES && state.value.ready && resetBoot == null) scope.launch { relock() } + throw e + } } private suspend fun runSession() { val link = linkProvider() - _state.value = AntennaState(phase = AntennaPhase.SEARCHING, kind = link.kind) + val previous = state.value + _state.value = AntennaState(phase = AntennaPhase.SEARCHING, kind = link.kind, lastLock = previous.lastLock, + lastDeviceError = previous.lastDeviceError, unlockCount = previous.unlockCount) val found = link.find() ?: return fail(AntennaError.NO_DEVICE) _state.update { it.copy(phase = AntennaPhase.DEVICE_FOUND, deviceLabel = found.label) } val session = try { @@ -124,7 +301,7 @@ class AntennaManager( }, ) } - _state.update { it.copy(phase = AntennaPhase.CONNECTING) } + _state.update { it.copy(phase = AntennaPhase.CONNECTING, activity = AntennaActivity.HELLO) } val c = LinkClient(session, scope, log) client = c val eventJob = scope.launch { for (event in c.events) handleEvent(event) } @@ -132,43 +309,123 @@ class AntennaManager( val hello = helloWithRetry(c) val proto = hello.str("proto") ?: "0.0" if (proto.substringBefore('.') != PROTO_MAJOR) return fail(AntennaError.PROTO_MISMATCH) - val deviceId = hello.str("device_id") ?: return fail(AntennaError.NO_INFO) - val maxText = hello.obj("limits")?.int("max_text_bytes") ?: MessageLimits.DEFAULT_MAX_TEXT_BYTES - val chip = hello.str("chip")?.substringBefore('-') - _state.update { - it.copy(deviceId = deviceId, maxTextBytes = maxText, fwVersion = hello.obj("fw")?.str("version"), - deviceLabel = chip ?: it.deviceLabel, textCodec = hello.str("text_codec") ?: MessageLimits.CODEC_RAW, - maxTextInputBytes = hello.obj("limits")?.int("max_text_input_bytes") ?: maxText) - } - if (!unlock(c, hello)) return fail(AntennaError.UNLOCK_FAILED) - if (hello.bool("lab_radio") == true) selectTextCodec(c) - val radio = c.call("radio.get") - val identity = c.call("id.get") - identity.str("public_key")?.let { settings.put(Settings.OWN_PUBLIC_KEY, it) } - _state.update { - it.copy(phase = AntennaPhase.READY, freqMhz = radio.double("freq_mhz"), nodeId = identity.str("node_id"), error = null) - } - listener.onReady(this, deviceId) + hello.str("device_id") ?: return fail(AntennaError.NO_INFO) + // Link spec 14 item 2: images that still report a mock device have no real authentication. + if (hello.bool("mock") == true) return fail(AntennaError.MOCK_FIRMWARE) + bringUp(c, hello) val heartbeat = scope.launch { heartbeat(c) } val cause = c.closed.await() heartbeat.cancel() - fail(if (cause != null) AntennaError.LOST else null) + // Somebody else may already have ended the session with a reason (a failed re-unlock); keep it. + if (state.value.phase != AntennaPhase.ERROR) fail(if (cause != null) AntennaError.LOST else null) + } catch (e: UnlockFailure) { + log("unlock failed: ${e.code}") + failUnlock(c, e) } catch (_: LinkTimeoutException) { fail(AntennaError.NO_INFO) } catch (_: LinkClosedException) { fail(AntennaError.LOST) } catch (e: LinkCommandException) { log("session failed: ${e.error.code}") - fail(if (e.error.code == "E_PROTO_MISMATCH") AntennaError.PROTO_MISMATCH else AntennaError.NO_INFO) + fail(if (e.error.code == "E_PROTO_MISMATCH") AntennaError.PROTO_MISMATCH else AntennaError.REJECTED, e.error.code) } finally { eventJob.cancel() } } - private fun fail(error: AntennaError?) { + /** + * From a `sys.hello` answer to "ready": open the vault, apply the text codec, read identity, radio, mesh, + * status and lab settings, then tell the listener. Used on connect, after an auto-lock or restart, and after a + * factory reset. + */ + private suspend fun bringUp(c: LinkClient, hello: JsonObject) { + val deviceId = hello.str("device_id")!! + val maxText = hello.obj("limits")?.int("max_text_bytes") ?: MessageLimits.DEFAULT_MAX_TEXT_BYTES + val chip = hello.str("chip")?.substringBefore('-') + val deviceState = hello.str("state") + val labRadio = hello.bool("lab_radio") == true + _state.update { + it.copy(deviceId = deviceId, maxTextBytes = maxText, groups = GroupSupport.parse(hello), fwVersion = hello.obj("fw")?.str("version"), + fwBuild = hello.obj("fw")?.str("build"), deviceLabel = chip ?: it.deviceLabel, + textCodec = hello.str("text_codec") ?: MessageLimits.CODEC_RAW, + maxTextInputBytes = hello.obj("limits")?.int("max_text_input_bytes") ?: maxText, + deviceState = deviceState, labRadio = labRadio, radioDiagnostics = hello.bool("radio_diagnostics") == true, + activity = when (deviceState) { + "unprovisioned" -> AntennaActivity.PROVISIONING + "locked" -> if (it.activity == AntennaActivity.RELOCKING) AntennaActivity.RELOCKING else AntennaActivity.UNLOCKING + else -> it.activity + }) + } + unlock(c, hello) + if (labRadio) selectTextCodec(c) + val radio = c.call("radio.get") + val identity = c.call("id.get") + identity.str("public_key")?.let { settings.put(Settings.OWN_PUBLIC_KEY, it) } + // Optional reads: older images may not know them, and none of them is needed to send messages. + val status = optional(c, "sys.status") + val mesh = optional(c, "mesh.get") + val policy = optional(c, "sec.get_policy") + val lab = if (labRadio) optional(c, "lab.get")?.let(LabConfig::parse) else null + _state.update { + it.copy(phase = AntennaPhase.READY, radio = RadioConfig.parse(radio), nodeId = identity.str("node_id"), + deviceName = identity.str("name"), deviceState = "unlocked", activity = null, + mesh = mesh?.let(MeshConfig::parse), lab = lab, + textCodec = lab?.textCodec ?: it.textCodec, maxTextInputBytes = lab?.maxTextInputBytes ?: it.maxTextInputBytes, + radioRunning = status?.obj("radio")?.bool("running"), + radioError = status?.obj("radio")?.int("last_error")?.takeIf { e -> e != 0 }, + vaultStatus = status?.obj("storage")?.str("vault_status"), + droppedEvents = status?.obj("queue")?.int("dropped_events"), + secureBoot = status?.obj("security")?.bool("secure_boot"), + flashEncryption = status?.obj("security")?.bool("flash_encryption"), + lockTimeoutS = policy?.int("lock_timeout_s"), + error = null, errorCode = null, lockReason = null, retryAt = null, + unlockCount = if (deviceState == "unlocked") it.unlockCount else it.unlockCount + 1) + } + listener.onReady(this, deviceId) + } + + private suspend fun optional(c: LinkClient, cmd: String, args: JsonObject? = null): JsonObject? = try { + c.call(cmd, args) + } catch (e: LinkCommandException) { + log("$cmd: ${e.error.code}") + null + } catch (_: LinkTimeoutException) { + null + } + + private fun fail(error: AntennaError?, code: String? = null, retryAt: Long? = null) { client?.close() client = null - _state.update { it.copy(phase = if (error == null) AntennaPhase.DISCONNECTED else AntennaPhase.ERROR, error = error) } + _state.update { + it.copy(phase = if (error == null) AntennaPhase.DISCONNECTED else AntennaPhase.ERROR, error = error, errorCode = code, + activity = null, retryAt = retryAt) + } + if (retryAt != null) { + retryJob?.cancel() + retryJob = scope.launch { + delay((retryAt - now()).coerceAtLeast(0)) + if (state.value.error == AntennaError.RATE_LIMITED) connect() + } + } + } + + /** + * Ends the session after a failed unlock. A rate limit gets its estimated end and an automatic retry then; an + * unreadable vault gets the antenna's `vault_status` (`sys.status` works in every state) for the note. + */ + private suspend fun failUnlock(c: LinkClient, e: UnlockFailure) { + when (e.error) { + AntennaError.RATE_LIMITED -> { + rateLimitedInRow++ + fail(e.error, e.code, AuthBackoff.retryAt(now(), authFailures, lastAuthFailureAt, rateLimitedInRow)) + } + AntennaError.VAULT_ERROR -> { + val vault = optional(c, "sys.status")?.obj("storage")?.str("vault_status") + _state.update { it.copy(vaultStatus = vault ?: it.vaultStatus) } + fail(e.error, e.code) + } + else -> fail(e.error, e.code) + } } /** Link spec 3.3: commands sent during boot are lost, so retry `sys.hello` every 500 ms. */ @@ -183,13 +440,26 @@ class AntennaManager( throw LinkTimeoutException("sys.hello") } + /** + * `sys.ping` about once per second (link spec 2, "Heartbeat and lock"): handled commands keep the antenna + * from locking itself after `lock_timeout_s`. Three unanswered pings in a row while the antenna is open end + * the session; during an unlock or a factory-reset restart missing answers are expected. + */ private suspend fun heartbeat(c: LinkClient) { + var missed = 0 while (true) { delay(HEARTBEAT_MS) try { - c.call("sys.ping") + c.call("sys.ping", timeoutMs = PING_TIMEOUT_MS) + missed = 0 } catch (_: LinkTimeoutException) { log("heartbeat timeout") + if (state.value.ready && resetBoot == null && ++missed >= MAX_MISSED_PINGS) { + fail(AntennaError.UNRESPONSIVE) + return + } + } catch (_: LinkCommandException) { + missed = 0 // any answer means it is alive } catch (_: LinkClosedException) { return } @@ -197,34 +467,94 @@ class AntennaManager( } /** - * Opens the vault. Order: provision a fresh device, unlock with our Keystore token, or, after a - * backup import, unlock once with the old phone's token and rotate to ours (link spec 6.10). + * Opens the vault (link spec 4). Each `sys.hello` session allows one attempt, so a state that changed in + * between (`E_NO_SESSION`, `E_NOT_PROVISIONED`, `E_ALREADY_PROVISIONED`) gets one more try with a fresh + * `sys.hello`; `E_ALREADY_UNLOCKED` means the vault is open. Throws [UnlockFailure]. */ - private suspend fun unlock(c: LinkClient, firstHello: JsonObject): Boolean = unlockMutex.withLock { - val deviceId = firstHello.str("device_id")!! - val deviceBytes = OgCrypto.unhex(deviceId) - when (firstHello.str("state")) { - "unlocked" -> return true - "unprovisioned" -> { - val name = settings.get(Settings.DISPLAY_NAME)?.takeIf(MessageLimits::isValidName) - c.call("sec.provision", wrapArgs(firstHello, tokenSource.token(deviceBytes), deviceBytes, name)) - return true + private suspend fun unlock(c: LinkClient, firstHello: JsonObject) = unlockMutex.withLock { + var hello = firstHello + for (attempt in 1..2) { + try { + openVault(c, hello) + return@withLock + } catch (e: LinkCommandException) { + val code = e.error.code + if (code == "E_ALREADY_UNLOCKED") return@withLock + if (attempt == 1 && code in RETRY_WITH_NEW_HELLO) { + hello = c.call("sys.hello", HELLO_ARGS) + continue + } + throw UnlockFailure(errorFor(code), code) } } + } + + /** + * Provision a fresh antenna, unlock with this phone's Keystore token, or, after a backup import, + * unlock once with the old phone's token and rotate to ours (link spec 4, `sec.rotate_token`). + */ + private suspend fun openVault(c: LinkClient, hello: JsonObject) { + val deviceId = hello.str("device_id")!! + val deviceBytes = OgCrypto.unhex(deviceId) + when (hello.str("state")) { + "unlocked" -> return + "unprovisioned" -> return provision(c, hello, deviceId, deviceBytes) + } try { - c.call("sec.unlock", wrapArgs(firstHello, tokenSource.token(deviceBytes), deviceBytes)) - return true + authCall(c, "sec.unlock", wrapArgs(hello, tokenSource.token(deviceBytes), deviceBytes)) + // A rotation whose answer was lost: the antenna already has our token, the old phone's is done with. + if (transferTokenFor(deviceId) != null) clearTransferToken() + return } catch (e: LinkCommandException) { if (e.error.code != "E_UNLOCK_FAILED") throw e } - val transfer = settings.get(Settings.TRANSFER_TOKEN) - if (transfer == null || settings.get(Settings.TRANSFER_DEVICE) != deviceId) return false + val transfer = transferTokenFor(deviceId) ?: throw UnlockFailure(AntennaError.UNLOCK_FAILED, "E_UNLOCK_FAILED") // The backup carries the old phone's token for exactly this device, not its Keystore key. - c.call("sec.unlock", wrapArgs(c.call("sys.hello", HELLO_ARGS), OgCrypto.unb64(transfer), deviceBytes)) + authCall(c, "sec.unlock", wrapArgs(c.call("sys.hello", HELLO_ARGS), transfer, deviceBytes)) + // Both tokens stay known until the antenna confirmed the rotation: if the link drops in between, the next + // connect tries ours first and falls back to the old phone's. c.call("sec.rotate_token", wrapArgs(c.call("sys.hello", HELLO_ARGS), tokenSource.token(deviceBytes), deviceBytes)) + clearTransferToken() + } + + /** An authenticating command: counts `E_UNLOCK_FAILED` for the [AuthBackoff] estimate, success clears it. */ + private suspend fun authCall(c: LinkClient, cmd: String, args: JsonObject): JsonObject { + try { + val result = c.call(cmd, args) + authFailures = 0 + rateLimitedInRow = 0 + return result + } catch (e: LinkCommandException) { + if (e.error.code == "E_UNLOCK_FAILED") { + authFailures++ + lastAuthFailureAt = now() + rateLimitedInRow = 0 + } + throw e + } + } + + /** + * Sets up an antenna without a vault: a new board, a reflashed one or one after a factory reset. + * The vault then only opens with this phone's token. The app never stores that token (it is derived + * from the Keystore key and the device_id each time), but a token from a backup import for this + * antenna can never open the new vault, so it goes. The contacts the antenna held are gone with the old + * vault; [Messaging] marks them for pairing again when it syncs the contact list. + */ + private suspend fun provision(c: LinkClient, hello: JsonObject, deviceId: String, deviceBytes: ByteArray) { + val name = settings.get(Settings.DISPLAY_NAME)?.takeIf(MessageLimits::isValidName) + authCall(c, "sec.provision", wrapArgs(hello, tokenSource.token(deviceBytes), deviceBytes, name)) + if (settings.get(Settings.TRANSFER_DEVICE) == deviceId) clearTransferToken() + } + + private suspend fun transferTokenFor(deviceId: String): ByteArray? { + val transfer = settings.get(Settings.TRANSFER_TOKEN) ?: return null + return if (settings.get(Settings.TRANSFER_DEVICE) == deviceId) OgCrypto.unb64(transfer) else null + } + + private suspend fun clearTransferToken() { settings.remove(Settings.TRANSFER_TOKEN) settings.remove(Settings.TRANSFER_DEVICE) - return true } /** @@ -245,13 +575,59 @@ class AntennaManager( } } - private fun wrapArgs(hello: JsonObject, token: ByteArray, deviceId: ByteArray, name: String? = null): JsonObject { + // ------------------------------------------------------------------ settings on the antenna + + /** `mesh.set` with the fields in [changes] (persisted on the antenna); returns and keeps the whole object. */ + suspend fun setMesh(changes: JsonObject): MeshConfig { + val mesh = MeshConfig.parse(call("mesh.set", changes)) + _state.update { it.copy(mesh = mesh) } + return mesh + } + + /** `lab.set` on a lab radio image (`text_codec`, `ignore_nodes`); returns and keeps the result. */ + suspend fun setLab(changes: JsonObject): LabConfig { + val lab = LabConfig.parse(call("lab.set", changes)) + _state.update { + it.copy(lab = lab, textCodec = lab.textCodec, maxTextInputBytes = lab.maxTextInputBytes ?: it.maxTextInputBytes) + } + return lab + } + + /** `radio.stats`, cleared afterwards with [reset]. */ + suspend fun radioStats(reset: Boolean = false): JsonObject = + call("radio.stats", if (reset) buildJsonObject { put("reset", true) } else null) + + /** Reads radio, mesh, status and lab settings again, for the advanced screen. */ + suspend fun refreshInfo() { + val c = client?.takeIf { state.value.ready } ?: return + val radio = optional(c, "radio.get") + val mesh = optional(c, "mesh.get") + val status = optional(c, "sys.status") + val lab = if (state.value.labRadio) optional(c, "lab.get")?.let(LabConfig::parse) else null + _state.update { + it.copy(radio = radio?.let(RadioConfig::parse) ?: it.radio, mesh = mesh?.let(MeshConfig::parse) ?: it.mesh, + lab = lab ?: it.lab, + radioRunning = status?.obj("radio")?.bool("running") ?: it.radioRunning, + radioError = if (status != null) status.obj("radio")?.int("last_error")?.takeIf { e -> e != 0 } else it.radioError, + vaultStatus = status?.obj("storage")?.str("vault_status") ?: it.vaultStatus, + droppedEvents = status?.obj("queue")?.int("dropped_events") ?: it.droppedEvents) + } + } + + private fun wrapArgs( + hello: JsonObject, + token: ByteArray, + deviceId: ByteArray, + name: String? = null, + purpose: WrapPurpose = WrapPurpose.UNLOCK, + ): JsonObject { val sessionInfo = hello.obj("session") ?: throw LinkCommandException("sys.hello", LinkError("E_NO_SESSION", null, null)) val wrapped = TokenWrap.wrap( token = token, deviceId = deviceId, deviceEphPub = OgCrypto.unb64(sessionInfo.str("device_eph_pub")!!), nonce = OgCrypto.unb64(sessionInfo.str("nonce")!!), + purpose = purpose, ) return buildJsonObject { put("app_eph_pub", OgCrypto.b64(wrapped.appEphPub)) @@ -263,33 +639,157 @@ class AntennaManager( /** This phone's unlock token for a device, exported in a backup so a new phone can take over (spec 6.10). */ fun tokenFor(deviceId: String): ByteArray = tokenSource.token(OgCrypto.unhex(deviceId)) + /** + * Erases the connected antenna (link spec 11, `method: "app"`): vault, identity, contacts and settings + * go, the device_id stays. This phone proves it is the owner with its token wrapped under the reset + * label; after a backup import the old phone's token is tried too. On success the antenna locks, + * restarts unprovisioned, and this manager sets it up again for this phone in the background. + */ + suspend fun factoryReset(): ResetResult { + val c = client ?: return ResetResult.NOT_CONNECTED + val deviceId = state.value.deviceId?.takeIf { state.value.ready } ?: return ResetResult.NOT_CONNECTED + val deviceBytes = OgCrypto.unhex(deviceId) + val tokens = listOfNotNull(tokenSource.token(deviceBytes), transferTokenFor(deviceId)) + val boot = CompletableDeferred() + resetBoot = boot + try { + for (token in tokens) { + val args = buildJsonObject { + put("confirm", "ERASE") + put("method", "app") + wrapArgs(c.call("sys.hello", HELLO_ARGS), token, deviceBytes, purpose = WrapPurpose.RESET) + .forEach { (k, v) -> put(k, v) } + } + try { + authCall(c, "sys.factory_reset", args) + } catch (e: LinkCommandException) { + log("factory reset refused: ${e.error.code}") + when (e.error.code) { + "E_UNLOCK_FAILED" -> continue + "E_RATE_LIMITED" -> return ResetResult.RATE_LIMITED.also { resetBoot = null } + // Older images confirm the reset with the button instead (E_BUSY) or do not know it. + "E_BUSY", "E_UNKNOWN_CMD" -> return ResetResult.UNSUPPORTED.also { resetBoot = null } + else -> return ResetResult.FAILED.also { resetBoot = null } + } + } + clearTransferToken() + _state.update { + it.copy(phase = AntennaPhase.CONNECTING, activity = AntennaActivity.RESETTING, lockReason = "factory_reset") + } + scope.launch { setUpAfterReset(c, boot) } + return ResetResult.DONE + } + resetBoot = null + return ResetResult.WRONG_PHONE + } catch (_: LinkTimeoutException) { + resetBoot = null + return ResetResult.FAILED + } catch (_: LinkClosedException) { + resetBoot = null + return ResetResult.NOT_CONNECTED + } + } + + /** Waits for the restart after a reset (`sys.boot`), then provisions the empty antenna again. */ + private suspend fun setUpAfterReset(c: LinkClient, boot: CompletableDeferred) { + try { + // The serial port of the Heltec V3 stays open over the restart; without sys.boot, sys.hello retries decide. + withTimeoutOrNull(RESET_BOOT_TIMEOUT_MS) { boot.await() } + resetBoot = null + bringUp(c, helloWithRetry(c)) + } catch (e: UnlockFailure) { + failUnlock(c, e) + } catch (_: LinkTimeoutException) { + fail(AntennaError.NO_INFO) + } catch (_: LinkClosedException) { + fail(AntennaError.LOST) + } catch (e: LinkCommandException) { + fail(AntennaError.REJECTED, e.error.code) + } finally { + resetBoot = null + } + } + private suspend fun handleEvent(event: Incoming.Event) { + val reset = resetBoot when (event.name) { - "sys.boot" -> if (state.value.ready) { - // The device restarted under us: its queue is gone and it is locked again. - listener.onDeviceRebooted() - relock() + "sys.boot" -> when { + reset != null -> { + listener.onDeviceRebooted() + reset.complete(Unit) + } + state.value.ready -> { + // The device restarted under us: its queue is gone and it is locked again. + _state.update { it.copy(lastLock = LockEvent(REASON_RESTART, now())) } + listener.onDeviceRebooted() + relock() + } + } + "sec.state" -> when (event.data.str("state")) { + "locked" -> { + val reason = event.data.str("reason") ?: "lock" + _state.update { it.copy(lockReason = reason, lastLock = LockEvent(reason, now()), deviceState = "locked") } + if (reset == null && state.value.ready) relock() + } + "unlocked" -> _state.update { it.copy(deviceState = "unlocked") } + } + "error" -> { + _state.update { it.copy(lastDeviceError = event.data.str("code")) } + listener.onEvent(event) } - "sec.state" -> if (event.data.str("state") == "locked" && state.value.ready) relock() else -> listener.onEvent(event) } } + /** + * Opens the vault again after an auto-lock, a restart or a lost `sec.state`; ends the session with the reason + * when that fails. Runs once at a time, and not at all when a fresh `sys.hello` says the antenna is still open. + */ private suspend fun relock() { val c = client ?: return + if (!relockMutex.tryLock()) return try { val hello = c.call("sys.hello", HELLO_ARGS) - if (!unlock(c, hello)) fail(AntennaError.UNLOCK_FAILED) else listener.onReady(this, hello.str("device_id")!!) - } catch (e: Exception) { - log("re-unlock failed: ${e.message}") + if (hello.str("state") == "unlocked" && state.value.ready) return + _state.update { it.copy(phase = AntennaPhase.CONNECTING, activity = AntennaActivity.RELOCKING) } + bringUp(c, hello) + } catch (e: UnlockFailure) { + log("re-unlock failed: ${e.code}") + failUnlock(c, e) + } catch (e: LinkCommandException) { + log("re-unlock failed: ${e.error.code}") + fail(AntennaError.REJECTED, e.error.code) + } catch (_: LinkTimeoutException) { + fail(AntennaError.NO_INFO) + } catch (_: LinkClosedException) { + // runSession reports the lost link + } finally { + relockMutex.unlock() } } - private companion object { - const val PROTO_MAJOR = "1" + companion object { + /** [LockEvent.reason] for a restart noticed through `sys.boot` (not a `sec.state` reason). */ + const val REASON_RESTART = "restart" + + private const val PROTO_MAJOR = "1" // 8 s: an image that plays its OLED boot animation in setup() answers only after it ends. - const val HELLO_ATTEMPTS = 16 - const val HEARTBEAT_MS = 5_000L - val HELLO_ARGS = buildJsonObject { put("app", "offgrid-android"); put("app_proto", "1.0") } + private const val HELLO_ATTEMPTS = 16 + private const val HEARTBEAT_MS = 1_000L + private const val PING_TIMEOUT_MS = 2_000L + private const val MAX_MISSED_PINGS = 3 + private const val RESET_BOOT_TIMEOUT_MS = 15_000L + private val HELLO_ARGS = buildJsonObject { put("app", "offgrid-android"); put("app_proto", "1.1") } + private val RETRY_WITH_NEW_HELLO = setOf("E_NO_SESSION", "E_NOT_PROVISIONED", "E_ALREADY_PROVISIONED") + private val LOCKED_CODES = setOf("E_LOCKED", "E_NOT_PROVISIONED") + + private fun errorFor(code: String): AntennaError = when (code) { + "E_UNLOCK_FAILED" -> AntennaError.UNLOCK_FAILED + "E_RATE_LIMITED" -> AntennaError.RATE_LIMITED + "E_NO_SESSION" -> AntennaError.NO_SESSION + "E_INTERNAL" -> AntennaError.VAULT_ERROR + "E_PROTO_MISMATCH" -> AntennaError.PROTO_MISMATCH + else -> AntennaError.REJECTED + } } } diff --git a/native-android/app/src/main/java/ch/offgrid/android/domain/Backup.kt b/native-android/app/src/main/java/ch/offgrid/android/domain/Backup.kt index d3e2a3a..1a7fcbc 100644 --- a/native-android/app/src/main/java/ch/offgrid/android/domain/Backup.kt +++ b/native-android/app/src/main/java/ch/offgrid/android/domain/Backup.kt @@ -126,7 +126,7 @@ class BackupService( /** Replaces all local data, keeps the old phone's token for one unlock, then reconnects. */ suspend fun import(text: String, password: String) { val data = withContext(Dispatchers.Default) { BackupCodec.decrypt(text, password) } - db.maintenance().replaceAll(data.contacts, data.messages, data.groups, data.groupMembers) + db.maintenance().replaceAll(data.contacts, data.messages, data.groups, uniqueMemberIndexes(data.groupMembers)) data.displayName?.let { settings.put(Settings.DISPLAY_NAME, it) } settings.put(Settings.ONBOARDED, "true") data.unlock?.let { @@ -138,6 +138,16 @@ class BackupService( } companion object { + /** + * Backups from before database version 4 have no member index (it reads as 0 for all of them). Members of one + * group without distinct indexes get 1, 2, ... in file order, so they fit the (group, member) key. + */ + internal fun uniqueMemberIndexes(members: List): List = + members.groupBy { it.groupId }.values.flatMap { group -> + if (group.map { it.member }.distinct().size == group.size) group + else group.mapIndexed { i, m -> m.copy(member = i + 1) } + } + /** `offgrid-backup-YYYY-MM-DD.ogx` in Swiss local time. */ fun fileName(now: Long): String = "offgrid-backup-${Instant.ofEpochMilli(now).atZone(Formats.ZONE).toLocalDate()}.ogx" } diff --git a/native-android/app/src/main/java/ch/offgrid/android/domain/DeviceInfo.kt b/native-android/app/src/main/java/ch/offgrid/android/domain/DeviceInfo.kt new file mode 100644 index 0000000..b20de25 --- /dev/null +++ b/native-android/app/src/main/java/ch/offgrid/android/domain/DeviceInfo.kt @@ -0,0 +1,145 @@ +package ch.offgrid.android.domain + +import ch.offgrid.android.link.bool +import ch.offgrid.android.link.double +import ch.offgrid.android.link.int +import ch.offgrid.android.link.str +import kotlinx.serialization.json.JsonArray +import kotlinx.serialization.json.JsonObject +import kotlinx.serialization.json.JsonPrimitive + +/** `radio.get` (link spec 7): the PHY settings every node of a mesh has to share. */ +data class RadioConfig( + val freqMhz: Double?, + val bwKhz: Double?, + val sf: Int?, + val cr: Int?, + val txPowerDbm: Int?, + val preamble: Int?, + val syncWord: Int?, + /** Estimated airtime of a 23-byte packet at these settings. */ + val airtime23Ms: Int?, +) { + companion object { + fun parse(o: JsonObject) = RadioConfig( + freqMhz = o.double("freq_mhz"), bwKhz = o.double("bw_khz"), sf = o.int("sf"), cr = o.int("cr"), + txPowerDbm = o.int("tx_power_dbm"), preamble = o.int("preamble"), syncWord = o.int("sync_word"), + airtime23Ms = o.int("est_airtime_ms_23b"), + ) + } +} + +/** `mesh.get` / `mesh.set` (link spec 8). Fields an older image does not report stay null. */ +data class MeshConfig( + val hopDefault: Int?, + val relayEnabled: Boolean?, + val relayWhenLocked: Boolean?, + val retries: Int?, + val cadEnabled: Boolean?, +) { + companion object { + const val MAX_HOPS = 7 + + fun parse(o: JsonObject) = MeshConfig( + hopDefault = o.int("hop_default"), relayEnabled = o.bool("relay_enabled"), + relayWhenLocked = o.bool("relay_when_locked"), retries = o.int("retries"), cadEnabled = o.bool("cad_enabled"), + ) + } +} + +/** + * `lab.get` / `lab.set` of the lab radio image (only when `sys.hello.lab_radio` is true, only unlocked). + * [ignoreNodes] are NodeIDs whose directly heard packets the antenna drops as if they were out of range; + * copies relayed by another node still arrive. That forces A→B→C routes with all boards in one room. + */ +data class LabConfig( + val textCodec: String, + val maxTextInputBytes: Int?, + val nodeId: String?, + val fw: String?, + /** Null when the image predates the ignore list. */ + val ignoreNodes: List?, +) { + companion object { + const val MAX_IGNORE_NODES = 8 + private val NODE_ID = Regex("^[0-9A-F]{4}$") + + fun parse(o: JsonObject) = LabConfig( + textCodec = o.str("text_codec") ?: MessageLimits.CODEC_RAW, + maxTextInputBytes = o.int("max_text_input_bytes"), + nodeId = o.str("node_id"), + fw = o.str("fw"), + ignoreNodes = (o["ignore_nodes"] as? JsonArray)?.mapNotNull { (it as? JsonPrimitive)?.content }, + ) + + /** Normalises user input to the four upper-case hex digits of a NodeID, or null when it is not one. */ + fun normalizeNodeId(input: String): String? = + input.trim().removePrefix("0x").removePrefix("0X").uppercase().takeIf { NODE_ID.matches(it) } + + /** The ignore list with [input] added, or why it cannot be added. */ + fun withIgnored(current: List, input: String, ownNodeId: String?): IgnoreEdit { + val id = normalizeNodeId(input) ?: return IgnoreEdit.Refused(IgnoreEdit.Reason.INVALID) + return when { + ownNodeId != null && id.equals(ownNodeId, ignoreCase = true) -> IgnoreEdit.Refused(IgnoreEdit.Reason.OWN) + id in current -> IgnoreEdit.Refused(IgnoreEdit.Reason.DUPLICATE) + current.size >= MAX_IGNORE_NODES -> IgnoreEdit.Refused(IgnoreEdit.Reason.FULL) + else -> IgnoreEdit.Changed(current + id) + } + } + } +} + +/** Result of [LabConfig.withIgnored]. */ +sealed interface IgnoreEdit { + data class Changed(val nodes: List) : IgnoreEdit + data class Refused(val reason: Reason) : IgnoreEdit + + enum class Reason { INVALID, OWN, DUPLICATE, FULL } +} + +/** Counters of `radio.stats` in the order the advanced screen lists them, with German labels. */ +object RadioStats { + val LABELS: List> = listOf( + "tx_packets" to "Gesendete Pakete", + "rx_packets" to "Empfangene Pakete", + "relayed" to "Weitergeleitet", + "relay_suppressed" to "Weiterleitung unterdrückt", + "relay_dropped" to "Weiterleitung verworfen", + "rate_limit_drops" to "Verworfen (Ratenlimit)", + "acks_sent" to "Bestätigungen gesendet", + "acks_received" to "Bestätigungen empfangen", + "retries" to "Wiederholungen", + "resends" to "Erneut gesendet (wartend)", + "rx_crc_errors" to "CRC-Fehler", + "rx_tag_failures" to "Authentifizierung fehlgeschlagen", + "rx_malformed" to "Fehlerhafte Pakete", + "rx_dedupe_drops" to "Duplikate verworfen", + "cad_scans" to "Kanalprüfungen", + "cad_busy" to "Kanal belegt", + "tx_airtime_ms_total" to "Sendezeit gesamt (ms)", + "tx_duty_cycle_max_percent" to "Duty Cycle max. (%)", + "locked_buffered" to "Gepuffert während gesperrt", + "locked_expired" to "Puffer abgelaufen", + "radio_failures" to "Funkfehler", + "radio_timeouts" to "Funk-Zeitüberschreitungen", + "dropped_events" to "Verlorene Ereignisse", + "dropped_acks" to "Verlorene Bestätigungen", + "last_rssi" to "Letzter RSSI (dBm)", + "last_snr" to "Letzter SNR (dB)", + ) + + /** Label and printable value for every known counter in [result], then any unknown numeric fields. */ + fun rows(result: JsonObject): List> { + val known = LABELS.mapNotNull { (key, label) -> format(result[key])?.let { label to it } } + val extra = result.keys.filter { key -> LABELS.none { it.first == key } }.sorted() + .mapNotNull { key -> format(result[key])?.let { key to it } } + return known + extra + } + + private fun format(value: Any?): String? { + val p = value as? JsonPrimitive ?: return null + if (p.isString) return null + val d = p.content.toDoubleOrNull() ?: return null + return if (d == Math.floor(d) && !d.isInfinite()) d.toLong().toString() else String.format(java.util.Locale.ROOT, "%.1f", d) + } +} diff --git a/native-android/app/src/main/java/ch/offgrid/android/domain/GroupSync.kt b/native-android/app/src/main/java/ch/offgrid/android/domain/GroupSync.kt new file mode 100644 index 0000000..1793801 --- /dev/null +++ b/native-android/app/src/main/java/ch/offgrid/android/domain/GroupSync.kt @@ -0,0 +1,59 @@ +package ch.offgrid.android.domain + +import ch.offgrid.android.data.GroupMemberEntity +import ch.offgrid.android.data.KeyState + +/** + * Key delivery of an owned group (link spec 6, "Groups"). `group.sync` is an acknowledged direct message to + * one member, so a member's [KeyState] follows the same `msg.status` events and the same reconnect rules as a + * direct message ([OutboxReconciler]): the `msg_ref` is only valid in one link session, and what the antenna + * lost is "fehlgeschlagen" with a way to send it again, never resent on its own. + */ +object GroupSync { + /** Back to waiting for the antenna: a new attempt gets a new ref, the old outcome is forgotten. */ + fun requeue(m: GroupMemberEntity): GroupMemberEntity = + m.copy(keyState = KeyState.QUEUED, syncRef = null, syncSession = null, syncReason = null) + + fun pending(m: GroupMemberEntity, ref: Int, session: String): GroupMemberEntity = + m.copy(keyState = KeyState.PENDING, syncRef = ref, syncSession = session, syncReason = null) + + fun failed(m: GroupMemberEntity, reason: String): GroupMemberEntity = + m.copy(keyState = KeyState.FAILED, syncRef = null, syncSession = null, syncReason = reason) + + private fun lost(m: GroupMemberEntity) = failed(m, OutboxReconciler.REASON_LOST) + + /** + * Applies a `msg.status` state of the sync to [m]. Only the ACK ends it well; `failed` and `cancelled` end it + * badly, everything else (`queued`, `sent`, `relayed`, `retrying`, `waiting`) keeps it pending. Null when + * nothing changes. + */ + fun applyEvent(m: GroupMemberEntity, state: String, reason: String?): GroupMemberEntity? { + if (m.keyState != KeyState.PENDING) return null + return when (state) { + "delivered" -> m.copy(keyState = KeyState.DELIVERED, syncRef = null, syncSession = null, syncReason = null) + "failed" -> failed(m, reason ?: "failed") + "cancelled" -> failed(m, "cancelled") + else -> null + } + } + + /** + * Settles the [open] syncs (accepted by an antenna, no final state) against [snapshot], the `msg.pending` + * answer at the start of link session [session], like [OutboxReconciler.reconcile]: still queued means the + * sync moves into the new session, a final outcome in `recent` is applied, anything else was lost. Returns + * only the rows that changed. + */ + fun reconcile(open: List, snapshot: PendingSnapshot, session: String): List { + val pending = snapshot.pending.associateBy { it.ref } + val recent = snapshot.recent.associateBy { it.ref } + return open.mapNotNull { m -> + val ref = m.syncRef ?: return@mapNotNull null + val updated = when { + pending[ref] != null -> pending.getValue(ref).let { applyEvent(m, it.state, it.reason) ?: m.copy(syncSession = session) } + recent[ref] != null -> recent.getValue(ref).let { applyEvent(m, it.state, it.reason) ?: lost(m) } + else -> lost(m) + } + updated.takeIf { it != m } + } + } +} diff --git a/native-android/app/src/main/java/ch/offgrid/android/domain/Limits.kt b/native-android/app/src/main/java/ch/offgrid/android/domain/Limits.kt index aa9f4d0..a959ad8 100644 --- a/native-android/app/src/main/java/ch/offgrid/android/domain/Limits.kt +++ b/native-android/app/src/main/java/ch/offgrid/android/domain/Limits.kt @@ -26,21 +26,54 @@ object MessageLimits { const val CODEC_OGZ1 = "ogz1" /** - * Bytes [text] takes in the TEXT body on air, to compare with `AntennaState.maxTextBytes`. With `ogz1` - * the antenna sends the OGZ1 encoding whenever it is shorter (protocol 8.1, inner flag bit 2), so the - * same 83 bytes hold about twice the text. Above [maxInputBytes] the antenna refuses the text, and the - * raw size is returned so the count shows it as too long. + * Bytes [text] takes in the TEXT body on air, to compare with `AntennaState.maxTextBytes`. With `ogz1` the + * lab image 0.3.0-lab.3 sends texts that fit raw unchanged, so a board on the team firmware (which rejects + * compressed bodies) can still read them, and compresses only longer ones (protocol 8.1, inner flag bit 2); + * then the same 83 bytes hold about twice the text. Above [maxInputBytes] the antenna refuses the text, and + * the raw size is returned so the count shows it as too long. */ fun onAirTextBytes(text: String, codec: String, maxInputBytes: Int): Int { val raw = text.toByteArray(Charsets.UTF_8) - if (codec != CODEC_OGZ1 || raw.size > maxInputBytes || raw.size < 2) return raw.size - return OgzCodec.compress(raw, capacity = raw.size - 1)?.size ?: raw.size + if (codec != CODEC_OGZ1 || raw.size <= DEFAULT_MAX_TEXT_BYTES || raw.size > maxInputBytes) return raw.size + return OgzCodec.compress(raw, capacity = DEFAULT_MAX_TEXT_BYTES)?.size ?: raw.size } /** [canSend] for the connected antenna, including its TEXT codec. */ fun canSend(text: String, antenna: AntennaState): Boolean = text.isNotBlank() && onAirTextBytes(text, antenna.textCodec, antenna.maxTextInputBytes) <= antenna.maxTextBytes + /** Most radio messages one text is split into; longer drafts cannot be sent. */ + const val MAX_PARTS = 4 + + /** + * The radio messages the app sends for [text]: the text itself when it fits one packet of [antenna] (with + * OGZ1 on a lab image possibly compressed), else raw pieces of at most `maxTextBytes`. The firmware does not + * fragment (link spec 10: longer texts are split by the app). Raw pieces stay readable for boards on the + * team firmware, which drop OGZ1 bodies without an ACK. + */ + fun split(text: String, antenna: AntennaState): List { + val trimmed = text.trim() + if (trimmed.isEmpty()) return emptyList() + if (canSend(trimmed, antenna)) return listOf(trimmed) + return splitRaw(trimmed, antenna.maxTextBytes) + } + + /** Pieces of at most [maxBytes] UTF-8 bytes, cut after a space or line break when one is in the second half. */ + fun splitRaw(text: String, maxBytes: Int): List { + val parts = mutableListOf() + var rest = text.trim() + while (rest.isNotEmpty()) { + var piece = clampToBytes(rest, maxBytes) + if (piece.length < rest.length) { + val cut = piece.indexOfLast { it.isWhitespace() } + if (cut >= piece.length / 2) piece = piece.substring(0, cut) + } + parts += piece.trim() + rest = rest.substring(piece.length).trimStart() + } + return parts + } + fun isValidName(name: String): Boolean { val trimmed = name.trim() return trimmed.isNotEmpty() && utf8Bytes(trimmed) <= MAX_NAME_BYTES diff --git a/native-android/app/src/main/java/ch/offgrid/android/domain/MessageDetails.kt b/native-android/app/src/main/java/ch/offgrid/android/domain/MessageDetails.kt new file mode 100644 index 0000000..ca20c86 --- /dev/null +++ b/native-android/app/src/main/java/ch/offgrid/android/domain/MessageDetails.kt @@ -0,0 +1,84 @@ +package ch.offgrid.android.domain + +import ch.offgrid.android.data.MessageEntity +import ch.offgrid.android.data.MessageStatus + +/** + * The "Details" sheet of a message: what the antenna reported about its way over the air. Outgoing messages + * carry the values of `msg.send` and `msg.status` (retries, and on delivery hops and the time to the ACK), + * incoming ones those of `msg.received` (hops, RSSI, SNR, RETRY of the copy). Values the firmware did not + * report are left out; the team firmware has no `compressed` and no delivery hops. + */ +object MessageDetails { + /** Status in words, more precise than the meta line under the bubble. */ + fun status(m: MessageEntity, recipient: String? = null): String { + if (m.direction == "in") return "Empfangen" + return when (m.status) { + MessageStatus.DELIVERED -> if (m.deliveredOffline) "Zugestellt, während offline" else "Zugestellt" + MessageStatus.SENT -> when (m.deviceState) { + "relayed" -> "Von einem anderen Gerät weitergeleitet" + "retrying" -> "Gesendet, wird wiederholt" + else -> if (m.groupId != null) "An die Gruppe gesendet" else "Gesendet, noch keine Bestätigung" + } + MessageStatus.WAITING -> "Wartet auf ${recipient ?: "Empfänger"}" + MessageStatus.DEVICE_QUEUED -> "In der Warteschlange der Antenne" + MessageStatus.LOCAL_QUEUED -> "Auf dem Handy, noch nicht an der Antenne" + MessageStatus.FAILED -> if (failedBeforeSending(m.failReason)) "Nicht gesendet" else "Nicht zugestellt" + else -> "Unbekannt" + } + } + + /** True when the antenna refused the message (an `E_…` code from `msg.send` or `group.send`, or no contact or group slot). */ + fun failedBeforeSending(reason: String?): Boolean = + reason != null && (reason.startsWith("E_") || reason == "no_contact" || reason == "no_group") + + /** Why a message failed, for the details sheet. */ + fun reason(reason: String?): String? = when (reason) { + null -> null + "timeout", "no_ack" -> "Keine Bestätigung nach allen Versuchen" + OutboxReconciler.REASON_LOST -> "Die Antenne kennt die Nachricht nicht mehr (Neustart oder neu verbunden)" + "cancelled" -> "Abgebrochen" + "locked" -> "Die Antenne wurde gesperrt" + "contact_deleted" -> "Kontakt auf der Antenne gelöscht" + "radio_error" -> "Funkfehler der Antenne" + "no_contact" -> "Kontakt ist nicht auf der Antenne" + "no_group" -> "Gruppe ist nicht auf der Antenne" + "E_TOO_LONG" -> "Zu lang für ein Funkpaket" + "E_BUSY" -> "Zähler aufgebraucht, bitte neu koppeln" + "E_NO_SUCH_CONTACT" -> "Kontakt ist nicht auf der Antenne" + "E_NO_SUCH_GROUP" -> "Gruppe ist nicht auf der Antenne" + "E_RADIO" -> "Funkmodul der Antenne nicht bereit" + "E_INVALID_ARG" -> "Die Antenne hat die Nachricht abgelehnt" + else -> reason + } + + fun rows(m: MessageEntity, recipient: String? = null): List> = buildList { + add("Status" to status(m, recipient)) + reason(m.failReason)?.takeIf { m.status == MessageStatus.FAILED }?.let { add("Grund" to it) } + m.hops?.let { add("Hops" to hops(it)) } + if (m.direction == "in") { + m.rssi?.let { add("RSSI" to "$it dBm") } + m.snr?.let { add("SNR" to String.format(Formats.LOCALE, "%.1f dB", it)) } + m.retry?.let { add("Empfangene Sendung" to if (it == 0) "Erste Sendung" else "Wiederholung $it") } + } else { + m.retry?.let { add("Wiederholungen" to it.toString()) } + m.rttMs?.let { add("Zeit bis Bestätigung" to duration(it)) } + m.bytesOnAir?.let { add("Bytes auf Funk" to "$it B") } + m.airtimeMs?.let { add("Sendezeit pro Versuch" to "≈ $it ms") } + } + m.compressed?.let { add("Komprimiert (OGZ1)" to if (it) "Ja" else "Nein") } + m.ctr?.let { add("Zähler" to it.toString()) } + } + + /** True when the antenna reported anything beyond the status (team firmware without delivery details). */ + fun hasRadioDetails(m: MessageEntity): Boolean = + listOf(m.hops, m.rssi, m.snr, m.retry, m.rttMs, m.compressed, m.bytesOnAir).any { it != null } + + private fun hops(n: Int) = when (n) { + 0 -> "Direkt" + 1 -> "1 Weiterleitung" + else -> "$n Weiterleitungen" + } + + private fun duration(ms: Int) = if (ms < 1_000) "$ms ms" else String.format(Formats.LOCALE, "%.1f s", ms / 1000.0) +} diff --git a/native-android/app/src/main/java/ch/offgrid/android/domain/Messaging.kt b/native-android/app/src/main/java/ch/offgrid/android/domain/Messaging.kt index c45a5b9..513aa53 100644 --- a/native-android/app/src/main/java/ch/offgrid/android/domain/Messaging.kt +++ b/native-android/app/src/main/java/ch/offgrid/android/domain/Messaging.kt @@ -4,6 +4,7 @@ import ch.offgrid.android.analytics.AnalyticsEvent import ch.offgrid.android.data.ContactEntity import ch.offgrid.android.data.GroupEntity import ch.offgrid.android.data.GroupMemberEntity +import ch.offgrid.android.data.KeyState import ch.offgrid.android.data.MessageEntity import ch.offgrid.android.data.MessageStatus import ch.offgrid.android.data.OffGridDatabase @@ -11,6 +12,8 @@ import ch.offgrid.android.link.Incoming import ch.offgrid.android.link.LinkClosedException import ch.offgrid.android.link.LinkCommandException import ch.offgrid.android.link.LinkTimeoutException +import ch.offgrid.android.link.bool +import ch.offgrid.android.link.dbm import ch.offgrid.android.link.double import ch.offgrid.android.link.int import ch.offgrid.android.link.isNull @@ -53,13 +56,21 @@ class Messaging( private val db: OffGridDatabase, private val antenna: AntennaManager, private val scope: CoroutineScope, + private val settings: Settings, private val onIncoming: (MessageEntity) -> Unit = {}, private val track: (AnalyticsEvent) -> Unit = {}, private val now: () -> Long = System::currentTimeMillis, ) : AntennaListener { private val sendMutex = Mutex() + + /** Held while refs are handed out, matched or reconciled, so an event never sees half an update. */ + private val refMutex = Mutex() private var currentDevice: String? = null + /** Link session whose refs `msg.status` events may update; null until the outbox was reconciled. */ + @Volatile + private var currentSession: String? = null + val conversations: Flow> = combine( db.contacts().observeAll(), db.groups().observeAll(), @@ -82,9 +93,16 @@ class Messaging( unread = unread.firstOrNull { it.groupId == g.id }?.n ?: 0, ) } - // Active conversations by last activity, pending contacts ("Schlüssel ausstehend") at the end. + // Active conversations by last activity, then contacts to pair again ("Neu koppeln"), then pending + // contacts ("Schlüssel ausstehend"). (contactItems + groupItems).sortedWith( - compareBy { it.contact?.state == "pending" }.thenByDescending { it.activity }, + compareBy { + when (it.contact?.state) { + UNPAIRED -> 1 + "pending" -> 2 + else -> 0 + } + }.thenByDescending { it.activity }, ) } @@ -99,26 +117,34 @@ class Messaging( // ------------------------------------------------------------------ sending + /** A text longer than one packet goes out as several messages, see [MessageLimits.split]. */ fun sendText(contactId: Long, text: String) = enqueue( - MessageEntity(contactId = contactId, direction = "out", kind = "text", text = text.trim(), - status = MessageStatus.LOCAL_QUEUED, sentAt = now()), + MessageLimits.split(text, antenna.state.value).map { + MessageEntity(contactId = contactId, direction = "out", kind = "text", text = it, status = MessageStatus.LOCAL_QUEUED, sentAt = now()) + }, ) + /** Group texts go out raw, at most `max_group_text_bytes` each (the lab codec does not apply to groups). */ fun sendGroupText(groupId: Long, text: String) = enqueue( - MessageEntity(groupId = groupId, direction = "out", kind = "text", text = text.trim(), - status = MessageStatus.LOCAL_QUEUED, sentAt = now()), + MessageLimits.splitRaw(text, antenna.state.value.groups?.maxTextBytes ?: MessageLimits.DEFAULT_MAX_TEXT_BYTES).map { + MessageEntity(groupId = groupId, direction = "out", kind = "text", text = it, status = MessageStatus.LOCAL_QUEUED, sentAt = now()) + }, ) fun sendLocation(contactId: Long, fix: GeoFix) = enqueue( - MessageEntity(contactId = contactId, direction = "out", kind = "geo", lat = fix.latitude, lon = fix.longitude, + listOf(MessageEntity(contactId = contactId, direction = "out", kind = "geo", lat = fix.latitude, lon = fix.longitude, accuracyM = fix.accuracyM, ageS = ((now() - fix.at) / 1000).toInt().coerceIn(0, 2550), - status = MessageStatus.LOCAL_QUEUED, sentAt = now()), + status = MessageStatus.LOCAL_QUEUED, sentAt = now())), ) fun retry(messageId: Long) { scope.launch { val m = db.messages().byId(messageId) ?: return@launch - db.messages().update(m.copy(status = MessageStatus.LOCAL_QUEUED, failReason = null, msgRef = null)) + // A new attempt: the antenna gives it a new ref and counter, the old outcome is forgotten. + db.messages().update( + m.copy(status = MessageStatus.LOCAL_QUEUED, failReason = null, msgRef = null, refSession = null, deviceState = null, + retry = null, hops = null, rttMs = null, compressed = null, bytesOnAir = null, airtimeMs = null), + ) flushQueue() } } @@ -126,38 +152,52 @@ class Messaging( fun markRead(contactId: Long) = scope.launch { db.messages().markContactRead(contactId, now()) } fun markGroupRead(groupId: Long) = scope.launch { db.messages().markGroupRead(groupId, now()) } - private fun enqueue(message: MessageEntity) { + /** Inserts in order (the queue sends by `sentAt`, then id), then hands them to the antenna. */ + private fun enqueue(messages: List) { + if (messages.isEmpty()) return track(AnalyticsEvent.MessageSent) scope.launch { - db.messages().insert(message) + messages.forEach { db.messages().insert(it) } flushQueue() } } - /** Hands every locally queued message to the device, oldest first. */ + /** Hands every locally queued message to the device, oldest first, once the outbox was reconciled. */ suspend fun flushQueue() = sendMutex.withLock { if (!antenna.state.value.ready) return@withLock + val session = currentSession ?: return@withLock + // Keys first: a group message is only readable for members who have the key. + if (!handOverSyncs(session)) return@withLock for (m in db.messages().localQueue()) { - if (!handOver(m)) break + if (!handOver(m, session)) break } } /** Returns false when the link went away; the message then stays queued locally. */ - private suspend fun handOver(m: MessageEntity): Boolean { + private suspend fun handOver(m: MessageEntity, session: String): Boolean { val args = argsFor(m) ?: run { - db.messages().update(m.copy(status = MessageStatus.FAILED, failReason = "no_contact")) + db.messages().update(m.copy(status = MessageStatus.FAILED, failReason = if (m.groupId != null) "no_group" else "no_contact")) return true } return try { val cmd = if (m.groupId != null) "group.send" else "msg.send" - val result = antenna.call(cmd, args) - db.messages().update( - m.copy(status = MessageStatus.DEVICE_QUEUED, msgRef = result.int("msg_ref"), ctr = result.int("ctr") ?: m.ctr), - ) + // Under refMutex: a msg.status event for the new ref waits until the ref is stored. + refMutex.withLock { + val result = antenna.call(cmd, args) + db.messages().update( + m.copy(status = MessageStatus.DEVICE_QUEUED, msgRef = result.int("msg_ref"), refSession = session, + ctr = result.int("ctr") ?: m.ctr, deviceState = result.str("state") ?: "queued", + compressed = result.bool("compressed"), bytesOnAir = result.int("bytes_on_air"), + airtimeMs = result.int("est_airtime_ms")), + ) + } true } catch (e: LinkCommandException) { when (e.error.code) { - "E_LOCKED", "E_QUEUE_FULL", "E_BUSY" -> false + // Passing states: the antenna locked, or its 8 slots are taken (waiting messages hold theirs + // up to 30 minutes). The message stays queued; a final msg.status or the next connect flushes again. + // E_BUSY means the counter is exhausted (Commands.cpp: "re-pair"), so it fails like other refusals. + "E_LOCKED", "E_QUEUE_FULL" -> false else -> { db.messages().update(m.copy(status = MessageStatus.FAILED, failReason = e.error.code)) true @@ -170,12 +210,54 @@ class Messaging( } } + /** Hands every queued `group.sync` to the device. Returns false when the link went away or its queue is full. */ + private suspend fun handOverSyncs(session: String): Boolean { + for (member in db.groups().queuedSyncs()) { + if (!handOverSync(member, session)) return false + } + return true + } + + private suspend fun handOverSync(m: GroupMemberEntity, session: String): Boolean { + val group = db.groups().byId(m.groupId)?.takeIf { it.deviceGroupId != NO_GROUP } + val contact = m.contactId?.let { db.contacts().byId(it) }?.takeIf { it.deviceContactId != NO_SLOT } + if (group == null || contact == null) { + db.groups().updateMember(GroupSync.failed(m, if (group == null) "no_group" else "no_contact")) + return true + } + return try { + refMutex.withLock { + val result = antenna.call("group.sync", buildJsonObject { + put("group_id", group.deviceGroupId); put("contact_id", contact.deviceContactId) + }) + val ref = result.int("msg_ref") + db.groups().updateMember(if (ref == null) GroupSync.failed(m, "failed") else GroupSync.pending(m, ref, session)) + } + true + } catch (e: LinkCommandException) { + when (e.error.code) { + // Like msg.send: a locked antenna or a full queue is passing, the sync stays queued. + "E_LOCKED", "E_QUEUE_FULL" -> false + else -> { + db.groups().updateMember(GroupSync.failed(m, e.error.code)) + true + } + } + } catch (_: LinkClosedException) { + false + } catch (_: LinkTimeoutException) { + false + } + } + private suspend fun argsFor(m: MessageEntity): JsonObject? { if (m.groupId != null) { - val g = db.groups().all().firstOrNull { it.id == m.groupId } ?: return null - return buildJsonObject { put("group_id", g.deviceGroupId); put("text", m.text) } + // Group messages are text only and have no receipt: the firmware rejects `ack`. + val g = db.groups().byId(m.groupId)?.takeIf { it.deviceGroupId != NO_GROUP } ?: return null + return buildJsonObject { put("group_id", g.deviceGroupId); put("type", "text"); put("text", m.text) } } - val c = m.contactId?.let { db.contacts().byId(it) } ?: return null + // A contact the antenna no longer holds has no slot to send to until it is paired again. + val c = m.contactId?.let { db.contacts().byId(it) }?.takeIf { it.deviceContactId != NO_SLOT } ?: return null return when (m.kind) { "geo" -> buildJsonObject { put("to", c.deviceContactId); put("type", "geo"); put("lat", m.lat); put("lon", m.lon) @@ -212,34 +294,46 @@ class Messaging( val name = displayName.trim() db.contacts().update(c.copy(displayName = name, firstName = firstName?.trim()?.ifEmpty { null }, lastName = lastName?.trim()?.ifEmpty { null })) - runCatching { - antenna.call("contact.rename", buildJsonObject { put("contact_id", c.deviceContactId); put("name", name) }) + if (c.deviceContactId != NO_SLOT) { + runCatching { + antenna.call("contact.rename", buildJsonObject { put("contact_id", c.deviceContactId); put("name", name) }) + } } } suspend fun deleteContact(id: Long) { val c = db.contacts().byId(id) ?: return - runCatching { - antenna.call("contact.delete", buildJsonObject { put("contact_id", c.deviceContactId); put("confirm", true) }) + if (c.deviceContactId != NO_SLOT) { + runCatching { + antenna.call("contact.delete", buildJsonObject { put("contact_id", c.deviceContactId); put("confirm", true) }) + } } db.messages().deleteForContact(id) db.contacts().delete(id) } /** - * "Alle Daten löschen": removes the contacts from the device too, otherwise the next - * `contact.list` sync would bring them back. Settings and the device identity stay. + * "Alle Daten löschen". With the antenna connected it is erased too, with the authenticated factory + * reset (link spec 6.11): contacts, keys and identity on the antenna go, and the app sets it up again + * for this phone. The local data is only deleted when the antenna confirmed, so a refused reset does + * not leave contacts on the antenna that the app no longer shows. Without an antenna only this phone + * is cleared. Settings stay. */ - suspend fun deleteAll() { - db.contacts().all().filter { it.deviceContactId != NO_SLOT }.forEach { c -> - runCatching { - antenna.call("contact.delete", buildJsonObject { put("contact_id", c.deviceContactId); put("confirm", true) }) - } + suspend fun deleteAll(): ResetResult { + val result = if (antenna.state.value.ready) antenna.factoryReset() else ResetResult.NOT_CONNECTED + if (result == ResetResult.DONE || result == ResetResult.NOT_CONNECTED) { + db.maintenance().clearAll() + settings.remove(Settings.REPAIR_NOTICE) } - db.maintenance().clearAll() + return result } - /** Proposed `group.create`; firmware without it answers `E_UNKNOWN_CMD`. */ + // ------------------------------------------------------------------ groups + + /** + * `group.create` on the antenna, then one `group.sync` per member in the outbox: until a member has the key + * ("Schlüssel zugestellt") it cannot read the group. Firmware without groups answers `E_UNKNOWN_CMD`. + */ suspend fun createGroup(name: String, contactIds: List): Result = runCatching { val contacts = contactIds.mapNotNull { db.contacts().byId(it) } val result = antenna.call("group.create", buildJsonObject { @@ -247,31 +341,169 @@ class Messaging( putJsonArray("members") { contacts.forEach { add(JsonPrimitive(it.deviceContactId)) } } }) val deviceId = antenna.state.value.deviceId ?: error("no device") - val id = db.groups().insert( - GroupEntity(deviceId = deviceId, deviceGroupId = result.int("group_id")!!, name = name.trim(), createdAt = now()), - ) - db.groups().insertMembers(contacts.map { GroupMemberEntity(id, it.id) }) + val id = storeGroup(deviceId, result.obj("group") ?: error("group.create returned no group"), queueSyncs = true) + scope.launch { flushQueue() } id } + /** `group.add` (owner only); the new epoch needs a fresh key for every member that stays. */ + suspend fun addMembers(groupId: Long, contactIds: List): Result = runCatching { + val group = db.groups().byId(groupId) ?: error("no group") + val contacts = contactIds.mapNotNull { db.contacts().byId(it) } + val result = antenna.call("group.add", buildJsonObject { + put("group_id", group.deviceGroupId) + putJsonArray("members") { contacts.forEach { add(JsonPrimitive(it.deviceContactId)) } } + }) + storeGroup(group.deviceId, result.obj("group") ?: error("group.add returned no group"), queueSyncs = true) + scope.launch { flushQueue() } + } + + /** + * `group.remove` (owner only) by member index. The removed member is not told and keeps the old key, but + * cannot read the new epoch, which every remaining member gets. + */ + suspend fun removeMember(groupId: Long, member: Int): Result = runCatching { + val group = db.groups().byId(groupId) ?: error("no group") + val result = antenna.call("group.remove", buildJsonObject { + put("group_id", group.deviceGroupId) + putJsonArray("members") { add(JsonPrimitive(member)) } + }) + storeGroup(group.deviceId, result.obj("group") ?: error("group.remove returned no group"), queueSyncs = true) + scope.launch { flushQueue() } + } + + /** "Erneut senden" for a key that was not delivered. */ + fun resendKey(groupId: Long, member: Int) { + scope.launch { + val m = db.groups().membersOf(groupId).firstOrNull { it.member == member } ?: return@launch + db.groups().updateMember(GroupSync.requeue(m)) + flushQueue() + } + } + + /** + * `group.delete` (this device only, the other members keep the group), then the local group and its history. + * A group the antenna no longer holds is removed without asking it. + */ + suspend fun deleteGroup(groupId: Long): Result = runCatching { + val group = db.groups().byId(groupId) ?: return@runCatching + if (group.deviceGroupId != NO_GROUP) { + try { + antenna.call("group.delete", buildJsonObject { put("group_id", group.deviceGroupId); put("confirm", true) }) + } catch (e: LinkCommandException) { + if (e.error.code != "E_NO_SUCH_GROUP") throw e + } + } + db.messages().deleteForGroup(groupId) + db.groups().deleteMembers(groupId) + db.groups().delete(groupId) + } + + /** + * Stores a device group object (link spec 6, "Groups") and returns the local group id. A slot that now holds + * another group (different `gid`) lets the old local group go: it keeps its history and loses its slot. Key + * states of members that stayed are kept; with [queueSyncs] (this phone changed the group) every member is + * queued for a new key instead, because the epoch changed. + */ + private suspend fun storeGroup(deviceId: String, g: JsonObject, queueSyncs: Boolean): Long { + val slot = g.int("group_id") ?: error("group without group_id") + val gid = g.str("gid").orEmpty() + val inSlot = db.groups().byDeviceGroup(deviceId, slot) + val existing = inSlot?.takeIf { it.gid == gid } + if (inSlot != null && existing == null) db.groups().update(inSlot.copy(deviceGroupId = NO_GROUP)) + val entity = (existing ?: GroupEntity(deviceId = deviceId, deviceGroupId = slot, name = "", createdAt = now())).copy( + name = g.str("name") ?: existing?.name.orEmpty(), gid = gid, epoch = g.int("epoch") ?: 1, owner = g.bool("owner") ?: false, + ) + val id = if (existing == null) db.groups().insert(entity) else entity.id.also { db.groups().update(entity) } + val own = g.int("member") ?: 0 + val before = db.groups().membersOf(id).associateBy { it.member } + val members = (g["members"] as? JsonArray).orEmpty().mapNotNull { it as? JsonObject }.mapNotNull { m -> + val index = m.int("member")?.takeIf { it != own } ?: return@mapNotNull null + val nodeId = m.str("node_id").orEmpty() + val contact = m.int("contact_id")?.let { db.contacts().bySlot(deviceId, it) } + val kept = before[index]?.takeIf { it.nodeId == nodeId } + val member = GroupMemberEntity(groupId = id, member = index, contactId = contact?.id, nodeId = nodeId) + when { + queueSyncs -> GroupSync.requeue(member) + kept != null -> member.copy(keyState = kept.keyState, syncRef = kept.syncRef, syncSession = kept.syncSession, + syncReason = kept.syncReason) + else -> member + } + } + db.groups().replaceMembers(id, members) + return id + } + + /** + * Mirrors the antenna's groups into the local table on connect: groups joined while the phone was away, + * changed epochs, and local groups of this device that it no longer holds (they keep their history and lose + * their slot, like [syncContacts] does for contacts). + */ + private suspend fun syncGroups(deviceId: String) { + if (antenna.state.value.groups == null) return + val list = runCatching { antenna.call("group.list") }.getOrNull() ?: return + val onDevice = (list["groups"] as? JsonArray).orEmpty().mapNotNull { it as? JsonObject } + for (g in onDevice) { + val slot = g.int("group_id") ?: continue + val local = db.groups().byDeviceGroup(deviceId, slot) + if (local != null && local.gid == g.str("gid") && local.epoch == g.int("epoch")) continue + val full = runCatching { antenna.call("group.get", buildJsonObject { put("group_id", slot) }) }.getOrNull()?.obj("group") ?: continue + storeGroup(deviceId, full, queueSyncs = false) + } + val slots = onDevice.mapNotNull { it.int("group_id") }.toSet() + db.groups().all().filter { it.deviceId == deviceId && it.deviceGroupId != NO_GROUP && it.deviceGroupId !in slots } + .forEach { db.groups().update(it.copy(deviceGroupId = NO_GROUP)) } + } + // ------------------------------------------------------------------ device callbacks override suspend fun onReady(antenna: AntennaManager, deviceId: String) { currentDevice = deviceId syncContacts(deviceId) + syncGroups(deviceId) + reconcileOutbox(deviceId) flushQueue() } + /** + * The antenna restarted while connected: its queue is gone (link spec 7.5), so every message it had + * is lost, and until the next [onReady] no ref is valid. + */ override suspend fun onDeviceRebooted() { - db.messages().failDeviceQueued() - db.messages().clearRefs() + val device = currentDevice ?: return + refMutex.withLock { + currentSession = null + OutboxReconciler.reconcile(db.messages().openOutgoing(), device, PendingSnapshot.EMPTY, session = "") + .forEach { db.messages().update(it) } + GroupSync.reconcile(db.groups().openSyncs(device), PendingSnapshot.EMPTY, session = "").forEach { db.groups().updateMember(it) } + } + } + + /** Settles messages of earlier link sessions with `msg.pending` and starts a new session (see [OutboxReconciler]). */ + private suspend fun reconcileOutbox(deviceId: String) = refMutex.withLock { + currentSession = null + val session = OutboxReconciler.newSession(deviceId) + val snapshot = try { + PendingSnapshot.parse(antenna.call("msg.pending")) + } catch (_: LinkCommandException) { + // Without the queue nothing can be settled; the messages keep their state until the next connect. + currentSession = session + return@withLock + } catch (_: LinkClosedException) { + return@withLock + } catch (_: LinkTimeoutException) { + return@withLock + } + OutboxReconciler.reconcile(db.messages().openOutgoing(), deviceId, snapshot, session).forEach { db.messages().update(it) } + GroupSync.reconcile(db.groups().openSyncs(deviceId), snapshot, session).forEach { db.groups().updateMember(it) } + currentSession = session } /** * Mirrors the device's contact slots (state, RSSI) into the local table. Local contacts of this - * device that it no longer lists fall back to `pending`: the current firmware mock keeps contacts - * in RAM only, so after a reset they must be paired again (pairing the same key reuses the row - * and its history). + * device that it no longer lists become [UNPAIRED]: the antenna was reset or reflashed (new vault, + * new identity) or the contact was deleted there. They keep their history and must be paired again; + * pairing the same key reuses the row. The count goes to [Settings.REPAIR_NOTICE] for the contact list. */ private suspend fun syncContacts(deviceId: String) { var offset = 0 @@ -288,9 +520,12 @@ class Messaging( offset += list.size if (list.isEmpty() || offset >= (page.int("total") ?: 0)) break } - db.contacts().all() - .filter { it.deviceId == deviceId && it.publicKey !in seen && it.deviceContactId != NO_SLOT } - .forEach { db.contacts().update(it.copy(state = "pending", deviceContactId = NO_SLOT)) } + val gone = db.contacts().all().filter { it.deviceId == deviceId && it.publicKey !in seen && it.deviceContactId != NO_SLOT } + gone.forEach { db.contacts().update(it.copy(state = UNPAIRED, deviceContactId = NO_SLOT)) } + if (gone.isNotEmpty()) { + val before = settings.get(Settings.REPAIR_NOTICE)?.toIntOrNull() ?: 0 + settings.put(Settings.REPAIR_NOTICE, (before + gone.size).toString()) + } } /** Stores a device contact object (link spec 7.4). Returns the local contact id. */ @@ -309,7 +544,7 @@ class Messaging( displayName = if (keepName && existing != null) existing.displayName else json.str("name") ?: base.displayName, fingerprint = json.str("fingerprint") ?: base.fingerprint, state = json.str("state") ?: base.state, - lastRssi = json.int("last_rssi") ?: base.lastRssi, + lastRssi = json.dbm("last_rssi") ?: base.lastRssi, lastSnr = json.double("last_snr") ?: base.lastSnr, ) return if (existing == null) db.contacts().insert(updated) else updated.id.also { db.contacts().update(updated) } @@ -320,6 +555,8 @@ class Messaging( when (event.name) { "msg.status" -> onStatus(d) "msg.received" -> onReceived(d) + "group.received" -> onGroupReceived(d) + "group.state" -> onGroupState(d) "contact.state" -> { val c = contactForSlot(d.int("contact_id")) ?: return db.contacts().update(c.copy(state = d.str("state") ?: c.state, lastSeenAt = now())) @@ -333,34 +570,37 @@ class Messaging( } private suspend fun onStatus(d: JsonObject) { - val m = d.int("msg_ref")?.let { db.messages().byMsgRef(it) } ?: return - val status = when (d.str("state")) { - "queued" -> MessageStatus.DEVICE_QUEUED - "sent", "relayed", "retrying" -> MessageStatus.SENT - "delivered" -> MessageStatus.DELIVERED - "failed", "cancelled" -> MessageStatus.FAILED - else -> return + val ref = d.int("msg_ref") ?: return + val state = d.str("state") ?: return + val updated = refMutex.withLock { + // Only refs of the current session: a ref from an earlier boot must never touch a newer message. + val session = currentSession ?: return + // A `group.sync` is an acknowledged direct message to one member: its state is the member's key state. + db.groups().bySyncRef(ref, session)?.let { member -> + if (GroupSync.applyEvent(member, state, d.str("reason"))?.also { db.groups().updateMember(it) } != null) { + scope.launch { flushQueue() } + } + return + } + val m = db.messages().byMsgRef(ref, session) ?: return + OutboxReconciler.applyEvent(m, state, d.str("reason"), DeliveryDetails.parse(d))?.also { db.messages().update(it) } ?: return } - // Group messages have no end-to-end ACK, so "sent" is their final state. - val done = status == MessageStatus.DELIVERED || status == MessageStatus.FAILED || (m.groupId != null && status == MessageStatus.SENT) - db.messages().update(m.copy(status = status, failReason = d.str("reason"), msgRef = if (done) null else m.msgRef)) - if (status == MessageStatus.DELIVERED) { - m.contactId?.let { db.contacts().byId(it) }?.let { db.contacts().update(it.copy(lastSeenAt = now())) } + if (updated.status == MessageStatus.DELIVERED) { + updated.contactId?.let { db.contacts().byId(it) }?.let { db.contacts().update(it.copy(lastSeenAt = now())) } } + // A final state frees a slot in the antenna's queue; messages that met E_QUEUE_FULL can go now. + if (updated.msgRef == null) scope.launch { flushQueue() } } private suspend fun onReceived(d: JsonObject) { val c = contactForSlot(d.int("from")) ?: return - val rssi = d.int("rssi") + val rssi = d.dbm("rssi") db.contacts().update(c.copy(lastRssi = rssi ?: c.lastRssi, lastSnr = d.double("snr") ?: c.lastSnr, lastSeenAt = now())) - val groupSlot = d.int("group") - val group = groupSlot?.let { gs -> currentDevice?.let { db.groups().byDeviceGroup(it, gs) } } + // Group texts arrive as `group.received`, never here (link spec 10). val base = MessageEntity( - contactId = if (group == null) c.id else null, - groupId = group?.id, - senderContactId = if (group != null) c.id else null, - senderName = if (group != null) c.displayName else null, + contactId = c.id, direction = "in", kind = "text", status = MessageStatus.DELIVERED, ctr = d.int("ctr"), rssi = rssi, sentAt = now(), + snr = d.double("snr"), hops = d.int("hops"), retry = d.int("retry"), compressed = d.bool("compressed"), ) val message = when (d.str("type")) { "text" -> base.copy(text = d.str("text") ?: return) @@ -375,6 +615,40 @@ class Messaging( onIncoming(message.copy(id = id)) } + /** + * A text from a group member. `from` is the sender's contact slot, or null when the antenna has no contact for + * that NodeID; the sender is then known by `node_id` only. Groups are text only here, so a `geo` payload is dropped. + */ + private suspend fun onGroupReceived(d: JsonObject) { + val device = currentDevice ?: return + val group = d.int("group_id")?.let { db.groups().byDeviceGroup(device, it) } ?: return + if (d.str("type") != "text") return + val text = d.str("text") ?: return + val rssi = d.dbm("rssi") + val sender = contactForSlot(d.int("from"))?.also { + db.contacts().update(it.copy(lastRssi = rssi ?: it.lastRssi, lastSnr = d.double("snr") ?: it.lastSnr, lastSeenAt = now())) + } + val nodeId = d.str("node_id") + val message = MessageEntity( + groupId = group.id, senderContactId = sender?.id, senderName = sender?.displayName ?: nodeId, senderNodeId = nodeId, + direction = "in", kind = "text", text = text, status = MessageStatus.DELIVERED, ctr = d.int("ctr"), rssi = rssi, + snr = d.double("snr"), hops = d.int("hops"), retry = d.int("retry"), sentAt = now(), + ) + val id = db.messages().insert(message) + onIncoming(message.copy(id = id)) + } + + /** + * The owner's sync was applied on the antenna (`joined` or `updated`): read the group, its members and its + * epoch with `group.get`. A group this phone did not know yet is created. + */ + private suspend fun onGroupState(d: JsonObject) { + val device = currentDevice ?: return + val slot = d.int("group_id") ?: return + val group = runCatching { antenna.call("group.get", buildJsonObject { put("group_id", slot) }) }.getOrNull()?.obj("group") ?: return + storeGroup(device, group, queueSyncs = false) + } + /** A reaction targets my message (`author: "me"`) by the low 16 bits of its counter. */ private suspend fun onReaction(c: ContactEntity, d: JsonObject) { val target = d.obj("target") ?: return @@ -388,6 +662,12 @@ class Messaging( /** Slot of a contact the device no longer holds (device slots are 1 to 32). */ const val NO_SLOT = 0 + /** Slot of a group the device no longer holds (device slots are 1 to 8). */ + const val NO_GROUP = 0 + + /** Local contact state: the antenna lost this contact's keys (reset, reflash); pair again. */ + const val UNPAIRED = "unpaired" + /** Empty "remove my reaction" packet after pairing; the peer's first valid packet activates the contact. */ fun pingArgs(slot: Int) = buildJsonObject { put("to", slot); put("type", "reaction") diff --git a/native-android/app/src/main/java/ch/offgrid/android/domain/OutboxReconciler.kt b/native-android/app/src/main/java/ch/offgrid/android/domain/OutboxReconciler.kt new file mode 100644 index 0000000..a8193f7 --- /dev/null +++ b/native-android/app/src/main/java/ch/offgrid/android/domain/OutboxReconciler.kt @@ -0,0 +1,146 @@ +package ch.offgrid.android.domain + +import ch.offgrid.android.data.MessageEntity +import ch.offgrid.android.data.MessageStatus +import ch.offgrid.android.link.int +import ch.offgrid.android.link.str +import kotlinx.serialization.json.JsonArray +import kotlinx.serialization.json.JsonObject +import java.util.UUID + +/** One `msg.pending` item or `recent` entry. */ +data class DeviceMessage(val ref: Int, val state: String, val reason: String? = null, val ctr: Int? = null, val retry: Int? = null) + +/** + * What a `msg.status` event or a queue item tells about the transport of an outgoing message: the retries so + * far and, once delivered, the hops the ACK reported and the time to it (link spec 7.3, lab.3). + */ +data class DeliveryDetails(val retry: Int? = null, val hops: Int? = null, val rttMs: Int? = null) { + fun applyTo(m: MessageEntity): MessageEntity = + m.copy(retry = retry ?: m.retry, hops = hops ?: m.hops, rttMs = rttMs ?: m.rttMs) + + companion object { + fun parse(d: JsonObject) = DeliveryDetails(d.int("retry"), d.int("hops"), d.int("rtt_ms")) + } +} + +/** + * A `msg.pending` result: what the antenna still has in its queue and, on the lab image, the last 16 + * messages that reached a final state since it booted (`recent`, newest first). + */ +data class PendingSnapshot(val pending: List, val recent: List) { + companion object { + val EMPTY = PendingSnapshot(emptyList(), emptyList()) + + fun parse(result: JsonObject): PendingSnapshot { + fun list(key: String) = (result[key] as? JsonArray).orEmpty().mapNotNull { item -> + val o = item as? JsonObject ?: return@mapNotNull null + DeviceMessage(o.int("msg_ref") ?: return@mapNotNull null, o.str("state") ?: return@mapNotNull null, o.str("reason"), + o.int("ctr"), o.int("retry")) + } + return PendingSnapshot(list("pending"), list("recent")) + } + } +} + +/** + * Keeps the local delivery state of outgoing messages in step with the antenna (lab contract item 5). + * + * A `msg_ref` means something only on one antenna and within one boot of it, and `msg.status` events + * are lost while the phone is not connected. So every message the antenna accepted carries the link + * session it was confirmed in ([MessageEntity.refSession]); events only update messages of the current + * session, and on every (re)connect [reconcile] settles the messages of earlier sessions against + * `msg.pending`: + * + * - still in the queue: take over its state (never backwards) and move it into the new session; + * - in `recent`: apply the final state the event would have brought; a delivery found this way is marked + * [MessageEntity.deliveredOffline] ("zugestellt, während offline"); + * - neither: the antenna lost it (restart, older image without `recent`, or more than 16 outcomes + * since), so it fails with reason [REASON_LOST] and the user can send it again. The app never resends + * on its own: the receiver could already have it, and a resend gets a new counter. + * + * A message that reaches a final state drops its ref and session, so an old ref can never touch it again. + */ +object OutboxReconciler { + /** The antenna no longer knows the message; shown as "Nicht zugestellt". */ + const val REASON_LOST = "lost" + + fun newSession(deviceId: String): String = "$deviceId/${UUID.randomUUID()}" + + private fun deviceOf(session: String): String = session.substringBefore('/') + + /** Local status for a `msg.status` / `msg.pending` state, null for states this app does not know. */ + fun statusFor(state: String): Int? = when (state) { + "queued" -> MessageStatus.DEVICE_QUEUED + "sent", "relayed", "retrying" -> MessageStatus.SENT + "waiting" -> MessageStatus.WAITING + "delivered" -> MessageStatus.DELIVERED + "failed", "cancelled" -> MessageStatus.FAILED + else -> null + } + + /** Order of the open states; a late event must not move a message back (waiting, then a stale "sent"). */ + private fun rank(status: Int): Int = when (status) { + MessageStatus.DEVICE_QUEUED -> 1 + MessageStatus.SENT -> 2 + MessageStatus.WAITING -> 3 + else -> 0 + } + + /** + * Applies a device state from a `msg.status` event to [m]. Returns the new row, or null when nothing + * changes. Group messages have no end-to-end ACK, so "sent" is final for them. Within the same rank the + * device state and the [details] still update (`sent`, then `retrying` with a higher retry count). + */ + fun applyEvent(m: MessageEntity, state: String, reason: String?, details: DeliveryDetails = DeliveryDetails()): MessageEntity? { + if (rank(m.status) == 0) return null // already final, or not yet with the antenna + val status = statusFor(state) ?: return null + val final = status == MessageStatus.DELIVERED || status == MessageStatus.FAILED || + (m.groupId != null && status == MessageStatus.SENT) + if (final) return details.applyTo(finished(m, status, state, reason)) + if (rank(status) < rank(m.status)) return null + return details.applyTo(m.copy(status = status, failReason = null, deviceState = state)).takeIf { it != m } + } + + private fun finished(m: MessageEntity, status: Int, state: String, reason: String?): MessageEntity = m.copy( + status = status, + failReason = if (status == MessageStatus.FAILED) (if (state == "cancelled") "cancelled" else reason ?: "failed") else null, + deviceState = state, + msgRef = null, + refSession = null, + ) + + /** + * Settles the [open] messages (accepted by an antenna, no final state) against [snapshot], the + * `msg.pending` answer of antenna [deviceId] at the start of link session [session]. Messages of other + * antennas stay as they are. Returns only the rows that changed. + * + * Rows from before refs had a session (database version 1) cannot prove which boot their ref belongs + * to; they only stay open when a queue item has the same ref and the same counter. + */ + fun reconcile(open: List, deviceId: String, snapshot: PendingSnapshot, session: String): List { + val pending = snapshot.pending.associateBy { it.ref } + val recent = snapshot.recent.associateBy { it.ref } + return open.mapNotNull { m -> + val ref = m.msgRef ?: return@mapNotNull null + val legacy = m.refSession == null + if (!legacy && deviceOf(m.refSession!!) != deviceId) return@mapNotNull null + val queued = pending[ref]?.takeIf { !legacy || (it.ctr != null && it.ctr == m.ctr) } + val done = recent[ref]?.takeIf { !legacy } + val updated = when { + queued != null -> { + val next = applyEvent(m, queued.state, queued.reason, DeliveryDetails(retry = queued.retry)) ?: m + if (next.msgRef == null) next else next.copy(refSession = session) + } + done != null -> statusFor(done.state)?.let { + finished(m, it, done.state, done.reason).copy(deliveredOffline = it == MessageStatus.DELIVERED) + } ?: lost(m) + else -> lost(m) + } + updated.takeIf { it != m } + } + } + + fun lost(m: MessageEntity): MessageEntity = + m.copy(status = MessageStatus.FAILED, failReason = REASON_LOST, msgRef = null, refSession = null) +} diff --git a/native-android/app/src/main/java/ch/offgrid/android/domain/Pairing.kt b/native-android/app/src/main/java/ch/offgrid/android/domain/Pairing.kt index 260fbbe..3a986e5 100644 --- a/native-android/app/src/main/java/ch/offgrid/android/domain/Pairing.kt +++ b/native-android/app/src/main/java/ch/offgrid/android/domain/Pairing.kt @@ -2,7 +2,6 @@ package ch.offgrid.android.domain import ch.offgrid.android.analytics.AnalyticsEvent import ch.offgrid.android.crypto.OgCrypto -import ch.offgrid.android.data.OffGridDatabase import ch.offgrid.android.link.LinkClosedException import ch.offgrid.android.link.LinkCommandException import ch.offgrid.android.link.LinkTimeoutException @@ -15,19 +14,32 @@ import kotlinx.coroutines.delay import kotlinx.coroutines.flow.MutableStateFlow import kotlinx.coroutines.flow.StateFlow import kotlinx.coroutines.flow.asStateFlow -import kotlinx.coroutines.flow.filterNotNull +import kotlinx.coroutines.flow.Flow import kotlinx.coroutines.flow.first import kotlinx.coroutines.flow.update import kotlinx.coroutines.launch +import kotlinx.coroutines.withTimeoutOrNull +import kotlinx.serialization.json.JsonObject import kotlinx.serialization.json.buildJsonObject import kotlinx.serialization.json.put -enum class PairingError { INVALID_QR, ANTENNA_NOT_READY, CONTACT_EXISTS, SELF_PAIR, FAILED } +enum class PairingError { + INVALID_QR, ANTENNA_NOT_READY, CONTACT_EXISTS, SELF_PAIR, FAILED, + + /** The antenna refused a second `pair.complete` with the same peer code (no key and counter reuse). */ + CODE_USED, +} data class PairingState( /** QR text from `pair.begin`; rendered as the QR code. */ val qr: String? = null, + /** Increases with every `pair.begin` answer the screen shows, also when the code stayed the same. */ + val codeVersion: Int = 0, + /** The shown code was replaced after someone may already have scanned the old one: they must scan again. */ + val codeRenewed: Boolean = false, val error: PairingError? = null, + /** With [PairingError.CONTACT_EXISTS]: the scanned code, to pair again with `replace: true`. */ + val replaceCode: String? = null, /** Set after we scanned the other side. */ val scannedName: String? = null, val scannedContactId: Long? = null, @@ -38,23 +50,35 @@ data class PairingState( ) /** - * QR key exchange as in link spec 7.4. Both people show their code (`pair.begin`) and scan the - * other one (`pair.complete`). The contact is `pending` until the first valid packet from the peer; - * to make that happen right away, the app sends an empty reaction as a ping (see README). + * QR key exchange as in link spec 5. Both people show their code (`pair.begin`) and scan the other one + * (`pair.complete`) from the same pairing session; the contact is `pending` until the first authenticated + * packet from the peer. To make that happen right away, the app sends an empty reaction as a ping. + * + * The code on screen must belong to the session the antenna completes with. Nils' firmware draws a new salt on + * every `pair.begin` and the lab image only within its 5-minute window, so this class keeps the session of the + * last `pair.begin` and shows it again when the screen is opened again, instead of asking for a new one. It is + * renewed only when less than a minute is left, after a lock or restart of the antenna (the salt is gone), or + * when the antenna says it is gone (`E_NO_PAIRING`). Leaving the screen does not cancel it. */ class Pairing( private val antenna: AntennaManager, - private val messaging: Messaging, - private val db: OffGridDatabase, + private val store: Store, private val scope: CoroutineScope, private val track: (AnalyticsEvent) -> Unit = {}, + private val now: () -> Long = System::currentTimeMillis, ) { private val _state = MutableStateFlow(PairingState()) val state: StateFlow = _state.asStateFlow() private var refreshJob: Job? = null private var watchJob: Job? = null - /** Requests a fresh QR from the device and refreshes it shortly before the 300 s expiry. */ + /** The antenna's pairing session behind [PairingState.qr]. */ + private data class Session(val qr: String, val expiresAt: Long, val unlockCount: Int, val deviceId: String?) + + @Volatile + private var session: Session? = null + + /** Shows this antenna's code: the open session when it is still good, else a new one. */ fun begin() { track(AnalyticsEvent.PairingStarted) refreshJob?.cancel() @@ -64,19 +88,53 @@ class Pairing( _state.update { it.copy(error = PairingError.ANTENNA_NOT_READY) } antenna.state.first { it.ready } } - val result = runCatching { antenna.call("pair.begin") }.getOrNull() - if (result == null) { + val current = try { + currentSession() + } catch (_: LinkCommandException) { + null + } catch (_: LinkClosedException) { + null + } catch (_: LinkTimeoutException) { + null + } + if (current == null) { delay(1_000) continue } - _state.update { it.copy(qr = result.str("qr"), error = null) } - // Spec: do not refresh between being scanned and scanning back; 280 s leaves room for that. - delay(((result.int("expires_s") ?: 300) - 20) * 1_000L) + _state.update { + it.copy(qr = current.qr, codeVersion = it.codeVersion + 1, error = it.error.takeIf { e -> e != PairingError.ANTENNA_NOT_READY }) + } + // Renew a minute before the end; after our own scan never, the peer may still scan this code. + withTimeoutOrNull((current.expiresAt - RENEW_BEFORE_MS - now()).coerceAtLeast(1_000)) { + _state.first { it.scannedName != null } + } + if (_state.value.scannedName != null) return@launch } } } - fun complete(qrText: String) { + private fun usable(s: Session?): Boolean { + val a = antenna.state.value + return s != null && s.unlockCount == a.unlockCount && s.deviceId == a.deviceId && s.expiresAt - now() > RENEW_BEFORE_MS + } + + private suspend fun currentSession(): Session = session.takeIf(::usable) ?: newSession() + + private suspend fun newSession(): Session { + val result = antenna.call("pair.begin") + val a = antenna.state.value + return Session(result.str("qr")!!, now() + (result.int("expires_s") ?: 300) * 1_000L, a.unlockCount, a.deviceId) + .also { session = it } + } + + /** + * Completes with the scanned [qrText]. When the antenna has no session any more (`E_NO_PAIRING`: expired, + * locked, or the firmware ended it after an earlier completion), it gets a fresh one, the screen shows the new + * code, and the completion is tried once more. A second refusal means the antenna does not take the same peer + * code twice: the peer has to open a new code. [replace] re-pairs a contact the antenna already has; both sides + * have to do that (link spec 5). + */ + fun complete(qrText: String, replace: Boolean = false) { scope.launch { val qr = qrText.trim() if (!looksLikeOffGridQr(qr)) { @@ -87,18 +145,32 @@ class Pairing( _state.update { it.copy(error = PairingError.ANTENNA_NOT_READY) } return@launch } + val args = buildJsonObject { + put("qr", qr) + if (replace) put("replace", true) + } try { val result = try { - antenna.call("pair.complete", buildJsonObject { put("qr", qr) }) + antenna.call("pair.complete", args) } catch (e: LinkCommandException) { if (e.error.code != "E_NO_PAIRING") throw e - antenna.call("pair.begin") - antenna.call("pair.complete", buildJsonObject { put("qr", qr) }) + renewSession() + try { + antenna.call("pair.complete", args) + } catch (again: LinkCommandException) { + if (again.error.code == "E_NO_PAIRING") { + _state.update { it.copy(error = PairingError.CODE_USED) } + return@launch + } + throw again + } } val contactJson = result.obj("contact")!! val deviceId = antenna.state.value.deviceId!! - val id = messaging.upsertFromDevice(deviceId, contactJson, keepName = false) - _state.update { it.copy(error = null, scannedName = contactJson.str("name"), scannedContactId = id, pingSent = false) } + val id = store.save(deviceId, contactJson) + _state.update { + it.copy(error = null, replaceCode = null, scannedName = contactJson.str("name"), scannedContactId = id, pingSent = false) + } watchConfirmation(id) // The contact is stored at this point; the ping only speeds up activation. Firmware that // rejects it (the team image up to ed9fd57 refuses every reaction, see docs/hardware.md) @@ -112,12 +184,15 @@ class Pairing( _state.update { it.copy(pingSent = pinged) } } catch (e: LinkCommandException) { _state.update { - it.copy(error = when (e.error.code) { - "E_INVALID_QR" -> PairingError.INVALID_QR - "E_CONTACT_EXISTS" -> PairingError.CONTACT_EXISTS - "E_SELF_PAIR" -> PairingError.SELF_PAIR - else -> PairingError.FAILED - }) + it.copy( + error = when (e.error.code) { + "E_INVALID_QR" -> PairingError.INVALID_QR + "E_CONTACT_EXISTS" -> PairingError.CONTACT_EXISTS + "E_SELF_PAIR" -> PairingError.SELF_PAIR + else -> PairingError.FAILED + }, + replaceCode = qr.takeIf { e.error.code == "E_CONTACT_EXISTS" }, + ) } } catch (_: LinkClosedException) { _state.update { it.copy(error = PairingError.ANTENNA_NOT_READY) } @@ -127,26 +202,55 @@ class Pairing( } } + /** `pair.cancel` and `pair.begin`: a new salt, shown at once; whoever scanned the old code must scan again. */ + private suspend fun renewSession() { + runCatching { antenna.call("pair.cancel") } + val shown = _state.value.qr + val fresh = newSession() + _state.update { it.copy(qr = fresh.qr, codeVersion = it.codeVersion + 1, codeRenewed = shown != null && shown != fresh.qr) } + } + private fun watchConfirmation(contactId: Long) { watchJob?.cancel() watchJob = scope.launch { - db.contacts().observe(contactId).filterNotNull().first { it.state == "active" } + store.contactState(contactId).first { it == "active" } _state.update { it.copy(confirmedContactId = contactId) } track(AnalyticsEvent.PairingCompleted) } } - /** Leaves the screen: discard the pending pairing on the device (spec `pair.cancel`). */ - fun cancel() { + /** + * Leaves the screen without a finished pairing. The session stays open on the antenna (it ends by itself after + * 5 minutes), so opening the screen again shows the same code to someone who already scanned it. + */ + fun leave() { refreshJob?.cancel() watchJob?.cancel() _state.value = PairingState() + } + + /** Both sides scanned and the peer's packet arrived: end the session on the antenna (`pair.cancel`). */ + fun finish() { + leave() + session = null scope.launch { runCatching { antenna.call("pair.cancel") } } } - fun clearError() = _state.update { it.copy(error = null) } + fun clearError() = _state.update { it.copy(error = null, replaceCode = null) } + + /** Where paired contacts go: [Messaging.upsertFromDevice] and the contacts table in the app. */ + interface Store { + /** Stores the `pair.complete` contact object and returns the local contact id. */ + suspend fun save(deviceId: String, contact: JsonObject): Long + + /** The local contact's state (`pending`, `active`, …), null while it does not exist. */ + fun contactState(contactId: Long): Flow + } companion object { + /** A code is renewed when less than this is left, like the lab image's salt window. */ + const val RENEW_BEFORE_MS = 60_000L + /** Cheap local check before bothering the device: Base64 of "OG1" + 32 B key + 16 B salt + name. */ fun looksLikeOffGridQr(text: String): Boolean { val raw = runCatching { OgCrypto.unb64(text) }.getOrNull() ?: return false diff --git a/native-android/app/src/main/java/ch/offgrid/android/domain/Settings.kt b/native-android/app/src/main/java/ch/offgrid/android/domain/Settings.kt index 0509482..7c4d3bb 100644 --- a/native-android/app/src/main/java/ch/offgrid/android/domain/Settings.kt +++ b/native-android/app/src/main/java/ch/offgrid/android/domain/Settings.kt @@ -30,9 +30,15 @@ class Settings(private val dao: SettingDao, scope: CoroutineScope) { const val INSTALL_ID = "install_id" const val BG_RECEIVE = "bg_receive" const val VIBRATE = "vibrate" + + /** Shows "Erweitert" for boards on the team firmware too; lab boards always show it. */ + const val SHOW_ADVANCED = "show_advanced" const val LINK_KIND = "link_kind" const val OWN_PUBLIC_KEY = "own_public_key" + /** Number of contacts the antenna lost (reset or reflash) that the contact list still has to point out. */ + const val REPAIR_NOTICE = "repair_notice" + /** Unlock token restored from a backup, used once to take over the antenna, then rotated. */ const val TRANSFER_TOKEN = "transfer_token" const val TRANSFER_DEVICE = "transfer_device" diff --git a/native-android/app/src/main/java/ch/offgrid/android/link/LinkClient.kt b/native-android/app/src/main/java/ch/offgrid/android/link/LinkClient.kt index 4d0bf45..743cb95 100644 --- a/native-android/app/src/main/java/ch/offgrid/android/link/LinkClient.kt +++ b/native-android/app/src/main/java/ch/offgrid/android/link/LinkClient.kt @@ -23,8 +23,8 @@ class LinkClosedException(cause: Throwable? = null) : Exception("link closed", c * Request/response client for the JSON Lines link protocol on top of an open [LinkSession]. * * - Request ids are chosen here and matched against responses (spec 4.1/4.2). - * - At most 4 requests are in flight (spec 4.4). - * - Timeouts: 2 s for normal commands, 5 s for vault commands (spec 4.4). + * - One request is in flight at a time (link spec 1); the timeout starts when it is written. + * - Timeouts: 2 s for normal commands, 5 s for commands that write the vault or settings. * - Events are delivered through [events] in arrival order. The consumer must not call [call] from * inside the reader, which is why events go through a channel instead of a callback. */ @@ -104,8 +104,13 @@ class LinkClient( } companion object { - const val MAX_IN_FLIGHT = 4 - private val VAULT_COMMANDS = setOf("pair.complete", "contact.delete") + /** Link spec 1: one request in flight at a time is recommended; others wait for the line, not for a timeout. */ + const val MAX_IN_FLIGHT = 1 + /** Commands that write the vault or NVS on the antenna and can take longer than a plain read. */ + private val VAULT_COMMANDS = setOf( + "pair.complete", "contact.delete", "contact.rename", "id.set_name", "mesh.set", "radio.set", "lab.set", + "led.set", "sys.factory_reset", + ) fun timeoutFor(cmd: String): Long = if (cmd.startsWith("sec.") || cmd in VAULT_COMMANDS) 5_000 else 2_000 diff --git a/native-android/app/src/main/java/ch/offgrid/android/link/LinkCodec.kt b/native-android/app/src/main/java/ch/offgrid/android/link/LinkCodec.kt index f0a4316..7e45374 100644 --- a/native-android/app/src/main/java/ch/offgrid/android/link/LinkCodec.kt +++ b/native-android/app/src/main/java/ch/offgrid/android/link/LinkCodec.kt @@ -9,6 +9,7 @@ import kotlinx.serialization.json.booleanOrNull import kotlinx.serialization.json.buildJsonObject import kotlinx.serialization.json.contentOrNull import kotlinx.serialization.json.longOrNull +import kotlin.math.roundToInt /** Error object of a failed response (link spec 4.2). */ data class LinkError(val code: String, val message: String?, val field: String?) @@ -131,6 +132,11 @@ fun JsonObject.long(key: String): Long? = this[key]?.takeIf { it !is JsonNull }? fun JsonObject.int(key: String): Int? = long(key)?.toInt() fun JsonObject.double(key: String): Double? = (this[key] as? JsonPrimitive)?.takeIf { !it.isString && it !is JsonNull }?.content?.toDoubleOrNull() +/** + * A signal value in whole dB. The firmware writes RSSI as a float (`"rssi": -91.5`, `Contacts::View::rssi`), + * which [int] rejects as not an integer. + */ +fun JsonObject.dbm(key: String): Int? = double(key)?.roundToInt() fun JsonObject.bool(key: String): Boolean? = (this[key] as? JsonPrimitive)?.takeIf { !it.isString }?.booleanOrNull fun JsonObject.obj(key: String): JsonObject? = this[key] as? JsonObject fun JsonObject.isNull(key: String): Boolean = this[key] is JsonNull diff --git a/native-android/app/src/main/java/ch/offgrid/android/link/sim/SimState.kt b/native-android/app/src/main/java/ch/offgrid/android/link/sim/SimState.kt index b8d6e44..24af921 100644 --- a/native-android/app/src/main/java/ch/offgrid/android/link/sim/SimState.kt +++ b/native-android/app/src/main/java/ch/offgrid/android/link/sim/SimState.kt @@ -22,6 +22,16 @@ data class SimFlash( val bwKhz: Double = 125.0, val txPowerDbm: Int = 14, val lockTimeoutS: Int = 15, + /** Lab image `lab.set {text_codec}`, persisted like the lab settings in NVS. */ + val textCodec: String = "raw", + /** Lab image `lab.set {ignore_nodes}`: NodeIDs whose directly heard packets are dropped. */ + val ignoreNodes: List = emptyList(), + /** `mesh.set` fields (link spec 8), persisted like `og_cfg`. */ + val hopDefault: Int = 3, + val relayEnabled: Boolean = true, + val relayWhenLocked: Boolean = false, + val retries: Int = 3, + val cadEnabled: Boolean = true, ) @Serializable @@ -38,9 +48,24 @@ data class SimContact( val lastSnr: Double? = null, ) -/** Proposed link 1.1 extension, see README "Gruppen". */ +/** A member of a simulated group; [contactId] is null for a member the board holds no contact for. */ @Serializable -data class SimGroup(val groupId: Int, val name: String, val members: List) +data class SimGroupMember(val member: Int, val nodeId: String, val contactId: Int? = null) + +/** A group slot of the board (link spec 6, "Groups"). [ownMember] is 0 on the owner. */ +@Serializable +data class SimGroup( + val groupId: Int, + val gid: String, + val name: String, + val epoch: Int, + val owner: Boolean, + val ownMember: Int, + val members: List, + /** Contact slot of the owner on a joined group. */ + val ownerContactId: Int? = null, + val txCtr: Int = 0, +) /** * A simulated person with their own OffGrid node somewhere in radio range. Used to demo the whole diff --git a/native-android/app/src/main/java/ch/offgrid/android/link/sim/SimulatedHeltec.kt b/native-android/app/src/main/java/ch/offgrid/android/link/sim/SimulatedHeltec.kt index f0d2020..638da5a 100644 --- a/native-android/app/src/main/java/ch/offgrid/android/link/sim/SimulatedHeltec.kt +++ b/native-android/app/src/main/java/ch/offgrid/android/link/sim/SimulatedHeltec.kt @@ -2,6 +2,7 @@ package ch.offgrid.android.link.sim import ch.offgrid.android.crypto.OgCrypto import ch.offgrid.android.crypto.TokenWrap +import ch.offgrid.android.crypto.WrapPurpose import ch.offgrid.android.domain.MessageLimits import ch.offgrid.android.link.FramedLine import ch.offgrid.android.link.LineFramer @@ -10,6 +11,7 @@ import ch.offgrid.android.link.Request import ch.offgrid.android.link.bool import ch.offgrid.android.link.double import ch.offgrid.android.link.int +import ch.offgrid.android.link.long import ch.offgrid.android.link.obj import ch.offgrid.android.link.str import kotlinx.coroutines.CoroutineScope @@ -18,6 +20,7 @@ import kotlinx.coroutines.channels.Channel import kotlinx.coroutines.delay import kotlinx.coroutines.isActive import kotlinx.coroutines.launch +import kotlinx.coroutines.withTimeoutOrNull import kotlinx.serialization.json.JsonArray import kotlinx.serialization.json.JsonNull import kotlinx.serialization.json.JsonObject @@ -27,22 +30,56 @@ import kotlinx.serialization.json.buildJsonObject import kotlinx.serialization.json.put import kotlinx.serialization.json.putJsonArray import kotlinx.serialization.json.putJsonObject -import java.util.concurrent.atomic.AtomicInteger +import kotlin.random.Random private class CommandError(val code: String, message: String, val field: String? = null) : Exception(message) +/** Mesh timing of the simulated antenna. Defaults follow the lab.3 contract; tests shorten them. */ +data class SimTiming( + val firstTxMs: Long = 350, + val ackWaitMs: Long = 900, + val retryMs: Long = 2_000, + val retries: Int = 3, + /** Lab.3 item 5: after the last retry a message waits and is sent again this often ... */ + val resendMs: Long = 60_000, + /** ... or at once when its contact sends anything, until this long after it was queued; then `failed timeout`. */ + val parkMs: Long = 30 * 60_000L, + /** A `group.sync` takes this long to reach the member, and a simulated invitation to arrive, after the send. */ + val groupSyncMs: Long = 1_500, +) + +/** A message in the device's pending queue (`msg.pending` item). */ +private class SimPending(val ref: Int, val to: Int, val type: String, val ctr: Int?, val createdAt: Long, val group: Int? = null) { + var state = "queued" + var retry = 0 + var job: Job? = null + + /** A packet from the contact arrived: a waiting message is sent again at once. */ + val wake = Channel(Channel.CONFLATED) +} + +/** A final outcome kept for `msg.pending.recent` (lab.3 item 5). */ +private data class SimRecent(val ref: Int, val state: String, val reason: String?) + /** * In-process stand-in for the Heltec V3 firmware. It speaks the JSON Lines link protocol * byte-for-byte (requests in, responses and events out) and models the device states, the * vault unlock, pairing, the pending queue with ACKs and retries, and a few virtual peers. * + * With [labRadio] it behaves like our lab image 0.3.0-lab.3 (pairing salt kept per window, `waiting`, + * `recent`, `lab.*` with OGZ1 and the ignore list); without it like Nils' team firmware 0.3.0 (a new salt on + * every `pair.begin`, `failed timeout` after the retries, no `lab.*`). + * * It does not model the radio bytes (AES-CCM, flooding); those belong to the firmware. Peers are - * resolved logically, which is enough to exercise every app path without hardware. + * resolved logically, which is enough to exercise every app path without hardware. A peer whose NodeID is + * on the ignore list counts as out of range, as there are no relays in the simulation. */ class SimulatedHeltec( private val store: SimFlashStore, private val scope: CoroutineScope, private val clock: () -> Long = System::currentTimeMillis, + private val timing: SimTiming = SimTiming(), + val labRadio: Boolean = true, ) { private var flash: SimFlash = store.load() ?: SimFlash(deviceId = OgCrypto.hex(OgCrypto.randomBytes(6))) .also(store::save) @@ -52,11 +89,25 @@ class SimulatedHeltec( private var identityPrivate: ByteArray? = null private var session: Pair? = null // device_eph_private, nonce private var pairing: Pair? = null // salt, expiry + /** Lab: peer codes completed in the current window, with the time they may be used again. */ + private val usedPeerCodes = HashMap() private var failedUnlocks = 0 private var rateLimitedUntil = 0L private var lastActivity = clock() - private val msgRef = AtomicInteger(0) - private val pendingJobs = mutableMapOf() + /** Lab.3: `msg_ref` starts at a random value per boot, so a ref from an earlier boot never matches. */ + private var nextRef = randomRef() + private val pending = LinkedHashMap() + private val recent = ArrayDeque() + private var txPackets = 0 + private var groupRxCtr = 0 + private var rxPackets = 0 + private var acksReceived = 0 + private var retriesScheduled = 0 + private var resends = 0 + private var resetAuthorized = false + + /** Events of a command that the firmware writes after its response line. */ + private val afterResponseEvents = mutableListOf() private var output: Channel? = null private val framer = LineFramer(dropFirstPartialLine = false) private var watchdog: Job? = null @@ -89,6 +140,7 @@ class SimulatedHeltec( } fun receive(bytes: ByteArray) { + if (hung) return val lines = synchronized(lock) { framer.feed(bytes) } for (line in lines) { if (line !is FramedLine.Json) { @@ -109,7 +161,11 @@ class SimulatedHeltec( LinkCodec.encodeResponseError(request.id, e.code, e.message ?: e.code, e.field) } send(reply) - synchronized(lock) { afterResponse(request) } + synchronized(lock) { + afterResponseEvents.forEach(::send) + afterResponseEvents.clear() + afterResponse(request) + } } } @@ -121,6 +177,10 @@ class SimulatedHeltec( private fun emitEvent(name: String, data: JsonObject) = send(LinkCodec.encodeEvent(name, uptime(), data)) + private fun emitAfterResponse(name: String, data: JsonObject) { + afterResponseEvents += LinkCodec.encodeEvent(name, uptime(), data) + } + private fun startWatchdog() { if (watchdog?.isActive == true) return watchdog = scope.launch { @@ -145,10 +205,7 @@ class SimulatedHeltec( "sys.status" -> status() "sys.ping" -> buildJsonObject { put("uptime_ms", uptime()) } "sys.reboot" -> buildJsonObject { put("rebooting", true) } - "sys.factory_reset" -> { - if (a.str("confirm") != "ERASE") throw CommandError("E_CONFIRM_REQUIRED", "confirm must be ERASE", "confirm") - buildJsonObject { put("armed", true); put("expires_s", 10); put("action", "hold PRG button for 3 s") } - } + "sys.factory_reset" -> factoryReset(a) "sys.set_log_level" -> buildJsonObject { put("level", a.str("level") ?: "info") } "sec.provision" -> provision(a) "sec.unlock" -> unlock(a) @@ -185,27 +242,37 @@ class SimulatedHeltec( requireUnlocked() val c = contact(a) if (a.bool("confirm") != true) throw CommandError("E_CONFIRM_REQUIRED", "confirm must be true", "confirm") + pending.values.filter { it.to == c.contactId } + .forEach { finish(it, "failed", "contact_deleted", afterResponse = true, stop = true) } save(flash.copy(contacts = flash.contacts.filter { it.contactId != c.contactId })) buildJsonObject { put("deleted", true) } } "msg.send" -> msgSend(a) "msg.cancel" -> { requireUnlocked() - val ref = a.int("msg_ref") ?: throw CommandError("E_INVALID_ARG", "msg_ref missing", "msg_ref") - pendingJobs.remove(ref)?.cancel() + val ref = a.long("msg_ref")?.takeIf { it in 1..0xFFFFFFFFL } + ?: throw CommandError("E_INVALID_ARG", "msg_ref must be a positive integer", "msg_ref") + val p = pending[ref.toInt()] ?: throw CommandError("E_INVALID_ARG", "message is not pending", "msg_ref") + finish(p, "cancelled", null, afterResponse = true, stop = true) buildJsonObject { put("state", "cancelled") } } - "msg.pending" -> { requireUnlocked(); buildJsonObject { putJsonArray("pending") {} } } + "msg.pending" -> { requireUnlocked(); pendingJson() } "radio.get" -> radioJson() "radio.set" -> { requireUnlocked(); radioSet(a) } - "radio.stats" -> { requireUnlocked(); buildJsonObject { put("tx_packets", msgRef.get()); put("rx_packets", 0) } } - "mesh.get" -> buildJsonObject { - put("hop_default", 3); put("relay_enabled", true); put("relay_when_locked", false) - put("cad_enabled", true); put("retries", 3) - } + "radio.stats" -> { requireUnlocked(); radioStats(a.bool("reset") == true) } + "lab.get" -> { requireLab(); requireUnlocked(); labJson() } + "lab.set" -> { requireLab(); requireUnlocked(); labSet(a) } + "mesh.get" -> meshJson() + "mesh.set" -> { requireUnlocked(); meshSet(a) } "led.get" -> buildJsonObject { put("enabled", true); put("brightness", 128) } "group.create" -> groupCreate(a) + "group.list" -> groupList() + "group.get" -> { requireUnlocked(); buildJsonObject { put("group", groupJson(group(a), withMembers = true)) } } + "group.sync" -> groupSync(a) + "group.add" -> groupAdd(a) + "group.remove" -> groupRemove(a) "group.send" -> groupSend(a) + "group.delete" -> groupDelete(a) else -> throw CommandError("E_UNKNOWN_CMD", "unknown command ${r.cmd}", "cmd") } } @@ -214,33 +281,74 @@ class SimulatedHeltec( private fun afterResponse(r: Request) { when (r.cmd) { "sys.reboot" -> reboot("software") + "sys.factory_reset" -> if (resetAuthorized) eraseAndRestart() } } // ---------------------------------------------------------------- system and security + private val fwVersion: String get() = if (labRadio) FW_VERSION else TEAM_FW_VERSION + private fun bootData(reason: String) = buildJsonObject { - put("device_id", flash.deviceId); put("fw", FW_VERSION); put("proto", PROTO); put("state", state) - put("reset_reason", reason) + put("device_id", flash.deviceId); put("fw", fwVersion); put("proto", PROTO); put("state", state) + put("mock", false); put("radio_diagnostics", false); put("reset_reason", reason) } + /** A restart loses the RAM queue without any event; the app learns it from `sys.boot` and `msg.pending`. */ private fun reboot(reason: String) { - failAllPending("locked") + pending.values.forEach { it.job?.cancel() } + pending.clear() + recent.clear() + nextRef = randomRef() state = if (flash.provisioned) "locked" else "unprovisioned" identityPrivate = null session = null + pairing = null + usedPeerCodes.clear() + resetAuthorized = false bootAt = clock() emitEvent("sys.boot", bootData(reason)) } + /** + * Link spec 6.11 with `method: "app"`: the reset needs this phone's token wrapped with the reset label. + * The firmware locks, answers `{pending: true}`, erases `og_vault` and `og_cfg` and restarts unprovisioned. + */ + private fun factoryReset(a: JsonObject): JsonObject { + if (a.str("confirm") != "ERASE") throw CommandError("E_CONFIRM_REQUIRED", "confirm must be ERASE", "confirm") + val method = a.str("method") + if (a.containsKey("method") && method != "app" && method != "master") { + throw CommandError("E_INVALID_ARG", "method must be app or master", "method") + } + if (method == "master") throw CommandError("E_UNLOCK_FAILED", "the simulator has no master key") + authenticate(a, WrapPurpose.RESET) + lockVault("factory_reset") + resetAuthorized = true + return buildJsonObject { put("pending", true) } + } + + private fun eraseAndRestart() { + store.wipe() + // The virtual peers are people around the antenna, not part of its flash. + save(SimFlash(deviceId = flash.deviceId, peers = flash.peers)) + failedUnlocks = 0 + rateLimitedUntil = 0 + reboot("software") + } + private fun hello(): JsonObject { val ephPrivate = OgCrypto.x25519PrivateKey() val nonce = OgCrypto.randomBytes(16) session = ephPrivate to nonce return buildJsonObject { put("device", "heltec_wifi_lora_32_v3"); put("chip", "ESP32-S3"); put("device_id", flash.deviceId) - putJsonObject("fw") { put("version", FW_VERSION); put("build", "simulator") } - put("proto", PROTO); put("state", state) + putJsonObject("fw") { put("version", fwVersion); put("build", "simulator") } + put("proto", PROTO); put("state", state); put("mock", mockImage); put("radio_diagnostics", false) + putJsonArray("features") { add(JsonPrimitive("groups")) } + put("authentication", "x25519-aes256gcm"); put("config_storage", "nvs") + if (labRadio) { + put("lab_radio", true); put("text_codec", flash.textCodec) + } putJsonObject("session") { put("device_eph_pub", OgCrypto.b64(OgCrypto.x25519PublicKey(ephPrivate))) put("nonce", OgCrypto.b64(nonce)) @@ -248,34 +356,70 @@ class SimulatedHeltec( putJsonObject("limits") { put("max_line", 2048); put("max_contacts", 32) put("max_text_bytes", MessageLimits.DEFAULT_MAX_TEXT_BYTES); put("pending_queue", 8) + put("max_groups", MAX_GROUPS); put("max_group_members", MAX_GROUP_MEMBERS) + put("max_group_text_bytes", MessageLimits.DEFAULT_MAX_TEXT_BYTES) + if (labRadio) put("max_text_input_bytes", maxTextInputBytes()) } + putJsonObject("recovery") { put("master", "ECDSA-P256-SHA256"); put("app_wrap_label", "og-reset-wrap-v1") } } } + /** `sys.status` in every state (link spec 3). */ private fun status() = buildJsonObject { - put("state", state); put("uptime_ms", uptime()); put("reset_reason", "power_on") - put("heap_free", 172304); put("battery_mv", JsonNull) - putJsonObject("radio") { put("running", state == "unlocked"); put("relay_only", false) } + put("state", state); put("uptime_ms", uptime()) + put("heap_free", 172304); put("battery_mv", JsonNull); put("mock", false) + putJsonObject("radio") { + val relayOnly = state == "locked" && flash.relayEnabled && flash.relayWhenLocked + put("running", state == "unlocked" || relayOnly); put("relay_only", relayOnly); put("initialized", true); put("last_error", 0) + } + putJsonObject("storage") { + put("config_status", "loaded"); put("writable", true) + put("vault_status", if (flash.provisioned) "ready" else "missing"); put("generation", 1) + } + putJsonObject("security") { put("secure_boot", false); put("flash_encryption", false) } if (state == "unlocked") { - putJsonObject("queue") { put("pending", pendingJobs.size); put("capacity", 8) } putJsonObject("contacts") { put("used", flash.contacts.size); put("capacity", 32) } + putJsonObject("groups") { put("used", flash.groups.size); put("capacity", MAX_GROUPS) } + putJsonObject("queue") { put("pending", pending.size); put("capacity", 8); put("dropped_events", 0); put("dropped_acks", 0) } } - putJsonObject("security") { put("secure_boot", false); put("flash_encryption", false) } } /** Consumes the `sys.hello` session and returns the unwrapped token (spec 6.7: single use). */ - private fun consumeToken(a: JsonObject): ByteArray { + private fun consumeToken(a: JsonObject, purpose: WrapPurpose = WrapPurpose.UNLOCK): ByteArray { val (ephPrivate, nonce) = session ?: throw CommandError("E_NO_SESSION", "call sys.hello first") session = null val appPub = a.str("app_eph_pub") ?: throw CommandError("E_INVALID_ARG", "app_eph_pub missing", "app_eph_pub") val wrapped = a.str("wrapped_token") ?: throw CommandError("E_INVALID_ARG", "wrapped_token missing", "wrapped_token") return try { - TokenWrap.unwrap(OgCrypto.unb64(wrapped), OgCrypto.unhex(flash.deviceId), ephPrivate, OgCrypto.unb64(appPub), nonce) + TokenWrap.unwrap(OgCrypto.unb64(wrapped), OgCrypto.unhex(flash.deviceId), ephPrivate, OgCrypto.unb64(appPub), nonce, purpose) } catch (_: Exception) { throw CommandError("E_UNLOCK_FAILED", "unlock failed") } } + /** + * `Security::authenticate` for unlock and reset: every attempt consumes the session, the rate limit is + * checked before the envelope, and a wrong envelope or token counts as a failure. + */ + private fun authenticate(a: JsonObject, purpose: WrapPurpose) { + if (session == null) throw CommandError("E_NO_SESSION", "call sys.hello first") + if (clock() < rateLimitedUntil) { + session = null + throw CommandError("E_RATE_LIMITED", "too many failed attempts") + } + val token = try { + consumeToken(a, purpose) + } catch (e: CommandError) { + if (e.code == "E_UNLOCK_FAILED") registerFailure() + throw e + } + if (!flash.provisioned || vaultCheck(token, OgCrypto.unb64(flash.vaultSalt!!)) != flash.vaultCheck) { + registerFailure() + throw CommandError("E_UNLOCK_FAILED", "unlock failed") + } + failedUnlocks = 0 + } + private fun vaultCheck(token: ByteArray, salt: ByteArray): String = OgCrypto.b64(OgCrypto.sha256(OgCrypto.hkdfSha256(token, salt, "og-vault-v1".toByteArray(), 32))) @@ -290,7 +434,13 @@ class SimulatedHeltec( identityPrivate = identity state = "unlocked" emitLater("sec.state", buildJsonObject { put("state", "unlocked"); put("reason", "provision") }) - return identity().let { id -> buildJsonObject { id.forEach { (k, v) -> put(k, v) }; put("state", state) } } + return openedJson() + } + + /** Result of `sec.provision` and `sec.unlock` (link spec 4). */ + private fun openedJson() = buildJsonObject { + put("state", state); identity().forEach { (k, v) -> put(k, v) }; put("contacts", flash.contacts.size) + putJsonObject("radio") { put("running", true); put("relay_only", false); put("last_error", 0) } } private fun unlock(a: JsonObject): JsonObject { @@ -298,26 +448,12 @@ class SimulatedHeltec( "unprovisioned" -> throw CommandError("E_NOT_PROVISIONED", "device has no vault") "unlocked" -> throw CommandError("E_ALREADY_UNLOCKED", "already unlocked") } - if (clock() < rateLimitedUntil) throw CommandError("E_RATE_LIMITED", "too many failed unlocks") - val token = try { - consumeToken(a) - } catch (e: CommandError) { - if (e.code == "E_UNLOCK_FAILED") registerFailure() - throw e - } - if (vaultCheck(token, OgCrypto.unb64(flash.vaultSalt!!)) != flash.vaultCheck) { - registerFailure() - throw CommandError("E_UNLOCK_FAILED", "unlock failed") - } - failedUnlocks = 0 + authenticate(a, WrapPurpose.UNLOCK) identityPrivate = OgCrypto.unb64(flash.identityPrivate!!) state = "unlocked" lastActivity = clock() emitLater("sec.state", buildJsonObject { put("state", "unlocked"); put("reason", "unlock") }) - return buildJsonObject { - put("state", state); put("node_id", nodeId()); put("name", flash.name); put("contacts", flash.contacts.size) - putJsonObject("radio") { put("running", true); put("relay_only", false) } - } + return openedJson() } private fun registerFailure() { @@ -333,17 +469,23 @@ class SimulatedHeltec( val token = consumeToken(a) val salt = OgCrypto.randomBytes(16) save(flash.copy(vaultSalt = OgCrypto.b64(salt), vaultCheck = vaultCheck(token, salt))) - return buildJsonObject { put("rotated", true) } + return buildJsonObject { put("state", state); identity().forEach { (k, v) -> put(k, v) } } } private fun lockVault(reason: String) { if (state != "unlocked") return failAllPending("locked") + pairing = null identityPrivate = null state = "locked" emitEvent("sec.state", buildJsonObject { put("state", "locked"); put("reason", reason) }) } + /** Lab commands exist only on the lab image; the team firmware answers `E_UNKNOWN_CMD` (link spec 12). */ + private fun requireLab() { + if (!labRadio) throw CommandError("E_UNKNOWN_CMD", "unknown command", "cmd") + } + private fun requireUnlocked() { when (state) { "unprovisioned" -> throw CommandError("E_NOT_PROVISIONED", "device has no vault") @@ -368,20 +510,39 @@ class SimulatedHeltec( // ---------------------------------------------------------------- pairing and contacts + /** + * `pair.begin`. The lab image keeps one salt per 5-minute window and draws a new one only when less than 60 s + * are left, so opening the pairing screen again shows the same code; a completion ends it. Nils' firmware 0.3.0 draws a new salt on + * every call (link spec 5, "Starts/replaces the device's five-minute pairing session"). + */ private fun pairBegin(): JsonObject { requireUnlocked() - val salt = OgCrypto.randomBytes(16) - pairing = salt to clock() + 300_000 + val current = pairing + val now = clock() + val (salt, expiry) = if (labRadio && current != null && current.second - now > PAIR_RENEW_MS) { + current + } else { + OgCrypto.randomBytes(16) to now + PAIR_WINDOW_MS + } + pairing = salt to expiry val payload = "OG1".toByteArray() + publicKey() + salt + (flash.name ?: "").toByteArray() - return buildJsonObject { put("qr", OgCrypto.b64(payload)); put("qr_bytes", payload.size); put("expires_s", 300) } + return buildJsonObject { + put("qr", OgCrypto.b64(payload)); put("qr_bytes", payload.size); put("expires_s", ((expiry - now) / 1000).coerceAtLeast(1)) + } } + /** Salt of the open pairing session, for tests that check which code a completion used. */ + fun pairingSalt(): ByteArray? = synchronized(lock) { pairing?.first?.copyOf() } + private fun pairComplete(a: JsonObject): JsonObject { requireUnlocked() val (_, expiry) = pairing ?: throw CommandError("E_NO_PAIRING", "call pair.begin first") if (clock() > expiry) throw CommandError("E_NO_PAIRING", "pairing expired") val qr = a.str("qr") ?: throw CommandError("E_INVALID_ARG", "qr missing", "qr") val parsed = parseQr(qr) ?: throw CommandError("E_INVALID_QR", "bad QR payload", "qr") + // Lab: the same peer code is completed only once per window, so keys and counters are never reused. + usedPeerCodes.entries.removeAll { it.value < clock() } + if (labRadio && qr.trim() in usedPeerCodes) throw CommandError("E_NO_PAIRING", "peer code already used") val (peerPub, _, qrName) = parsed if (peerPub.contentEquals(publicKey())) throw CommandError("E_SELF_PAIR", "QR contains my own key") val pubB64 = OgCrypto.b64(peerPub) @@ -396,6 +557,9 @@ class SimulatedHeltec( fingerprint = OgCrypto.fingerprint(publicKey(), peerPub), ) save(flash.copy(contacts = flash.contacts.filter { it.contactId != id } + contact)) + // Success ends the pairing session (the lab image too since its salt fix of 2026-10-24). + pairing = null + usedPeerCodes[qr.trim()] = clock() + PAIR_WINDOW_MS val warnings = if (flash.contacts.count { it.nodeId == contact.nodeId } > 1) listOf("node_id_collision") else emptyList() if (peer != null && peer.scansBack && peer.inRange) { // The peer scans our code too and its app pings us; the first valid packet activates the contact. @@ -440,7 +604,8 @@ class SimulatedHeltec( private fun contactJson(c: SimContact) = buildJsonObject { put("contact_id", c.contactId); put("name", c.name); put("node_id", c.nodeId); put("public_key", c.publicKey) put("state", c.state); put("fingerprint", c.fingerprint); put("tx_ctr", c.txCtr) - put("rx_highest_ctr", c.rxHighestCtr); put("last_rssi", c.lastRssi); put("last_snr", c.lastSnr) + // The firmware reports RSSI as a float (`Contacts::View::rssi`), so the simulator does too. + put("rx_highest_ctr", c.rxHighestCtr); put("last_rssi", c.lastRssi?.toDouble()); put("last_snr", c.lastSnr) } // ---------------------------------------------------------------- messages @@ -455,10 +620,13 @@ class SimulatedHeltec( val text = a.str("text") ?: throw CommandError("E_INVALID_ARG", "text missing", "text") val n = MessageLimits.utf8Bytes(text) if (n == 0) throw CommandError("E_INVALID_ARG", "text is empty", "text") - if (n > MessageLimits.DEFAULT_MAX_TEXT_BYTES) { - throw CommandError("E_TOO_LONG", "text is $n bytes, max is ${MessageLimits.DEFAULT_MAX_TEXT_BYTES}", "text") + // Lab.3: with ogz1 up to 160 bytes are accepted; only texts over 83 bytes are compressed. + val max = maxTextInputBytes() + val onAir = MessageLimits.onAirTextBytes(text, codec(), max) + if (n > max || onAir > MessageLimits.DEFAULT_MAX_TEXT_BYTES) { + throw CommandError("E_TOO_LONG", "text is $n bytes, max is ${MessageLimits.DEFAULT_MAX_TEXT_BYTES} on air", "text") } - n + onAir } "reaction" -> { if (a.obj("target") == null) throw CommandError("E_INVALID_ARG", "target missing", "target") @@ -474,55 +642,154 @@ class SimulatedHeltec( } else -> throw CommandError("E_INVALID_ARG", "unknown type", "type") } - if (pendingJobs.size >= 8) throw CommandError("E_QUEUE_FULL", "pending queue is full") + if (pending.size >= 8) throw CommandError("E_QUEUE_FULL", "pending queue is full") val ack = a.bool("ack") ?: (type == "text") - val hops = a.int("hops") ?: 3 - val ref = msgRef.incrementAndGet() + val hops = a.int("hops") ?: flash.hopDefault + if (hops !in 0..7) throw CommandError("E_INVALID_ARG", "hops must be 0 to 7", "hops") val ctr = c.txCtr + 1 updateContact(c.copy(txCtr = ctr)) + val p = enqueue(c.contactId, type, ctr) val onAir = 17 + bodyBytes - pendingJobs[ref] = scope.launch { deliver(ref, c.contactId, ack, a, type) } + p.job = scope.launch { deliver(p, ack, a) } return buildJsonObject { - put("msg_ref", ref); put("ctr", ctr); put("ack_requested", ack); put("hops", hops); put("state", "queued") + put("msg_ref", p.ref); put("ctr", ctr); put("ack_requested", ack); put("hops", hops); put("state", "queued") put("bytes_on_air", onAir); put("est_airtime_ms", 120 + onAir * 4) + if (labRadio && type == "text") put("compressed", MessageLimits.utf8Bytes(a.str("text")!!) > MessageLimits.DEFAULT_MAX_TEXT_BYTES) } } - private fun status(ref: Int, to: Int, state: String, retry: Int, extra: JsonObjectBuilder.() -> Unit = {}) = - emitEvent("msg.status", buildJsonObject { - put("msg_ref", ref); put("to", to); put("state", state); put("retry", retry); extra() - }) + private fun enqueue(to: Int, type: String, ctr: Int?, group: Int? = null): SimPending { + val p = SimPending(nextRef++, to, type, ctr, clock(), group) + pending[p.ref] = p + return p + } + + private fun statusData(p: SimPending, reason: String?, extra: JsonObjectBuilder.() -> Unit = {}) = buildJsonObject { + put("msg_ref", p.ref) + if (p.to > 0) put("to", p.to) + if (p.group != null) put("group_id", p.group) + put("state", p.state); put("retry", p.retry) + if (reason != null) put("reason", reason) + extra() + } - private suspend fun deliver(ref: Int, to: Int, ack: Boolean, args: JsonObject, type: String) { - delay(350) - val peer = synchronized(lock) { peerFor(to) } - synchronized(lock) { status(ref, to, "sent", 0) } + /** Moves a pending message to a non-final state and reports it (`msg.status`). */ + private fun progress(p: SimPending, state: String, reason: String? = null): Boolean { + if (pending[p.ref] !== p) return false + p.state = state + if (state == "sent") txPackets++ + if (state == "retrying") { + txPackets++ + retriesScheduled++ + } + emitEvent("msg.status", statusData(p, reason)) + return true + } + + /** + * Ends a pending message: `msg.status`, then it leaves the queue and enters `recent` (newest first, 16). + * Callers outside the message's own coroutine pass [stop] so its delivery loop ends. + */ + private fun finish( + p: SimPending, + state: String, + reason: String?, + afterResponse: Boolean = false, + stop: Boolean = false, + extra: JsonObjectBuilder.() -> Unit = {}, + ) { + if (pending.remove(p.ref) !== p) return + if (stop) p.job?.cancel() + p.state = state + val data = statusData(p, reason, extra) + if (afterResponse) emitAfterResponse("msg.status", data) else emitEvent("msg.status", data) + recent.addFirst(SimRecent(p.ref, state, reason)) + while (recent.size > RECENT_CAPACITY) recent.removeLast() + } + + private fun pendingJson() = buildJsonObject { + putJsonArray("pending") { + pending.values.forEach { p -> + add(buildJsonObject { + put("msg_ref", p.ref); if (p.to > 0) put("to", p.to); if (p.group != null) put("group_id", p.group) + put("type", p.type); put("ctr", p.ctr) + put("state", p.state); put("retry", p.retry) + }) + } + } + if (labRadio) { + putJsonArray("recent") { + recent.forEach { r -> + add(buildJsonObject { put("msg_ref", r.ref); put("state", r.state); if (r.reason != null) put("reason", r.reason) }) + } + } + } + } + + /** + * MeshEngine with the lab.3 lost-message fix: `sent`, retries, then `waiting` (reason `no_ack`) with the + * same counter until the contact shows a sign of life or [SimTiming.resendMs] passed, and `failed timeout` + * [SimTiming.parkMs] after it was queued. + */ + private suspend fun deliver(p: SimPending, ack: Boolean, args: JsonObject) { + delay(timing.firstTxMs) + if (!synchronized(lock) { progress(p, "sent") }) return + if (p.type == "group_sync") delay(timing.groupSyncMs) if (!ack) { - synchronized(lock) { pendingJobs.remove(ref) } - if (peer != null && peer.inRange) reactTo(peer, to, args, type) + val peer = synchronized(lock) { + finish(p, "sent", null) + peerFor(p.to) + } + if (peer != null && reachable(peer)) reactTo(peer, p.to, args, p.type) return } - for (retry in 0..3) { - if (retry > 0) synchronized(lock) { status(ref, to, "retrying", retry) } - delay(if (retry == 0) 900 else 2_000) - val reachable = synchronized(lock) { - val p = peerFor(to) - p != null && p.inRange && p.scansBack && state == "unlocked" - } - if (reachable) { - synchronized(lock) { - status(ref, to, "delivered", retry) { put("hops", 1); put("rtt_ms", 842) } - pendingJobs.remove(ref) - activate(to, peer!!) + for (retry in 0..timing.retries) { + if (retry > 0) { + val stillPending = synchronized(lock) { + p.retry = retry + progress(p, "retrying") } - reactTo(peer!!, to, args, type) + if (!stillPending) return + } + delay(if (retry == 0) timing.ackWaitMs else timing.retryMs) + if (tryDeliver(p, args)) return + } + if (!labRadio) { + // Team firmware: no ACK after the last retry is final. + synchronized(lock) { finish(p, "failed", "timeout") } + return + } + if (!synchronized(lock) { progress(p, "waiting", "no_ack") }) return + while (true) { + val left = p.createdAt + timing.parkMs - clock() + if (left <= 0) { + synchronized(lock) { finish(p, "failed", "timeout") } return } + withTimeoutOrNull(minOf(timing.resendMs, left)) { p.wake.receive() } + synchronized(lock) { + if (pending[p.ref] === p) { + txPackets++ + resends++ + } + } + if (tryDeliver(p, args)) return } - synchronized(lock) { - status(ref, to, "failed", 3) { put("reason", "timeout") } - pendingJobs.remove(ref) + } + + /** One transmission reached the contact when its peer is in range, has us paired and we are unlocked. */ + private suspend fun tryDeliver(p: SimPending, args: JsonObject): Boolean { + val peer = synchronized(lock) { + val peer = peerFor(p.to) + if (pending[p.ref] !== p || peer == null || !reachable(peer) || !peer.scansBack || state != "unlocked") return false + acksReceived++ + rxPackets++ + finish(p, "delivered", null) { put("hops", 0); put("rtt_ms", (clock() - p.createdAt).coerceAtLeast(1)) } + activate(p.to, peer) + peer } + reactTo(peer, p.to, args, p.type) + return true } /** Virtual peers answer questions and share their position back. */ @@ -548,18 +815,21 @@ class SimulatedHeltec( } /** A valid packet from [peer] arrived: deliver it to the app and activate the contact. */ - private fun incoming(peer: VirtualPeer, contactId: Int, body: JsonObject, group: Int? = null) { - if (state != "unlocked") return + private fun incoming(peer: VirtualPeer, contactId: Int, body: JsonObject) { + if (state != "unlocked" || !reachable(peer)) return val c = flash.contacts.firstOrNull { it.contactId == contactId } ?: return + rxPackets++ val ctr = (c.rxHighestCtr ?: 0) + 1 updateContact(c.copy(rxHighestCtr = ctr, lastRssi = peer.rssi, lastSnr = peer.snr)) emitEvent("msg.received", buildJsonObject { put("from", contactId) - if (group != null) put("group", group) body.forEach { (k, v) -> put(k, v) } - put("ctr", ctr); put("hops", 1); put("retry", 0); put("rssi", peer.rssi); put("snr", peer.snr) + if (labRadio && body.str("type") == "text") put("compressed", false) + put("ctr", ctr); put("hops", 0); put("retry", 0); put("rssi", peer.rssi.toDouble()); put("snr", peer.snr) }) activate(contactId, peer) + // Lab.3 item 5: any authenticated packet from the contact sends its waiting messages again at once. + pending.values.filter { it.to == contactId && it.state == "waiting" }.forEach { it.wake.trySend(Unit) } } /** First packet from the peer after it scanned our code: an empty "remove reaction" ping. */ @@ -578,23 +848,92 @@ class SimulatedHeltec( emitEvent("contact.state", buildJsonObject { put("contact_id", contactId); put("state", "active") }) } + /** In range and not on the lab ignore list (without relays an ignored node is out of reach). */ + private fun reachable(peer: VirtualPeer): Boolean = + peer.inRange && OgCrypto.nodeId(OgCrypto.unb64(peer.publicKey)) !in flash.ignoreNodes + private fun peerFor(contactId: Int): VirtualPeer? { val c = flash.contacts.firstOrNull { it.contactId == contactId } ?: return null return flash.peers.firstOrNull { it.publicKey == c.publicKey } } private fun failAllPending(reason: String) { - pendingJobs.forEach { (ref, job) -> - job.cancel() - emitEvent("msg.status", buildJsonObject { - put("msg_ref", ref); put("to", JsonNull); put("state", "failed"); put("retry", 0); put("reason", reason) - }) - } - pendingJobs.clear() + pending.values.toList().forEach { finish(it, "failed", reason, stop = true) } } // ---------------------------------------------------------------- radio + private fun radioStats(reset: Boolean): JsonObject { + val result = buildJsonObject { + put("tx_packets", txPackets); put("rx_packets", rxPackets); put("rx_crc_errors", 0); put("rx_tag_failures", 0) + put("rx_malformed", 0); put("rx_dedupe_drops", 0); put("relayed", 0); put("relay_suppressed", 0); put("relay_dropped", 0) + put("rate_limit_drops", 0); put("acks_sent", rxPackets); put("acks_received", acksReceived); put("retries", retriesScheduled) + put("tx_airtime_ms_total", txPackets * 206); put("cad_scans", txPackets); put("cad_busy", 0) + put("radio_failures", 0); put("radio_timeouts", 0); put("dropped_events", 0); put("dropped_acks", 0) + put("radio_dropped_events", 0); put("trace_dropped_events", 0); put("last_rssi", -71.0); put("last_snr", 9.5) + put("tx_duty_cycle_max_percent", if (labRadio && flash.freqMhz in 869.40..869.65) 10 else 1) + if (labRadio) { + put("resends", resends); put("locked_buffered", 0); put("locked_expired", 0) + } + } + if (reset) { + txPackets = 0 + rxPackets = 0 + acksReceived = 0 + retriesScheduled = 0 + resends = 0 + } + return result + } + + private fun meshJson() = buildJsonObject { + put("hop_default", flash.hopDefault); put("relay_enabled", flash.relayEnabled); put("relay_when_locked", flash.relayWhenLocked) + put("cad_enabled", flash.cadEnabled); put("backoff_slots", 8); put("retries", flash.retries); put("retry_base_ms", 0) + put("rate_limit_per_src", 20) + putJsonObject("ack_default") { put("text", true); put("reaction", false); put("geo", false) } + } + + /** `mesh.set`: validates the whole candidate first, then applies it (link spec 8). */ + private fun meshSet(a: JsonObject): JsonObject { + fun boolArg(key: String, current: Boolean): Boolean { + if (!a.containsKey(key)) return current + return a.bool(key) ?: throw CommandError("E_INVALID_ARG", "$key must be a boolean", key) + } + fun intArg(key: String, current: Int, range: IntRange): Int { + if (!a.containsKey(key)) return current + return a.int(key)?.takeIf { it in range } ?: throw CommandError("E_INVALID_ARG", "invalid configuration candidate", key) + } + save(flash.copy( + hopDefault = intArg("hop_default", flash.hopDefault, 0..7), + retries = intArg("retries", flash.retries, 0..3), + relayEnabled = boolArg("relay_enabled", flash.relayEnabled), + relayWhenLocked = boolArg("relay_when_locked", flash.relayWhenLocked), + cadEnabled = boolArg("cad_enabled", flash.cadEnabled), + )) + return meshJson() + } + + /** Lab contract `lab.set {text_codec?, ignore_nodes?}`, both persisted. */ + private fun labSet(a: JsonObject): JsonObject { + var next = flash + if (a.containsKey("text_codec")) { + val codec = a.str("text_codec") + if (codec != MessageLimits.CODEC_RAW && codec != MessageLimits.CODEC_OGZ1) { + throw CommandError("E_INVALID_ARG", "text_codec must be raw or ogz1", "text_codec") + } + next = next.copy(textCodec = codec) + } + if (a.containsKey("ignore_nodes")) { + val list = (a["ignore_nodes"] as? JsonArray)?.map { (it as? JsonPrimitive)?.takeIf { p -> p.isString }?.content } + if (list == null || list.size > 8 || list.any { it == null || !NODE_ID.matches(it) }) { + throw CommandError("E_INVALID_ARG", "ignore_nodes must be up to 8 four-hex-digit NodeIDs", "ignore_nodes") + } + next = next.copy(ignoreNodes = list.filterNotNull().map { it.uppercase() }.distinct()) + } + save(next) + return labJson() + } + private fun radioJson() = buildJsonObject { put("freq_mhz", flash.freqMhz); put("bw_khz", flash.bwKhz); put("sf", flash.sf); put("cr", 5) put("tx_power_dbm", flash.txPowerDbm); put("preamble", 8); put("sync_word", 79) @@ -613,7 +952,46 @@ class SimulatedHeltec( } } - // ---------------------------------------------------------------- groups (proposed link 1.1 extension) + // ---------------------------------------------------------------- groups (link spec 6, "Groups") + + private fun group(a: JsonObject): SimGroup { + val id = a.int("group_id") ?: throw CommandError("E_INVALID_ARG", "group_id missing", "group_id") + return flash.groups.firstOrNull { it.groupId == id } ?: throw CommandError("E_NO_SUCH_GROUP", "no group $id") + } + + private fun ownedGroup(a: JsonObject): SimGroup = + group(a).also { if (!it.owner) throw CommandError("E_INVALID_ARG", "only the owner changes the group", "group_id") } + + private fun updateGroup(g: SimGroup) { + save(flash.copy(groups = flash.groups.map { if (it.groupId == g.groupId) g else it })) + } + + private fun groupJson(g: SimGroup, withMembers: Boolean) = buildJsonObject { + put("group_id", g.groupId); put("gid", g.gid); put("name", g.name); put("epoch", g.epoch); put("owner", g.owner) + put("owner_contact_id", g.ownerContactId); put("member", g.ownMember); put("member_count", g.members.size + 1) + if (withMembers) { + putJsonArray("members") { + add(buildJsonObject { put("member", g.ownMember); put("node_id", nodeId()); put("contact_id", JsonNull) }) + g.members.forEach { m -> + add(buildJsonObject { put("member", m.member); put("node_id", m.nodeId); put("contact_id", m.contactId) }) + } + } + } + } + + private fun intList(a: JsonObject, key: String): List { + val ids = (a[key] as? JsonArray)?.map { (it as? JsonPrimitive)?.takeIf { p -> !p.isString }?.content?.toIntOrNull() } + ?: throw CommandError("E_INVALID_ARG", "$key missing", key) + if (ids.any { it == null } || ids.distinct().size != ids.size) throw CommandError("E_INVALID_ARG", "$key must be distinct integers", key) + return ids.filterNotNull() + } + + private fun membersFor(contactIds: List, firstIndex: Int): List = contactIds.mapIndexed { i, id -> + val c = flash.contacts.firstOrNull { it.contactId == id } ?: throw CommandError("E_NO_SUCH_CONTACT", "no contact $id") + SimGroupMember(firstIndex + i, c.nodeId, c.contactId) + } + + private fun freeGroupSlot(): Int? = (1..MAX_GROUPS).firstOrNull { s -> flash.groups.none { it.groupId == s } } private fun groupCreate(a: JsonObject): JsonObject { requireUnlocked() @@ -621,56 +999,158 @@ class SimulatedHeltec( if (name.isEmpty() || MessageLimits.utf8Bytes(name) > MessageLimits.MAX_NAME_BYTES) { throw CommandError("E_INVALID_ARG", "name must be 1 to 24 bytes", "name") } - val members = (a["members"] as? JsonArray)?.mapNotNull { (it as? JsonPrimitive)?.content?.toIntOrNull() } - ?: throw CommandError("E_INVALID_ARG", "members missing", "members") - if (members.isEmpty() || members.size > MessageLimits.MAX_GROUP_MEMBERS) { - throw CommandError("E_INVALID_ARG", "1 to 8 members", "members") - } - members.forEach { id -> - val c = flash.contacts.firstOrNull { it.contactId == id } ?: throw CommandError("E_NO_SUCH_CONTACT", "no contact $id") - if (c.state != "active") throw CommandError("E_INVALID_ARG", "contact $id is pending", "members") + val ids = intList(a, "members") + if (ids.isEmpty() || ids.size > MAX_GROUP_MEMBERS - 1) throw CommandError("E_INVALID_ARG", "1 to 15 members", "members") + val members = membersFor(ids, firstIndex = 1) + val slot = freeGroupSlot() ?: throw CommandError("E_STORAGE_FULL", "all group slots are used") + val g = SimGroup(slot, OgCrypto.hex(OgCrypto.randomBytes(4)).uppercase(), name, epoch = 1, owner = true, ownMember = 0, members = members) + save(flash.copy(groups = flash.groups + g)) + return buildJsonObject { put("group", groupJson(g, withMembers = true)) } + } + + private fun groupList(): JsonObject { + requireUnlocked() + return buildJsonObject { + putJsonArray("groups") { flash.groups.sortedBy { it.groupId }.forEach { add(groupJson(it, withMembers = false)) } } + put("total", flash.groups.size) } - val id = (flash.groups.maxOfOrNull { it.groupId } ?: 0) + 1 - save(flash.copy(groups = flash.groups + SimGroup(id, name, members))) + } + + /** `group.sync`: the current key and member list to one member as an acknowledged DM; its `msg.status` carries `to` and `group_id`. */ + private fun groupSync(a: JsonObject): JsonObject { + requireUnlocked() + val g = ownedGroup(a) + val to = a.int("contact_id") ?: throw CommandError("E_INVALID_ARG", "contact_id missing", "contact_id") + val c = flash.contacts.firstOrNull { it.contactId == to } ?: throw CommandError("E_NO_SUCH_CONTACT", "no contact $to") + if (g.members.none { it.contactId == to }) throw CommandError("E_INVALID_ARG", "contact is not a member", "contact_id") + if (pending.size >= 8) throw CommandError("E_QUEUE_FULL", "pending queue is full") + val hops = a.int("hops") ?: flash.hopDefault + if (hops !in 0..7) throw CommandError("E_INVALID_ARG", "hops must be 0 to 7", "hops") + val ctr = c.txCtr + 1 + updateContact(c.copy(txCtr = ctr)) + val p = enqueue(to, "group_sync", ctr, group = g.groupId) + p.job = scope.launch { deliver(p, ack = true, args = a) } + val onAir = 17 + 33 return buildJsonObject { - put("group_id", id); put("name", name) - putJsonArray("members") { members.forEach { add(JsonPrimitive(it)) } } + put("msg_ref", p.ref); put("ctr", ctr); put("ack_requested", true); put("hops", hops); put("state", "queued") + put("bytes_on_air", onAir); put("est_airtime_ms", 120 + onAir * 4) + } + } + + /** A member change starts a new epoch; syncs of the old one are cancelled (their `msg.status` follows the response). */ + private fun newEpoch(g: SimGroup, members: List): SimGroup { + if (g.epoch >= 255) throw CommandError("E_BUSY", "epoch 255 reached, create a new group") + val next = g.copy(epoch = g.epoch + 1, members = members) + pending.values.filter { it.type == "group_sync" && it.group == g.groupId } + .forEach { finish(it, "cancelled", null, afterResponse = true, stop = true) } + updateGroup(next) + return next + } + + private fun groupAdd(a: JsonObject): JsonObject { + requireUnlocked() + val g = ownedGroup(a) + val ids = intList(a, "members") + if (ids.isEmpty() || ids.any { id -> g.members.any { it.contactId == id } }) { + throw CommandError("E_INVALID_ARG", "members must be new contacts", "members") + } + if (g.members.size + 1 + ids.size > MAX_GROUP_MEMBERS) throw CommandError("E_INVALID_ARG", "a group takes 16 members", "members") + val firstIndex = (g.members.maxOfOrNull { it.member } ?: 0) + 1 + val next = newEpoch(g, g.members + membersFor(ids, firstIndex)) + return buildJsonObject { put("group", groupJson(next, withMembers = true)) } + } + + private fun groupRemove(a: JsonObject): JsonObject { + requireUnlocked() + val g = ownedGroup(a) + val indexes = intList(a, "members") + if (indexes.isEmpty() || indexes.any { i -> i == 0 || g.members.none { it.member == i } }) { + throw CommandError("E_INVALID_ARG", "members must be member indexes other than 0", "members") } + val rest = g.members.filter { it.member !in indexes } + if (rest.isEmpty()) throw CommandError("E_INVALID_ARG", "at least 2 members stay", "members") + return buildJsonObject { put("group", groupJson(newEpoch(g, rest), withMembers = true)) } + } + + private fun groupDelete(a: JsonObject): JsonObject { + requireUnlocked() + val g = group(a) + if (a.bool("confirm") != true) throw CommandError("E_CONFIRM_REQUIRED", "confirm must be true", "confirm") + pending.values.filter { it.group == g.groupId }.forEach { finish(it, "cancelled", null, afterResponse = true, stop = true) } + save(flash.copy(groups = flash.groups.filter { it.groupId != g.groupId })) + return buildJsonObject { put("deleted", true) } } + /** `group.send`: no receipt and no retries, `sent` is final; `ack: true` is refused. */ private fun groupSend(a: JsonObject): JsonObject { requireUnlocked() - val gid = a.int("group_id") ?: throw CommandError("E_INVALID_ARG", "group_id missing", "group_id") - val group = flash.groups.firstOrNull { it.groupId == gid } ?: throw CommandError("E_INVALID_ARG", "no group $gid", "group_id") - val text = a.str("text") ?: throw CommandError("E_INVALID_ARG", "text missing", "text") - val n = MessageLimits.utf8Bytes(text) - if (n == 0 || n > MessageLimits.DEFAULT_MAX_TEXT_BYTES) throw CommandError("E_TOO_LONG", "text is $n bytes", "text") - val ref = msgRef.incrementAndGet() - pendingJobs[ref] = scope.launch { - delay(400) + val g = group(a) + val type = a.str("type") ?: throw CommandError("E_INVALID_ARG", "type missing", "type") + if (a.bool("ack") == true) throw CommandError("E_INVALID_ARG", "group messages have no receipts", "ack") + val body = when (type) { + "text" -> { + val text = a.str("text") ?: throw CommandError("E_INVALID_ARG", "text missing", "text") + val n = MessageLimits.utf8Bytes(text) + if (n == 0) throw CommandError("E_INVALID_ARG", "text is empty", "text") + if (n > MessageLimits.DEFAULT_MAX_TEXT_BYTES) throw CommandError("E_TOO_LONG", "text is $n bytes", "text") + n + } + "geo" -> { + if (a.double("lat") == null || a.double("lon") == null) throw CommandError("E_INVALID_ARG", "lat and lon missing", "lat") + 6 + } + else -> throw CommandError("E_INVALID_ARG", "type must be text or geo", "type") + } + if (pending.size >= 8) throw CommandError("E_QUEUE_FULL", "pending queue is full") + val hops = a.int("hops") ?: flash.hopDefault + if (hops !in 0..7) throw CommandError("E_INVALID_ARG", "hops must be 0 to 7", "hops") + val ctr = g.txCtr + 1 + updateGroup(g.copy(txCtr = ctr)) + val p = enqueue(0, type, ctr, group = g.groupId) + p.job = scope.launch { + delay(timing.firstTxMs) synchronized(lock) { - status(ref, 0, "sent", 0) { put("group", gid) } - pendingJobs.remove(ref) + txPackets++ + finish(p, "sent", null) } - if (text.contains('?')) { + if (type == "text" && a.str("text")!!.contains('?')) { val replier = synchronized(lock) { - group.members.firstNotNullOfOrNull { id -> peerFor(id)?.takeIf { it.inRange }?.let { id to it } } + g.members.firstNotNullOfOrNull { m -> m.contactId?.let { id -> peerFor(id)?.takeIf { reachable(it) }?.let { m to it } } } } if (replier != null) { delay(3_000) - synchronized(lock) { - incoming(replier.second, replier.first, buildJsonObject { - put("type", "text"); put("text", replier.second.replies.firstOrNull() ?: "Ok") - }, group = gid) - } + synchronized(lock) { groupIncoming(g.groupId, replier.first, replier.second.replies.firstOrNull() ?: "Ok") } } } } - return buildJsonObject { put("msg_ref", ref); put("ack_requested", false); put("state", "queued") } + val bytes = 17 + body + return buildJsonObject { + put("msg_ref", p.ref); put("ctr", ctr); put("ack_requested", false); put("hops", hops); put("state", "queued") + put("bytes_on_air", bytes); put("est_airtime_ms", 120 + bytes * 4) + } + } + + /** A text from [from] arrived in a group: `group.received`, with `from` null when the board has no contact for the NodeID. */ + private fun groupIncoming(groupId: Int, from: SimGroupMember, text: String) { + if (state != "unlocked") return + if (flash.groups.none { it.groupId == groupId }) return + rxPackets++ + emitEvent("group.received", buildJsonObject { + put("type", "text"); put("text", text); put("group_id", groupId); put("member", from.member); put("node_id", from.nodeId) + put("from", from.contactId); put("ctr", ++groupRxCtr); put("retry", 0); put("hops", 0); put("rssi", -72.0); put("snr", 9.0) + }) } // ---------------------------------------------------------------- test harness API (not part of the protocol) + /** A hung board: the port stays open but nothing is answered. */ + @Volatile + var hung: Boolean = false + + /** An old image that still reports `mock: true` in `sys.hello`. */ + @Volatile + var mockImage: Boolean = false + /** Creates a virtual peer and returns the QR text its app would show. */ fun addVirtualPeer( name: String, @@ -696,19 +1176,52 @@ class SimulatedHeltec( incoming(peer, contactId, buildJsonObject { put("type", "text"); put("text", text) }) } + /** + * A virtual peer (a paired contact) owns a group and invites us: after [SimTiming.groupSyncMs] the board + * applies the sync and reports `group.state joined`, as the firmware does once the owner's key arrives. + * [others] are further members, given by NodeID, that the board holds no contact for. Returns the slot. + */ + fun peerInvites(contactId: Int, name: String, others: List = emptyList()): Int = synchronized(lock) { + val c = flash.contacts.firstOrNull { it.contactId == contactId } ?: error("no contact $contactId") + val slot = freeGroupSlot() ?: error("all group slots are used") + val members = listOf(SimGroupMember(0, c.nodeId, c.contactId)) + + others.mapIndexed { i, node -> SimGroupMember(i + 2, node.uppercase(), null) } + val g = SimGroup(slot, OgCrypto.hex(OgCrypto.randomBytes(4)).uppercase(), name, epoch = 1, owner = false, + ownMember = 1, members = members, ownerContactId = c.contactId) + scope.launch { + delay(timing.groupSyncMs) + synchronized(lock) { + if (state != "unlocked") return@synchronized + save(flash.copy(groups = flash.groups + g)) + emitEvent("group.state", buildJsonObject { put("group_id", slot); put("state", "joined"); put("epoch", 1) }) + } + } + slot + } + + /** Member [member] of group [groupId] says [text] (the owner is member 0). */ + fun memberSays(groupId: Int, member: Int, text: String) = synchronized(lock) { + val m = flash.groups.firstOrNull { it.groupId == groupId }?.members?.firstOrNull { it.member == member } ?: return@synchronized + groupIncoming(groupId, m, text) + } + fun setPeerInRange(contactId: Int, inRange: Boolean) = synchronized(lock) { val c = flash.contacts.firstOrNull { it.contactId == contactId } ?: return@synchronized save(flash.copy(peers = flash.peers.map { if (it.publicKey == c.publicKey) it.copy(inRange = inRange) else it })) } - /** Factory reset without the button dance, for the "Alle Daten löschen" demo path. */ - fun wipe() = synchronized(lock) { - failAllPending("locked") - store.wipe() - flash = SimFlash(deviceId = flash.deviceId).also(store::save) - state = "unprovisioned" - identityPrivate = null - emitEvent("sys.boot", bootData("factory_reset")) + /** Restarts the simulated board as a power cut would: RAM queue and `recent` are gone, the vault is locked. */ + fun powerCycle() = synchronized(lock) { reboot("power_on") } + + private fun codec(): String = if (labRadio) flash.textCodec else MessageLimits.CODEC_RAW + + private fun maxTextInputBytes(): Int = + if (codec() == MessageLimits.CODEC_OGZ1) OGZ1_MAX_TEXT_INPUT_BYTES else MessageLimits.DEFAULT_MAX_TEXT_BYTES + + private fun labJson() = buildJsonObject { + put("text_codec", flash.textCodec); put("max_text_input_bytes", maxTextInputBytes()); put("node_id", nodeId()) + put("fw", fwVersion) + putJsonArray("ignore_nodes") { flash.ignoreNodes.forEach { add(JsonPrimitive(it)) } } } private fun emitLater(name: String, data: JsonObject) { @@ -724,7 +1237,21 @@ class SimulatedHeltec( } companion object { - const val FW_VERSION = "0.1.0-sim" - const val PROTO = "1.0" + /** Behaves like the lab image 0.3.0-lab.3 (lab contract of 2026-10-24). */ + const val FW_VERSION = "0.3.0-lab.3-sim" + + /** Behaves like Nils' team firmware 0.3.0 (`feature/firmware-hardening`). */ + const val TEAM_FW_VERSION = "0.3.0-sim" + private const val PAIR_WINDOW_MS = 300_000L + private const val PAIR_RENEW_MS = 60_000L + private val NODE_ID = Regex("^[0-9A-Fa-f]{4}$") + const val PROTO = "1.1" + private const val MAX_GROUPS = 8 + private const val MAX_GROUP_MEMBERS = 16 + private const val RECENT_CAPACITY = 16 + private const val OGZ1_MAX_TEXT_INPUT_BYTES = 160 + + /** 1 .. 2^30, like the lab image's first `msg_ref` after boot. */ + private fun randomRef(): Int = Random.nextInt(1 shl 30) + 1 } } diff --git a/native-android/app/src/main/java/ch/offgrid/android/ui/AppNavHost.kt b/native-android/app/src/main/java/ch/offgrid/android/ui/AppNavHost.kt index c1ab17f..b9a4ee1 100644 --- a/native-android/app/src/main/java/ch/offgrid/android/ui/AppNavHost.kt +++ b/native-android/app/src/main/java/ch/offgrid/android/ui/AppNavHost.kt @@ -28,12 +28,14 @@ import ch.offgrid.android.analytics.Screen import ch.offgrid.android.domain.Conversation import ch.offgrid.android.domain.Settings import ch.offgrid.android.ui.screens.AddContactScreen +import ch.offgrid.android.ui.screens.AdvancedScreen import ch.offgrid.android.ui.screens.ChatScreen import ch.offgrid.android.ui.screens.ConnectScreen import ch.offgrid.android.ui.screens.ContactAddedScreen import ch.offgrid.android.ui.screens.ContactsScreen import ch.offgrid.android.ui.screens.ExportScreen import ch.offgrid.android.ui.screens.GroupChatScreen +import ch.offgrid.android.ui.screens.GroupMembersScreen import ch.offgrid.android.ui.screens.ImportScreen import ch.offgrid.android.ui.screens.LocationScreen import ch.offgrid.android.ui.screens.NameScreen @@ -56,14 +58,17 @@ object Routes { const val SETTINGS = "einstellungen" const val EXPORT = "einstellungen/export" const val IMPORT = "einstellungen/import" + const val ADVANCED = "einstellungen/erweitert" const val NEW_GROUP = "gruppe/neu" const val GROUP = "gruppe/{groupId}" + const val GROUP_MEMBERS = "gruppe/{groupId}/mitglieder" fun add(scan: Boolean = false) = "kontakte/neu?tab=${if (scan) "scan" else "mine"}" fun added(id: Long) = "kontakte/neu/fertig/$id" fun chat(id: Long) = "chat/$id" fun location(contactId: Long, messageId: Long) = "chat/$contactId/standort/$messageId" fun group(id: Long) = "gruppe/$id" + fun groupMembers(id: Long) = "gruppe/$id/mitglieder" } /** Shared-axis step between screens: 30 dp slide plus fade, reversed on back. */ @@ -136,10 +141,14 @@ fun AppNavHost(openRequest: MutableStateFlow) { composable(Routes.SETTINGS) { SettingsScreen(nav) } composable(Routes.EXPORT) { ExportScreen(nav) } composable(Routes.IMPORT) { ImportScreen(nav) } + composable(Routes.ADVANCED) { AdvancedScreen(nav) } composable(Routes.NEW_GROUP) { NewGroupScreen(nav) } composable(Routes.GROUP, arguments = listOf(navArgument("groupId") { type = NavType.LongType })) { GroupChatScreen(nav, it.arguments!!.getLong("groupId")) } + composable(Routes.GROUP_MEMBERS, arguments = listOf(navArgument("groupId") { type = NavType.LongType })) { + GroupMembersScreen(nav, it.arguments!!.getLong("groupId")) + } } } diff --git a/native-android/app/src/main/java/ch/offgrid/android/ui/components/ChatComponents.kt b/native-android/app/src/main/java/ch/offgrid/android/ui/components/ChatComponents.kt index 7e50317..fa22cc7 100644 --- a/native-android/app/src/main/java/ch/offgrid/android/ui/components/ChatComponents.kt +++ b/native-android/app/src/main/java/ch/offgrid/android/ui/components/ChatComponents.kt @@ -123,7 +123,10 @@ fun DayDivider(label: String) { } } -/** Meta line under outgoing bubbles: time, status word and small signal bars, or the retry row. */ +/** + * Meta line under outgoing bubbles: time, status word and small signal bars, a clock while the antenna + * waits for the contact, or the failure word from [meta] with the retry button. + */ @Composable private fun OutMeta(status: Int, meta: String, onRetry: () -> Unit) { AnimatedContent( @@ -134,7 +137,7 @@ private fun OutMeta(status: Int, meta: String, onRetry: () -> Unit) { ) { failed -> if (failed) { Row(Modifier.padding(end = 2.dp), verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(10.dp)) { - Text("Nicht gesendet", style = OgType.meta.copy(color = Og.danger)) + Text(meta, style = OgType.meta.copy(color = Og.danger)) Box( Modifier.heightIn(min = 32.dp).clip(RoundedCornerShape(10.dp)).background(Og.surface) .border(1.dp, Og.border, RoundedCornerShape(10.dp)) @@ -149,8 +152,14 @@ private fun OutMeta(status: Int, meta: String, onRetry: () -> Unit) { else -> 0 } Row(Modifier.padding(end = 6.dp), verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(6.dp)) { - Text(meta, style = OgType.meta) - SignalBars(level, small = true) + if (status == MessageStatus.WAITING) { + // No check mark: the antenna sent it but has no ACK yet and tries again when the contact is heard. + OgIconView(OgIcon.Clock, Og.text3) + Text(meta, style = OgType.meta) + } else { + Text(meta, style = OgType.meta) + SignalBars(level, small = true) + } } } } @@ -211,6 +220,7 @@ fun MessageBubble( reaction: String? = null, onRetry: () -> Unit = {}, onLongPress: (() -> Unit)? = null, + longPressLabel: String = "Details", ) { Column(Modifier.fillMaxWidth().padding(top = if (groupStart) 8.dp else 0.dp), horizontalAlignment = if (out) Alignment.End else Alignment.Start) { Column( @@ -229,7 +239,7 @@ fun MessageBubble( Box( Modifier .then(if (out) Modifier.outBubble(status, shape) else Modifier.clip(shape).background(Og.surface).border(1.dp, Og.border, shape)) - .then(if (onLongPress != null) Modifier.longPressAction("Reagieren", onLongPress) else Modifier) + .then(if (onLongPress != null) Modifier.longPressAction(longPressLabel, onLongPress) else Modifier) .padding(horizontal = 14.dp, vertical = 10.dp), ) { Text( @@ -350,8 +360,11 @@ fun Composer( maxBytes: Int, onSend: () -> Unit, onLocation: (() -> Unit)?, + parts: Int = 1, + maxParts: Int = 1, ) { - val over = usedBytes > maxBytes + // A text longer than one radio message is split by the app into up to maxParts messages. + val over = parts > maxParts || (maxParts == 1 && usedBytes > maxBytes) val canSend = text.isNotBlank() && !over // The design keeps the send button at full colour while the field is empty; only an // over-long text dims it. @@ -399,7 +412,11 @@ fun Composer( }, ) Text( - "$usedBytes / $maxBytes Zeichen pro Funkspruch", + when { + parts > maxParts -> "Zu lang: höchstens $maxParts Funksprüche" + parts > 1 -> "Wird als $parts Funksprüche gesendet" + else -> "$usedBytes / $maxBytes Zeichen pro Funkspruch" + }, style = OgType.meta.copy(color = counterColor), modifier = Modifier.padding(start = 4.dp).onSizeChanged { counterHeight = it.height }, ) diff --git a/native-android/app/src/main/java/ch/offgrid/android/ui/components/OgIcons.kt b/native-android/app/src/main/java/ch/offgrid/android/ui/components/OgIcons.kt index 284d1b2..613ea9b 100644 --- a/native-android/app/src/main/java/ch/offgrid/android/ui/components/OgIcons.kt +++ b/native-android/app/src/main/java/ch/offgrid/android/ui/components/OgIcons.kt @@ -32,6 +32,7 @@ enum class OgIcon(val size: Dp, val stroke: Float, vararg val paths: String) { Download(22.dp, 2f, "M12 3v12", "M7 10l5 5 5-5", "M5 15v4a2 2 0 0 0 2 2h10a2 2 0 0 0 2-2v-4"), File(20.dp, 2f, "M14 3H7a2 2 0 0 0-2 2v14a2 2 0 0 0 2 2h10a2 2 0 0 0 2-2V8z", "M14 3v5h5"), Info(18.dp, 2f, circle(12f, 12f, 9f), "M12 8v5", "M12 16.5v.01"), + Clock(14.dp, 2.2f, circle(12f, 12f, 9f), "M12 7v5l3 2"), Warning(18.dp, 2f, "M12 3l9.5 17h-19z", "M12 10v4", "M12 17v.01"), Pin(22.dp, 2f, "M12 21s-6.5-5.6-6.5-11a6.5 6.5 0 0 1 13 0c0 5.4-6.5 11-6.5 11z", circle(12f, 10f, 2.5f)), Map(20.dp, 2.2f, "M9 4 3 6v14l6-2 6 2 6-2V4l-6 2z", "M9 4v14", "M15 6v14"), diff --git a/native-android/app/src/main/java/ch/offgrid/android/ui/screens/AddContactScreen.kt b/native-android/app/src/main/java/ch/offgrid/android/ui/screens/AddContactScreen.kt index 86e0da9..784bca1 100644 --- a/native-android/app/src/main/java/ch/offgrid/android/ui/screens/AddContactScreen.kt +++ b/native-android/app/src/main/java/ch/offgrid/android/ui/screens/AddContactScreen.kt @@ -125,6 +125,13 @@ fun AddContactScreen(nav: NavHostController, scanTab: Boolean) { ScanTab(ui, simulated = linkKind == LinkKind.SIMULATED, onStart = vm::clearError, onCode = vm::scan) } ui.error?.let { OgNote(it.text()) } + if (ui.canReplace) { + OgButton("Neu koppeln", vm::replace, Modifier.padding(start = 16.dp, top = 10.dp, end = 16.dp), + variant = ButtonVariant.Secondary) + } + if (ui.codeRenewed && tab == "mine") { + OgNote("Dein Code hat sich erneuert. Hat dein Gegenüber den alten schon gescannt, muss es diesen neu scannen.") + } Spacer(Modifier.height(16.dp)) Spacer(Modifier.weight(1f)) if (tab == "mine") { diff --git a/native-android/app/src/main/java/ch/offgrid/android/ui/screens/AddContactViewModel.kt b/native-android/app/src/main/java/ch/offgrid/android/ui/screens/AddContactViewModel.kt index 9d7af6f..fad2b57 100644 --- a/native-android/app/src/main/java/ch/offgrid/android/ui/screens/AddContactViewModel.kt +++ b/native-android/app/src/main/java/ch/offgrid/android/ui/screens/AddContactViewModel.kt @@ -54,31 +54,37 @@ class AddContactViewModel( fun clearError() = pairing.clearError() + /** "Neu koppeln" after `E_CONTACT_EXISTS`: replaces the keys of that contact; the peer has to do the same. */ + fun replace() { + val code = pairing.state.value.replaceCode ?: return + pairing.complete(code, replace = true) + } + /** The contact is confirmed: end the session before the screen navigates on. */ fun finish() { if (finished) return finished = true - pairing.cancel() + pairing.finish() } private suspend fun onReconnected() { if (finished) return val before = pairing.state.value val code = waitingCode - // Unplugging the antenna restarts it and loses the pending salt behind the shown code, so - // fetch a fresh one. After our own scan the contact is stored with that salt and the code - // must stay the same until the other side has scanned it (link spec 7.4). + // Unplugging the antenna restarts it and loses the pending salt behind the shown code; Pairing then + // fetches a fresh one (it keeps the code when the antenna stayed unlocked). After our own scan the + // contact is stored with that salt and the code must stay the same until the other side has scanned it. val freshCode = before.scannedName == null if (freshCode && before.qr != null) pairing.begin() if (code == null) return // `pair.complete` must run against the pairing that belongs to the code on screen. - if (freshCode) pairing.state.first { it.qr != null && it.qr != before.qr } + if (freshCode) pairing.state.first { it.qr != null && it.codeVersion > before.codeVersion } waitingCode = null pairing.complete(code) } override fun onCleared() { - if (!finished) pairing.cancel() + if (!finished) pairing.leave() } } @@ -87,6 +93,10 @@ data class AddContactUi( /** QR text to render; null while it loads or while the antenna is away and the code may be stale. */ val qr: String?, val error: PairingError?, + /** The code changed after it may have been scanned; the other side has to scan it again. */ + val codeRenewed: Boolean = false, + /** "Neu koppeln" is offered for a contact the antenna already has. */ + val canReplace: Boolean = false, val scannedName: String?, val pingSent: Boolean, val confirmedContactId: Long?, @@ -101,6 +111,8 @@ fun addContactUi(pairing: PairingState, antennaReady: Boolean): AddContactUi { qr = pairing.qr.takeIf { antennaReady || scanned }, // Pairing only notices a lost antenna at its next refresh, so the screen reports it at once. error = pairing.error ?: PairingError.ANTENNA_NOT_READY.takeIf { !antennaReady }, + codeRenewed = pairing.codeRenewed, + canReplace = pairing.replaceCode != null && antennaReady, scannedName = pairing.scannedName, pingSent = pairing.pingSent, confirmedContactId = pairing.confirmedContactId, diff --git a/native-android/app/src/main/java/ch/offgrid/android/ui/screens/AdvancedScreen.kt b/native-android/app/src/main/java/ch/offgrid/android/ui/screens/AdvancedScreen.kt new file mode 100644 index 0000000..3e984fc --- /dev/null +++ b/native-android/app/src/main/java/ch/offgrid/android/ui/screens/AdvancedScreen.kt @@ -0,0 +1,341 @@ +package ch.offgrid.android.ui.screens + +import androidx.compose.foundation.background +import androidx.compose.foundation.border +import androidx.compose.foundation.clickable +import androidx.compose.foundation.layout.Arrangement +import androidx.compose.foundation.layout.Box +import androidx.compose.foundation.layout.Column +import androidx.compose.foundation.layout.Row +import androidx.compose.foundation.layout.fillMaxWidth +import androidx.compose.foundation.layout.heightIn +import androidx.compose.foundation.layout.padding +import androidx.compose.foundation.rememberScrollState +import androidx.compose.foundation.shape.RoundedCornerShape +import androidx.compose.foundation.verticalScroll +import androidx.compose.material3.Text +import androidx.compose.runtime.Composable +import androidx.compose.runtime.LaunchedEffect +import androidx.compose.runtime.getValue +import androidx.compose.runtime.mutableStateOf +import androidx.compose.runtime.remember +import androidx.compose.runtime.rememberCoroutineScope +import androidx.compose.runtime.saveable.rememberSaveable +import androidx.compose.runtime.setValue +import androidx.compose.ui.Alignment +import androidx.compose.ui.Modifier +import androidx.compose.ui.draw.alpha +import androidx.compose.ui.draw.clip +import androidx.compose.ui.semantics.Role +import androidx.compose.ui.semantics.contentDescription +import androidx.compose.ui.semantics.semantics +import androidx.compose.ui.text.TextStyle +import androidx.compose.ui.text.font.FontWeight +import androidx.compose.ui.text.input.ImeAction +import androidx.compose.ui.text.input.KeyboardCapitalization +import androidx.compose.ui.unit.dp +import androidx.compose.ui.unit.sp +import androidx.lifecycle.compose.collectAsStateWithLifecycle +import androidx.navigation.NavHostController +import ch.offgrid.android.domain.AntennaState +import ch.offgrid.android.domain.Formats +import ch.offgrid.android.domain.IgnoreEdit +import ch.offgrid.android.domain.LabConfig +import ch.offgrid.android.domain.MeshConfig +import ch.offgrid.android.domain.MessageLimits +import ch.offgrid.android.domain.RadioStats +import ch.offgrid.android.link.LinkClosedException +import ch.offgrid.android.link.LinkCommandException +import ch.offgrid.android.link.LinkTimeoutException +import ch.offgrid.android.ui.LocalApp +import ch.offgrid.android.ui.back +import ch.offgrid.android.ui.components.ButtonVariant +import ch.offgrid.android.ui.components.CardDivider +import ch.offgrid.android.ui.components.InfoRow +import ch.offgrid.android.ui.components.OgButton +import ch.offgrid.android.ui.components.OgCard +import ch.offgrid.android.ui.components.OgNote +import ch.offgrid.android.ui.components.OgSegmented +import ch.offgrid.android.ui.components.OgTextField +import ch.offgrid.android.ui.components.OgTopBar +import ch.offgrid.android.ui.components.SectionLabel +import ch.offgrid.android.ui.theme.Grotesk +import ch.offgrid.android.ui.theme.Mono +import ch.offgrid.android.ui.theme.Og +import ch.offgrid.android.ui.theme.OgType +import kotlinx.coroutines.launch +import kotlinx.serialization.json.JsonObject +import kotlinx.serialization.json.JsonPrimitive +import kotlinx.serialization.json.buildJsonObject +import kotlinx.serialization.json.put +import kotlinx.serialization.json.putJsonArray + +/** + * "Erweitert / Lab": what the antenna is and how its radio and mesh are set, for lab tests and support. Mesh and + * lab settings go to the antenna (`mesh.set`, `lab.set`) and are persisted there; every node of a test has to be + * set on its own. Lab boards always reach this screen from the settings, team boards behind a switch. + */ +@Composable +fun AdvancedScreen(nav: NavHostController) { + val app = LocalApp.current + val scope = rememberCoroutineScope() + val antenna by app.antenna.state.collectAsStateWithLifecycle() + var stats by remember { mutableStateOf(null) } + var busy by remember { mutableStateOf(false) } + var error by remember { mutableStateOf(null) } + var nodeInput by rememberSaveable { mutableStateOf("") } + var nodeError by remember { mutableStateOf(null) } + val ready = antenna.ready + + fun run(action: suspend () -> Unit) { + if (busy) return + scope.launch { + busy = true + error = null + error = try { + action() + null + } catch (e: LinkCommandException) { + "Die Antenne hat abgelehnt: ${e.error.code}" + (e.error.message?.let { " ($it)" } ?: "") + } catch (_: LinkClosedException) { + "Die Antenne ist nicht verbunden." + } catch (_: LinkTimeoutException) { + "Die Antenne hat nicht geantwortet." + } + busy = false + } + } + + LaunchedEffect(ready) { + if (ready) run { + app.antenna.refreshInfo() + stats = app.antenna.radioStats() + } + } + + Page { + OgTopBar(if (antenna.labRadio) "Erweitert / Lab" else "Erweitert", onBack = { nav.back() }, backLabel = "Zurück zu den Einstellungen") + Column(Modifier.weight(1f).verticalScroll(rememberScrollState()).padding(bottom = 32.dp)) { + if (!ready) OgNote("Die Antenne ist nicht verbunden. Die Werte sind vom letzten Verbinden, ändern geht erst wieder verbunden.") + error?.let { OgNote(it) } + + FirmwareSection(antenna) + RadioSection(antenna) + MeshSection(antenna.mesh, enabled = ready && !busy) { changes -> run { app.antenna.setMesh(changes) } } + + if (antenna.labRadio) { + val lab = antenna.lab + SectionLabel("Lab") + OgCard { + InfoRow("Eigene NodeID", antenna.nodeId ?: lab?.nodeId ?: "–") + Column(Modifier.padding(start = 16.dp, top = 12.dp, end = 16.dp, bottom = 4.dp), verticalArrangement = Arrangement.spacedBy(6.dp)) { + Text("Text-Codec", style = OgType.row.copy(fontSize = 15.sp)) + } + Box(Modifier.alpha(if (ready && !busy) 1f else 0.4f)) { + OgSegmented( + listOf(MessageLimits.CODEC_RAW to "Roh (UTF-8)", MessageLimits.CODEC_OGZ1 to "OGZ1"), + selected = lab?.textCodec ?: antenna.textCodec, + label = "Text-Codec", + ) { codec -> + if (ready && !busy && codec != (lab?.textCodec ?: antenna.textCodec)) { + run { app.antenna.setLab(buildJsonObject { put("text_codec", codec) }) } + } + } + } + Text( + "OGZ1 komprimiert nur Texte über 83 Bytes (bis ${lab?.maxTextInputBytes ?: 160} Bytes Eingabe). " + + "Solche Nachrichten kann ein Board mit der Team-Firmware nicht lesen; es bestätigt sie nicht, " + + "und die Nachricht scheitert nach den Wiederholungen. Längere Texte teilt die App sonst selbst auf.", + style = OgType.help.copy(fontSize = 13.sp), + modifier = Modifier.padding(start = 16.dp, top = 10.dp, end = 16.dp, bottom = 14.dp), + ) + } + + SectionLabel("Ignorierliste") + OgCard { + val ignored = lab?.ignoreNodes + if (ignored == null) { + InfoRow("Ignorierliste", "nicht unterstützt", last = true) + } else { + Text( + "Direkt gehörte Pakete dieser NodeIDs verwirft die Antenne, als wären sie ausser Reichweite. " + + "Über ein anderes Gerät weitergeleitete Kopien kommen an. So lassen sich Wege A → B → C im selben Raum testen.", + style = OgType.help.copy(fontSize = 13.sp), + modifier = Modifier.padding(start = 16.dp, top = 14.dp, end = 16.dp, bottom = 6.dp), + ) + ignored.forEach { id -> + Row( + Modifier.fillMaxWidth().heightIn(min = Og.rowMin).padding(horizontal = 16.dp), + verticalAlignment = Alignment.CenterVertically, + ) { + Text(id, style = OgType.value.copy(fontFamily = Mono, fontSize = 15.sp), modifier = Modifier.weight(1f)) + SmallButton("Entfernen", enabled = ready && !busy, description = "$id von der Ignorierliste entfernen") { + run { app.antenna.setLab(ignoreArgs(ignored - id)) } + } + } + CardDivider() + } + if (ignored.isEmpty()) { + InfoRow("Keine NodeID ignoriert", null) + } + Column(Modifier.padding(16.dp), verticalArrangement = Arrangement.spacedBy(10.dp)) { + OgTextField( + "NodeID hinzufügen", nodeInput, { nodeInput = it.take(6); nodeError = null }, + placeholder = "z. B. 3F2A", + hint = "4 Hex-Ziffern, höchstens ${LabConfig.MAX_IGNORE_NODES}. Jedes Board zeigt seine NodeID hier unter «Eigene NodeID».", + error = nodeError, + capitalization = KeyboardCapitalization.Characters, + imeAction = ImeAction.Done, + ) + OgButton("Hinzufügen", { + when (val edit = LabConfig.withIgnored(ignored, nodeInput, antenna.nodeId ?: lab.nodeId)) { + is IgnoreEdit.Changed -> run { + app.antenna.setLab(ignoreArgs(edit.nodes)) + nodeInput = "" + } + is IgnoreEdit.Refused -> nodeError = when (edit.reason) { + IgnoreEdit.Reason.INVALID -> "Eine NodeID hat genau 4 Hex-Ziffern (0–9, A–F)." + IgnoreEdit.Reason.OWN -> "Das ist die NodeID dieser Antenne." + IgnoreEdit.Reason.DUPLICATE -> "Diese NodeID ist schon auf der Liste." + IgnoreEdit.Reason.FULL -> "Die Liste ist voll (${LabConfig.MAX_IGNORE_NODES} NodeIDs)." + } + } + }, variant = ButtonVariant.Secondary, enabled = ready && !busy && nodeInput.isNotBlank()) + } + } + } + } + + SectionLabel("Funkstatistik") + OgCard { + val rows = stats?.let(RadioStats::rows).orEmpty() + if (rows.isEmpty()) { + InfoRow("Statistik", if (ready) "–" else "nicht verbunden") + } else { + rows.forEach { (label, value) -> InfoRow(label, value) } + } + Row(Modifier.padding(horizontal = 16.dp, vertical = 14.dp), horizontalArrangement = Arrangement.spacedBy(10.dp)) { + OgButton("Aktualisieren", { run { app.antenna.refreshInfo(); stats = app.antenna.radioStats() } }, Modifier.weight(1f), + variant = ButtonVariant.Secondary, enabled = ready && !busy, height = 46.dp, radius = 14.dp) + OgButton("Zurücksetzen", { run { stats = app.antenna.radioStats(reset = true) } }, Modifier.weight(1f), + variant = ButtonVariant.Secondary, enabled = ready && !busy, height = 46.dp, radius = 14.dp) + } + } + } + } +} + +private fun ignoreArgs(nodes: List) = buildJsonObject { + putJsonArray("ignore_nodes") { nodes.forEach { add(JsonPrimitive(it)) } } +} + +@Composable +private fun FirmwareSection(a: AntennaState) { + SectionLabel("Firmware") + OgCard { + InfoRow("Geräte-ID", a.deviceId ?: "–") + InfoRow("NodeID", a.nodeId ?: "–") + a.deviceName?.let { InfoRow("Name auf der Antenne", it) } + InfoRow("Version", a.fwVersion ?: "–") + a.fwBuild?.let { InfoRow("Build", it) } + InfoRow( + "Art", + when { + a.deviceId == null -> "–" + a.labRadio -> "Lab-Image" + a.radioDiagnostics -> "Team-Firmware, Diagnoseprofil" + else -> "Team-Firmware" + }, + ) + a.vaultStatus?.let { InfoRow("Tresor", it) } + a.secureBoot?.let { InfoRow("Secure Boot", if (it) "an" else "aus") } + a.flashEncryption?.let { InfoRow("Flash-Verschlüsselung", if (it) "an" else "aus") } + a.lockTimeoutS?.let { InfoRow("Sperrt ohne Befehl nach", if (it == 0) "nie" else "$it s") } + a.lastLock?.let { InfoRow("Zuletzt gesperrt", "${Formats.time(it.at)} · ${lockReasonShort(it.reason)}") } + a.lastDeviceError?.let { InfoRow("Letzter Gerätefehler", it) } + InfoRow("Verlorene Ereignisse", a.droppedEvents?.toString() ?: "–", last = true) + } +} + +@Composable +private fun RadioSection(a: AntennaState) { + val r = a.radio + SectionLabel("Funk") + OgCard { + InfoRow( + "Funkmodul", + when (a.radioRunning) { + true -> "läuft" + false -> "aus" + (a.radioError?.let { " (Fehler $it)" } ?: "") + null -> "–" + }, + ) + InfoRow("Frequenz", r?.freqMhz?.let { "${Formats.exactMhz(it)} MHz" } ?: "–") + r?.bwKhz?.let { InfoRow("Bandbreite", "${Formats.exactMhz(it)} kHz") } + r?.sf?.let { InfoRow("Spreading Factor", "SF$it") } + r?.cr?.let { InfoRow("Coding Rate", "4/$it") } + r?.txPowerDbm?.let { InfoRow("Sendeleistung", "$it dBm") } + r?.preamble?.let { InfoRow("Präambel", "$it Symbole") } + r?.syncWord?.let { InfoRow("Sync-Word", "0x" + it.toString(16).uppercase().padStart(2, '0')) } + InfoRow("Sendezeit 23 Bytes", r?.airtime23Ms?.let { "≈ $it ms" } ?: "–", last = true) + } +} + +@Composable +private fun MeshSection(mesh: MeshConfig?, enabled: Boolean, onChange: (JsonObject) -> Unit) { + SectionLabel("Mesh") + OgCard { + if (mesh == null) { + InfoRow("Mesh-Einstellungen", "nicht gelesen", last = true) + return@OgCard + } + mesh.hopDefault?.let { hops -> + Row( + Modifier.fillMaxWidth().heightIn(min = 68.dp).padding(horizontal = 16.dp, vertical = 10.dp).alpha(if (enabled) 1f else 0.4f), + verticalAlignment = Alignment.CenterVertically, + horizontalArrangement = Arrangement.spacedBy(10.dp), + ) { + Column(Modifier.weight(1f), verticalArrangement = Arrangement.spacedBy(3.dp)) { + Text("Hop-Limit", style = OgType.body) + Text("Wie oft andere Geräte eine eigene Nachricht höchstens weiterleiten (0 = nur direkt).", style = OgType.help.copy(fontSize = 13.sp)) + } + SmallButton("−", enabled = enabled && hops > 0, description = "Hop-Limit verringern") { + onChange(buildJsonObject { put("hop_default", hops - 1) }) + } + Text(hops.toString(), style = OgType.value.copy(fontSize = 16.sp), modifier = Modifier.semantics { contentDescription = "Hop-Limit $hops" }) + SmallButton("+", enabled = enabled && hops < MeshConfig.MAX_HOPS, description = "Hop-Limit erhöhen") { + onChange(buildJsonObject { put("hop_default", hops + 1) }) + } + } + CardDivider() + } + mesh.relayEnabled?.let { relay -> + SwitchRow("Weiterleiten", "Nachrichten anderer Geräte weitersenden.", relay, enabled) { on -> + onChange(buildJsonObject { put("relay_enabled", on) }) + } + CardDivider() + mesh.relayWhenLocked?.let { locked -> + SwitchRow("Auch gesperrt weiterleiten", "Die Antenne leitet weiter, auch wenn kein Handy sie entsperrt hat.", + locked, enabled && relay) { on -> onChange(buildJsonObject { put("relay_when_locked", on) }) } + CardDivider() + } + } + mesh.retries?.let { InfoRow("Wiederholungen pro Nachricht", it.toString()) } + InfoRow("Kanalprüfung vor dem Senden (CAD)", mesh.cadEnabled?.let { if (it) "an" else "aus" } ?: "–", last = true) + } +} + +@Composable +private fun SmallButton(text: String, enabled: Boolean, description: String, onClick: () -> Unit) { + Box( + Modifier.heightIn(min = 40.dp).clip(RoundedCornerShape(12.dp)).background(Og.surface2) + .border(1.dp, Og.border, RoundedCornerShape(12.dp)).alpha(if (enabled) 1f else 0.4f) + .clickable(enabled = enabled, role = Role.Button, onClick = onClick) + .semantics { contentDescription = description } + .padding(horizontal = 14.dp), + contentAlignment = Alignment.Center, + ) { + Text(text, style = TextStyle(fontFamily = Grotesk, fontSize = 15.sp, fontWeight = FontWeight(600), color = Og.text), + modifier = Modifier.padding(vertical = 8.dp)) + } +} diff --git a/native-android/app/src/main/java/ch/offgrid/android/ui/screens/ChatScreen.kt b/native-android/app/src/main/java/ch/offgrid/android/ui/screens/ChatScreen.kt index 4ab79e7..a786741 100644 --- a/native-android/app/src/main/java/ch/offgrid/android/ui/screens/ChatScreen.kt +++ b/native-android/app/src/main/java/ch/offgrid/android/ui/screens/ChatScreen.kt @@ -5,7 +5,6 @@ import androidx.activity.compose.rememberLauncherForActivityResult import androidx.activity.result.contract.ActivityResultContracts import androidx.compose.foundation.background import androidx.compose.foundation.border -import androidx.compose.foundation.clickable import androidx.compose.foundation.layout.Arrangement import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.BoxScope @@ -33,7 +32,6 @@ import androidx.compose.runtime.setValue import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.draw.clip -import androidx.compose.ui.semantics.Role import androidx.compose.ui.semantics.contentDescription import androidx.compose.ui.semantics.heading import androidx.compose.ui.semantics.semantics @@ -52,8 +50,9 @@ import ch.offgrid.android.domain.Conversation import ch.offgrid.android.domain.Formats import ch.offgrid.android.domain.Geo import ch.offgrid.android.domain.GeoFix +import ch.offgrid.android.domain.MessageDetails import ch.offgrid.android.domain.MessageLimits -import ch.offgrid.android.domain.REACTIONS +import ch.offgrid.android.domain.Messaging import ch.offgrid.android.ui.LocalApp import ch.offgrid.android.ui.Routes import ch.offgrid.android.ui.back @@ -89,7 +88,7 @@ fun ChatScreen(nav: NavHostController, contactId: Long) { val now = rememberNow() var draft by rememberSaveable { mutableStateOf("") } var locationSheet by rememberSaveable { mutableStateOf(false) } - var reactTo by remember { mutableStateOf(null) } + var detailsFor by remember { mutableStateOf(null) } LaunchedEffect(messages.size) { app.messaging.markRead(contactId) } ConversationOnScreen(Conversation.Direct(contactId)) // Opened from a notification for a contact that was deleted since: nothing to show. @@ -110,6 +109,13 @@ fun ChatScreen(nav: NavHostController, contactId: Long) { }, ) if (!ready) DisconnectedBanner { nav.navigate(Routes.CONNECT) } + if (c.state == Messaging.UNPAIRED) { + OgBanner( + "Neu koppeln", + "Die Antenne kennt ${c.firstName ?: c.displayName} nicht mehr. Scannt eure Codes erneut, dann könnt ihr wieder schreiben.", + "Koppeln", + ) { nav.navigate(Routes.add()) } + } MessageList(messages, now, Modifier.weight(1f), empty = "Noch keine Nachrichten. Schreib die erste.") { row -> val m = row.message if (m.kind == "geo") { @@ -119,12 +125,13 @@ fun ChatScreen(nav: NavHostController, contactId: Long) { out = m.direction == "out", status = m.status, text = m.text, - meta = metaFor(m, ready), + meta = metaFor(m, ready, c.firstName ?: c.displayName), groupStart = row.groupStart, continued = row.continued, reaction = m.peerReaction, onRetry = { app.messaging.retry(m.id) }, - onLongPress = if (m.direction == "in" && m.ctr != null) ({ reactTo = m }) else null, + onLongPress = { detailsFor = m.id }, + longPressLabel = if (m.direction == "in" && m.ctr != null) "Reagieren und Details" else "Details", ) } } @@ -146,25 +153,12 @@ fun ChatScreen(nav: NavHostController, contactId: Long) { app.messaging.sendLocation(c.id, fix) locationSheet = false } - // Keep the last target while the sheet slides out. - var lastReactTo by remember { mutableStateOf(null) } - reactTo?.let { lastReactTo = it } - OgSheet(reactTo != null, "Reaktion", onClose = { reactTo = null }) { - Row(Modifier.fillMaxWidth(), horizontalArrangement = Arrangement.SpaceBetween) { - REACTIONS.forEach { emoji -> - val chosen = lastReactTo?.peerReaction == emoji - Box( - Modifier.size(48.dp).clip(RoundedCornerShape(14.dp)).background(if (chosen) Og.accentSoft else Og.surface2) - .clickable(role = Role.Button, onClickLabel = if (chosen) "Reaktion entfernen" else "Reagieren") { - lastReactTo?.let { app.messaging.react(it, if (chosen) null else emoji) } - reactTo = null - }, - contentAlignment = Alignment.Center, - ) { Text(emoji, fontSize = 22.sp) } - } - } - OgButton("Abbrechen", { reactTo = null }, variant = ButtonVariant.Secondary) - } + MessageSheet( + message = detailsFor?.let { id -> messages.firstOrNull { it.id == id } }, + recipient = c.firstName ?: c.displayName, + onClose = { detailsFor = null }, + onReact = { m, emoji -> app.messaging.react(m, emoji) }, + ) } } @@ -231,18 +225,34 @@ fun MessageList( } } -/** Meta line: in → time; out → "14:03 · zugestellt", "wartet auf Funk …" or "in Warteschlange". */ -fun metaFor(m: MessageEntity, ready: Boolean): String { +/** + * Meta line: in → time; out → "14:03 · zugestellt" (", während offline" when only the reconciliation + * found the delivery), "14:03 · weitergeleitet", "Wartet auf Anna", "wartet auf Funk …", + * "in Warteschlange", or the failure word shown next to "Erneut senden". + */ +fun metaFor(m: MessageEntity, ready: Boolean, recipient: String? = null): String { val time = Formats.time(m.sentAt) if (m.direction == "in") return time return when (m.status) { - MessageStatus.DELIVERED -> "$time · zugestellt" - MessageStatus.SENT -> "$time · gesendet" + MessageStatus.DELIVERED -> if (m.deliveredOffline) "$time · zugestellt, während offline" else "$time · zugestellt" + MessageStatus.SENT -> when (m.deviceState) { + "relayed" -> "$time · weitergeleitet" + "retrying" -> "$time · wird wiederholt" + else -> "$time · gesendet" + } + MessageStatus.WAITING -> "Wartet auf ${recipient ?: "Empfänger"}" MessageStatus.LOCAL_QUEUED, MessageStatus.DEVICE_QUEUED -> if (ready) "wartet auf Funk …" else "in Warteschlange" + MessageStatus.FAILED -> failureText(m.failReason) else -> time } } +/** + * "Nicht gesendet" when the antenna refused the message (an `E_…` code from `msg.send`, or no contact + * slot); "Nicht zugestellt" when the antenna had it and gave up or lost it (`timeout`, `locked`, `lost` …). + */ +fun failureText(reason: String?): String = if (MessageDetails.failedBeforeSending(reason)) "Nicht gesendet" else "Nicht zugestellt" + @Composable private fun GeoBubble(row: MessageRow.Msg, c: ContactEntity, myFix: GeoFix?, now: Long, ready: Boolean, onOpen: () -> Unit, onRetry: () -> Unit) { val m = row.message @@ -258,7 +268,7 @@ private fun GeoBubble(row: MessageRow.Msg, c: ContactEntity, myFix: GeoFix?, now title = if (out) "Mein Standort" else "Standort von ${c.firstName ?: c.displayName}", coordinate = Geo.formatCoordinate(lat, lon), accuracy = m.accuracyM?.let(Geo::formatAccuracy), - meta = metaFor(m, ready), + meta = metaFor(m, ready, c.firstName ?: c.displayName), distance = if (fresh) Geo.formatDistance(Geo.distanceMeters(myFix!!.latitude, myFix.longitude, lat, lon)) else null, directionText = bearing?.let { "Richtung ${Geo.compassName(it)}" }, bearing = bearing, @@ -278,6 +288,8 @@ fun ChatComposer( antenna: AntennaState, onSend: () -> Unit, onLocation: (() -> Unit)?, + /** A group chat counts plain UTF-8 bytes against `max_group_text_bytes`; the lab codec does not apply to groups. */ + groupMaxBytes: Int? = null, ) { val ready = antenna.ready Composer( @@ -287,10 +299,13 @@ fun ChatComposer( label = "Nachricht an $target", sendLabel = if (ready) "Senden" else "In Warteschlange legen", // On air, not typed: a lab image with the OGZ1 codec fits more text into the same bytes. - usedBytes = MessageLimits.onAirTextBytes(draft, antenna.textCodec, antenna.maxTextInputBytes), - maxBytes = antenna.maxTextBytes, + usedBytes = if (groupMaxBytes != null) MessageLimits.utf8Bytes(draft) + else MessageLimits.onAirTextBytes(draft, antenna.textCodec, antenna.maxTextInputBytes), + maxBytes = groupMaxBytes ?: antenna.maxTextBytes, onSend = onSend, onLocation = onLocation, + parts = if (groupMaxBytes != null) MessageLimits.splitRaw(draft, groupMaxBytes).size else MessageLimits.split(draft, antenna).size, + maxParts = MessageLimits.MAX_PARTS, ) } diff --git a/native-android/app/src/main/java/ch/offgrid/android/ui/screens/Common.kt b/native-android/app/src/main/java/ch/offgrid/android/ui/screens/Common.kt index f9fe4a0..074b447 100644 --- a/native-android/app/src/main/java/ch/offgrid/android/ui/screens/Common.kt +++ b/native-android/app/src/main/java/ch/offgrid/android/ui/screens/Common.kt @@ -16,11 +16,14 @@ import androidx.compose.runtime.remember import androidx.compose.runtime.setValue import androidx.compose.ui.Modifier import androidx.lifecycle.compose.LifecycleResumeEffect +import ch.offgrid.android.domain.AntennaActivity import ch.offgrid.android.domain.AntennaError +import ch.offgrid.android.domain.AntennaManager import ch.offgrid.android.domain.Conversation import ch.offgrid.android.domain.KeyPattern import ch.offgrid.android.domain.LocationError import ch.offgrid.android.domain.PairingError +import ch.offgrid.android.domain.ResetResult import ch.offgrid.android.ui.LocalApp import ch.offgrid.android.ui.theme.Og import kotlinx.coroutines.delay @@ -47,23 +50,91 @@ fun rememberNow(): Long { return now } +/** Whole seconds until [at] (phone time), ticking every second; null when [at] is null. */ +@Composable +fun rememberSecondsUntil(at: Long?): Long? { + if (at == null) return null + var left by remember(at) { mutableLongStateOf(((at - System.currentTimeMillis() + 999) / 1000).coerceAtLeast(0)) } + LaunchedEffect(at) { + while (left > 0) { + delay(1_000) + left = ((at - System.currentTimeMillis() + 999) / 1000).coerceAtLeast(0) + } + } + return left +} + fun patternFor(fingerprint: String): BooleanArray = KeyPattern.fromSeed(KeyPattern.contactSeed(fingerprint)) -/** Texts from the screen spec table "Fehlertexte". */ -fun AntennaError.text(): String = when (this) { +/** + * Texts from the screen spec table "Fehlertexte". [code] is the link error code behind [AntennaError.REJECTED], + * [retryInS] the estimated seconds left of a rate limit, [vaultStatus] what `sys.status` says about the vault. + */ +fun AntennaError.text(code: String? = null, retryInS: Long? = null, vaultStatus: String? = null): String = when (this) { AntennaError.NO_DEVICE -> "Keine Antenne gefunden. Prüfe das USB-C-Kabel." AntennaError.PERMISSION_DENIED -> "Zugriff auf die Antenne wurde nicht erlaubt." AntennaError.OPEN_FAILED -> "Die Antenne liess sich nicht öffnen. Steck sie neu ein." AntennaError.NO_INFO -> "Die Antenne antwortet nicht." AntennaError.PROTO_MISMATCH -> "Die Firmware der Antenne passt nicht zu dieser App-Version." - AntennaError.LOST -> "Verbindung zur Antenne verloren." + AntennaError.LOST -> "Verbindung zur Antenne verloren. Ist das Kabel noch eingesteckt?" AntennaError.UNLOCK_FAILED -> "Diese Antenne ist mit einem anderen Handy verbunden. Übertrage sie mit „Daten exportieren“ vom alten Handy." + AntennaError.RATE_LIMITED -> "Zu viele fehlgeschlagene Entsperrversuche. Die Antenne lässt erst nach einer Wartezeit wieder einen Versuch zu " + + "(bis zu einer Minute)." + when { + retryInS == null -> "" + retryInS > 0 -> " Neuer Versuch in $retryInS s." + else -> " Neuer Versuch läuft …" + } + AntennaError.NO_SESSION -> "Die Anmeldung bei der Antenne ist abgelaufen. Tippe auf „Erneut suchen“." + AntennaError.VAULT_ERROR -> "Die Antenne kann ihren Schlüsselspeicher nicht lesen" + (vaultStatus?.let { " ($it)" } ?: "") + + ". Steck sie neu ein. Hilft das nicht, muss sie zurückgesetzt werden." + AntennaError.MOCK_FIRMWARE -> "Auf der Antenne läuft eine Test-Firmware ohne echte Verschlüsselung. Spiel eine aktuelle Firmware auf." + AntennaError.UNRESPONSIVE -> "Die Antenne antwortet nicht mehr. Steck sie neu ein." + AntennaError.REJECTED -> "Die Antenne hat die Verbindung abgelehnt" + (code?.let { " ($it)." } ?: ".") +} + +/** Why the antenna locked itself (`sec.state` reason, or a restart), for the connect screen and the antenna info. */ +fun lockReasonText(reason: String): String = when (reason) { + "heartbeat_timeout" -> "Die Antenne hat sich gesperrt, weil sie zu lange nichts vom Handy gehört hat." + "lock" -> "Die Antenne wurde gesperrt." + "factory_reset" -> "Die Antenne wird zurückgesetzt und danach für dieses Handy neu eingerichtet." + "error" -> "Die Antenne hat sich wegen eines internen Fehlers gesperrt." + AntennaManager.REASON_RESTART -> "Die Antenne wurde neu gestartet und war danach gesperrt." + else -> "Die Antenne ist gesperrt." +} + +/** Short form of [lockReasonText] for an info row. */ +fun lockReasonShort(reason: String): String = when (reason) { + "heartbeat_timeout" -> "kein Lebenszeichen vom Handy" + "lock" -> "gesperrt" + "factory_reset" -> "Zurücksetzen" + "error" -> "interner Fehler" + AntennaManager.REASON_RESTART -> "Neustart" + else -> reason +} + +/** Meta of the step "Verbindung wird aufgebaut" while the session works on the antenna. */ +fun AntennaActivity.text(): String = when (this) { + AntennaActivity.HELLO -> "Antenne startet …" + AntennaActivity.PROVISIONING -> "Neue Antenne wird eingerichtet" + AntennaActivity.UNLOCKING -> "Wird entsperrt" + AntennaActivity.RELOCKING -> "Wird wieder entsperrt" + AntennaActivity.RESETTING -> "Wird zurückgesetzt" +} + +/** Why "Alle Daten löschen" stopped; null when it went through. */ +fun ResetResult.text(): String? = when (this) { + ResetResult.DONE, ResetResult.NOT_CONNECTED -> null + ResetResult.WRONG_PHONE -> "Die Antenne gehört zu einem anderen Handy und wurde nicht zurückgesetzt. Auf diesem Handy wurde nichts gelöscht." + ResetResult.RATE_LIMITED -> "Zu viele fehlgeschlagene Versuche. Die Antenne wartet bis zu einer Minute. Versuch es dann erneut. Es wurde nichts gelöscht." + ResetResult.UNSUPPORTED -> "Diese Antennen-Firmware lässt sich nur mit dem Knopf zurücksetzen. Es wurde nichts gelöscht." + ResetResult.FAILED -> "Die Antenne konnte nicht zurückgesetzt werden. Es wurde nichts gelöscht." } fun PairingError.text(): String = when (this) { PairingError.INVALID_QR -> "Das ist kein OffGrid-Code." PairingError.ANTENNA_NOT_READY -> "Antenne nicht verbunden. Der Schlüssel wird gesendet, sobald sie verbunden ist." - PairingError.CONTACT_EXISTS -> "Dieser Kontakt ist schon gespeichert." + PairingError.CONTACT_EXISTS -> "Dieser Kontakt ist schon gespeichert. „Neu koppeln“ ersetzt eure Schlüssel; dein Gegenüber muss dich dann auch neu scannen." + PairingError.CODE_USED -> "Diesen Code hat die Antenne schon verwendet. Dein Gegenüber soll „Kontakt hinzufügen“ neu öffnen, dann scannst du den neuen Code." PairingError.SELF_PAIR -> "Das ist dein eigener Code." PairingError.FAILED -> "Der Schlüsselaustausch hat nicht geklappt. Versucht es erneut." } diff --git a/native-android/app/src/main/java/ch/offgrid/android/ui/screens/ConnectScreen.kt b/native-android/app/src/main/java/ch/offgrid/android/ui/screens/ConnectScreen.kt index d4f15d3..d8216ba 100644 --- a/native-android/app/src/main/java/ch/offgrid/android/ui/screens/ConnectScreen.kt +++ b/native-android/app/src/main/java/ch/offgrid/android/ui/screens/ConnectScreen.kt @@ -72,6 +72,8 @@ fun ConnectScreen(onNext: (onboardingDone: Boolean) -> Unit) { // On phone-sized screens the note sits below the fold; bring it into view when it appears. LaunchedEffect(state.error) { if (state.error != null) scroll.animateScrollTo(scroll.maxValue) } val phase = state.phase + val radioDown = state.ready && state.radioRunning == false + val retryIn = rememberSecondsUntil(state.retryAt) val found = phase == AntennaPhase.DEVICE_FOUND || phase == AntennaPhase.CONNECTING || phase == AntennaPhase.READY Page { Column(Modifier.weight(1f).verticalScroll(scroll)) { @@ -117,15 +119,23 @@ fun ConnectScreen(onNext: (onboardingDone: Boolean) -> Unit) { AntennaPhase.CONNECTING, AntennaPhase.DEVICE_FOUND -> StepState.Active else -> StepState.Todo }, + meta = state.activity?.text() ?: if (phase == AntennaPhase.READY) state.deviceId else null, ), Step( - "Funkmodul bereit", - if (phase == AntennaPhase.READY) StepState.Done else StepState.Todo, + if (radioDown) "Funkmodul nicht bereit" else "Funkmodul bereit", + if (phase == AntennaPhase.READY && !radioDown) StepState.Done else StepState.Todo, meta = if (phase == AntennaPhase.READY) state.fwVersion?.let { "FW $it" } else null, ), ), ) - state.error?.let { OgNote(it.text()) } + state.lockReason?.takeIf { !state.ready }?.let { OgNote(lockReasonText(it)) } + state.error?.let { OgNote(it.text(state.errorCode, retryIn, state.vaultStatus)) } + if (radioDown) { + OgNote( + "Die Antenne ist entsperrt, aber ihr Funkmodul läuft nicht" + (state.radioError?.let { " (Fehler $it)" } ?: "") + + ". Nachrichten bleiben in der Warteschlange. Steck die Antenne neu ein.", + ) + } Spacer(Modifier.height(16.dp)) } Footer(top = 0.dp) { diff --git a/native-android/app/src/main/java/ch/offgrid/android/ui/screens/ContactsScreen.kt b/native-android/app/src/main/java/ch/offgrid/android/ui/screens/ContactsScreen.kt index c721676..cef9f45 100644 --- a/native-android/app/src/main/java/ch/offgrid/android/ui/screens/ContactsScreen.kt +++ b/native-android/app/src/main/java/ch/offgrid/android/ui/screens/ContactsScreen.kt @@ -40,9 +40,13 @@ import androidx.lifecycle.compose.collectAsStateWithLifecycle import androidx.navigation.NavHostController import ch.offgrid.android.BuildConfig import ch.offgrid.android.data.MessageEntity +import ch.offgrid.android.domain.AntennaActivity +import ch.offgrid.android.domain.AntennaPhase +import ch.offgrid.android.domain.AntennaState import ch.offgrid.android.domain.ConversationItem import ch.offgrid.android.domain.Formats import ch.offgrid.android.domain.KeyPattern +import ch.offgrid.android.domain.Messaging import ch.offgrid.android.domain.Settings import ch.offgrid.android.link.LinkKind import ch.offgrid.android.ui.LocalApp @@ -51,6 +55,7 @@ import ch.offgrid.android.ui.components.AvatarVariant import ch.offgrid.android.ui.components.Footer import ch.offgrid.android.ui.components.OgAvatar import ch.offgrid.android.ui.components.OgBadge +import ch.offgrid.android.ui.components.OgBanner import ch.offgrid.android.ui.components.OgButton import ch.offgrid.android.ui.components.OgIcon import ch.offgrid.android.ui.components.OgIconButton @@ -58,6 +63,7 @@ import ch.offgrid.android.ui.components.SignalBars import ch.offgrid.android.ui.components.StatusDot import ch.offgrid.android.ui.theme.Og import ch.offgrid.android.ui.theme.OgType +import kotlinx.coroutines.launch /** Screen 3 "Kontakte" with the empty state "Noch keine Kontakte". */ @OptIn(ExperimentalFoundationApi::class) @@ -98,14 +104,24 @@ fun ContactsScreen(nav: NavHostController) { Row(horizontalArrangement = Arrangement.spacedBy(8.dp)) { OgIconButton(OgIcon.Settings, "Einstellungen", { nav.navigate(Routes.SETTINGS) }) if (!empty) { - if (list.count { it.contact?.state == "active" } > 0) { + // Only firmware that lists the "groups" feature in sys.hello has group.* commands. + if (antenna.groups != null && list.count { it.contact?.state == "active" } > 0) { OgIconButton(OgIcon.Users, "Gruppe erstellen", { nav.navigate(Routes.NEW_GROUP) }) } OgIconButton(OgIcon.Plus, "Kontakt hinzufügen", { nav.navigate(Routes.add()) }) } } } - AntennaStatusLine(antenna.ready, antenna.kind, antenna.freqMhz) { nav.navigate(Routes.CONNECT) } + AntennaStatusLine(antenna) { nav.navigate(Routes.CONNECT) } + settings[Settings.REPAIR_NOTICE]?.toIntOrNull()?.takeIf { it > 0 }?.let { n -> + val who = if (n == 1) "einen Kontakt" else "$n Kontakte" + OgBanner( + "Neu koppeln", + "Die Antenne kennt $who nicht mehr, weil sie zurückgesetzt oder neu geflasht wurde. " + + "Scannt eure Codes erneut, dann könnt ihr wieder schreiben.", + "OK", + ) { app.scope.launch { app.settings.remove(Settings.REPAIR_NOTICE) } } + } HorizontalDivider(Modifier.padding(start = 20.dp, top = 6.dp, end = 20.dp, bottom = if (empty) 0.dp else 8.dp), thickness = 1.dp, color = Og.line) if (empty) { @@ -139,7 +155,8 @@ fun ContactsScreen(nav: NavHostController) { */ @OptIn(ExperimentalLayoutApi::class) @Composable -fun AntennaStatusLine(ready: Boolean, kind: LinkKind, freqMhz: Double?, onClick: () -> Unit) { +fun AntennaStatusLine(antenna: AntennaState, onClick: () -> Unit) { + val ready = antenna.ready Row( Modifier.padding(horizontal = 12.dp).fillMaxWidth().heightIn(min = 44.dp).clip(RoundedCornerShape(12.dp)) .clickable(role = Role.Button, onClick = onClick).padding(horizontal = 8.dp, vertical = 4.dp), @@ -148,11 +165,17 @@ fun AntennaStatusLine(ready: Boolean, kind: LinkKind, freqMhz: Double?, onClick: ) { StatusDot(ready) FlowRow(horizontalArrangement = Arrangement.spacedBy(8.dp), verticalArrangement = Arrangement.Center) { - Text(if (ready) "Antenne verbunden" else "Antenne getrennt", style = OgType.preview.copy(color = Og.text2), + Text(antennaStatusTitle(antenna), style = OgType.preview.copy(color = Og.text2), modifier = Modifier.align(Alignment.CenterVertically)) - val transport = if (kind == LinkKind.SIMULATED) "Simuliert" else "USB-C" + val transport = if (antenna.kind == LinkKind.SIMULATED) "Simuliert" else "USB-C" Text( - if (ready) "· $transport · ${freqMhz?.let(Formats::band) ?: "868"} MHz" else "· Tippen zum Verbinden", + when { + ready && antenna.radioRunning == false -> "· Funkmodul nicht bereit" + ready -> "· $transport · ${antenna.freqMhz?.let(Formats::band) ?: "868"} MHz" + antenna.phase == AntennaPhase.CONNECTING -> "· ${antenna.activity?.text() ?: "verbindet …"}" + antenna.busy -> "· sucht …" + else -> "· Tippen zum Verbinden" + }, style = OgType.meta, modifier = Modifier.align(Alignment.CenterVertically), ) @@ -160,10 +183,22 @@ fun AntennaStatusLine(ready: Boolean, kind: LinkKind, freqMhz: Double?, onClick: } } +/** First half of the status line: connected, being opened, locked with an error, or away. */ +fun antennaStatusTitle(antenna: AntennaState): String = when { + antenna.ready -> "Antenne verbunden" + antenna.phase == AntennaPhase.CONNECTING && antenna.activity == AntennaActivity.RELOCKING -> "Antenne gesperrt" + antenna.busy -> "Antenne wird verbunden" + antenna.phase == AntennaPhase.ERROR && antenna.deviceState == "locked" -> "Antenne gesperrt" + antenna.phase == AntennaPhase.ERROR -> "Antenne: Fehler" + else -> "Antenne getrennt" +} + @Composable private fun ConversationRow(item: ConversationItem, now: Long, onOpen: () -> Unit) { val contact = item.contact val pending = contact?.state == "pending" + // The antenna lost this contact's keys; the row keeps the history but needs a new pairing. + val unpaired = contact?.state == Messaging.UNPAIRED Row( Modifier.fillMaxWidth().clip(RoundedCornerShape(Og.rBtn)) .clickable(role = Role.Button, onClick = onOpen) @@ -173,7 +208,7 @@ private fun ConversationRow(item: ConversationItem, now: Long, onOpen: () -> Uni ) { when { item.group != null -> OgAvatar(groupPattern(item.group), 48.dp, AvatarVariant.Square) - pending -> OgAvatar(null, 48.dp, AvatarVariant.Pending) + pending || unpaired -> OgAvatar(null, 48.dp, AvatarVariant.Pending) else -> OgAvatar(patternFor(contact!!.fingerprint), 48.dp) } Column(Modifier.weight(1f), verticalArrangement = Arrangement.spacedBy(5.dp)) { @@ -181,13 +216,15 @@ private fun ConversationRow(item: ConversationItem, now: Long, onOpen: () -> Uni Text(item.group?.name ?: contact!!.displayName, style = OgType.bodyStrong, maxLines = 1, overflow = TextOverflow.Ellipsis, modifier = Modifier.weight(1f)) if (contact != null) { - val level = if (pending) 0 else Formats.signalLevel(contact.lastRssi, contact.lastSeenAt, now) - SignalBars(level, label = if (pending) null else Formats.signalLabel(level)) + val level = if (pending || unpaired) 0 else Formats.signalLevel(contact.lastRssi, contact.lastSeenAt, now) + SignalBars(level, label = if (pending || unpaired) null else Formats.signalLabel(level)) } } Row(horizontalArrangement = Arrangement.spacedBy(12.dp), verticalAlignment = Alignment.CenterVertically) { if (pending) { Text("Schlüssel ausstehend", style = OgType.preview.copy(color = Og.accent), modifier = Modifier.weight(1f)) + } else if (unpaired) { + Text("Neu koppeln", style = OgType.preview.copy(color = Og.danger), modifier = Modifier.weight(1f)) } else { Text( preview(item), diff --git a/native-android/app/src/main/java/ch/offgrid/android/ui/screens/GroupScreens.kt b/native-android/app/src/main/java/ch/offgrid/android/ui/screens/GroupScreens.kt index ffd22cf..b60e9b7 100644 --- a/native-android/app/src/main/java/ch/offgrid/android/ui/screens/GroupScreens.kt +++ b/native-android/app/src/main/java/ch/offgrid/android/ui/screens/GroupScreens.kt @@ -1,10 +1,21 @@ package ch.offgrid.android.ui.screens +import androidx.compose.foundation.layout.Arrangement +import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.Column +import androidx.compose.foundation.layout.Row +import androidx.compose.foundation.layout.Spacer +import androidx.compose.foundation.layout.fillMaxSize +import androidx.compose.foundation.layout.fillMaxWidth +import androidx.compose.foundation.layout.height +import androidx.compose.foundation.layout.heightIn import androidx.compose.foundation.layout.padding import androidx.compose.foundation.rememberScrollState +import androidx.compose.foundation.shape.RoundedCornerShape import androidx.compose.foundation.verticalScroll +import androidx.compose.material3.AlertDialog import androidx.compose.material3.Text +import androidx.compose.material3.TextButton import androidx.compose.runtime.Composable import androidx.compose.runtime.LaunchedEffect import androidx.compose.runtime.getValue @@ -13,31 +24,47 @@ import androidx.compose.runtime.remember import androidx.compose.runtime.rememberCoroutineScope import androidx.compose.runtime.saveable.rememberSaveable import androidx.compose.runtime.setValue +import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier +import androidx.compose.ui.text.TextStyle +import androidx.compose.ui.text.font.FontWeight import androidx.compose.ui.unit.dp import androidx.compose.ui.unit.em import androidx.lifecycle.compose.collectAsStateWithLifecycle import androidx.navigation.NavHostController +import ch.offgrid.android.data.ContactEntity import ch.offgrid.android.data.GroupEntity +import ch.offgrid.android.data.GroupMemberEntity +import ch.offgrid.android.data.KeyState import ch.offgrid.android.domain.Conversation import ch.offgrid.android.domain.KeyPattern +import ch.offgrid.android.domain.MessageDetails import ch.offgrid.android.domain.MessageLimits +import ch.offgrid.android.domain.Messaging import ch.offgrid.android.link.LinkClosedException import ch.offgrid.android.link.LinkCommandException import ch.offgrid.android.ui.LocalApp import ch.offgrid.android.ui.Routes import ch.offgrid.android.ui.back import ch.offgrid.android.ui.components.AvatarVariant +import ch.offgrid.android.ui.components.ButtonVariant +import ch.offgrid.android.ui.components.CardDivider import ch.offgrid.android.ui.components.CheckRow import ch.offgrid.android.ui.components.Footer +import ch.offgrid.android.ui.components.InfoRow import ch.offgrid.android.ui.components.MessageBubble import ch.offgrid.android.ui.components.OgAvatar +import ch.offgrid.android.ui.components.OgBanner import ch.offgrid.android.ui.components.OgButton import ch.offgrid.android.ui.components.OgCard +import ch.offgrid.android.ui.components.OgIcon +import ch.offgrid.android.ui.components.OgIconButton import ch.offgrid.android.ui.components.OgNote import ch.offgrid.android.ui.components.OgTextField import ch.offgrid.android.ui.components.OgTopBar import ch.offgrid.android.ui.components.SectionLabel +import ch.offgrid.android.ui.theme.Grotesk +import ch.offgrid.android.ui.theme.Og import ch.offgrid.android.ui.theme.OgType import kotlinx.coroutines.launch @@ -52,12 +79,14 @@ fun toggleMember(selected: List, id: Long, max: Int): List = when { else -> selected } -/** Group screen "Neue Gruppe" (optional T20; on the link a proposed `group.create`, see README). */ +/** Group screen "Neue Gruppe": `group.create` on the antenna, then the key goes to every member by `group.sync`. */ @Composable fun NewGroupScreen(nav: NavHostController) { val app = LocalApp.current val scope = rememberCoroutineScope() val contacts by app.messaging.contacts.collectAsStateWithLifecycle(initialValue = emptyList()) + val antenna by app.antenna.state.collectAsStateWithLifecycle() + val limit = antenna.groups?.maxOtherMembers ?: MessageLimits.MAX_GROUP_MEMBERS val active = contacts.filter { it.state == "active" } var name by rememberSaveable { mutableStateOf("") } // A LongArray is bundle-safe, so the ticks survive rotation and process death. @@ -75,7 +104,7 @@ fun NewGroupScreen(nav: NavHostController) { OgTextField("Gruppenname", name, { name = MessageLimits.clampToBytes(it, MessageLimits.MAX_NAME_BYTES) }, error = if (name.isNotEmpty() && !nameValid) GROUP_NAME_ERROR else null) } - SectionLabel("Mitglieder · ${selected.size} von ${MessageLimits.MAX_GROUP_MEMBERS}", list = false, weight = 500) + SectionLabel("Mitglieder · ${selected.size} von $limit", list = false, weight = 500) OgCard { active.forEachIndexed { i, c -> val checked = c.id in selected @@ -83,9 +112,9 @@ fun NewGroupScreen(nav: NavHostController) { name = c.displayName, pattern = patternFor(c.fingerprint), checked = checked, - enabled = checked || selected.size < MessageLimits.MAX_GROUP_MEMBERS, + enabled = checked || selected.size < limit, last = i == active.lastIndex, - ) { selectedIds = toggleMember(selected, c.id, MessageLimits.MAX_GROUP_MEMBERS).toLongArray() } + ) { selectedIds = toggleMember(selected, c.id, limit).toLongArray() } } } Text( @@ -107,6 +136,8 @@ fun NewGroupScreen(nav: NavHostController) { e is LinkClosedException -> "Antenne nicht verbunden. Gruppen werden auf der Antenne angelegt." e is LinkCommandException && e.error.code == "E_UNKNOWN_CMD" -> "Diese Antennen-Firmware kennt noch keine Gruppen." + e is LinkCommandException && e.error.code == "E_STORAGE_FULL" -> + "Die Antenne hat keinen freien Gruppenplatz mehr. Lösche zuerst eine Gruppe." else -> "Die Gruppe konnte nicht erstellt werden." } } @@ -117,7 +148,7 @@ fun NewGroupScreen(nav: NavHostController) { } } -/** Group chat: sender names over incoming bubbles, no location button, no delivery receipts. */ +/** Group chat: sender names over incoming bubbles, no location button, no delivery receipts, text only. */ @Composable fun GroupChatScreen(nav: NavHostController, groupId: Long) { val app = LocalApp.current @@ -127,6 +158,7 @@ fun GroupChatScreen(nav: NavHostController, groupId: Long) { val antenna by app.antenna.state.collectAsStateWithLifecycle() val now = rememberNow() var draft by rememberSaveable { mutableStateOf("") } + var detailsFor by remember { mutableStateOf(null) } LaunchedEffect(messages.size) { app.messaging.markGroupRead(groupId) } // A deleted group, or a stale id after process death, leads back instead of an empty screen. LeaveWhenGone(group == Lookup.Gone, nav) @@ -136,38 +168,220 @@ fun GroupChatScreen(nav: NavHostController, groupId: Long) { return } val count = members.count { it.groupId == groupId } + 1 + val pendingKeys = g.owner && members.any { it.groupId == groupId && (it.keyState == KeyState.QUEUED || it.keyState == KeyState.PENDING) } + val failedKeys = g.owner && members.any { it.groupId == groupId && it.keyState == KeyState.FAILED } - Page { - ChatHeader( - title = g.name, - meta = "Gruppe · $count Mitglieder", - onBack = { nav.back() }, - avatar = { OgAvatar(groupPattern(g), 40.dp, AvatarVariant.Square) }, - ) - if (!antenna.ready) DisconnectedBanner { nav.navigate(Routes.CONNECT) } - MessageList(messages, now, Modifier.weight(1f), empty = "Noch keine Nachrichten. Schreib die erste.") { row -> - val m = row.message - MessageBubble( - out = m.direction == "out", - status = m.status, - text = m.text, - meta = metaFor(m, antenna.ready), - groupStart = row.groupStart, - continued = row.continued, - senderName = if (row.showSender) m.senderName else null, - onRetry = { app.messaging.retry(m.id) }, + Box(Modifier.fillMaxSize()) { + Page { + ChatHeader( + title = g.name, + meta = "Gruppe · $count Mitglieder", + onBack = { nav.back() }, + avatar = { OgAvatar(groupPattern(g), 40.dp, AvatarVariant.Square) }, + trailing = { OgIconButton(OgIcon.Users, "Mitglieder", { nav.navigate(Routes.groupMembers(groupId)) }) }, + ) + if (!antenna.ready) DisconnectedBanner { nav.navigate(Routes.CONNECT) } + if (failedKeys) { + OgBanner("Schlüssel fehlt", "Nicht alle Mitglieder haben den Gruppenschlüssel bekommen. Sie können noch nicht mitlesen.", "Mitglieder") { + nav.navigate(Routes.groupMembers(groupId)) + } + } else if (pendingKeys) { + OgNote("Der Gruppenschlüssel wird noch an Mitglieder gesendet.") + } + MessageList(messages, now, Modifier.weight(1f), empty = "Noch keine Nachrichten. Schreib die erste.") { row -> + val m = row.message + MessageBubble( + out = m.direction == "out", + status = m.status, + text = m.text, + meta = metaFor(m, antenna.ready), + groupStart = row.groupStart, + continued = row.continued, + senderName = if (row.showSender) m.senderName else null, + onRetry = { app.messaging.retry(m.id) }, + onLongPress = { detailsFor = m.id }, + ) + } + ChatComposer( + draft = draft, + onDraft = { draft = it }, + target = g.name, + antenna = antenna, + onSend = { + app.messaging.sendGroupText(g.id, draft) + draft = "" + }, + onLocation = null, + groupMaxBytes = antenna.groups?.maxTextBytes ?: MessageLimits.DEFAULT_MAX_TEXT_BYTES, ) } - ChatComposer( - draft = draft, - onDraft = { draft = it }, - target = g.name, - antenna = antenna, - onSend = { - app.messaging.sendGroupText(g.id, draft) - draft = "" + MessageSheet(detailsFor?.let { id -> messages.firstOrNull { it.id == id } }, recipient = null, onClose = { detailsFor = null }) + } +} + +/** Key line of a member for the owner; null when there is nothing to deliver. */ +fun keyStateText(state: String): String? = when (state) { + KeyState.DELIVERED -> "Schlüssel zugestellt" + KeyState.QUEUED, KeyState.PENDING -> "Schlüssel ausstehend" + KeyState.FAILED -> "Schlüssel fehlgeschlagen" + else -> null +} + +/** A member the antenna holds no contact for is only known by its NodeID. */ +fun memberName(member: GroupMemberEntity, contacts: List): String = + contacts.firstOrNull { it.id == member.contactId }?.displayName ?: "Knoten ${member.nodeId}" + +/** + * Members of a group. The owner adds and removes members (each change gives every remaining member a new key) and + * sees which keys arrived, with "Erneut senden" for those that did not. + */ +@Composable +fun GroupMembersScreen(nav: NavHostController, groupId: Long) { + val app = LocalApp.current + val scope = rememberCoroutineScope() + val group by remember(groupId) { app.messaging.group(groupId).asLookup() }.collectAsStateWithLifecycle(Lookup.Loading) + val allMembers by app.messaging.members.collectAsStateWithLifecycle(initialValue = emptyList()) + val contacts by app.messaging.contacts.collectAsStateWithLifecycle(initialValue = emptyList()) + val antenna by app.antenna.state.collectAsStateWithLifecycle() + var addIds by rememberSaveable { mutableStateOf(LongArray(0)) } + var error by rememberSaveable { mutableStateOf(null) } + var working by remember { mutableStateOf(false) } + var confirmDelete by remember { mutableStateOf(false) } + LeaveWhenGone(group == Lookup.Gone, nav) + val g = group.found ?: run { + Page {} + return + } + val members = allMembers.filter { it.groupId == groupId }.sortedBy { it.member } + val limit = antenna.groups?.maxOtherMembers ?: MessageLimits.MAX_GROUP_MEMBERS + val candidates = contacts.filter { c -> c.state == "active" && members.none { it.contactId == c.id } } + val selected = addIds.filter { id -> candidates.any { it.id == id } } + val canChange = g.owner && antenna.ready && g.deviceGroupId != Messaging.NO_GROUP + + fun change(block: suspend () -> Result) { + working = true + error = null + scope.launch { + block().onFailure { e -> + error = when { + e is LinkClosedException -> "Antenne nicht verbunden." + e is LinkCommandException && e.error.code == "E_BUSY" -> + "Die Gruppe kann nicht mehr geändert werden. Erstelle eine neue Gruppe." + e is LinkCommandException && e.error.code == "E_INVALID_ARG" -> + "Die Antenne hat die Änderung abgelehnt. Eine Gruppe braucht mindestens zwei Mitglieder." + else -> "Die Änderung war nicht möglich." + } + }.onSuccess { addIds = LongArray(0) } + working = false + } + } + + Page { + OgTopBar(g.name, onBack = { nav.back() }, backLabel = "Zurück zur Gruppe") + Column(Modifier.weight(1f).verticalScroll(rememberScrollState())) { + SectionLabel("Mitglieder · ${members.size + 1}", list = false, weight = 500) + OgCard { + InfoRow("Ich", if (g.owner) "Besitzer" else null, last = members.isEmpty()) + members.forEachIndexed { i, m -> + val keyText = if (g.owner) keyStateText(m.keyState) else null + Column { + Row( + Modifier.fillMaxWidth().heightIn(min = 64.dp).padding(start = 16.dp, end = 4.dp), + verticalAlignment = Alignment.CenterVertically, + ) { + Column(Modifier.weight(1f), verticalArrangement = Arrangement.spacedBy(2.dp)) { + Text( + memberName(m, contacts) + if (!g.owner && m.member == 0) " · Besitzer" else "", + style = OgType.bodyStrong, maxLines = 1, + ) + if (keyText != null) { + val reason = MessageDetails.reason(m.syncReason)?.takeIf { m.keyState == KeyState.FAILED } + Text(listOfNotNull(keyText, reason).joinToString(" · "), style = OgType.help) + } + } + if (m.keyState == KeyState.FAILED) { + TextButton(onClick = { app.messaging.resendKey(groupId, m.member) }, enabled = antenna.ready) { + Text("Erneut senden", style = TextStyle(fontFamily = Grotesk, fontWeight = FontWeight(600), color = Og.text)) + } + } + if (canChange) { + TextButton(onClick = { change { app.messaging.removeMember(groupId, m.member) } }, enabled = !working) { + Text("Entfernen", style = TextStyle(fontFamily = Grotesk, fontWeight = FontWeight(600), color = Og.text)) + } + } + } + if (i != members.lastIndex) CardDivider() + } + } + } + if (g.owner) { + val room = limit - members.size + SectionLabel("Hinzufügen · ${selected.size} von $room", list = false, weight = 500) + if (candidates.isEmpty() || room <= 0) { + Text( + if (room <= 0) "Die Gruppe ist voll: höchstens $limit Mitglieder und du." + else "Alle Kontakte mit abgeschlossenem Handshake sind schon in der Gruppe.", + style = OgType.help.copy(lineHeight = 1.45.em), + modifier = Modifier.padding(start = 28.dp, end = 28.dp), + ) + } else { + OgCard { + candidates.forEachIndexed { i, c -> + val checked = c.id in selected + CheckRow( + name = c.displayName, + pattern = patternFor(c.fingerprint), + checked = checked, + enabled = canChange && (checked || selected.size < room), + last = i == candidates.lastIndex, + ) { addIds = toggleMember(selected, c.id, room).toLongArray() } + } + } + } + Text( + "Jede Änderung gibt allen Mitgliedern einen neuen Gruppenschlüssel. Entfernte Mitglieder können danach nicht mehr mitlesen.", + style = OgType.help.copy(lineHeight = 1.45.em), + modifier = Modifier.padding(start = 28.dp, top = 14.dp, end = 28.dp), + ) + } + error?.let { OgNote(it) } + Spacer(Modifier.height(12.dp)) + OgButton("Gruppe löschen", { confirmDelete = true }, variant = ButtonVariant.DangerText, enabled = !working) + } + if (g.owner && selected.isNotEmpty()) { + Footer(top = 0.dp) { + OgButton("Hinzufügen", enabled = canChange && !working, onClick = { change { app.messaging.addMembers(groupId, selected) } }) + } + } + } + + if (confirmDelete) { + AlertDialog( + onDismissRequest = { confirmDelete = false }, + containerColor = Og.surface, + shape = RoundedCornerShape(Og.rCard), + text = { + Text( + "Die Gruppe und ihr Verlauf werden auf diesem Handy und der Antenne gelöscht. Die anderen Mitglieder behalten die Gruppe.", + style = OgType.body, + ) + }, + confirmButton = { + TextButton(onClick = { + confirmDelete = false + // App scope: the delete must not be cut off when this screen goes away with the group. + app.scope.launch { + app.messaging.deleteGroup(groupId).onFailure { + error = if (it is LinkClosedException) "Antenne nicht verbunden. Die Gruppe wird auf der Antenne gelöscht." else "Die Gruppe konnte nicht gelöscht werden." + } + } + }) { Text("Löschen", style = TextStyle(fontFamily = Grotesk, fontWeight = FontWeight(700), color = Og.danger)) } + }, + dismissButton = { + TextButton(onClick = { confirmDelete = false }) { + Text("Abbrechen", style = TextStyle(fontFamily = Grotesk, fontWeight = FontWeight(600), color = Og.text)) + } }, - onLocation = null, ) } } diff --git a/native-android/app/src/main/java/ch/offgrid/android/ui/screens/MessageRows.kt b/native-android/app/src/main/java/ch/offgrid/android/ui/screens/MessageRows.kt index 94eaf8e..cda0fb7 100644 --- a/native-android/app/src/main/java/ch/offgrid/android/ui/screens/MessageRows.kt +++ b/native-android/app/src/main/java/ch/offgrid/android/ui/screens/MessageRows.kt @@ -40,7 +40,8 @@ fun messageRows(messages: List, now: Long): List = bu groupStart = previous != null && previous.direction != m.direction, continued = m.direction == "out" && previous?.direction == "out" && previous.status != MessageStatus.FAILED, showSender = m.direction == "in" && - (previous == null || previous.direction != "in" || previous.senderContactId != m.senderContactId), + (previous == null || previous.direction != "in" || previous.senderContactId != m.senderContactId || + previous.senderNodeId != m.senderNodeId), key = "msg-${m.id}", ), ) diff --git a/native-android/app/src/main/java/ch/offgrid/android/ui/screens/MessageSheet.kt b/native-android/app/src/main/java/ch/offgrid/android/ui/screens/MessageSheet.kt new file mode 100644 index 0000000..0ef79dc --- /dev/null +++ b/native-android/app/src/main/java/ch/offgrid/android/ui/screens/MessageSheet.kt @@ -0,0 +1,79 @@ +package ch.offgrid.android.ui.screens + +import androidx.compose.foundation.background +import androidx.compose.foundation.border +import androidx.compose.foundation.clickable +import androidx.compose.foundation.layout.Arrangement +import androidx.compose.foundation.layout.Box +import androidx.compose.foundation.layout.BoxScope +import androidx.compose.foundation.layout.Column +import androidx.compose.foundation.layout.Row +import androidx.compose.foundation.layout.fillMaxWidth +import androidx.compose.foundation.layout.size +import androidx.compose.foundation.shape.RoundedCornerShape +import androidx.compose.material3.Text +import androidx.compose.runtime.Composable +import androidx.compose.runtime.getValue +import androidx.compose.runtime.mutableStateOf +import androidx.compose.runtime.remember +import androidx.compose.runtime.setValue +import androidx.compose.ui.Alignment +import androidx.compose.ui.Modifier +import androidx.compose.ui.draw.clip +import androidx.compose.ui.semantics.Role +import androidx.compose.ui.unit.dp +import androidx.compose.ui.unit.sp +import ch.offgrid.android.data.MessageEntity +import ch.offgrid.android.domain.MessageDetails +import ch.offgrid.android.domain.REACTIONS +import ch.offgrid.android.ui.components.ButtonVariant +import ch.offgrid.android.ui.components.InfoRow +import ch.offgrid.android.ui.components.OgButton +import ch.offgrid.android.ui.components.OgSheet +import ch.offgrid.android.ui.theme.Og +import ch.offgrid.android.ui.theme.OgType + +/** + * Sheet after a long press on a bubble: the reactions for a peer's message (when [onReact] is set) and the + * transport details from [MessageDetails]. [message] is the live row, so a delivery that arrives while the + * sheet is open shows at once. + */ +@Composable +fun BoxScope.MessageSheet( + message: MessageEntity?, + recipient: String?, + onClose: () -> Unit, + onReact: ((MessageEntity, String?) -> Unit)? = null, +) { + // Keep the last message while the sheet slides out. + var last by remember { mutableStateOf(null) } + message?.let { last = it } + val m = last + val reactions = onReact != null && m != null && m.direction == "in" && m.ctr != null + OgSheet(message != null, if (reactions) "Nachricht" else "Details", onClose = onClose) { + if (m == null) return@OgSheet + if (reactions) { + Row(Modifier.fillMaxWidth(), horizontalArrangement = Arrangement.SpaceBetween) { + REACTIONS.forEach { emoji -> + val chosen = m.peerReaction == emoji + Box( + Modifier.size(48.dp).clip(RoundedCornerShape(14.dp)).background(if (chosen) Og.accentSoft else Og.surface2) + .clickable(role = Role.Button, onClickLabel = if (chosen) "Reaktion entfernen" else "Reagieren") { + onReact?.invoke(m, if (chosen) null else emoji) + onClose() + }, + contentAlignment = Alignment.Center, + ) { Text(emoji, fontSize = 22.sp) } + } + } + } + val rows = MessageDetails.rows(m, recipient) + Column(Modifier.fillMaxWidth().clip(RoundedCornerShape(Og.rCard)).border(1.dp, Og.border, RoundedCornerShape(Og.rCard))) { + rows.forEachIndexed { i, (label, value) -> InfoRow(label, value, last = i == rows.lastIndex) } + } + if (!MessageDetails.hasRadioDetails(m) && m.direction == "out") { + Text("Hops, Wiederholungen und Laufzeit meldet die Antenne mit der Zustellung. Ältere Firmware meldet sie nicht.", style = OgType.meta) + } + OgButton("Schliessen", onClose, variant = ButtonVariant.Secondary) + } +} diff --git a/native-android/app/src/main/java/ch/offgrid/android/ui/screens/SettingsScreen.kt b/native-android/app/src/main/java/ch/offgrid/android/ui/screens/SettingsScreen.kt index af1edd5..577dc90 100644 --- a/native-android/app/src/main/java/ch/offgrid/android/ui/screens/SettingsScreen.kt +++ b/native-android/app/src/main/java/ch/offgrid/android/ui/screens/SettingsScreen.kt @@ -32,6 +32,7 @@ import androidx.compose.runtime.saveable.rememberSaveable import androidx.compose.runtime.setValue import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier +import androidx.compose.ui.draw.alpha import androidx.compose.ui.platform.LocalContext import androidx.compose.ui.platform.LocalFocusManager import androidx.compose.ui.semantics.Role @@ -62,6 +63,7 @@ import ch.offgrid.android.ui.components.OgButton import ch.offgrid.android.ui.components.OgCard import ch.offgrid.android.ui.components.OgIcon import ch.offgrid.android.ui.components.OgIconView +import ch.offgrid.android.ui.components.OgNote import ch.offgrid.android.ui.components.OgSwitch import ch.offgrid.android.ui.components.OgTextField import ch.offgrid.android.ui.components.OgTopBar @@ -92,6 +94,8 @@ fun SettingsScreen(nav: NavHostController) { var name by rememberSaveable { mutableStateOf(null) } var nameError by rememberSaveable { mutableStateOf(false) } var confirmDelete by rememberSaveable { mutableStateOf(false) } + var deleting by remember { mutableStateOf(false) } + var deleteError by remember { mutableStateOf(null) } LaunchedEffect(settings[Settings.DISPLAY_NAME]) { if (name == null) name = settings[Settings.DISPLAY_NAME] } val pattern = remember(settings[Settings.OWN_PUBLIC_KEY], installId) { KeyPattern.fromSeed(settings[Settings.OWN_PUBLIC_KEY] ?: installId ?: "") @@ -186,6 +190,24 @@ fun SettingsScreen(nav: NavHostController) { } } + SectionLabel("Erweitert") + OgCard { + // Lab boards always show it; for the team firmware it is behind a switch, most people never need it. + if (!antenna.labRadio) { + SwitchRow("Erweiterte Einstellungen", "Firmware, Funk, Mesh und Statistik der Antenne.", + settings[Settings.SHOW_ADVANCED] == "true") { on -> + scope.launch { app.settings.put(Settings.SHOW_ADVANCED, on.toString()) } + } + } + if (antenna.labRadio || settings[Settings.SHOW_ADVANCED] == "true") { + if (!antenna.labRadio) CardDivider() + LinkRow(OgIcon.Antenna, if (antenna.labRadio) "Erweitert / Lab" else "Erweitert", + "Firmware, Funk, Mesh${if (antenna.labRadio) ", Ignorierliste, Codec" else ""} und Funkstatistik.") { + nav.navigate(Routes.ADVANCED) + } + } + } + SectionLabel("Handywechsel") OgCard { LinkRow(OgIcon.Upload, "Daten exportieren", "Kontakte, Schlüssel und Nachrichten als Datei, mit Passwort geschützt.") { @@ -199,8 +221,10 @@ fun SettingsScreen(nav: NavHostController) { OgCard { InfoRow("Kontakte", contacts.size.toString()) InfoRow("Nachrichten", messageCount.toString()) - OgButton("Alle Daten löschen", { confirmDelete = true }, variant = ButtonVariant.DangerText) + OgButton(if (deleting) "Wird gelöscht …" else "Alle Daten löschen", { deleteError = null; confirmDelete = true }, + variant = ButtonVariant.DangerText, enabled = !deleting) } + deleteError?.let { OgNote(it) } Text( "OffGrid ${BuildConfig.VERSION_NAME}", style = OgType.meta, @@ -217,17 +241,31 @@ fun SettingsScreen(nav: NavHostController) { shape = RoundedCornerShape(Og.rCard), text = { Text( - "Alle Kontakte und Nachrichten auf diesem Handy löschen? Das lässt sich nicht rückgängig machen.", + if (antenna.ready) { + "Alle Kontakte und Nachrichten löschen und die Antenne auf Werkseinstellungen zurücksetzen? " + + "Danach müsst ihr euch neu koppeln. Das lässt sich nicht rückgängig machen." + } else { + "Alle Kontakte und Nachrichten auf diesem Handy löschen? Die Antenne ist nicht verbunden und " + + "behält ihre Kontakte; verbinde sie zuerst, um sie mitzulöschen. Das lässt sich nicht rückgängig machen." + }, style = OgType.body, ) }, confirmButton = { TextButton(onClick = { confirmDelete = false - scope.launch { - app.messaging.deleteAll() - app.resetAnalyticsId() - nav.navigate(Routes.CONTACTS) { popUpTo(Routes.CONTACTS) { inclusive = true } } + deleting = true + // App scope: the reset must not be cut off when this screen goes away. + app.scope.launch { + val result = app.messaging.deleteAll() + scope.launch { + deleting = false + deleteError = result.text() + if (deleteError == null) { + app.resetAnalyticsId() + nav.navigate(Routes.CONTACTS) { popUpTo(Routes.CONTACTS) { inclusive = true } } + } + } } }) { Text("Löschen", style = TextStyle(fontFamily = Grotesk, fontWeight = FontWeight(700), color = Og.danger)) } }, @@ -241,11 +279,11 @@ fun SettingsScreen(nav: NavHostController) { } @Composable -private fun SwitchRow(title: String, help: String?, checked: Boolean, onChange: (Boolean) -> Unit) { +internal fun SwitchRow(title: String, help: String?, checked: Boolean, enabled: Boolean = true, onChange: (Boolean) -> Unit) { // The whole row toggles, so TalkBack reads title, help and state as one switch. Row( - Modifier.fillMaxWidth().heightIn(min = if (help != null) 68.dp else 60.dp) - .toggleable(checked, role = Role.Switch, onValueChange = onChange) + Modifier.fillMaxWidth().heightIn(min = if (help != null) 68.dp else 60.dp).alpha(if (enabled) 1f else 0.4f) + .toggleable(checked, enabled = enabled, role = Role.Switch, onValueChange = onChange) .padding(horizontal = 16.dp, vertical = 10.dp), verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(14.dp), @@ -259,7 +297,7 @@ private fun SwitchRow(title: String, help: String?, checked: Boolean, onChange: } @Composable -private fun LinkRow(icon: OgIcon, title: String, text: String, onClick: () -> Unit) { +internal fun LinkRow(icon: OgIcon, title: String, text: String, onClick: () -> Unit) { Row( Modifier.fillMaxWidth().heightIn(min = 72.dp).clickable(role = Role.Button, onClick = onClick).padding(horizontal = 16.dp, vertical = 12.dp), verticalAlignment = Alignment.CenterVertically, diff --git a/native-android/app/src/test/java/ch/offgrid/android/crypto/TokenWrapFirmwareVectorTest.kt b/native-android/app/src/test/java/ch/offgrid/android/crypto/TokenWrapFirmwareVectorTest.kt new file mode 100644 index 0000000..e5e472b --- /dev/null +++ b/native-android/app/src/test/java/ch/offgrid/android/crypto/TokenWrapFirmwareVectorTest.kt @@ -0,0 +1,69 @@ +package ch.offgrid.android.crypto + +import org.junit.Assert.assertArrayEquals +import org.junit.Assert.assertEquals +import org.junit.Assert.assertThrows +import org.junit.Test + +/** + * The app's token wrap against vectors computed independently from the firmware's `Security::unwrap` + * (OffGridCH/firmware `feature/mesh-direct`, `src/security/Security.cpp`) with Python `cryptography`. + * Regenerate with `python tools/wrap_vectors.py`; the inputs below are the script's fixed inputs. + */ +class TokenWrapFirmwareVectorTest { + // byte i of the 12-hex device_id string is byte i of the device_id the firmware binds into HKDF and AAD + private val deviceId = OgCrypto.unhex("A4CF12F00D42") + private val kPhone = OgCrypto.sha256("offgrid-lab3-test-phone".toByteArray()) + private val devicePriv = OgCrypto.sha256("lab3-device-eph".toByteArray()) + private val appPriv = OgCrypto.sha256("lab3-app-eph".toByteArray()) + private val nonce = ByteArray(16) { (0xA0 + it).toByte() } + private val iv = ByteArray(12) { (0xC0 + it).toByte() } + private val token = FixedKeyUnlockTokenSource(kPhone).token(deviceId) + private val devicePub = OgCrypto.x25519PublicKey(devicePriv) + + @Test + fun tokenAndKeysMatchThePythonVectors() { + assertEquals("94b40ca8489d5c45e898aa06ea1c1be498e76a413b071d642944f452971a2fba", OgCrypto.hex(kPhone).lowercase()) + assertEquals("9d13223c326261038551a88b95344e773776b4933cdff1d65c5a09160ed3861d", OgCrypto.hex(token).lowercase()) + assertEquals("GwmZHT/GaxR8zgYEQpZbj8cLL6pe/VwVM+nsod1y+D8=", OgCrypto.b64(devicePub)) + assertEquals("oKGio6SlpqeoqaqrrK2urw==", OgCrypto.b64(nonce)) + } + + @Test + fun unlockEnvelopeMatchesTheFirmwareLayout() { + val w = TokenWrap.wrap(token, deviceId, devicePub, nonce, WrapPurpose.UNLOCK, appEphPrivate = appPriv, iv = iv) + assertEquals("++O/5uAfCkpZuRYN3vtPMk0AhUKWY52l6HQOz/nkMGw=", OgCrypto.b64(w.appEphPub)) + assertEquals("wMHCw8TFxsfIycrLFVGt58hU/tktNkM7r316VJHwE3EHbF7nXE8G6qMlr6ed7nWJACkngOAbP7bruJl7", OgCrypto.b64(w.wrapped)) + assertEquals(60, w.wrapped.size) + assertArrayEquals("iv leads the envelope", iv, w.wrapped.copyOfRange(0, 12)) + assertArrayEquals(token, TokenWrap.unwrap(w.wrapped, deviceId, devicePriv, w.appEphPub, nonce, WrapPurpose.UNLOCK)) + } + + @Test + fun resetEnvelopeUsesItsOwnLabel() { + val w = TokenWrap.wrap(token, deviceId, devicePub, nonce, WrapPurpose.RESET, appEphPrivate = appPriv, iv = iv) + assertEquals("wMHCw8TFxsfIycrL+9LSWnqL0CAeOvJeke4W5qztIr+2+yn3oVLnCvwyohkK58V/Ke7YA0aHRGS4TJUd", OgCrypto.b64(w.wrapped)) + assertArrayEquals(token, TokenWrap.unwrap(w.wrapped, deviceId, devicePriv, w.appEphPub, nonce, WrapPurpose.RESET)) + } + + @Test + fun anUnlockEnvelopeCannotAuthorizeAReset() { + val unlock = TokenWrap.wrap(token, deviceId, devicePub, nonce, WrapPurpose.UNLOCK, appEphPrivate = appPriv, iv = iv) + assertThrows(Exception::class.java) { + TokenWrap.unwrap(unlock.wrapped, deviceId, devicePriv, unlock.appEphPub, nonce, WrapPurpose.RESET) + } + val reset = TokenWrap.wrap(token, deviceId, devicePub, nonce, WrapPurpose.RESET, appEphPrivate = appPriv, iv = iv) + assertThrows(Exception::class.java) { + TokenWrap.unwrap(reset.wrapped, deviceId, devicePriv, reset.appEphPub, nonce, WrapPurpose.UNLOCK) + } + } + + @Test + fun theEnvelopeIsBoundToTheDeviceId() { + val w = TokenWrap.wrap(token, deviceId, devicePub, nonce, appEphPrivate = appPriv, iv = iv) + val otherDevice = OgCrypto.unhex("420DF012CFA4") + assertThrows(Exception::class.java) { + TokenWrap.unwrap(w.wrapped, otherDevice, devicePriv, w.appEphPub, nonce) + } + } +} diff --git a/native-android/app/src/test/java/ch/offgrid/android/data/MigrationTest.kt b/native-android/app/src/test/java/ch/offgrid/android/data/MigrationTest.kt new file mode 100644 index 0000000..11d60b1 --- /dev/null +++ b/native-android/app/src/test/java/ch/offgrid/android/data/MigrationTest.kt @@ -0,0 +1,125 @@ +package ch.offgrid.android.data + +import kotlinx.serialization.json.Json +import kotlinx.serialization.json.JsonArray +import kotlinx.serialization.json.JsonObject +import kotlinx.serialization.json.jsonArray +import kotlinx.serialization.json.jsonObject +import kotlinx.serialization.json.jsonPrimitive +import org.junit.After +import org.junit.Assert.assertEquals +import org.junit.Before +import org.junit.Test +import java.io.File +import java.sql.Connection +import java.sql.DriverManager + +/** + * Runs [MIGRATION_3_4_SQL] on a plain SQLite database built from the exported Room schemas. Room's own + * `MigrationTestHelper` needs a device; this checks the same two things: the data survives, and the result has + * exactly the tables `4.json` describes (columns, types, null rules, defaults, keys). + */ +class MigrationTest { + private lateinit var old: Connection + private lateinit var fresh: Connection + + @Before + fun open() { + old = DriverManager.getConnection("jdbc:sqlite::memory:") + fresh = DriverManager.getConnection("jdbc:sqlite::memory:") + createSchema(old, 3) + createSchema(fresh, 4) + } + + @After + fun close() { + old.close() + fresh.close() + } + + private fun schema(version: Int): JsonObject { + val file = File("schemas/ch.offgrid.android.data.OffGridDatabase/$version.json") + return Json.parseToJsonElement(file.readText()).jsonObject["database"]!!.jsonObject + } + + private fun createSchema(db: Connection, version: Int) { + schema(version)["entities"]!!.jsonArray.forEach { entity -> + val e = entity.jsonObject + val table = e["tableName"]!!.jsonPrimitive.content + db.createStatement().use { it.execute(e["createSql"]!!.jsonPrimitive.content.replace("\${TABLE_NAME}", table)) } + (e["indices"] as? JsonArray).orEmpty().forEach { index -> + db.createStatement().use { it.execute(index.jsonObject["createSql"]!!.jsonPrimitive.content.replace("\${TABLE_NAME}", table)) } + } + } + } + + private fun exec(db: Connection, sql: String) = db.createStatement().use { it.execute(sql) } + + private fun columns(db: Connection, table: String): List> = db.createStatement().use { st -> + st.executeQuery("PRAGMA table_info(`$table`)").use { rs -> + buildList { + while (rs.next()) { + // name, type, notnull, default, pk position; the column order is not part of the contract. + add(listOf(rs.getString("name"), rs.getString("type"), rs.getString("notnull"), rs.getString("dflt_value"), rs.getString("pk"))) + } + }.sortedBy { it[0] } + } + } + + @Test + fun migrationKeepsGroupsAndMembersAndGivesTheNewShape() { + exec(old, "INSERT INTO contacts VALUES (1,'D1',3,'Anna',NULL,NULL,'E841','pkA','fp','active',NULL,NULL,NULL,1)") + exec(old, "INSERT INTO contacts VALUES (2,'D1',4,'Luca',NULL,NULL,'5C07','pkL','fp','active',NULL,NULL,NULL,1)") + exec(old, "INSERT INTO groups VALUES (1,'D1',2,'Gipfeltour',100)") + exec(old, "INSERT INTO group_members VALUES (1,2)") + exec(old, "INSERT INTO group_members VALUES (1,1)") + exec( + old, + "INSERT INTO messages (groupId, direction, kind, text, status, senderContactId, senderName, sentAt) " + + "VALUES (1,'in','text','Hoi',3,1,'Anna',200)", + ) + + MIGRATION_3_4_SQL.forEach { exec(old, it) } + + old.createStatement().use { st -> + st.executeQuery("SELECT gid, epoch, owner, name, deviceGroupId FROM groups").use { rs -> + assertEquals(true, rs.next()) + assertEquals("", rs.getString("gid")) + assertEquals(1, rs.getInt("epoch")) + assertEquals(1, rs.getInt("owner")) + assertEquals("Gipfeltour", rs.getString("name")) + assertEquals(2, rs.getInt("deviceGroupId")) + } + // Old members get indexes 1, 2 in contact order, with the NodeID of their contact. + st.executeQuery("SELECT member, contactId, nodeId, keyState FROM group_members ORDER BY member").use { rs -> + val rows = buildList { while (rs.next()) add(listOf(rs.getInt(1), rs.getInt(2), rs.getString(3), rs.getString(4))) } + assertEquals(listOf(listOf(1, 1, "E841", "none"), listOf(2, 2, "5C07", "none")), rows) + } + st.executeQuery("SELECT text, senderNodeId FROM messages").use { rs -> + assertEquals(true, rs.next()) + assertEquals("Hoi", rs.getString("text")) + assertEquals(null, rs.getString("senderNodeId")) + } + } + } + + @Test + fun migratedTablesMatchTheExportedVersion4Schema() { + MIGRATION_3_4_SQL.forEach { exec(old, it) } + for (table in listOf("groups", "group_members", "messages", "contacts")) { + assertEquals(table, columns(fresh, table), columns(old, table)) + } + } + + @Test + fun anOldGroupWithoutMembersMigrates() { + exec(old, "INSERT INTO groups VALUES (1,'D1',1,'Leer',100)") + MIGRATION_3_4_SQL.forEach { exec(old, it) } + old.createStatement().use { st -> + st.executeQuery("SELECT COUNT(*) FROM group_members").use { rs -> + rs.next() + assertEquals(0, rs.getInt(1)) + } + } + } +} diff --git a/native-android/app/src/test/java/ch/offgrid/android/domain/AntennaSecurityTest.kt b/native-android/app/src/test/java/ch/offgrid/android/domain/AntennaSecurityTest.kt new file mode 100644 index 0000000..1dc7fe8 --- /dev/null +++ b/native-android/app/src/test/java/ch/offgrid/android/domain/AntennaSecurityTest.kt @@ -0,0 +1,325 @@ +package ch.offgrid.android.domain + +import ch.offgrid.android.crypto.FixedKeyUnlockTokenSource +import ch.offgrid.android.crypto.OgCrypto +import ch.offgrid.android.data.SettingDao +import ch.offgrid.android.data.SettingEntity +import ch.offgrid.android.link.Incoming +import ch.offgrid.android.link.int +import ch.offgrid.android.link.sim.SimFlashStore +import ch.offgrid.android.link.sim.SimulatedHeltec +import ch.offgrid.android.link.sim.SimulatedLink +import kotlinx.coroutines.CoroutineScope +import kotlinx.coroutines.Dispatchers +import kotlinx.coroutines.SupervisorJob +import kotlinx.coroutines.cancel +import kotlinx.coroutines.channels.Channel +import kotlinx.coroutines.flow.Flow +import kotlinx.coroutines.flow.MutableStateFlow +import kotlinx.coroutines.flow.first +import kotlinx.coroutines.flow.map +import kotlinx.coroutines.launch +import kotlinx.coroutines.runBlocking +import kotlinx.coroutines.withTimeout +import kotlinx.serialization.json.buildJsonObject +import kotlinx.serialization.json.JsonPrimitive +import kotlinx.serialization.json.put +import kotlinx.serialization.json.putJsonArray +import org.junit.After +import org.junit.Assert.assertEquals +import org.junit.Assert.assertNotEquals +import org.junit.Assert.assertFalse +import org.junit.Assert.assertNull +import org.junit.Assert.assertTrue +import org.junit.Test +import java.io.File + +/** + * The app's antenna session against the simulated lab.3 antenna: provisioning, wrong phone, rate limit, + * auto-lock and the authenticated factory reset. Real hardware is not involved. + */ +class AntennaSecurityTest { + private val scope = CoroutineScope(SupervisorJob() + Dispatchers.Default) + private val flashFile = File.createTempFile("sim-heltec", ".json").also { it.delete() } + private val device = SimulatedHeltec(SimFlashStore(flashFile), scope) + private val link = SimulatedLink(device) + private val readyCount = Channel(Channel.UNLIMITED) + + @After + fun tearDown() { + scope.cancel() + flashFile.delete() + } + + private fun manager(phone: String, settings: Settings = Settings(MemorySettingDao(), scope)) = + AntennaManager(scope, { link }, FixedKeyUnlockTokenSource(OgCrypto.sha256(phone.toByteArray())), settings).apply { + listener = object : AntennaListener { + override suspend fun onReady(antenna: AntennaManager, deviceId: String) { readyCount.trySend(deviceId) } + override suspend fun onEvent(event: Incoming.Event) {} + override suspend fun onDeviceRebooted() {} + } + } + + private suspend fun AntennaManager.settle(): AntennaState = withTimeout(15_000) { + state.first { it.phase == AntennaPhase.READY || it.phase == AntennaPhase.ERROR } + } + + private suspend fun AntennaManager.reconnect(): AntennaState { + disconnect() + connect() + return settle() + } + + @Test + fun anotherPhoneSeesUnlockFailedThenRateLimited() = runBlocking { + val owner = manager("phone-a") + owner.connect() + assertEquals(AntennaPhase.READY, owner.settle().phase) + owner.disconnect() + device.powerCycle() // locked again, as after unplugging it + + val other = manager("phone-b") + other.connect() + assertEquals(AntennaError.UNLOCK_FAILED, other.settle().error) + assertEquals(AntennaError.UNLOCK_FAILED, other.reconnect().error) + assertEquals(AntennaError.UNLOCK_FAILED, other.reconnect().error) + // Three failures: the antenna waits 2 s before it checks a token again (Security.cpp backoff). + with(other.reconnect()) { + assertEquals(AntennaError.RATE_LIMITED, error) + assertEquals("E_RATE_LIMITED", errorCode) + } + } + + @Test + fun rateLimitCarriesTheEstimatedEndAndRetriesOnItsOwn() = runBlocking { + val owner = manager("phone-a") + owner.connect() + owner.settle() + owner.disconnect() + device.powerCycle() + + val other = manager("phone-b") + other.connect() + other.settle() + other.reconnect() + other.reconnect() + val limited = other.reconnect() + assertEquals(AntennaError.RATE_LIMITED, limited.error) + // Third failure: 2 s backoff, counted from that failure. + val retryAt = limited.retryAt!! + assertTrue(retryAt - System.currentTimeMillis() in 1..2_000) + // When it ends the session tries again by itself and meets the wrong token, not the rate limit. + val again = withTimeout(6_000) { other.state.first { it.phase == AntennaPhase.ERROR && it.error != AntennaError.RATE_LIMITED } } + assertEquals(AntennaError.UNLOCK_FAILED, again.error) + assertNull(again.retryAt) + } + + @Test + fun backoffEstimateFollowsSecurityFailure() { + assertEquals(0, AuthBackoff.delayAfter(2)) + assertEquals(2_000, AuthBackoff.delayAfter(3)) + assertEquals(16_000, AuthBackoff.delayAfter(6)) + assertEquals(60_000, AuthBackoff.delayAfter(8)) + assertEquals(60_000, AuthBackoff.delayAfter(30)) + // Own failures known: from the last failure. Unknown (another phone failed): 2 s, then doubling. + assertEquals(1_500L + 4_000, AuthBackoff.retryAt(now = 2_000, failures = 4, lastFailureAt = 1_500, rateLimited = 1)) + assertEquals(10_000L + 2_000, AuthBackoff.retryAt(now = 10_000, failures = 0, lastFailureAt = 0, rateLimited = 1)) + assertEquals(10_000L + 8_000, AuthBackoff.retryAt(now = 10_000, failures = 0, lastFailureAt = 0, rateLimited = 3)) + assertEquals(10_000L + 60_000, AuthBackoff.retryAt(now = 10_000, failures = 0, lastFailureAt = 0, rateLimited = 9)) + } + + @Test + fun autoLockIsReopenedAndTheReasonKeptAsLastLock() = runBlocking { + val m = manager("phone-a") + m.connect() + m.settle() + readyCount.receive() + m.call("sec.lock") + withTimeout(5_000) { readyCount.receive() } + val state = m.state.value + assertEquals(AntennaPhase.READY, state.phase) + assertNull(state.lockReason) + assertEquals("lock", state.lastLock?.reason) + assertEquals(2, state.unlockCount) + } + + @Test + fun aRestartIsNoticedAndTheVaultOpenedAgain() = runBlocking { + val m = manager("phone-a") + m.connect() + m.settle() + readyCount.receive() + device.powerCycle() + withTimeout(5_000) { readyCount.receive() } + assertEquals(AntennaPhase.READY, m.state.value.phase) + assertEquals(AntennaManager.REASON_RESTART, m.state.value.lastLock?.reason) + } + + @Test + fun provisioningReportsDeviceStateRadioMeshAndLab() = runBlocking { + val m = manager("phone-a") + val seen = mutableListOf() + val watcher = scope.launch { m.state.collect { s -> s.activity?.let { if (seen.lastOrNull() != it) seen += it } } } + m.connect() + val s = m.settle() + watcher.cancel() + assertEquals(AntennaPhase.READY, s.phase) + assertTrue(AntennaActivity.PROVISIONING in seen) + assertEquals("unlocked", s.deviceState) + assertEquals(true, s.radioRunning) + assertEquals("ready", s.vaultStatus) + assertEquals(15, s.lockTimeoutS) + assertEquals(3, s.mesh?.hopDefault) + assertTrue(s.labRadio) + assertEquals(s.nodeId, s.lab?.nodeId) + assertEquals(emptyList(), s.lab?.ignoreNodes) + assertEquals(869.525, s.freqMhz!!, 0.0001) + } + + @Test + fun teamFirmwareHasNoLabSettings() = runBlocking { + val team = SimulatedHeltec(SimFlashStore(null), scope, labRadio = false) + val m = AntennaManager(scope, { SimulatedLink(team) }, FixedKeyUnlockTokenSource(OgCrypto.sha256("p".toByteArray())), + Settings(MemorySettingDao(), scope)).apply { listener = NoopListener } + m.connect() + val s = m.settle() + assertEquals(AntennaPhase.READY, s.phase) + assertFalse(s.labRadio) + assertNull(s.lab) + assertEquals(SimulatedHeltec.TEAM_FW_VERSION, s.fwVersion) + assertEquals(MessageLimits.CODEC_RAW, s.textCodec) + } + + @Test + fun aMockImageIsRefused() = runBlocking { + device.mockImage = true + val m = manager("phone-a") + m.connect() + assertEquals(AntennaError.MOCK_FIRMWARE, m.settle().error) + } + + @Test + fun aHungAntennaEndsTheSessionAsUnresponsive() = runBlocking { + val m = manager("phone-a") + m.connect() + m.settle() + device.hung = true + val s = withTimeout(15_000) { m.state.first { it.phase == AntennaPhase.ERROR } } + assertEquals(AntennaError.UNRESPONSIVE, s.error) + } + + @Test + fun meshAndLabSettingsAreWrittenAndKept() = runBlocking { + val m = manager("phone-a") + m.connect() + m.settle() + val mesh = m.setMesh(buildJsonObject { put("hop_default", 1); put("relay_enabled", false) }) + assertEquals(1, mesh.hopDefault) + assertEquals(false, m.state.value.mesh?.relayEnabled) + val lab = m.setLab(buildJsonObject { putJsonArray("ignore_nodes") { add(JsonPrimitive("033B")) } }) + assertEquals(listOf("033B"), lab.ignoreNodes) + assertEquals(listOf("033B"), m.state.value.lab?.ignoreNodes) + val stats = m.radioStats() + assertTrue(RadioStats.rows(stats).any { it.first == "Gesendete Pakete" }) + } + + @Test + fun provisioningAFreshVaultDropsAnOldTransferToken() = runBlocking { + val settings = Settings(MemorySettingDao(), scope) + settings.put(Settings.TRANSFER_TOKEN, OgCrypto.b64(ByteArray(32))) + settings.put(Settings.TRANSFER_DEVICE, device.deviceIdHex) + val m = manager("phone-a", settings) + m.connect() + assertEquals(AntennaPhase.READY, m.settle().phase) + assertNull(settings.get(Settings.TRANSFER_TOKEN)) + assertNull(settings.get(Settings.TRANSFER_DEVICE)) + } + + @Test + fun aBackupImportRotatesToTheNewPhoneAndKeepsBothTokensUntilConfirmed() = runBlocking { + val owner = manager("phone-a") + owner.connect() + assertEquals(AntennaPhase.READY, owner.settle().phase) + owner.call("sec.lock") + owner.disconnect() + val deviceBytes = OgCrypto.unhex(device.deviceIdHex) + val oldToken = FixedKeyUnlockTokenSource(OgCrypto.sha256("phone-a".toByteArray())).token(deviceBytes) + val settings = Settings(MemorySettingDao(), scope) + settings.put(Settings.TRANSFER_TOKEN, OgCrypto.b64(oldToken)) + settings.put(Settings.TRANSFER_DEVICE, device.deviceIdHex) + val newPhone = manager("phone-b", settings) + newPhone.connect() + assertEquals(AntennaPhase.READY, newPhone.settle().phase) + assertNull(settings.get(Settings.TRANSFER_TOKEN)) + // The rotation's answer got lost: the transfer token is still there, but the antenna takes ours already. + settings.put(Settings.TRANSFER_TOKEN, OgCrypto.b64(oldToken)) + settings.put(Settings.TRANSFER_DEVICE, device.deviceIdHex) + newPhone.call("sec.lock") + assertEquals(AntennaPhase.READY, newPhone.reconnect().phase) + assertNull(settings.get(Settings.TRANSFER_TOKEN)) + // The old phone's token no longer opens it. + newPhone.call("sec.lock") + newPhone.disconnect() + assertEquals(AntennaError.UNLOCK_FAILED, owner.reconnect().error) + } + + @Test + fun factoryResetErasesTheAntennaAndSetsItUpAgain() = runBlocking { + val m = manager("phone-a") + m.connect() + val before = m.settle() + readyCount.receive() + val qr = device.addVirtualPeer("Anna", -90) + m.call("pair.begin") + m.call("pair.complete", buildJsonObject { put("qr", qr) }) + assertEquals(1, m.call("contact.list", buildJsonObject { put("offset", 0); put("limit", 10) }).int("total")) + + assertEquals(ResetResult.DONE, m.factoryReset()) + withTimeout(10_000) { readyCount.receive() } + val after = m.state.value + assertEquals(AntennaPhase.READY, after.phase) + assertEquals(before.deviceId, after.deviceId) + // New vault, new identity, no contacts. + assertNotEquals(before.nodeId, after.nodeId) + assertEquals(0, m.call("contact.list", buildJsonObject { put("offset", 0); put("limit", 10) }).int("total")) + } + + @Test + fun onlyTheOwnersTokenResetsTheAntenna() = runBlocking { + val owner = manager("phone-a") + owner.connect() + owner.settle() + owner.disconnect() + // The antenna stays unlocked until its heartbeat timeout, so another phone gets a session without a + // token; the reset still needs the owner's token under the reset label. + val stranger = manager("phone-b") + stranger.connect() + assertEquals(AntennaPhase.READY, stranger.settle().phase) + assertEquals(ResetResult.WRONG_PHONE, stranger.factoryReset()) + stranger.disconnect() + + // After a backup import the old phone's token is tried as well. + val settings = Settings(MemorySettingDao(), scope) + settings.put(Settings.TRANSFER_TOKEN, OgCrypto.b64(owner.tokenFor(device.deviceIdHex))) + settings.put(Settings.TRANSFER_DEVICE, device.deviceIdHex) + val heir = manager("phone-c", settings) + heir.connect() + assertEquals(AntennaPhase.READY, heir.settle().phase) + assertEquals(ResetResult.DONE, heir.factoryReset()) + assertNull(settings.get(Settings.TRANSFER_TOKEN)) + } + + private object NoopListener : AntennaListener { + override suspend fun onReady(antenna: AntennaManager, deviceId: String) {} + override suspend fun onEvent(event: Incoming.Event) {} + override suspend fun onDeviceRebooted() {} + } + + private class MemorySettingDao : SettingDao { + private val map = MutableStateFlow>(emptyMap()) + override fun observeAll(): Flow> = map.map { m -> m.map { SettingEntity(it.key, it.value) } } + override suspend fun get(key: String): String? = map.value[key] + override suspend fun put(setting: SettingEntity) { map.value = map.value + (setting.key to setting.value) } + override suspend fun remove(key: String) { map.value = map.value - key } + } +} diff --git a/native-android/app/src/test/java/ch/offgrid/android/domain/DeviceInfoTest.kt b/native-android/app/src/test/java/ch/offgrid/android/domain/DeviceInfoTest.kt new file mode 100644 index 0000000..3b84c2a --- /dev/null +++ b/native-android/app/src/test/java/ch/offgrid/android/domain/DeviceInfoTest.kt @@ -0,0 +1,31 @@ +package ch.offgrid.android.domain + +import ch.offgrid.android.link.LinkCodec +import kotlinx.serialization.json.JsonObject +import org.junit.Assert.assertEquals +import org.junit.Test + +class DeviceInfoTest { + @Test + fun theIgnoreListTakesFourHexDigitsButNotTheOwnNodeOrMoreThanEight() { + assertEquals(IgnoreEdit.Changed(listOf("3F2A")), LabConfig.withIgnored(emptyList(), " 0x3f2a ", "A1B2")) + assertEquals(IgnoreEdit.Refused(IgnoreEdit.Reason.INVALID), LabConfig.withIgnored(emptyList(), "3F2", "A1B2")) + assertEquals(IgnoreEdit.Refused(IgnoreEdit.Reason.INVALID), LabConfig.withIgnored(emptyList(), "XYZW", "A1B2")) + assertEquals(IgnoreEdit.Refused(IgnoreEdit.Reason.OWN), LabConfig.withIgnored(emptyList(), "a1b2", "A1B2")) + assertEquals(IgnoreEdit.Refused(IgnoreEdit.Reason.DUPLICATE), LabConfig.withIgnored(listOf("3F2A"), "3f2a", null)) + val full = (1..8).map { "000$it" } + assertEquals(IgnoreEdit.Refused(IgnoreEdit.Reason.FULL), LabConfig.withIgnored(full, "1234", null)) + } + + @Test + fun labGetIsParsedWithTheIgnoreList() { + val lab = LabConfig.parse( + LinkCodec.json.parseToJsonElement( + """{"text_codec":"ogz1","max_text_input_bytes":160,"node_id":"A1B2","fw":"0.3.0-lab.3","ignore_nodes":["3F2A"]}""", + ) as JsonObject, + ) + assertEquals(LabConfig("ogz1", 160, "A1B2", "0.3.0-lab.3", listOf("3F2A")), lab) + // An image before the ignore list has no field: null, so the screen says "nicht unterstützt". + assertEquals(null, LabConfig.parse(JsonObject(emptyMap())).ignoreNodes) + } +} diff --git a/native-android/app/src/test/java/ch/offgrid/android/domain/FakeDatabase.kt b/native-android/app/src/test/java/ch/offgrid/android/domain/FakeDatabase.kt new file mode 100644 index 0000000..de678cf --- /dev/null +++ b/native-android/app/src/test/java/ch/offgrid/android/domain/FakeDatabase.kt @@ -0,0 +1,147 @@ +package ch.offgrid.android.domain + +import androidx.room.DatabaseConfiguration +import androidx.room.InvalidationTracker +import androidx.sqlite.db.SupportSQLiteOpenHelper +import ch.offgrid.android.data.ContactDao +import ch.offgrid.android.data.ContactEntity +import ch.offgrid.android.data.GroupDao +import ch.offgrid.android.data.GroupEntity +import ch.offgrid.android.data.GroupMemberEntity +import ch.offgrid.android.data.KeyState +import ch.offgrid.android.data.MaintenanceDao +import ch.offgrid.android.data.MessageDao +import ch.offgrid.android.data.MessageEntity +import ch.offgrid.android.data.OffGridDatabase +import ch.offgrid.android.data.SettingDao +import ch.offgrid.android.data.SettingEntity +import ch.offgrid.android.data.UnreadCount +import kotlinx.coroutines.flow.Flow +import kotlinx.coroutines.flow.MutableStateFlow +import kotlinx.coroutines.flow.map + +/** + * In-memory DAOs behind an [OffGridDatabase], so [Messaging] runs against the simulated antenna without Room or a + * device. Only the queries [Messaging] uses are modelled with their SQL semantics; the rest throw. + */ +class FakeDatabase : OffGridDatabase() { + val contactDao = FakeContactDao() + val messageDao = FakeMessageDao() + val groupDao = FakeGroupDao() + val settingDao = FakeSettingDao() + + override fun contacts(): ContactDao = contactDao + override fun messages(): MessageDao = messageDao + override fun groups(): GroupDao = groupDao + override fun settings(): SettingDao = settingDao + override fun maintenance(): MaintenanceDao = throw UnsupportedOperationException() + + override fun createOpenHelper(config: DatabaseConfiguration): SupportSQLiteOpenHelper = throw UnsupportedOperationException() + override fun createInvalidationTracker(): InvalidationTracker = InvalidationTracker(this, "contacts") + override fun clearAllTables() = throw UnsupportedOperationException() +} + +class FakeContactDao : ContactDao { + val rows = MutableStateFlow>(emptyList()) + private var nextId = 1L + + override fun observeAll(): Flow> = rows + override fun observe(id: Long): Flow = rows.map { list -> list.firstOrNull { it.id == id } } + override suspend fun byId(id: Long) = rows.value.firstOrNull { it.id == id } + override suspend fun bySlot(deviceId: String, slot: Int) = rows.value.firstOrNull { it.deviceId == deviceId && it.deviceContactId == slot } + override suspend fun byPublicKey(publicKey: String) = rows.value.firstOrNull { it.publicKey == publicKey } + override suspend fun all() = rows.value + override suspend fun insert(contact: ContactEntity): Long = nextId++.also { rows.value += contact.copy(id = it) } + override suspend fun update(contact: ContactEntity) { + rows.value = rows.value.map { if (it.id == contact.id) contact else it } + } + override suspend fun delete(id: Long) { + rows.value = rows.value.filter { it.id != id } + } +} + +class FakeMessageDao : MessageDao { + val rows = MutableStateFlow>(emptyList()) + private var nextId = 1L + + override fun observeForContact(contactId: Long) = rows.map { l -> l.filter { it.contactId == contactId } } + override fun observeForGroup(groupId: Long) = rows.map { l -> l.filter { it.groupId == groupId } } + override fun observe(id: Long): Flow = rows.map { l -> l.firstOrNull { it.id == id } } + override suspend fun byId(id: Long) = rows.value.firstOrNull { it.id == id } + override fun observeLatest(): Flow> = rows.map { l -> + l.groupBy { it.contactId to it.groupId }.values.map { g -> g.maxWith(compareBy({ it.sentAt }, { it.id })) } + } + override fun observeUnread(): Flow> = rows.map { l -> + l.filter { it.direction == "in" && it.readAt == null }.groupBy { it.contactId to it.groupId } + .map { (k, v) -> UnreadCount(k.first, k.second, v.size) } + } + override fun observeCount(): Flow = rows.map { it.size } + override suspend fun byMsgRef(ref: Int, session: String) = + rows.value.filter { it.msgRef == ref && it.refSession == session && it.status in listOf(1, 2, 5) }.maxByOrNull { it.id } + override suspend fun openOutgoing() = rows.value.filter { it.direction == "out" && it.msgRef != null && it.status in listOf(1, 2, 5) }.sortedBy { it.id } + override suspend fun localQueue() = rows.value.filter { it.status == 0 && it.direction == "out" }.sortedWith(compareBy({ it.sentAt }, { it.id })) + override suspend fun ownByRef(contactId: Long, ref: Int) = + rows.value.filter { it.contactId == contactId && it.direction == "out" && it.ctr != null && (it.ctr!! and 65535) == ref }.maxByOrNull { it.id } + override suspend fun insert(message: MessageEntity): Long = nextId++.also { rows.value += message.copy(id = it) } + override suspend fun update(message: MessageEntity) { + rows.value = rows.value.map { if (it.id == message.id) message else it } + } + override suspend fun setReaction(id: Long, emoji: String?) { + rows.value = rows.value.map { if (it.id == id) it.copy(peerReaction = emoji) else it } + } + override suspend fun markContactRead(contactId: Long, at: Long) = throw UnsupportedOperationException() + override suspend fun markGroupRead(groupId: Long, at: Long) = throw UnsupportedOperationException() + override suspend fun deleteForContact(contactId: Long) { + rows.value = rows.value.filter { it.contactId != contactId } + } + override suspend fun deleteForGroup(groupId: Long) { + rows.value = rows.value.filter { it.groupId != groupId } + } + override suspend fun all() = rows.value +} + +class FakeGroupDao : GroupDao { + val groups = MutableStateFlow>(emptyList()) + val members = MutableStateFlow>(emptyList()) + private var nextId = 1L + + override fun observeAll(): Flow> = groups + override fun observe(id: Long): Flow = groups.map { l -> l.firstOrNull { it.id == id } } + override suspend fun byId(id: Long) = groups.value.firstOrNull { it.id == id } + override suspend fun byDeviceGroup(deviceId: String, groupId: Int) = + groups.value.firstOrNull { it.deviceId == deviceId && it.deviceGroupId == groupId } + override fun observeMembers(): Flow> = members + override suspend fun membersOf(groupId: Long) = members.value.filter { it.groupId == groupId }.sortedBy { it.member } + override suspend fun insert(group: GroupEntity): Long = nextId++.also { groups.value += group.copy(id = it) } + override suspend fun update(group: GroupEntity) { + groups.value = groups.value.map { if (it.id == group.id) group else it } + } + override suspend fun putMembers(members: List) { + this.members.value = this.members.value.filter { old -> members.none { it.groupId == old.groupId && it.member == old.member } } + members + } + override suspend fun updateMember(member: GroupMemberEntity) { + members.value = members.value.map { if (it.groupId == member.groupId && it.member == member.member) member else it } + } + override suspend fun deleteMembers(groupId: Long) { + members.value = members.value.filter { it.groupId != groupId } + } + override suspend fun delete(id: Long) { + groups.value = groups.value.filter { it.id != id } + } + override suspend fun bySyncRef(ref: Int, session: String) = + members.value.firstOrNull { it.syncRef == ref && it.syncSession == session && it.keyState == KeyState.PENDING } + override suspend fun openSyncs(deviceId: String) = members.value.filter { m -> + m.keyState == KeyState.PENDING && m.syncRef != null && groups.value.any { it.id == m.groupId && it.deviceId == deviceId } + } + override suspend fun queuedSyncs() = members.value.filter { it.keyState == KeyState.QUEUED }.sortedWith(compareBy({ it.groupId }, { it.member })) + override suspend fun all() = groups.value + override suspend fun allMembers() = members.value +} + +class FakeSettingDao : SettingDao { + private val map = MutableStateFlow>(emptyMap()) + override fun observeAll(): Flow> = map.map { m -> m.map { SettingEntity(it.key, it.value) } } + override suspend fun get(key: String): String? = map.value[key] + override suspend fun put(setting: SettingEntity) { map.value = map.value + (setting.key to setting.value) } + override suspend fun remove(key: String) { map.value = map.value - key } +} diff --git a/native-android/app/src/test/java/ch/offgrid/android/domain/GroupSyncTest.kt b/native-android/app/src/test/java/ch/offgrid/android/domain/GroupSyncTest.kt new file mode 100644 index 0000000..a624f02 --- /dev/null +++ b/native-android/app/src/test/java/ch/offgrid/android/domain/GroupSyncTest.kt @@ -0,0 +1,66 @@ +package ch.offgrid.android.domain + +import ch.offgrid.android.data.GroupMemberEntity +import ch.offgrid.android.data.KeyState +import org.junit.Assert.assertEquals +import org.junit.Assert.assertNull +import org.junit.Test + +class GroupSyncTest { + private val now = "dev/new" + + private fun member(index: Int, ref: Int?, state: String = KeyState.PENDING, session: String? = "dev/old") = + GroupMemberEntity(groupId = 1, member = index, contactId = index.toLong(), nodeId = "N$index", keyState = state, syncRef = ref, syncSession = session) + + @Test + fun onlyTheAckDeliversTheKeyAndFailureEndsIt() { + val m = member(1, 10) + assertEquals(KeyState.DELIVERED, GroupSync.applyEvent(m, "delivered", null)!!.keyState) + assertNull(GroupSync.applyEvent(m, "delivered", null)!!.syncRef) + with(GroupSync.applyEvent(m, "failed", "timeout")!!) { + assertEquals(KeyState.FAILED, keyState) + assertEquals("timeout", syncReason) + } + assertEquals("cancelled", GroupSync.applyEvent(m, "cancelled", null)!!.syncReason) + for (open in listOf("queued", "sent", "relayed", "retrying", "waiting")) assertNull(open, GroupSync.applyEvent(m, open, null)) + } + + @Test + fun aFinishedKeyIgnoresLateEvents() { + assertNull(GroupSync.applyEvent(member(1, null, KeyState.DELIVERED), "failed", "timeout")) + assertNull(GroupSync.applyEvent(member(1, null, KeyState.QUEUED), "delivered", null)) + } + + @Test + fun reconcileMovesQueuedSyncsAppliesOutcomesAndFailsTheLostOnes() { + val snapshot = PendingSnapshot( + pending = listOf(DeviceMessage(10, "sent")), + recent = listOf(DeviceMessage(11, "delivered"), DeviceMessage(12, "failed", "timeout")), + ) + val open = listOf(member(1, 10), member(2, 11), member(3, 12), member(4, 13)) + val byIndex = GroupSync.reconcile(open, snapshot, now).associateBy { it.member } + assertEquals(now, byIndex.getValue(1).syncSession) + assertEquals(KeyState.PENDING, byIndex.getValue(1).keyState) + assertEquals(KeyState.DELIVERED, byIndex.getValue(2).keyState) + assertEquals("timeout", byIndex.getValue(3).syncReason) + assertEquals(OutboxReconciler.REASON_LOST, byIndex.getValue(4).syncReason) + } + + @Test + fun aRestartLosesEveryOpenSyncAndResendingQueuesItAgain() { + val lost = GroupSync.reconcile(listOf(member(1, 10)), PendingSnapshot.EMPTY, "").single() + assertEquals(KeyState.FAILED, lost.keyState) + val again = GroupSync.requeue(lost) + assertEquals(KeyState.QUEUED, again.keyState) + assertNull(again.syncReason) + } + + @Test + fun backupsWithoutMemberIndexesGetDistinctOnes() { + fun m(group: Long, index: Int) = GroupMemberEntity(groupId = group, member = index, contactId = index.toLong()) + val old = listOf(m(1, 0), m(1, 0), m(1, 0), m(2, 3), m(2, 4)) + val fixed = BackupService.uniqueMemberIndexes(old) + assertEquals(listOf(1, 2, 3), fixed.filter { it.groupId == 1L }.map { it.member }) + assertEquals(listOf(3, 4), fixed.filter { it.groupId == 2L }.map { it.member }) + } +} diff --git a/native-android/app/src/test/java/ch/offgrid/android/domain/MessageDetailsTest.kt b/native-android/app/src/test/java/ch/offgrid/android/domain/MessageDetailsTest.kt new file mode 100644 index 0000000..a95e064 --- /dev/null +++ b/native-android/app/src/test/java/ch/offgrid/android/domain/MessageDetailsTest.kt @@ -0,0 +1,54 @@ +package ch.offgrid.android.domain + +import ch.offgrid.android.data.MessageEntity +import ch.offgrid.android.data.MessageStatus +import org.junit.Assert.assertEquals +import org.junit.Assert.assertFalse +import org.junit.Assert.assertTrue +import org.junit.Test + +class MessageDetailsTest { + private fun out(status: Int) = MessageEntity(contactId = 1, direction = "out", kind = "text", text = "Hallo", status = status, sentAt = 0) + + @Test + fun aDeliveredMessageShowsHopsRetriesAndTheTimeToTheAck() { + val m = out(MessageStatus.DELIVERED).copy(hops = 0, retry = 1, rttMs = 1840, ctr = 42, compressed = false, bytesOnAir = 30) + val rows = MessageDetails.rows(m, "Anna").toMap() + assertEquals("Zugestellt", rows["Status"]) + assertEquals("Direkt", rows["Hops"]) + assertEquals("1", rows["Wiederholungen"]) + assertEquals("1.8 s", rows["Zeit bis Bestätigung"]) + assertEquals("42", rows["Zähler"]) + assertEquals("Nein", rows["Komprimiert (OGZ1)"]) + } + + @Test + fun aDeliveryFoundAfterReconnectSaysSo() { + assertEquals("Zugestellt, während offline", MessageDetails.status(out(MessageStatus.DELIVERED).copy(deliveredOffline = true))) + assertEquals("Wartet auf Anna", MessageDetails.status(out(MessageStatus.WAITING), "Anna")) + assertEquals("Gesendet, wird wiederholt", MessageDetails.status(out(MessageStatus.SENT).copy(deviceState = "retrying"))) + } + + @Test + fun aReceivedMessageShowsTheSignalOfItsCopy() { + val m = MessageEntity(contactId = 1, direction = "in", kind = "text", text = "Hoi", status = MessageStatus.DELIVERED, sentAt = 0, + rssi = -91, snr = 6.25, hops = 2, retry = 1, compressed = true, ctr = 7) + val rows = MessageDetails.rows(m).toMap() + assertEquals("-91 dBm", rows["RSSI"]) + assertEquals("6.3 dB", rows["SNR"]) + assertEquals("2 Weiterleitungen", rows["Hops"]) + assertEquals("Wiederholung 1", rows["Empfangene Sendung"]) + assertEquals("Ja", rows["Komprimiert (OGZ1)"]) + assertTrue(MessageDetails.hasRadioDetails(m)) + } + + @Test + fun valuesTheFirmwareDidNotReportAreLeftOut() { + val m = out(MessageStatus.FAILED).copy(failReason = OutboxReconciler.REASON_LOST) + val rows = MessageDetails.rows(m).toMap() + assertEquals(setOf("Status", "Grund"), rows.keys) + assertEquals("Nicht zugestellt", rows["Status"]) + assertFalse(MessageDetails.hasRadioDetails(m)) + assertEquals("Nicht gesendet", MessageDetails.status(out(MessageStatus.FAILED).copy(failReason = "E_TOO_LONG"))) + } +} diff --git a/native-android/app/src/test/java/ch/offgrid/android/domain/MessageLimitsTest.kt b/native-android/app/src/test/java/ch/offgrid/android/domain/MessageLimitsTest.kt index b3ecb01..9cd7948 100644 --- a/native-android/app/src/test/java/ch/offgrid/android/domain/MessageLimitsTest.kt +++ b/native-android/app/src/test/java/ch/offgrid/android/domain/MessageLimitsTest.kt @@ -55,6 +55,13 @@ class MessageLimitsTest { assertEquals(161, MessageLimits.onAirTextBytes(hex + "a", MessageLimits.CODEC_OGZ1, 160)) } + @Test + fun ogz1LeavesTextsThatFitRawUncompressed() { + // Lab.3 compresses only texts over 83 bytes, so a team board can read everything up to that (OGZ1 would be 14). + val text = "Bin gleich da, wartet beim Eingang auf mich." + assertEquals(44, MessageLimits.onAirTextBytes(text, MessageLimits.CODEC_OGZ1, 160)) + } + @Test fun namesAreOneTo24Bytes() { assertTrue(MessageLimits.isValidName("Anna Meier")) @@ -63,4 +70,27 @@ class MessageLimitsTest { assertFalse(MessageLimits.isValidName("ü".repeat(13))) assertFalse(MessageLimits.isValidName(" ")) } + + @Test + fun longTextsAreSplitIntoRawPiecesAtSpaces() { + val text = "Wir sind bei der Hütte oben, das Wetter wird schlechter. Kommt bitte nicht mehr hoch, " + + "wir treffen uns um 16:30 beim Parkplatz." + val parts = MessageLimits.split(text, AntennaState()) + assertEquals(2, parts.size) + assertTrue(parts.all { MessageLimits.utf8Bytes(it) <= 83 }) + assertTrue(parts[0].endsWith("nicht mehr")) + assertEquals(text, parts.joinToString(" ")) + // A lab image with OGZ1 fits it into one packet, so it is not split. + assertEquals(listOf(text), MessageLimits.split(text, AntennaState(textCodec = MessageLimits.CODEC_OGZ1, maxTextInputBytes = 160))) + assertEquals(listOf("Hallo"), MessageLimits.split(" Hallo ", AntennaState())) + assertTrue(MessageLimits.split(" ", AntennaState()).isEmpty()) + } + + @Test + fun aWordLongerThanAPacketIsCutWithoutBreakingCodePoints() { + val parts = MessageLimits.splitRaw("ü".repeat(50) + "😀".repeat(30), 83) + assertTrue(parts.all { MessageLimits.utf8Bytes(it) <= 83 }) + assertEquals("ü".repeat(50) + "😀".repeat(30), parts.joinToString("")) + assertEquals(3, parts.size) + } } diff --git a/native-android/app/src/test/java/ch/offgrid/android/domain/MessagingGroupsTest.kt b/native-android/app/src/test/java/ch/offgrid/android/domain/MessagingGroupsTest.kt new file mode 100644 index 0000000..d021c61 --- /dev/null +++ b/native-android/app/src/test/java/ch/offgrid/android/domain/MessagingGroupsTest.kt @@ -0,0 +1,242 @@ +package ch.offgrid.android.domain + +import ch.offgrid.android.crypto.FixedKeyUnlockTokenSource +import ch.offgrid.android.crypto.OgCrypto +import ch.offgrid.android.data.GroupEntity +import ch.offgrid.android.data.GroupMemberEntity +import ch.offgrid.android.data.KeyState +import ch.offgrid.android.data.MessageEntity +import ch.offgrid.android.data.MessageStatus +import ch.offgrid.android.link.int +import ch.offgrid.android.link.obj +import ch.offgrid.android.link.sim.SimFlashStore +import ch.offgrid.android.link.sim.SimTiming +import ch.offgrid.android.link.sim.SimulatedHeltec +import ch.offgrid.android.link.sim.SimulatedLink +import kotlinx.coroutines.CoroutineScope +import kotlinx.coroutines.Dispatchers +import kotlinx.coroutines.SupervisorJob +import kotlinx.coroutines.cancel +import kotlinx.coroutines.delay +import kotlinx.coroutines.flow.first +import kotlinx.coroutines.runBlocking +import kotlinx.coroutines.withTimeout +import kotlinx.serialization.json.JsonPrimitive +import kotlinx.serialization.json.buildJsonObject +import kotlinx.serialization.json.put +import kotlinx.serialization.json.putJsonArray +import org.junit.After +import org.junit.Assert.assertEquals +import org.junit.Assert.assertFalse +import org.junit.Assert.assertNotNull +import org.junit.Assert.assertNull +import org.junit.Assert.assertTrue +import org.junit.Test + +/** Groups in [Messaging] against the simulated antenna: create and key delivery, joining, receiving, sending and member changes. */ +class MessagingGroupsTest { + private val scope = CoroutineScope(SupervisorJob() + Dispatchers.Default) + + @After + fun tearDown() = scope.cancel() + + private class Rig(val device: SimulatedHeltec, val antenna: AntennaManager, val messaging: Messaging, val db: FakeDatabase, val incoming: MutableList) { + val groups get() = db.groupDao + val contacts get() = db.contactDao.rows.value + } + + private suspend fun rig(vararg peers: String, labRadio: Boolean = true): Rig { + val device = SimulatedHeltec(SimFlashStore(null), scope, labRadio = labRadio, + timing = SimTiming(firstTxMs = 20, ackWaitMs = 40, retryMs = 40, retries = 2, resendMs = 150, parkMs = 1_500, groupSyncMs = 80)) + val db = FakeDatabase() + val settings = Settings(db.settingDao, scope) + val antenna = AntennaManager(scope, { SimulatedLink(device) }, FixedKeyUnlockTokenSource(OgCrypto.sha256("p".toByteArray())), settings) + val incoming = mutableListOf() + val messaging = Messaging(db, antenna, scope, settings, onIncoming = { incoming += it }) + antenna.listener = messaging + antenna.connect() + withTimeout(10_000) { antenna.state.first { it.ready } } + peers.forEach { name -> + antenna.call("pair.begin") + val contact = antenna.call("pair.complete", buildJsonObject { put("qr", device.addVirtualPeer(name, -90)) }).obj("contact")!! + messaging.upsertFromDevice(device.deviceIdHex, contact, keepName = false) + } + return Rig(device, antenna, messaging, db, incoming) + } + + private suspend fun eventually(what: String, block: suspend () -> T?): T = withTimeout(10_000) { + var value = block() + while (value == null) { + delay(25) + value = block() + } + value + } + + private suspend fun Rig.members(groupId: Long): List = groups.membersOf(groupId) + + @Test + fun hellosFeaturesDecideWhetherGroupsAreOffered() { + val withGroups = buildJsonObject { + putJsonArray("features") { add(JsonPrimitive("groups")) } + put("limits", buildJsonObject { put("max_groups", 4); put("max_group_members", 6); put("max_group_text_bytes", 60) }) + } + assertEquals(GroupSupport(maxGroups = 4, maxMembers = 6, maxTextBytes = 60), GroupSupport.parse(withGroups)) + assertEquals(5, GroupSupport.parse(withGroups)!!.maxOtherMembers) + assertEquals(8, GroupSupport().maxOtherMembers) // the app caps a group at 8 members plus the owner + assertNull(GroupSupport.parse(buildJsonObject { put("limits", buildJsonObject { put("max_groups", 8) }) })) + assertNull(GroupSupport.parse(buildJsonObject { putJsonArray("features") { add(JsonPrimitive("other")) } })) + } + + @Test + fun theAntennaStateCarriesTheLimitsFromHello() = runBlocking { + val r = rig() + val support = r.antenna.state.value.groups + assertEquals(GroupSupport(maxGroups = 8, maxMembers = 16, maxTextBytes = 83), support) + } + + @Test + fun createReadsTheGroupObjectAndDeliversTheKeyToEveryMember() = runBlocking { + val r = rig("Anna", "Luca") + val id = r.messaging.createGroup("Team", r.contacts.map { it.id }).getOrThrow() + + val g: GroupEntity = r.groups.byId(id)!! + assertEquals(1, g.deviceGroupId) + assertEquals(8, g.gid.length) + assertEquals(1, g.epoch) + assertTrue(g.owner) + val members = r.members(id) + assertEquals(listOf(1, 2), members.map { it.member }) + assertEquals(r.contacts.map { it.id }, members.map { it.contactId }) + assertEquals(r.contacts.map { it.nodeId }, members.map { it.nodeId }) + + // One group.sync per member, tracked from msg.status until the ACK. + eventually("keys delivered") { r.members(id).takeIf { m -> m.all { it.keyState == KeyState.DELIVERED } } } + assertTrue(r.members(id).all { it.syncRef == null && it.syncSession == null }) + } + + @Test + fun aFailedKeyCanBeSentAgain() = runBlocking { + val r = rig("Anna", labRadio = false) + r.device.setPeerInRange(r.contacts.single().deviceContactId, false) + val id = r.messaging.createGroup("Team", listOf(r.contacts.single().id)).getOrThrow() + + val failed = eventually("sync failed") { r.members(id).single().takeIf { it.keyState == KeyState.FAILED } } + assertEquals("timeout", failed.syncReason) + + r.device.setPeerInRange(r.contacts.single().deviceContactId, true) + r.messaging.resendKey(id, failed.member) + val delivered = eventually("key delivered") { r.members(id).single().takeIf { it.keyState == KeyState.DELIVERED } } + assertNull(delivered.syncReason) + } + + @Test + fun aGroupTextEndsAtSentWithoutAnAck() = runBlocking { + val r = rig("Anna") + val id = r.messaging.createGroup("Team", listOf(r.contacts.single().id)).getOrThrow() + r.messaging.sendGroupText(id, "Hallo Gruppe!") + + // msg.status of a group message carries group_id and no `to`; sent is final. + val sent = eventually("sent") { r.db.messageDao.rows.value.singleOrNull()?.takeIf { it.status == MessageStatus.SENT } } + assertEquals(id, sent.groupId) + assertEquals("sent", sent.deviceState) + assertNull(sent.msgRef) + assertNull(sent.failReason) + } + + @Test + fun aLongGroupTextIsSplitAtTheGroupLimit() = runBlocking { + val r = rig("Anna") + val id = r.messaging.createGroup("Team", listOf(r.contacts.single().id)).getOrThrow() + r.messaging.sendGroupText(id, List(30) { "wort$it" }.joinToString(" ")) + val parts = eventually("two parts sent") { r.db.messageDao.rows.value.takeIf { l -> l.size >= 2 && l.all { it.status == MessageStatus.SENT } } } + assertTrue(parts.all { MessageLimits.utf8Bytes(it.text) <= 83 }) + } + + @Test + fun groupReceivedWithoutAContactShowsTheNodeId() = runBlocking { + val r = rig("Anna") + val anna = r.contacts.single() + val slot = r.device.peerInvites(anna.deviceContactId, "Gipfeltour", others = listOf("ab12")) + val g = eventually("joined") { r.groups.byDeviceGroup(r.device.deviceIdHex, slot) } + + r.device.memberSays(slot, member = 2, text = "Wer bin ich?") + val stranger = eventually("text from node") { r.db.messageDao.rows.value.singleOrNull() } + assertEquals(g.id, stranger.groupId) + assertNull(stranger.contactId) + assertNull(stranger.senderContactId) + assertEquals("AB12", stranger.senderName) + assertEquals("AB12", stranger.senderNodeId) + assertEquals("in", stranger.direction) + + r.device.memberSays(slot, member = 0, text = "Hier Anna") + val known = eventually("text from contact") { r.db.messageDao.rows.value.firstOrNull { it.text == "Hier Anna" } } + assertEquals(anna.id, known.senderContactId) + assertEquals("Anna", known.senderName) + assertEquals(2, r.incoming.size) + } + + @Test + fun aJoinedGroupIsCreatedAndFilledFromGroupGet() = runBlocking { + val r = rig("Anna") + val anna = r.contacts.single() + val slot = r.device.peerInvites(anna.deviceContactId, "Gipfeltour", others = listOf("AB12")) + val g = eventually("joined") { r.groups.byDeviceGroup(r.device.deviceIdHex, slot) } + assertEquals("Gipfeltour", g.name) + assertFalse(g.owner) + assertEquals(1, g.epoch) + val members = r.members(g.id) + // The owner is member 0, I am member 1 and not listed, the stranger is known by NodeID only. + assertEquals(listOf(0, 2), members.map { it.member }) + assertEquals(anna.id, members[0].contactId) + assertNull(members[1].contactId) + assertEquals("AB12", members[1].nodeId) + assertTrue(members.all { it.keyState == KeyState.NONE }) + } + + @Test + fun addingAndRemovingMembersStartsANewEpochAndSyncsEveryoneAgain() = runBlocking { + val r = rig("Anna", "Luca", "Mia") + val (anna, luca, mia) = r.contacts + val id = r.messaging.createGroup("Team", listOf(anna.id, luca.id)).getOrThrow() + eventually("first keys") { r.members(id).takeIf { m -> m.all { it.keyState == KeyState.DELIVERED } } } + + r.messaging.addMembers(id, listOf(mia.id)).getOrThrow() + assertEquals(2, r.groups.byId(id)!!.epoch) + assertEquals(listOf(1, 2, 3), r.members(id).map { it.member }) + eventually("keys of epoch 2") { r.members(id).takeIf { m -> m.size == 3 && m.all { it.keyState == KeyState.DELIVERED } } } + + r.messaging.removeMember(id, member = 1).getOrThrow() + assertEquals(3, r.groups.byId(id)!!.epoch) + assertEquals(listOf(2, 3), r.members(id).map { it.member }) + assertEquals(listOf(luca.id, mia.id), r.members(id).map { it.contactId }) + eventually("keys of epoch 3") { r.members(id).takeIf { m -> m.all { it.keyState == KeyState.DELIVERED } } } + assertNotNull(r.groups.byId(id)) + } + + @Test + fun deletingAGroupFreesItsSlotAndHistory() = runBlocking { + val r = rig("Anna") + val id = r.messaging.createGroup("Team", listOf(r.contacts.single().id)).getOrThrow() + r.messaging.sendGroupText(id, "Hoi") + eventually("sent") { r.db.messageDao.rows.value.singleOrNull()?.takeIf { it.status == MessageStatus.SENT } } + + r.messaging.deleteGroup(id).getOrThrow() + assertNull(r.groups.byId(id)) + assertTrue(r.members(id).isEmpty()) + assertTrue(r.db.messageDao.rows.value.isEmpty()) + val next = r.antenna.call("group.create", buildJsonObject { + put("name", "Neu"); putJsonArray("members") { add(JsonPrimitive(r.contacts.single().deviceContactId)) } + }) + assertEquals(1, next.obj("group")!!.int("group_id")) + } + + @Test + fun aGroupRemovedFromTheAntennaKeepsItsHistoryButLosesItsSlotOnReconnect() = runBlocking { + val r = rig("Anna") + val id = r.messaging.createGroup("Team", listOf(r.contacts.single().id)).getOrThrow() + r.antenna.call("group.delete", buildJsonObject { put("group_id", 1); put("confirm", true) }) + r.messaging.onReady(r.antenna, r.device.deviceIdHex) + assertEquals(Messaging.NO_GROUP, r.groups.byId(id)!!.deviceGroupId) + } +} diff --git a/native-android/app/src/test/java/ch/offgrid/android/domain/OutboxReconcilerTest.kt b/native-android/app/src/test/java/ch/offgrid/android/domain/OutboxReconcilerTest.kt new file mode 100644 index 0000000..2f20c35 --- /dev/null +++ b/native-android/app/src/test/java/ch/offgrid/android/domain/OutboxReconcilerTest.kt @@ -0,0 +1,171 @@ +package ch.offgrid.android.domain + +import ch.offgrid.android.data.MessageEntity +import ch.offgrid.android.data.MessageStatus +import ch.offgrid.android.link.Incoming +import ch.offgrid.android.link.LinkCodec +import kotlinx.serialization.json.JsonObject +import org.junit.Assert.assertEquals +import org.junit.Assert.assertNull +import org.junit.Assert.assertTrue +import org.junit.Test + +class OutboxReconcilerTest { + private val device = "A4CF12F00D42" + private val old = "$device/old-session" + private val now = "$device/new-session" + + private fun out(id: Long, ref: Int?, status: Int = MessageStatus.SENT, session: String? = old, ctr: Int? = id.toInt(), group: Long? = null) = + MessageEntity(id = id, contactId = if (group == null) 1 else null, groupId = group, direction = "out", kind = "text", + text = "m$id", status = status, msgRef = ref, refSession = session, ctr = ctr, sentAt = id) + + private fun snapshot(pending: List = emptyList(), recent: List = emptyList()) = PendingSnapshot(pending, recent) + + private fun List.byId(id: Long) = single { it.id == id } + + @Test + fun stillQueuedMessagesTakeTheDeviceStateAndMoveIntoTheNewSession() { + val changed = OutboxReconciler.reconcile( + listOf(out(1, 100, MessageStatus.DEVICE_QUEUED), out(2, 101, MessageStatus.WAITING)), + device, + snapshot(pending = listOf(DeviceMessage(100, "waiting", "no_ack"), DeviceMessage(101, "retrying"))), + now, + ) + with(changed.byId(1)) { + assertEquals(MessageStatus.WAITING, status) + assertEquals(100, msgRef) + assertEquals(now, refSession) + } + // A queue state behind the local one does not move the message back, it only renews the session. + with(changed.byId(2)) { + assertEquals(MessageStatus.WAITING, status) + assertEquals(now, refSession) + } + } + + @Test + fun finalOutcomesFromRecentAreAppliedAndDropTheRef() { + val changed = OutboxReconciler.reconcile( + listOf(out(1, 100), out(2, 101, MessageStatus.WAITING), out(3, 102)), + device, + snapshot(recent = listOf( + DeviceMessage(102, "cancelled"), + DeviceMessage(101, "failed", "timeout"), + DeviceMessage(100, "delivered"), + )), + now, + ) + assertEquals(MessageStatus.DELIVERED, changed.byId(1).status) + assertEquals(MessageStatus.FAILED, changed.byId(2).status) + assertEquals("timeout", changed.byId(2).failReason) + assertEquals("cancelled", changed.byId(3).failReason) + assertTrue(changed.all { it.msgRef == null && it.refSession == null }) + // The delivery was only found afterwards: shown as "zugestellt, während offline", not as lost. + assertTrue(changed.byId(1).deliveredOffline) + assertTrue(changed.none { it.id != 1L && it.deliveredOffline }) + } + + @Test + fun eventsCarryRetriesHopsAndTheTimeToTheAck() { + val sent = out(1, 100, MessageStatus.SENT, session = now).copy(deviceState = "sent") + val retrying = OutboxReconciler.applyEvent(sent, "retrying", null, DeliveryDetails(retry = 1))!! + assertEquals(MessageStatus.SENT, retrying.status) + assertEquals("retrying", retrying.deviceState) + assertEquals(1, retrying.retry) + val relayed = OutboxReconciler.applyEvent(retrying, "relayed", null)!! + assertEquals(1, relayed.retry) + val delivered = OutboxReconciler.applyEvent(relayed, "delivered", null, DeliveryDetails(retry = 2, hops = 1, rttMs = 1840))!! + assertEquals(MessageStatus.DELIVERED, delivered.status) + assertEquals(1, delivered.hops) + assertEquals(1840, delivered.rttMs) + assertEquals(2, delivered.retry) + assertEquals(false, delivered.deliveredOffline) + assertEquals(DeliveryDetails(2, 1, 1840), DeliveryDetails.parse( + LinkCodec.json.parseToJsonElement("""{"msg_ref":100,"state":"delivered","retry":2,"hops":1,"rtt_ms":1840}""") as JsonObject, + )) + } + + @Test + fun aMessageTheAntennaNoLongerKnowsIsLost() { + val changed = OutboxReconciler.reconcile(listOf(out(1, 100, MessageStatus.WAITING)), device, PendingSnapshot.EMPTY, now) + with(changed.single()) { + assertEquals(MessageStatus.FAILED, status) + assertEquals(OutboxReconciler.REASON_LOST, failReason) + assertNull(msgRef) + assertNull(refSession) + } + } + + @Test + fun messagesOfAnotherAntennaAreLeftAlone() { + val other = out(1, 100, session = "112233445566/s") + assertTrue(OutboxReconciler.reconcile(listOf(other), device, PendingSnapshot.EMPTY, now).isEmpty()) + } + + @Test + fun rowsWithoutSessionNeedTheSameCounterToStayOpen() { + val changed = OutboxReconciler.reconcile( + listOf(out(1, 7, session = null, ctr = 41), out(2, 8, session = null, ctr = 42), out(3, 9, session = null)), + device, + snapshot( + pending = listOf(DeviceMessage(7, "sent", ctr = 41), DeviceMessage(8, "sent", ctr = 99)), + recent = listOf(DeviceMessage(9, "delivered")), + ), + now, + ) + assertEquals(now, changed.byId(1).refSession) + assertEquals(7, changed.byId(1).msgRef) + // Same ref but another counter: a message of a later boot, not this one. + assertEquals(OutboxReconciler.REASON_LOST, changed.byId(2).failReason) + // `recent` has no counter to prove it, so an old row is not marked delivered on a ref alone. + assertEquals(OutboxReconciler.REASON_LOST, changed.byId(3).failReason) + } + + @Test + fun aRefFromAnEarlierBootCanNeverReachALaterMessage() { + // Ref 5 was given out before the antenna restarted; after the restart the same number names a new message. + val before = out(1, 5, MessageStatus.SENT, session = old) + val settled = OutboxReconciler.reconcile(listOf(before), device, PendingSnapshot.EMPTY, now).single() + assertNull(settled.msgRef) + assertNull(settled.refSession) + // Events match by (ref, current session), which this row no longer has; and a final row never changes. + assertNull(OutboxReconciler.applyEvent(settled, "delivered", null)) + assertNull(OutboxReconciler.applyEvent(out(2, 6, MessageStatus.DELIVERED, session = now), "sent", null)) + } + + @Test + fun eventsNeverMoveAMessageBackAndFinalsClearTheRef() { + val waiting = out(1, 100, MessageStatus.WAITING, session = now).copy(deviceState = "waiting") + assertNull(OutboxReconciler.applyEvent(waiting, "sent", null)) + assertNull(OutboxReconciler.applyEvent(waiting, "waiting", "no_ack")) + assertNull(OutboxReconciler.applyEvent(waiting, "something_new", null)) + with(OutboxReconciler.applyEvent(waiting, "delivered", null)!!) { + assertEquals(MessageStatus.DELIVERED, status) + assertNull(msgRef) + assertNull(refSession) + } + assertEquals("locked", OutboxReconciler.applyEvent(waiting, "failed", "locked")!!.failReason) + assertEquals(MessageStatus.WAITING, OutboxReconciler.applyEvent(out(2, 101, session = now), "waiting", "no_ack")!!.status) + } + + @Test + fun sentIsFinalForGroupMessages() { + val group = out(1, 100, MessageStatus.DEVICE_QUEUED, session = now, group = 3) + with(OutboxReconciler.applyEvent(group, "sent", null)!!) { + assertEquals(MessageStatus.SENT, status) + assertNull(msgRef) + } + } + + @Test + fun parsesThePendingResultOfTheLabImage() { + val line = """{"id":3,"ok":true,"result":{"pending":[{"msg_ref":536870913,"to":2,"type":"text","ctr":12,"state":"waiting","retry":3}],""" + + """"recent":[{"msg_ref":536870912,"state":"failed","reason":"timeout"},{"msg_ref":536870911,"state":"delivered"}]}}""" + val result = (LinkCodec.decodeIncoming(line) as Incoming.Response).result + val s = PendingSnapshot.parse(result) + assertEquals(listOf(DeviceMessage(536870913, "waiting", null, 12, retry = 3)), s.pending) + assertEquals(listOf(DeviceMessage(536870912, "failed", "timeout"), DeviceMessage(536870911, "delivered")), s.recent) + // The team firmware has no `recent`. + assertTrue(PendingSnapshot.parse(JsonObject(emptyMap())).recent.isEmpty()) + } +} diff --git a/native-android/app/src/test/java/ch/offgrid/android/domain/PairingTest.kt b/native-android/app/src/test/java/ch/offgrid/android/domain/PairingTest.kt new file mode 100644 index 0000000..82eca18 --- /dev/null +++ b/native-android/app/src/test/java/ch/offgrid/android/domain/PairingTest.kt @@ -0,0 +1,184 @@ +package ch.offgrid.android.domain + +import ch.offgrid.android.crypto.FixedKeyUnlockTokenSource +import ch.offgrid.android.crypto.OgCrypto +import ch.offgrid.android.data.SettingDao +import ch.offgrid.android.data.SettingEntity +import ch.offgrid.android.link.Incoming +import ch.offgrid.android.link.int +import ch.offgrid.android.link.sim.SimFlashStore +import ch.offgrid.android.link.sim.SimulatedHeltec +import ch.offgrid.android.link.sim.SimulatedLink +import kotlinx.coroutines.CoroutineScope +import kotlinx.coroutines.Dispatchers +import kotlinx.coroutines.SupervisorJob +import kotlinx.coroutines.cancel +import kotlinx.coroutines.flow.Flow +import kotlinx.coroutines.flow.MutableStateFlow +import kotlinx.coroutines.flow.first +import kotlinx.coroutines.flow.map +import kotlinx.coroutines.runBlocking +import kotlinx.coroutines.withTimeout +import kotlinx.serialization.json.JsonObject +import org.junit.After +import org.junit.Assert.assertArrayEquals +import org.junit.Assert.assertEquals +import org.junit.Assert.assertFalse +import org.junit.Assert.assertNotEquals +import org.junit.Assert.assertTrue +import org.junit.Test + +/** + * The QR flow of link spec 5 against both simulated firmwares: the shown code has to stay the one the antenna + * completes with, also when the pairing screen is opened several times. + */ +class PairingTest { + private val scope = CoroutineScope(SupervisorJob() + Dispatchers.Default) + + @After + fun tearDown() = scope.cancel() + + private class Rig(val device: SimulatedHeltec, val antenna: AntennaManager, val pairing: Pairing, val store: FakeStore) + + private fun rig(lab: Boolean): Rig { + val device = SimulatedHeltec(SimFlashStore(null), scope, labRadio = lab) + val antenna = AntennaManager(scope, { SimulatedLink(device) }, FixedKeyUnlockTokenSource(OgCrypto.sha256("p".toByteArray())), + Settings(MemorySettingDao(), scope)).apply { + listener = object : AntennaListener { + override suspend fun onReady(antenna: AntennaManager, deviceId: String) {} + override suspend fun onEvent(event: Incoming.Event) {} + override suspend fun onDeviceRebooted() {} + } + } + val store = FakeStore() + return Rig(device, antenna, Pairing(antenna, store, scope), store) + } + + private suspend fun Rig.ready() { + antenna.connect() + withTimeout(10_000) { antenna.state.first { it.ready } } + } + + private suspend fun Rig.shownCode(after: Int = 0): String = withTimeout(5_000) { + pairing.state.first { it.qr != null && it.codeVersion > after }.qr!! + } + + private suspend fun Rig.settled(): PairingState = withTimeout(5_000) { + pairing.state.first { it.error != null || it.scannedName != null } + } + + private fun saltOf(qr: String) = OgCrypto.unb64(qr).copyOfRange(35, 51) + + private fun reopenKeepsTheCode(lab: Boolean) = runBlocking { + val r = rig(lab) + r.ready() + r.pairing.begin() + val first = r.shownCode() + r.pairing.leave() + r.pairing.begin() + assertEquals(first, r.shownCode()) + r.pairing.leave() + r.pairing.begin() + assertEquals(first, r.shownCode()) + // The antenna still has exactly the salt in the code, so a peer who scanned it gets the same key. + assertArrayEquals(saltOf(first), r.device.pairingSalt()) + } + + @Test + fun reopeningTheScreenKeepsTheCodeOnTeamFirmware() = reopenKeepsTheCode(lab = false) + + @Test + fun reopeningTheScreenKeepsTheCodeOnTheLabImage() = reopenKeepsTheCode(lab = true) + + @Test + fun aLockedAntennaGetsANewCode() = runBlocking { + val r = rig(lab = true) + r.ready() + r.pairing.begin() + val first = r.shownCode() + r.pairing.leave() + val before = r.antenna.state.value.unlockCount + r.antenna.call("sec.lock") + withTimeout(5_000) { r.antenna.state.first { it.ready && it.unlockCount > before } } + r.pairing.begin() + assertNotEquals(first, r.shownCode()) + } + + @Test + fun anEndedSessionIsRenewedAndTheNewCodeShown() = runBlocking { + val r = rig(lab = false) + r.ready() + r.pairing.begin() + val v = r.pairing.state.value.codeVersion + val shown = r.shownCode() + r.pairing.complete(r.device.addVirtualPeer("Anna", -80)) + assertEquals("Anna", r.settled().scannedName) + // Team firmware: the completion ended the session. A second peer in the same visit needs a new one. + r.pairing.leave() + r.pairing.begin() + assertEquals(shown, r.shownCode(after = v)) + r.pairing.complete(r.device.addVirtualPeer("Ben", -80)) + val s = withTimeout(5_000) { r.pairing.state.first { it.scannedName == "Ben" } } + assertTrue(s.codeRenewed) + assertNotEquals(shown, s.qr) + } + + @Test + fun theSamePeerCodeTwiceIsCodeUsedOnTheLabImage() = runBlocking { + val r = rig(lab = true) + r.ready() + r.pairing.begin() + r.shownCode() + val anna = r.device.addVirtualPeer("Anna", -80) + r.pairing.complete(anna) + r.settled() + r.pairing.leave() + r.pairing.begin() + r.shownCode() + r.pairing.complete(anna, replace = true) + assertEquals(PairingError.CODE_USED, r.settled().error) + } + + @Test + fun anExistingContactCanBePairedAgainWithReplace() = runBlocking { + val r = rig(lab = false) + r.ready() + r.pairing.begin() + r.shownCode() + val anna = r.device.addVirtualPeer("Anna", -80) + r.pairing.complete(anna) + r.settled() + r.pairing.leave() + r.pairing.begin() + r.shownCode() + r.pairing.complete(anna) + val refused = r.settled() + assertEquals(PairingError.CONTACT_EXISTS, refused.error) + assertEquals(anna, refused.replaceCode) + r.pairing.complete(refused.replaceCode!!, replace = true) + val s = withTimeout(5_000) { r.pairing.state.first { it.scannedName != null } } + assertEquals(null, s.error) + assertEquals(1, r.antenna.call("contact.list").int("total")) + assertFalse(r.store.saved.isEmpty()) + } + + private class FakeStore : Pairing.Store { + val saved = mutableListOf() + private val states = MutableStateFlow>(emptyMap()) + override suspend fun save(deviceId: String, contact: JsonObject): Long { + saved += contact + val id = contact.int("contact_id")!!.toLong() + states.value = states.value + (id to "pending") + return id + } + override fun contactState(contactId: Long): Flow = states.map { it[contactId] } + } + + private class MemorySettingDao : SettingDao { + private val map = MutableStateFlow>(emptyMap()) + override fun observeAll(): Flow> = map.map { m -> m.map { SettingEntity(it.key, it.value) } } + override suspend fun get(key: String): String? = map.value[key] + override suspend fun put(setting: SettingEntity) { map.value = map.value + (setting.key to setting.value) } + override suspend fun remove(key: String) { map.value = map.value - key } + } +} diff --git a/native-android/app/src/test/java/ch/offgrid/android/link/LinkCodecTest.kt b/native-android/app/src/test/java/ch/offgrid/android/link/LinkCodecTest.kt index 916826b..454e296 100644 --- a/native-android/app/src/test/java/ch/offgrid/android/link/LinkCodecTest.kt +++ b/native-android/app/src/test/java/ch/offgrid/android/link/LinkCodecTest.kt @@ -38,6 +38,18 @@ class LinkCodecTest { assertEquals("E_PARSE", parse.error?.code) } + @Test + fun readsTheFirmwaresFloatRssi() { + // msg.received and contact views carry RSSI and SNR as floats (Commands.cpp, Contacts::View). + val event = LinkCodec.decodeIncoming("{\"evt\":\"msg.received\",\"t\":5,\"data\":{\"rssi\":-91.6,\"snr\":7.25,\"last_rssi\":-85}}") + as Incoming.Event + assertNull(event.data.int("rssi")) + assertEquals(-92, event.data.dbm("rssi")) + assertEquals(-85, event.data.dbm("last_rssi")) + assertEquals(7.25, event.data.double("snr")!!, 0.0) + assertNull(event.data.dbm("missing")) + } + @Test fun ignoresGarbage() { assertNull(LinkCodec.decodeIncoming("{not json")) diff --git a/native-android/app/src/test/java/ch/offgrid/android/link/SimulatedHeltecGroupsTest.kt b/native-android/app/src/test/java/ch/offgrid/android/link/SimulatedHeltecGroupsTest.kt new file mode 100644 index 0000000..5f82b4e --- /dev/null +++ b/native-android/app/src/test/java/ch/offgrid/android/link/SimulatedHeltecGroupsTest.kt @@ -0,0 +1,247 @@ +package ch.offgrid.android.link + +import ch.offgrid.android.crypto.FixedKeyUnlockTokenSource +import ch.offgrid.android.crypto.OgCrypto +import ch.offgrid.android.crypto.TokenWrap +import ch.offgrid.android.link.sim.SimFlashStore +import ch.offgrid.android.link.sim.SimTiming +import ch.offgrid.android.link.sim.SimulatedHeltec +import ch.offgrid.android.link.sim.SimulatedLink +import kotlinx.coroutines.CoroutineScope +import kotlinx.coroutines.Dispatchers +import kotlinx.coroutines.SupervisorJob +import kotlinx.coroutines.cancel +import kotlinx.coroutines.runBlocking +import kotlinx.coroutines.withTimeout +import kotlinx.serialization.json.JsonArray +import kotlinx.serialization.json.JsonObject +import kotlinx.serialization.json.JsonPrimitive +import kotlinx.serialization.json.buildJsonObject +import kotlinx.serialization.json.put +import kotlinx.serialization.json.putJsonArray +import org.junit.After +import org.junit.Assert.assertEquals +import org.junit.Assert.assertFalse +import org.junit.Assert.assertNotNull +import org.junit.Assert.assertNull +import org.junit.Assert.assertTrue +import org.junit.Test + +/** The group commands, events and result shapes of the simulated antenna against the firmware doc (link spec 6 and 10). */ +class SimulatedHeltecGroupsTest { + private val scope = CoroutineScope(SupervisorJob() + Dispatchers.Default) + private val device = SimulatedHeltec(SimFlashStore(null), scope, timing = SimTiming(firstTxMs = 20, ackWaitMs = 40, retryMs = 40, retries = 2, groupSyncMs = 100)) + private val link = SimulatedLink(device) + private val tokens = FixedKeyUnlockTokenSource(OgCrypto.sha256("test-phone".toByteArray())) + private val hello = buildJsonObject { put("app", "offgrid-android"); put("app_proto", "1.1") } + + @After + fun tearDown() = scope.cancel() + + private class Rig(val client: LinkClient, val helloResult: JsonObject, val contacts: List) + + /** Provisions the board and pairs [names] with virtual peers; the contacts are returned in pairing order. */ + private suspend fun rig(vararg names: String): Rig { + val client = LinkClient(link.open(link.find()!!), scope) + val h = client.call("sys.hello", hello) + val deviceId = h.str("device_id")!! + val s = h.obj("session")!! + val wrapped = TokenWrap.wrap(tokens.token(OgCrypto.unhex(deviceId)), OgCrypto.unhex(deviceId), + OgCrypto.unb64(s.str("device_eph_pub")!!), OgCrypto.unb64(s.str("nonce")!!)) + client.call("sec.provision", buildJsonObject { + put("app_eph_pub", OgCrypto.b64(wrapped.appEphPub)); put("wrapped_token", OgCrypto.b64(wrapped.wrapped)); put("name", "HolyG") + }) + val contacts = names.map { name -> + val qr = device.addVirtualPeer(name, -90) + client.call("pair.begin") + client.call("pair.complete", buildJsonObject { put("qr", qr) }).obj("contact")!! + } + return Rig(client, h, contacts) + } + + private fun slots(contacts: List) = contacts.map { it.int("contact_id")!! } + + private suspend fun LinkClient.awaitEvent(name: String, match: (JsonObject) -> Boolean = { true }): JsonObject = withTimeout(10_000) { + var found: JsonObject? = null + while (found == null) { + val e = events.receive() + if (e.name == name && match(e.data)) found = e.data + } + found + } + + private suspend fun LinkClient.create(name: String, ids: List): JsonObject = call("group.create", buildJsonObject { + put("name", name) + putJsonArray("members") { ids.forEach { add(JsonPrimitive(it)) } } + }).obj("group")!! + + private fun members(ids: List) = buildJsonObject { putJsonArray("members") { ids.forEach { add(JsonPrimitive(it)) } } } + + @Test + fun helloListsTheGroupsFeatureAndLimits() = runBlocking { + val r = rig() + assertEquals("1.1", r.helloResult.str("proto")) + assertEquals(listOf("groups"), (r.helloResult["features"] as JsonArray).map { (it as JsonPrimitive).content }) + val limits = r.helloResult.obj("limits")!! + assertEquals(8, limits.int("max_groups")) + assertEquals(16, limits.int("max_group_members")) + assertEquals(83, limits.int("max_group_text_bytes")) + r.client.close() + } + + @Test + fun createReturnsTheGroupObjectWithMembersByNodeId() = runBlocking { + val r = rig("Anna", "Luca") + val ids = slots(r.contacts) + val g = r.client.create("Team", ids) + assertEquals(1, g.int("group_id")) + assertEquals(8, g.str("gid")!!.length) + assertEquals("Team", g.str("name")) + assertEquals(1, g.int("epoch")) + assertEquals(true, g.bool("owner")) + assertTrue(g.isNull("owner_contact_id")) + assertEquals(0, g.int("member")) + assertEquals(3, g.int("member_count")) + val members = (g["members"] as JsonArray).map { it as JsonObject } + assertEquals(listOf(0, 1, 2), members.map { it.int("member") }) + assertTrue(members[0].isNull("contact_id")) + assertEquals(ids, members.drop(1).map { it.int("contact_id") }) + assertEquals(r.contacts.map { it.str("node_id") }, members.drop(1).map { it.str("node_id") }) + + val list = r.client.call("group.list") + assertEquals(1, list.int("total")) + assertNull((list["groups"] as JsonArray).first().let { it as JsonObject }["members"]) + val got = r.client.call("group.get", buildJsonObject { put("group_id", 1) }).obj("group")!! + assertEquals(3, (got["members"] as JsonArray).size) + r.client.close() + } + + @Test + fun syncIsAnAcknowledgedDirectMessageWithToAndGroupId() = runBlocking { + val r = rig("Anna") + val slot = slots(r.contacts).single() + r.client.create("Team", listOf(slot)) + val sent = r.client.call("group.sync", buildJsonObject { put("group_id", 1); put("contact_id", slot) }) + val ref = sent.int("msg_ref")!! + assertEquals(true, sent.bool("ack_requested")) + val delivered = r.client.awaitEvent("msg.status") { it.int("msg_ref") == ref && it.str("state") == "delivered" } + assertEquals(slot, delivered.int("to")) + assertEquals(1, delivered.int("group_id")) + r.client.close() + } + + @Test + fun sendNeedsATypeRefusesAckAndEndsAtSent() = runBlocking { + val r = rig("Anna") + r.client.create("Team", slots(r.contacts)) + val refused = runCatching { + r.client.call("group.send", buildJsonObject { put("group_id", 1); put("type", "text"); put("text", "Hoi"); put("ack", true) }) + }.exceptionOrNull() as LinkCommandException + assertEquals("E_INVALID_ARG", refused.error.code) + + val sent = r.client.call("group.send", buildJsonObject { put("group_id", 1); put("type", "text"); put("text", "Hallo Gruppe!") }) + assertEquals(false, sent.bool("ack_requested")) + val ref = sent.int("msg_ref")!! + val status = r.client.awaitEvent("msg.status") { it.int("msg_ref") == ref } + assertEquals("sent", status.str("state")) + assertEquals(1, status.int("group_id")) + assertFalse(status.containsKey("to")) + // Group messages have no receipts: sent is final, the queue is empty. + assertEquals(0, (r.client.call("msg.pending")["pending"] as JsonArray).size) + r.client.close() + } + + @Test + fun aQuestionInTheGroupIsAnsweredWithGroupReceived() = runBlocking { + val r = rig("Anna") + r.client.create("Team", slots(r.contacts)) + r.client.call("group.send", buildJsonObject { put("group_id", 1); put("type", "text"); put("text", "Wer kommt?") }) + val received = r.client.awaitEvent("group.received") + assertEquals(1, received.int("group_id")) + assertEquals(1, received.int("member")) + assertEquals(r.contacts.single().int("contact_id"), received.int("from")) + assertEquals(r.contacts.single().str("node_id"), received.str("node_id")) + assertEquals("text", received.str("type")) + r.client.close() + } + + @Test + fun aMemberWithoutContactArrivesWithFromNull() = runBlocking { + val r = rig("Anna") + val slot = device.peerInvites(slots(r.contacts).single(), "Gipfeltour", others = listOf("ab12")) + r.client.awaitEvent("group.state") { it.str("state") == "joined" } + device.memberSays(slot, member = 2, text = "Wer bin ich?") + val received = r.client.awaitEvent("group.received") + assertTrue(received.isNull("from")) + assertEquals("AB12", received.str("node_id")) + assertEquals(2, received.int("member")) + r.client.close() + } + + @Test + fun aSimulatedInvitationJoinsAfterTheSyncDelay() = runBlocking { + val r = rig("Anna") + val anna = slots(r.contacts).single() + val slot = device.peerInvites(anna, "Gipfeltour") + val joined = r.client.awaitEvent("group.state") + assertEquals(slot, joined.int("group_id")) + assertEquals("joined", joined.str("state")) + assertEquals(1, joined.int("epoch")) + val g = r.client.call("group.get", buildJsonObject { put("group_id", slot) }).obj("group")!! + assertEquals(false, g.bool("owner")) + assertEquals(anna, g.int("owner_contact_id")) + assertEquals("Gipfeltour", g.str("name")) + // Only the owner changes members and hands out keys. + val refused = runCatching { r.client.call("group.add", buildJsonObject { put("group_id", slot); put("members", JsonArray(emptyList())) }) } + .exceptionOrNull() as LinkCommandException + assertEquals("E_INVALID_ARG", refused.error.code) + r.client.close() + } + + @Test + fun addAndRemoveStartANewEpochAndCancelOldSyncs() = runBlocking { + val r = rig("Anna", "Luca", "Mia") + val (anna, luca, mia) = slots(r.contacts) + r.client.create("Team", listOf(anna, luca)) + val pendingSync = r.client.call("group.sync", buildJsonObject { put("group_id", 1); put("contact_id", anna) }).int("msg_ref")!! + + val added = r.client.call("group.add", buildJsonObject { + put("group_id", 1) + putJsonArray("members") { add(JsonPrimitive(mia)) } + }).obj("group")!! + assertEquals(2, added.int("epoch")) + assertEquals(4, added.int("member_count")) + val cancelled = r.client.awaitEvent("msg.status") { it.int("msg_ref") == pendingSync } + assertEquals("cancelled", cancelled.str("state")) + + val removed = r.client.call("group.remove", buildJsonObject { + put("group_id", 1) + putJsonArray("members") { add(JsonPrimitive(1)) } + }).obj("group")!! + assertEquals(3, removed.int("epoch")) + assertEquals(listOf(0, 2, 3), (removed["members"] as JsonArray).map { (it as JsonObject).int("member") }) + + // The owner cannot be removed, and at least two members must stay. + for (bad in listOf(0, 9)) { + val e = runCatching { + r.client.call("group.remove", buildJsonObject { put("group_id", 1); putJsonArray("members") { add(JsonPrimitive(bad)) } }) + }.exceptionOrNull() as LinkCommandException + assertEquals("E_INVALID_ARG", e.error.code) + } + val tooFew = runCatching { r.client.call("group.remove", buildJsonObject { put("group_id", 1); put("members", members(listOf(2, 3))["members"]!!) }) } + .exceptionOrNull() as LinkCommandException + assertEquals("E_INVALID_ARG", tooFew.error.code) + r.client.close() + } + + @Test + fun deleteFreesTheSlotAndUnknownGroupsAreRefused() = runBlocking { + val r = rig("Anna") + r.client.create("Team", slots(r.contacts)) + assertEquals(true, r.client.call("group.delete", buildJsonObject { put("group_id", 1); put("confirm", true) }).bool("deleted")) + val gone = runCatching { r.client.call("group.get", buildJsonObject { put("group_id", 1) }) }.exceptionOrNull() as LinkCommandException + assertEquals("E_NO_SUCH_GROUP", gone.error.code) + assertNotNull(r.client.create("Neu", slots(r.contacts))) + r.client.close() + } +} diff --git a/native-android/app/src/test/java/ch/offgrid/android/link/SimulatedHeltecLab3Test.kt b/native-android/app/src/test/java/ch/offgrid/android/link/SimulatedHeltecLab3Test.kt new file mode 100644 index 0000000..e394779 --- /dev/null +++ b/native-android/app/src/test/java/ch/offgrid/android/link/SimulatedHeltecLab3Test.kt @@ -0,0 +1,301 @@ +package ch.offgrid.android.link + +import ch.offgrid.android.crypto.FixedKeyUnlockTokenSource +import ch.offgrid.android.crypto.OgCrypto +import ch.offgrid.android.crypto.TokenWrap +import ch.offgrid.android.crypto.WrapPurpose +import ch.offgrid.android.domain.MessageLimits +import ch.offgrid.android.link.sim.SimFlashStore +import ch.offgrid.android.link.sim.SimTiming +import ch.offgrid.android.link.sim.SimulatedHeltec +import ch.offgrid.android.link.sim.SimulatedLink +import kotlinx.coroutines.CoroutineScope +import kotlinx.coroutines.Dispatchers +import kotlinx.coroutines.SupervisorJob +import kotlinx.coroutines.cancel +import kotlinx.coroutines.runBlocking +import kotlinx.coroutines.withTimeout +import kotlinx.serialization.json.JsonArray +import kotlinx.serialization.json.JsonObject +import kotlinx.serialization.json.JsonPrimitive +import kotlinx.serialization.json.buildJsonObject +import kotlinx.serialization.json.put +import kotlinx.serialization.json.putJsonArray +import org.junit.After +import org.junit.Assert.assertEquals +import org.junit.Assert.assertNotEquals +import org.junit.Assert.assertTrue +import org.junit.Test + +/** The simulator follows the lab.3 host contract the app is written against (no hardware involved). */ +class SimulatedHeltecLab3Test { + private val scope = CoroutineScope(SupervisorJob() + Dispatchers.Default) + private val timing = SimTiming(firstTxMs = 20, ackWaitMs = 40, retryMs = 40, retries = 2, resendMs = 150, parkMs = 1_500) + private val device = SimulatedHeltec(SimFlashStore(null), scope, timing = timing) + private val link = SimulatedLink(device) + private val tokens = FixedKeyUnlockTokenSource(OgCrypto.sha256("test-phone".toByteArray())) + private val hello = buildJsonObject { put("app", "offgrid-android"); put("app_proto", "1.0") } + private lateinit var deviceId: String + + @After + fun tearDown() = scope.cancel() + + private suspend fun connect(): LinkClient = LinkClient(link.open(link.find()!!), scope) + + private fun wrapArgs(h: JsonObject, purpose: WrapPurpose = WrapPurpose.UNLOCK, token: ByteArray = token()) = buildJsonObject { + val s = h.obj("session")!! + val w = TokenWrap.wrap(token, OgCrypto.unhex(deviceId), OgCrypto.unb64(s.str("device_eph_pub")!!), OgCrypto.unb64(s.str("nonce")!!), purpose) + put("app_eph_pub", OgCrypto.b64(w.appEphPub)) + put("wrapped_token", OgCrypto.b64(w.wrapped)) + } + + private fun token() = tokens.token(OgCrypto.unhex(deviceId)) + + private suspend fun LinkClient.provisioned(): LinkClient { + val h = call("sys.hello", hello) + deviceId = h.str("device_id")!! + call("sec.provision", wrapArgs(h)) + return this + } + + private suspend fun LinkClient.pair(name: String, inRange: Boolean = true): Int { + val qr = device.addVirtualPeer(name, -90, inRange = inRange) + call("pair.begin") + return call("pair.complete", buildJsonObject { put("qr", qr) }).obj("contact")!!.int("contact_id")!! + } + + private suspend fun LinkClient.send(slot: Int, text: String = "Hallo") = + call("msg.send", buildJsonObject { put("to", slot); put("type", "text"); put("text", text); put("ack", true) }) + + private suspend fun LinkClient.awaitStatus(ref: Int, state: String): JsonObject = withTimeout(10_000) { + var found: JsonObject? = null + while (found == null) { + val e = events.receive() + if (e.name == "msg.status" && e.data.int("msg_ref") == ref && e.data.str("state") == state) found = e.data + } + found + } + + private suspend fun LinkClient.pending(): Pair, List> { + val r = call("msg.pending") + fun list(key: String) = (r[key] as JsonArray).map { it as JsonObject } + return list("pending") to list("recent") + } + + private suspend fun LinkClient.errorOf(cmd: String, args: JsonObject? = null): String = + (runCatching { call(cmd, args) }.exceptionOrNull() as LinkCommandException).error.code + + @Test + fun helloAnnouncesTheLabRadioAndRefsStartRandomly() = runBlocking { + val c = connect().provisioned() + val h = c.call("sys.hello", hello) + assertEquals(true, h.bool("lab_radio")) + assertEquals("raw", h.str("text_codec")) + assertEquals("0.3.0-lab.3-sim", h.obj("fw")!!.str("version")) + val slot = c.pair("Anna") + val first = c.send(slot).int("msg_ref")!! + assertTrue(first in 1..(1 shl 30)) + assertEquals(first + 1, c.send(slot).int("msg_ref")) + c.close() + } + + @Test + fun deliveredMessagesLandInRecentNewestFirst() = runBlocking { + val c = connect().provisioned() + val slot = c.pair("Anna") + val a = c.send(slot).int("msg_ref")!! + c.awaitStatus(a, "delivered") + val b = c.send(slot).int("msg_ref")!! + c.awaitStatus(b, "delivered") + val (pending, recent) = c.pending() + assertTrue(pending.isEmpty()) + assertEquals(listOf(b, a), recent.map { it.int("msg_ref") }) + assertEquals("delivered", recent.first().str("state")) + c.close() + } + + @Test + fun unansweredMessageWaitsThenDeliversWhenTheContactIsHeardAgain() = runBlocking { + val c = connect().provisioned() + val slot = c.pair("Mia", inRange = false) + val ref = c.send(slot).int("msg_ref")!! + val waiting = c.awaitStatus(ref, "waiting") + assertEquals("no_ack", waiting.str("reason")) + val item = c.pending().first.single() + assertEquals("waiting", item.str("state")) + assertEquals(ref, item.int("msg_ref")) + + device.setPeerInRange(slot, true) + device.peerSays(slot, "Bin wieder da") + c.awaitStatus(ref, "delivered") + assertEquals("delivered", c.pending().second.first { it.int("msg_ref") == ref }.str("state")) + c.close() + } + + @Test + fun waitingEndsAsTimeoutAfterTheParkTime() = runBlocking { + val c = connect().provisioned() + val slot = c.pair("Mia", inRange = false) + val ref = c.send(slot).int("msg_ref")!! + assertEquals("timeout", c.awaitStatus(ref, "failed").str("reason")) + val recent = c.pending().second.single() + assertEquals("failed", recent.str("state")) + assertEquals("timeout", recent.str("reason")) + c.close() + } + + @Test + fun lockFailsPendingAndRebootForgetsQueueAndRecent() = runBlocking { + val c = connect().provisioned() + val slot = c.pair("Mia", inRange = false) + val ref = c.send(slot).int("msg_ref")!! + c.call("sec.lock") + assertEquals("locked", c.awaitStatus(ref, "failed").str("reason")) + c.call("sec.unlock", wrapArgs(c.call("sys.hello", hello))) + assertEquals("locked", c.pending().second.single { it.int("msg_ref") == ref }.str("reason")) + + val beforeReboot = c.send(slot).int("msg_ref")!! + device.powerCycle() + c.call("sec.unlock", wrapArgs(c.call("sys.hello", hello))) + val (pending, recent) = c.pending() + assertTrue(pending.isEmpty() && recent.isEmpty()) + assertNotEquals(beforeReboot + 1, c.send(slot).int("msg_ref")) + c.close() + } + + @Test + fun cancelAnswersOnlyForPendingMessages() = runBlocking { + val c = connect().provisioned() + val slot = c.pair("Mia", inRange = false) + val ref = c.send(slot).int("msg_ref")!! + assertEquals("cancelled", c.call("msg.cancel", buildJsonObject { put("msg_ref", ref) }).str("state")) + c.awaitStatus(ref, "cancelled") + assertEquals("E_INVALID_ARG", c.errorOf("msg.cancel", buildJsonObject { put("msg_ref", ref) })) + c.close() + } + + @Test + fun factoryResetNeedsTheResetEnvelope() = runBlocking { + val c = connect().provisioned() + c.pair("Anna") + val erase = { h: JsonObject, purpose: WrapPurpose -> + buildJsonObject { + put("confirm", "ERASE"); put("method", "app") + wrapArgs(h, purpose).forEach { (k, v) -> put(k, v) } + } + } + assertEquals("E_CONFIRM_REQUIRED", c.errorOf("sys.factory_reset", buildJsonObject { put("confirm", "yes") })) + val unlockEnvelope = erase(c.call("sys.hello", hello), WrapPurpose.UNLOCK) + assertEquals("E_UNLOCK_FAILED", c.errorOf("sys.factory_reset", unlockEnvelope)) + // The failed attempt used up the session (spec 6.7), so the same envelope cannot be tried again. + assertEquals("E_NO_SESSION", c.errorOf("sys.factory_reset", unlockEnvelope)) + + assertEquals(true, c.call("sys.factory_reset", erase(c.call("sys.hello", hello), WrapPurpose.RESET)).bool("pending")) + withTimeout(5_000) { while (true) { val e = c.events.receive(); if (e.name == "sys.boot") break } } + val h = c.call("sys.hello", hello) + assertEquals("unprovisioned", h.str("state")) + assertEquals(deviceId, h.str("device_id")) + c.call("sec.provision", wrapArgs(h)) + assertEquals(0, c.call("contact.list", buildJsonObject { put("offset", 0); put("limit", 10) }).int("total")) + c.close() + } + + @Test + fun ogz1AcceptsLongerTextWhenItCompresses() = runBlocking { + val c = connect().provisioned() + val slot = c.pair("Anna") + val text = "Wir sind bei der Hütte und kommen in etwa zwanzig Minuten. Wartest du dort auf uns oder gehst du weiter?" + assertTrue(text.toByteArray().size in 84..160) + assertEquals("E_TOO_LONG", c.errorOf("msg.send", buildJsonObject { put("to", slot); put("type", "text"); put("text", text) })) + val lab = c.call("lab.set", buildJsonObject { put("text_codec", "ogz1") }) + assertEquals(160, lab.int("max_text_input_bytes")) + assertEquals("ogz1", c.call("sys.hello", hello).str("text_codec")) + assertTrue(MessageLimits.onAirTextBytes(text, MessageLimits.CODEC_OGZ1, 160) <= 83) + val sent = c.call("msg.send", buildJsonObject { put("to", slot); put("type", "text"); put("text", text) }) + assertTrue(sent.int("bytes_on_air")!! < 17 + text.toByteArray().size) + assertEquals(true, sent.bool("compressed")) + // Texts that fit raw stay raw, so a team board can read them. + assertEquals(false, c.send(slot, "Kurz").bool("compressed")) + c.close() + } + + @Test + fun pairBeginKeepsItsSaltForTheWindow() = runBlocking { + val c = connect().provisioned() + val first = c.call("pair.begin") + val again = c.call("pair.begin") + assertEquals(first.str("qr"), again.str("qr")) + assertTrue(again.int("expires_s")!! <= 300) + c.call("pair.cancel") + val second = c.call("pair.begin").str("qr") + assertNotEquals(first.str("qr"), second) + val qr = device.addVirtualPeer("Anna", -80) + c.call("pair.complete", buildJsonObject { put("qr", qr) }) + // A completion ends the session, and the same peer code is refused within the window. + assertNotEquals(second, c.call("pair.begin").str("qr")) + assertEquals("E_NO_PAIRING", c.errorOf("pair.complete", buildJsonObject { put("qr", qr); put("replace", true) })) + c.close() + } + + @Test + fun labSetValidatesAndPersistsTheIgnoreList() = runBlocking { + val c = connect().provisioned() + val own = c.call("lab.get") + assertEquals(c.call("id.get").str("node_id"), own.str("node_id")) + assertEquals("0.3.0-lab.3-sim", own.str("fw")) + assertTrue((own["ignore_nodes"] as JsonArray).isEmpty()) + val set = c.call("lab.set", buildJsonObject { putJsonArray("ignore_nodes") { add(JsonPrimitive("033b")); add(JsonPrimitive("E841")) } }) + assertEquals(listOf("033B", "E841"), (set["ignore_nodes"] as JsonArray).map { (it as JsonPrimitive).content }) + assertEquals("E_INVALID_ARG", c.errorOf("lab.set", buildJsonObject { putJsonArray("ignore_nodes") { add(JsonPrimitive("33B")) } })) + assertEquals("E_INVALID_ARG", c.errorOf("lab.set", buildJsonObject { + putJsonArray("ignore_nodes") { repeat(9) { add(JsonPrimitive("%04X".format(it))) } } + })) + assertEquals(2, (c.call("lab.get")["ignore_nodes"] as JsonArray).size) + c.call("sec.lock") + assertEquals("E_LOCKED", c.errorOf("lab.get")) + c.close() + } + + @Test + fun anIgnoredNodeIsOutOfReach() = runBlocking { + val c = connect().provisioned() + val slot = c.pair("Anna") + val node = c.call("contact.get", buildJsonObject { put("contact_id", slot) }).obj("contact")!!.str("node_id")!! + c.call("lab.set", buildJsonObject { putJsonArray("ignore_nodes") { add(JsonPrimitive(node)) } }) + val ref = c.send(slot).int("msg_ref")!! + assertEquals("no_ack", c.awaitStatus(ref, "waiting").str("reason")) + c.call("lab.set", buildJsonObject { putJsonArray("ignore_nodes") {} }) + device.peerSays(slot, "Hallo") + c.awaitStatus(ref, "delivered") + c.close() + } + + @Test + fun meshSettingsWorkInEveryStateForReadingAndUnlockedForWriting() = runBlocking { + val c = connect().provisioned() + assertEquals(3, c.call("mesh.get").int("hop_default")) + val set = c.call("mesh.set", buildJsonObject { put("hop_default", 5); put("relay_when_locked", true) }) + assertEquals(5, set.int("hop_default")) + assertEquals(true, set.bool("relay_when_locked")) + assertEquals("E_INVALID_ARG", c.errorOf("mesh.set", buildJsonObject { put("hop_default", 8) })) + assertEquals(5, c.call("msg.send", buildJsonObject { put("to", c.pair("Anna")); put("type", "text"); put("text", "x") }).int("hops")) + c.call("sec.lock") + assertEquals(5, c.call("mesh.get").int("hop_default")) + assertEquals(true, c.call("sys.status").obj("radio")!!.bool("relay_only")) + assertEquals("E_LOCKED", c.errorOf("mesh.set", buildJsonObject { put("hop_default", 1) })) + c.close() + } + + @Test + fun radioStatsCountAndReset() = runBlocking { + val c = connect().provisioned() + val slot = c.pair("Anna") + c.awaitStatus(c.send(slot).int("msg_ref")!!, "delivered") + val stats = c.call("radio.stats", buildJsonObject { put("reset", true) }) + assertTrue(stats.int("tx_packets")!! >= 1) + assertEquals(1, stats.int("acks_received")) + assertEquals(10, stats.int("tx_duty_cycle_max_percent")) + assertEquals(0, c.call("radio.stats").int("tx_packets")) + c.close() + } +} diff --git a/native-android/app/src/test/java/ch/offgrid/android/link/SimulatedHeltecTeamTest.kt b/native-android/app/src/test/java/ch/offgrid/android/link/SimulatedHeltecTeamTest.kt new file mode 100644 index 0000000..11b7151 --- /dev/null +++ b/native-android/app/src/test/java/ch/offgrid/android/link/SimulatedHeltecTeamTest.kt @@ -0,0 +1,97 @@ +package ch.offgrid.android.link + +import ch.offgrid.android.crypto.FixedKeyUnlockTokenSource +import ch.offgrid.android.crypto.OgCrypto +import ch.offgrid.android.crypto.TokenWrap +import ch.offgrid.android.link.sim.SimFlashStore +import ch.offgrid.android.link.sim.SimTiming +import ch.offgrid.android.link.sim.SimulatedHeltec +import ch.offgrid.android.link.sim.SimulatedLink +import kotlinx.coroutines.CoroutineScope +import kotlinx.coroutines.Dispatchers +import kotlinx.coroutines.SupervisorJob +import kotlinx.coroutines.cancel +import kotlinx.coroutines.runBlocking +import kotlinx.coroutines.withTimeout +import kotlinx.serialization.json.JsonObject +import kotlinx.serialization.json.buildJsonObject +import kotlinx.serialization.json.put +import org.junit.After +import org.junit.Assert.assertEquals +import org.junit.Assert.assertFalse +import org.junit.Assert.assertNotEquals +import org.junit.Assert.assertNull +import org.junit.Test + +/** The simulator without the lab image follows Nils' team firmware 0.3.0 (link spec on `feature/firmware-hardening`). */ +class SimulatedHeltecTeamTest { + private val scope = CoroutineScope(SupervisorJob() + Dispatchers.Default) + private val timing = SimTiming(firstTxMs = 20, ackWaitMs = 40, retryMs = 40, retries = 2) + private val device = SimulatedHeltec(SimFlashStore(null), scope, timing = timing, labRadio = false) + private val link = SimulatedLink(device) + private val tokens = FixedKeyUnlockTokenSource(OgCrypto.sha256("test-phone".toByteArray())) + private val hello = buildJsonObject { put("app", "offgrid-android"); put("app_proto", "1.0") } + + @After + fun tearDown() = scope.cancel() + + private suspend fun provisioned(): LinkClient { + val c = LinkClient(link.open(link.find()!!), scope) + val h = c.call("sys.hello", hello) + val deviceId = h.str("device_id")!! + val s = h.obj("session")!! + val w = TokenWrap.wrap(tokens.token(OgCrypto.unhex(deviceId)), OgCrypto.unhex(deviceId), + OgCrypto.unb64(s.str("device_eph_pub")!!), OgCrypto.unb64(s.str("nonce")!!)) + c.call("sec.provision", buildJsonObject { put("app_eph_pub", OgCrypto.b64(w.appEphPub)); put("wrapped_token", OgCrypto.b64(w.wrapped)) }) + return c + } + + private suspend fun LinkClient.errorOf(cmd: String, args: JsonObject? = null): String = + (runCatching { call(cmd, args) }.exceptionOrNull() as LinkCommandException).error.code + + @Test + fun helloHasNoLabFieldsAndMockIsFalse() = runBlocking { + val c = provisioned() + val h = c.call("sys.hello", hello) + assertNull(h["lab_radio"]) + assertEquals(false, h.bool("mock")) + assertEquals("og-reset-wrap-v1", h.obj("recovery")!!.str("app_wrap_label")) + assertEquals("E_UNKNOWN_CMD", c.errorOf("lab.get")) + c.close() + } + + @Test + fun everyPairBeginDrawsANewSaltAndCompletionEndsTheSession() = runBlocking { + val c = provisioned() + val first = c.call("pair.begin").str("qr") + assertNotEquals(first, c.call("pair.begin").str("qr")) + c.call("pair.complete", buildJsonObject { put("qr", device.addVirtualPeer("Anna", -80)) }) + assertEquals("E_NO_PAIRING", c.errorOf("pair.complete", buildJsonObject { put("qr", device.addVirtualPeer("Ben", -80)) })) + c.close() + } + + @Test + fun noAckAfterTheRetriesFailsWithTimeoutAndPendingHasNoRecent() = runBlocking { + val c = provisioned() + val qr = device.addVirtualPeer("Mia", -90, inRange = false) + c.call("pair.begin") + val slot = c.call("pair.complete", buildJsonObject { put("qr", qr) }).obj("contact")!!.int("contact_id")!! + val sent = c.call("msg.send", buildJsonObject { put("to", slot); put("type", "text"); put("text", "Hallo") }) + assertNull(sent["compressed"]) + val ref = sent.int("msg_ref")!! + val failed = withTimeout(5_000) { + var found: JsonObject? = null + while (found == null) { + val e = c.events.receive() + assertNotEquals("waiting", e.data.str("state")) + if (e.name == "msg.status" && e.data.int("msg_ref") == ref && e.data.str("state") == "failed") found = e.data + } + found + } + assertEquals("timeout", failed.str("reason")) + val pending = c.call("msg.pending") + assertFalse(pending.containsKey("recent")) + assertEquals("E_TOO_LONG", c.errorOf("msg.send", buildJsonObject { put("to", slot); put("type", "text"); put("text", "x".repeat(84)) })) + c.close() + } +} diff --git a/native-android/app/src/test/java/ch/offgrid/android/link/hw/RealAntennaTest.kt b/native-android/app/src/test/java/ch/offgrid/android/link/hw/RealAntennaTest.kt index 716fa7c..55f01c5 100644 --- a/native-android/app/src/test/java/ch/offgrid/android/link/hw/RealAntennaTest.kt +++ b/native-android/app/src/test/java/ch/offgrid/android/link/hw/RealAntennaTest.kt @@ -35,6 +35,7 @@ import kotlinx.coroutines.launch import kotlinx.coroutines.runBlocking import kotlinx.coroutines.withTimeout import kotlinx.coroutines.withTimeoutOrNull +import kotlinx.serialization.json.JsonArray import kotlinx.serialization.json.JsonObject import kotlinx.serialization.json.buildJsonObject import kotlinx.serialization.json.put @@ -197,23 +198,34 @@ class RealAntennaTest { log("msg.send: $sent") val ref = sent.long("msg_ref")!! val states = mutableListOf() - // Lab radio image: sent after TxDone, then three retries and failed(timeout) without a second - // antenna: about 32 s at SF9 with hops 0, over 2 min with the default 3 hops (protocol 12.2 scales the - // timeout with 2 x hops + 2). Team mock: sent, relayed, delivered on short timers. The heartbeat - // keeps the board from locking (and failing the message with reason locked) while we wait. + val lab = c.call("sys.hello", hello).bool("lab_radio") == true + // Lab radio image 0.2.0-lab.3: sent after TxDone, then three retries and, without a second antenna, + // waiting (no_ack) instead of failed: about 32 s at SF9 with hops 0, over 2 min with the default 3 + // hops (protocol 12.2 scales the timeout with 2 x hops + 2). Older lab images end in failed(timeout). + // Team mock: sent, relayed, delivered on short timers. The heartbeat keeps the board from locking + // (and failing the message with reason locked) while we wait. val heartbeat = scope.launch { while (true) { delay(5_000); c.call("sys.ping") } } val last = nextEvent(c, 120_000) { e -> if (e.name == "msg.status" && e.data.long("msg_ref") == ref) states += e.data.str("state")!! - e.name == "msg.status" && e.data.long("msg_ref") == ref && e.data.str("state") in setOf("delivered", "failed") + e.name == "msg.status" && e.data.long("msg_ref") == ref && e.data.str("state") in setOf("delivered", "failed", "waiting") } heartbeat.cancel() log("states: $states") assertTrue(states.firstOrNull() == "sent") - assertTrue(last?.data?.str("state") == "delivered" || last?.data?.str("reason") == "timeout") + if (last?.data?.str("state") == "waiting") { + // Lab contract item 5: the message keeps its slot as waiting, and msg.pending reports outcomes in recent. + assertEquals("no_ack", last.data.str("reason")) + val queued = (c.call("msg.pending")["pending"] as JsonArray).map { it as JsonObject }.single { it.long("msg_ref") == ref } + assertEquals("waiting", queued.str("state")) + c.call("msg.cancel", buildJsonObject { put("msg_ref", ref) }) + val recent = (c.call("msg.pending")["recent"] as JsonArray).map { it as JsonObject } + assertEquals("cancelled", recent.first { it.long("msg_ref") == ref }.str("state")) + } else { + assertTrue(last?.data?.str("state") == "delivered" || last?.data?.str("reason") == "timeout") + } // The pairing ping (empty reaction, ref 0) the app sends right after pair.complete. The team mock up // to ed9fd57 rejects every reaction ("target must be an object": `is()` on a const view), // so there it is recorded, not asserted; the lab image must accept it. - val lab = c.call("sys.hello", hello).bool("lab_radio") == true try { val ping = c.call("msg.send", Messaging.pingArgs(slot)) log("ping: $ping") diff --git a/native-android/app/src/test/java/ch/offgrid/android/link/hw/TeamFirmwareTest.kt b/native-android/app/src/test/java/ch/offgrid/android/link/hw/TeamFirmwareTest.kt new file mode 100644 index 0000000..0e6d1bc --- /dev/null +++ b/native-android/app/src/test/java/ch/offgrid/android/link/hw/TeamFirmwareTest.kt @@ -0,0 +1,245 @@ +package ch.offgrid.android.link.hw + +import ch.offgrid.android.crypto.FixedKeyUnlockTokenSource +import ch.offgrid.android.crypto.OgCrypto +import ch.offgrid.android.data.SettingDao +import ch.offgrid.android.data.SettingEntity +import ch.offgrid.android.domain.AntennaError +import ch.offgrid.android.domain.AntennaListener +import ch.offgrid.android.domain.AntennaManager +import ch.offgrid.android.domain.AntennaPhase +import ch.offgrid.android.domain.AntennaState +import ch.offgrid.android.domain.Pairing +import ch.offgrid.android.domain.ResetResult +import ch.offgrid.android.domain.Settings +import ch.offgrid.android.link.Incoming +import ch.offgrid.android.link.int +import ch.offgrid.android.link.str +import ch.offgrid.android.link.tcp.TcpLink +import kotlinx.coroutines.CoroutineScope +import kotlinx.coroutines.Dispatchers +import kotlinx.coroutines.SupervisorJob +import kotlinx.coroutines.cancel +import kotlinx.coroutines.delay +import kotlinx.coroutines.flow.Flow +import kotlinx.coroutines.flow.MutableSharedFlow +import kotlinx.coroutines.flow.MutableStateFlow +import kotlinx.coroutines.flow.first +import kotlinx.coroutines.flow.map +import kotlinx.coroutines.runBlocking +import kotlinx.coroutines.withTimeout +import kotlinx.coroutines.withTimeoutOrNull +import kotlinx.serialization.json.JsonObject +import kotlinx.serialization.json.buildJsonObject +import kotlinx.serialization.json.put +import kotlinx.serialization.json.putJsonObject +import org.junit.After +import org.junit.Assert.assertEquals +import org.junit.Assert.assertNotEquals +import org.junit.Assert.assertNotNull +import org.junit.Assert.assertTrue +import org.junit.Assume.assumeTrue +import org.junit.Before +import org.junit.Test + +/** + * The app's own link, security and pairing code against two boards running the team firmware unchanged + * (`OffGridCH/firmware` `main`, no lab image), behind `bridge.py` as for [RealAntennaTest]: + * + * ``` + * OFFGRID_TCP_LINK=127.0.0.1:7755 OFFGRID_TCP_LINK_PEER=127.0.0.1:7756 \ + * ./gradlew testDebugUnitTest --tests '*TeamFirmwareTest*' + * ``` + * + * Both boards must be erased (unprovisioned) or provisioned by this test's token sources. One scenario in a fixed + * order, because every step leaves the boards in the state the next one needs: provisioning, heartbeat, pairing + * the way the screens do it (each side leaves and reopens its code before and after scanning), text, location and + * reaction with the arguments [ch.offgrid.android.domain.Messaging] sends, a failed delivery to a locked peer, + * relock and unlock, wrong token and backoff, token rotation through a backup transfer, and the factory reset. + */ +class TeamFirmwareTest { + private val endpointA = System.getenv("OFFGRID_TCP_LINK").orEmpty() + private val endpointB = System.getenv("OFFGRID_TCP_LINK_PEER").orEmpty() + private val scope = CoroutineScope(SupervisorJob() + Dispatchers.Default) + + private fun log(text: String) = println("[team] $text") + + private class Phone(val label: String, val manager: AntennaManager, val settings: Settings) { + val events = MutableSharedFlow(replay = 64, extraBufferCapacity = 256) + val contacts = MutableStateFlow>(emptyMap()) + val states = MutableStateFlow>(emptyMap()) + val state: AntennaState get() = manager.state.value + } + + private fun phone(label: String, endpoint: String, key: String, settings: Settings = Settings(MemorySettingDao(), scope)): Phone { + val link = TcpLink(endpoint.substringBeforeLast(':'), endpoint.substringAfterLast(':').toInt()) + val tokens = FixedKeyUnlockTokenSource(OgCrypto.sha256(key.toByteArray())) + val manager = AntennaManager(scope, { link }, tokens, settings, log = { log("$label: $it") }) + val p = Phone(label, manager, settings) + manager.listener = object : AntennaListener { + override suspend fun onReady(antenna: AntennaManager, deviceId: String) = Unit + override suspend fun onEvent(event: Incoming.Event) { + log("$label event ${event.name} ${event.data}") + if (event.name == "contact.state") { + p.states.value = p.states.value + (event.data.int("contact_id")!! to event.data.str("state").orEmpty()) + } + p.events.emit(event) + } + override suspend fun onDeviceRebooted() = log("$label rebooted") + } + return p + } + + private fun store(p: Phone) = object : Pairing.Store { + override suspend fun save(deviceId: String, contact: JsonObject): Long { + val id = contact.int("contact_id")!!.toLong() + p.contacts.value = p.contacts.value + (id to contact) + return id + } + override fun contactState(contactId: Long): Flow = p.states.map { it[contactId.toInt()] } + } + + private suspend fun ready(p: Phone, timeoutMs: Long = 30_000): AntennaState = + withTimeout(timeoutMs) { p.manager.state.first { it.phase == AntennaPhase.READY } } + + private suspend fun event(p: Phone, timeoutMs: Long, match: (Incoming.Event) -> Boolean): Incoming.Event? = + withTimeoutOrNull(timeoutMs) { p.events.first(match) } + + private suspend fun sendAndDeliver(from: Phone, to: Phone, args: JsonObject, received: (JsonObject) -> Boolean): JsonObject { + val sent = from.manager.call("msg.send", args) + val ref = sent.int("msg_ref") + val got = event(to, 90_000) { it.name == "msg.received" && received(it.data) } + assertNotNull("${to.label} received ${args.str("type")}", got) + val done = event(from, 120_000) { it.name == "msg.status" && it.data.int("msg_ref") == ref && it.data.str("state") in FINAL } + assertEquals("${from.label} ${args.str("type")} delivered", "delivered", done?.data?.str("state")) + log("${args.str("type")} ${from.label}->${to.label}: rtt ${done?.data?.int("rtt_ms")} ms, rssi ${got!!.data.int("rssi")}") + return got.data + } + + @Before + fun setUp() = assumeTrue("OFFGRID_TCP_LINK and OFFGRID_TCP_LINK_PEER not set", ':' in endpointA && ':' in endpointB) + + @After + fun tearDown() = scope.cancel() + + @Test + fun appWorksWithTheTeamFirmware() = runBlocking { + val a = phone("A", endpointA, "team-test-phone-a") + val b = phone("B", endpointB, "team-test-phone-b") + + // Provision or unlock; the team firmware has no lab extras. + a.manager.connect(); b.manager.connect() + for (p in listOf(a, b)) { + val s = ready(p) + log("${p.label}: fw ${s.fwVersion} node ${s.nodeId} lab ${s.labRadio}") + assumeTrue("${p.label} runs a lab image", !s.labRadio) + assertEquals("1 % pacing", 1, p.manager.radioStats().int("tx_duty_cycle_max_percent")) + } + + // The app's 1 s heartbeat keeps both open past the 15 s lock timeout. + delay(20_000) + for (p in listOf(a, b)) assertEquals("unlocked", p.manager.call("sys.status").str("state")) + + // Pairing as on the screens: show, leave and reopen, scan, reopen again after the scan, then the peer scans. + for (p in listOf(a, b)) p.manager.call("pair.cancel") + val pa = Pairing(a.manager, store(a), scope) + val pb = Pairing(b.manager, store(b), scope) + pa.begin(); pb.begin() + val qrA = withTimeout(10_000) { pa.state.first { it.qr != null } }.qr!! + val qrB = withTimeout(10_000) { pb.state.first { it.qr != null } }.qr!! + pb.leave(); pb.begin() + assertEquals("B shows the same code after reopening", qrB, withTimeout(10_000) { pb.state.first { it.qr != null } }.qr) + pb.complete(qrA, replace = true) + withTimeout(15_000) { b.contacts.first { it.isNotEmpty() } } + pa.leave(); pa.begin() + assertEquals("A shows the same code after reopening", qrA, withTimeout(10_000) { pa.state.first { it.qr != null } }.qr) + pb.leave(); pb.begin() + assertEquals("B still shows its code after its own scan", qrB, withTimeout(10_000) { pb.state.first { it.qr != null } }.qr) + pa.complete(qrB, replace = true) + withTimeout(15_000) { a.contacts.first { it.isNotEmpty() } } + val slotAB = a.contacts.value.keys.first().toInt() + val slotBA = b.contacts.value.keys.first().toInt() + assertEquals(a.contacts.value.values.first().str("fingerprint"), b.contacts.value.values.first().str("fingerprint")) + + // Text both ways (umlauts and emoji, within 83 bytes), location, reaction: Messaging's arguments. + val textAB = "Grüezi aus der Hütte 🏔️ – alles ok?" + val gotB = sendAndDeliver(a, b, buildJsonObject { put("to", slotAB); put("type", "text"); put("text", textAB); put("ack", true) }) { + it.str("text") == textAB + } + assertEquals(0, gotB.int("hops")) + val textBA = "Ja, bis später! 👍" + sendAndDeliver(b, a, buildJsonObject { put("to", slotBA); put("type", "text"); put("text", textBA); put("ack", true) }) { + it.str("text") == textBA + } + sendAndDeliver(a, b, buildJsonObject { + put("to", slotAB); put("type", "geo"); put("lat", 47.0502); put("lon", 8.3093); put("age_s", 30); put("ack", true) + }) { it.str("type") == "geo" } + b.manager.call("msg.send", buildJsonObject { + put("to", slotBA); put("type", "reaction") + putJsonObject("target") { put("author", "peer"); put("ref", gotB.int("ctr")!! and 0xFFFF) } + put("emoji", "❤️") + }) + val reaction = event(a, 60_000) { it.name == "msg.received" && it.data.str("type") == "reaction" } + assertEquals("❤️", reaction?.data?.str("emoji")) + + // A peer that is locked (radio off on the team firmware) makes a delivery end as failed/timeout. + b.manager.disconnect() + delay(17_000) + val lost = a.manager.call("msg.send", buildJsonObject { put("to", slotAB); put("type", "text"); put("text", "Bist du da?"); put("ack", true) }) + val failed = event(a, 180_000) { it.name == "msg.status" && it.data.int("msg_ref") == lost.int("msg_ref") && it.data.str("state") in FINAL } + assertEquals("failed", failed?.data?.str("state")) + assertEquals("timeout", failed?.data?.str("reason")) + b.manager.connect() + assertEquals("B unlocks again after the heartbeat lock", AntennaPhase.READY, ready(b).phase) + + // Wrong token: unlock fails, the app counts the failures and backs off instead of hammering the board. + b.manager.disconnect() + val intruder = phone("X", endpointB, "some-other-phone") + intruder.manager.connect() + val refused = withTimeout(20_000) { intruder.manager.state.first { it.phase == AntennaPhase.ERROR } } + assertEquals(AntennaError.UNLOCK_FAILED, refused.error) + intruder.manager.disconnect() + repeat(3) { + intruder.manager.connect() + withTimeout(20_000) { intruder.manager.state.first { it.phase == AntennaPhase.ERROR } } + log("X attempt ${it + 2}: ${intruder.state.error} ${intruder.state.errorCode} retryAt ${intruder.state.retryAt}") + intruder.manager.disconnect() + } + assertTrue("backoff after repeated failures", intruder.state.error == AntennaError.RATE_LIMITED || intruder.state.retryAt != null) + delay(65_000) // let the board's backoff run out (60 s at most) + + // Token rotation: a new phone gets B's token through a backup transfer, unlocks once and rotates to its own. + val transferSettings = Settings(MemorySettingDao(), scope) + transferSettings.put(Settings.TRANSFER_TOKEN, OgCrypto.b64(b.manager.tokenFor(b.state.deviceId!!))) + transferSettings.put(Settings.TRANSFER_DEVICE, b.state.deviceId!!) + val newPhone = phone("B2", endpointB, "team-test-phone-b2", transferSettings) + newPhone.manager.connect() + assertEquals("new phone opens B with the transferred token", AntennaPhase.READY, ready(newPhone, 60_000).phase) + newPhone.manager.disconnect() + delay(1_000) + b.manager.connect() + val oldPhone = withTimeout(30_000) { b.manager.state.first { it.phase == AntennaPhase.ERROR || it.phase == AntennaPhase.READY } } + assertEquals("the old token no longer opens B", AntennaError.UNLOCK_FAILED, oldPhone.error) + b.manager.disconnect() + + // Factory reset through the serial API: new identity, no contacts, provisioned again by this phone. + val nodeBefore = a.state.nodeId + assertEquals(ResetResult.DONE, a.manager.factoryReset()) + val after = ready(a, 60_000) + assertNotEquals("new NodeID after the reset", nodeBefore, after.nodeId) + assertEquals(0, a.manager.call("contact.list", buildJsonObject { put("offset", 0); put("limit", 10) }).int("total")) + a.manager.disconnect() + } + + private class MemorySettingDao : SettingDao { + private val map = MutableStateFlow>(emptyMap()) + override fun observeAll(): Flow> = map.map { m -> m.map { SettingEntity(it.key, it.value) } } + override suspend fun get(key: String): String? = map.value[key] + override suspend fun put(setting: SettingEntity) { map.value = map.value + (setting.key to setting.value) } + override suspend fun remove(key: String) { map.value = map.value - key } + } + + private companion object { + val FINAL = setOf("delivered", "failed", "cancelled") + } +} diff --git a/native-android/docs/hardware.md b/native-android/docs/hardware.md index 7da8ba2..198efd3 100644 --- a/native-android/docs/hardware.md +++ b/native-android/docs/hardware.md @@ -49,7 +49,7 @@ reboots the board. | 1 | Reactions | `msg.send` with `type: "reaction"` and a `target` object | `ed9fd57` rejects every reaction with `E_INVALID_ARG`: `args["target"].is()` on a const ArduinoJson view is always false; it must be `is()` | Pairing sends a reaction as its ping, so every successful pairing was reported as failed | App: a failed ping no longer fails a stored pairing. Firmware: fixed in the lab fork only. | | 2 | First line after connect | The host may send right after opening | Answers the first `sys.hello` at once | `LineFramer` dropped the first line after opening, so every connect waited for the 500 ms retry | Fixed: a first line is kept when it parses as a complete JSON object. | | 3 | Radio | Messages travel over LoRa | No team image sends chat over the radio. The default env simulates delivery (`mock: true`); `radio_diag` exposes `radio.*` and rejects `msg.*` | Shows simulated delivery as real | The lab image sends and receives for real. | -| 4 | Authentication | X25519 + HKDF + AES-GCM token wrap | `authentication: "bypassed-envelope-shape-only"` | Performs the real handshake | Works; the board does not verify it yet (team and lab). | +| 4 | Authentication | X25519 + HKDF + AES-GCM token wrap | `feature/mesh-direct` verifies it (`Security.cpp`); older images: `authentication: "bypassed-envelope-shape-only"` | Performs the real handshake | Byte layout checked against `Security::unwrap` with independent vectors (see "App against lab.3"); not yet run against a board with lab.3. | | 5 | Persistence | Identity, contacts and provisioning survive a reboot | Only the config store is in NVS | Assumes they persist | The lab image stores identity, provisioning, name, codec and contacts in NVS; verified with an EN reset on both boards. | | 6 | Text budget | `limits.max_text_bytes`, 83 UTF-8 bytes | 83 | Uses `sys.hello` | Matches. With OGZ1 a TEXT of up to 160 input bytes fits (see below). | | 7 | Boot time | App retries `sys.hello` for about 8 s | `a23ff1b` played a blocking 6.6 s boot animation in `setup()` | | Upstream `ceb6843` (#6) now draws the animation from `tick()` and only blocks 100 ms in `init()`. The lab image also starts the panel from `tick()`; `sys.hello` answers in the same 220 ms during the animation as after it, and 1.2 s after a reset. | @@ -165,8 +165,43 @@ that both boards switch to OGZ1. 8. Unplug and replug one board: contact and unlock survive; send again. 9. Optional, with a third board in between: relaying, visible as a higher `hops` in `msg.status`. -If `Nicht gesendet` appears after about 2 minutes: check the distance, that both scanned each other's -code, and that both phones run the same APK. +With lab.3, a message without ACK after its retries (about 2 minutes) shows a clock and «Wartet auf +»; the board sends it again when it hears the other board or every 60 s, and only after 30 minutes +does it read «Nicht zugestellt». Then check the distance, that both scanned each other's code, and that +both phones run the same APK. + +## App against lab.3 (2026-10-24, simulator and source only) + +App 0.1.0-lab3 was adapted to the lab image 0.2.0-lab.3 (host contract of 2026-10-24) and the team +stack `feature/mesh-direct` at `c152810`. No board was available for this; everything below was checked +against the firmware source, independent vectors and the simulator, which now follows the contract. + +- **Token wrap:** HKDF salt = session nonce (16 B), info = label || device_id (6 B, byte i = hex pair i of + `device_id`), AES-256-GCM with a 12-byte IV, AAD = device_id, envelope iv || ciphertext || tag (60 B): + identical to `Security::unwrap`. `tools/wrap_vectors.py` computes unlock and reset envelopes with Python + `cryptography` from the firmware side; `TokenWrapFirmwareVectorTest` checks the app against them and that + an unlock envelope never verifies under the reset label. +- **Errors:** `E_UNLOCK_FAILED`, `E_RATE_LIMITED` (after 3 failures, 2 s doubling up to 60 s, checked + before the envelope), `E_NO_SESSION` (every attempt consumes the session) and `E_INTERNAL` end the + connection with their own German text; `sec.state` reasons (`heartbeat_timeout`, `lock`, `error`, + `factory_reset`) are shown on the connect screen while the board is locked. +- **Factory reset:** «Alle Daten löschen» sends `sys.factory_reset {confirm: "ERASE", method: "app"}` with + the token wrapped under `og-reset-wrap-v1`, waits for `{pending: true}` and the restart (`sys.boot` on the + CP2102 UART, else `sys.hello` retries), then provisions the board again. Local data is only deleted after + the board confirmed. Older images that answer `E_BUSY` (button reset) get a message instead. +- **Reflashed board:** an unprovisioned board with a known `device_id` is provisioned again, a backup + transfer token for it is dropped, and contacts it no longer lists become «Neu koppeln». +- **Lost messages (contract item 5):** see the README, "Delivery state survives reconnects". `waiting` + shows «Wartet auf »; after a reconnect the app settles its open messages with `msg.pending` and + `recent`; a message the board no longer knows reads «Nicht zugestellt» with «Erneut senden». +- **Commands checked against `Commands.cpp`:** RSSI is a float in `msg.received` and contact views (the app + read it as an integer and lost fractional values); `E_BUSY` from `msg.send` is an exhausted counter, no + longer a passing state; `contact.rename` and `contact.delete` are not sent for contacts without a slot. + The debug menu's `mock.receive` exists only on the team mock; lab.3 has `lab.inject` instead. + +Still to check on two lab.3 boards: provisioning and unlock from the phone, a wrong phone and the rate +limit, «Alle Daten löschen» with the restart, a reflashed board, «Wartet auf» and its later ✓✓, and a +reconnect while a message is waiting. ## Link-side changes in the app diff --git a/native-android/gradle/libs.versions.toml b/native-android/gradle/libs.versions.toml index fd68ae0..525676b 100644 --- a/native-android/gradle/libs.versions.toml +++ b/native-android/gradle/libs.versions.toml @@ -16,6 +16,7 @@ usbSerial = "3.8.1" bouncycastle = "1.79" splashscreen = "1.0.1" junit = "4.13.2" +sqliteJdbc = "3.41.2.2" [libraries] androidx-core-ktx = { group = "androidx.core", name = "core-ktx", version.ref = "coreKtx" } @@ -44,6 +45,7 @@ zxing-core = { group = "com.google.zxing", name = "core", version.ref = "zxing" usb-serial = { group = "com.github.mik3y", name = "usb-serial-for-android", version.ref = "usbSerial" } bouncycastle = { group = "org.bouncycastle", name = "bcprov-jdk18on", version.ref = "bouncycastle" } junit = { group = "junit", name = "junit", version.ref = "junit" } +sqlite-jdbc = { group = "org.xerial", name = "sqlite-jdbc", version.ref = "sqliteJdbc" } [plugins] android-application = { id = "com.android.application", version.ref = "agp" } diff --git a/native-android/tools/wrap_vectors.py b/native-android/tools/wrap_vectors.py new file mode 100644 index 0000000..4d8688f --- /dev/null +++ b/native-android/tools/wrap_vectors.py @@ -0,0 +1,79 @@ +#!/usr/bin/env python3 +"""Independent test vectors for the unlock and reset token wrap (link spec 6.5 and 6.11). + +Written from the firmware side, `src/security/Security.cpp` on OffGridCH/firmware +`feature/mesh-direct` (c152810), not from the app code: + + info = label || device_id_bytes label "og-unlock-wrap-v1" or "og-reset-wrap-v1" + key = HKDF-SHA256(ikm = X25519(device_eph, app_eph_pub), salt = session nonce (16 B), info, L = 32) + wrapped = iv (12 B) || ciphertext (32 B) || tag (16 B) + token = AES-256-GCM-decrypt(key, iv = wrapped[0:12], aad = device_id_bytes (6 B), + ciphertext = wrapped[12:44], tag = wrapped[44:60]) + +`device_id_bytes` are the 6 bytes of the 12-hex `device_id` from `sys.hello` in string order +(Commands::initSecure prints byte i of the eFuse MAC as hex pair i, App::init passes byte i as +deviceId[i]). The app's JVM test `TokenWrapFirmwareVectorTest` embeds the output. + +Requires `pip install cryptography`. Run: python tools/wrap_vectors.py +""" +import base64 +import hashlib +import hmac + +from cryptography.exceptions import InvalidTag +from cryptography.hazmat.primitives import hashes, serialization +from cryptography.hazmat.primitives.asymmetric.x25519 import X25519PrivateKey, X25519PublicKey +from cryptography.hazmat.primitives.ciphers.aead import AESGCM +from cryptography.hazmat.primitives.kdf.hkdf import HKDF + +RAW = dict(encoding=serialization.Encoding.Raw, format=serialization.PublicFormat.Raw) + +DEVICE_ID_HEX = "A4CF12F00D42" +K_PHONE = hashlib.sha256(b"offgrid-lab3-test-phone").digest() +DEVICE_EPH = X25519PrivateKey.from_private_bytes(hashlib.sha256(b"lab3-device-eph").digest()) +APP_EPH = X25519PrivateKey.from_private_bytes(hashlib.sha256(b"lab3-app-eph").digest()) +NONCE = bytes(range(0xA0, 0xB0)) +IV = bytes(range(0xC0, 0xCC)) + + +def device_unwrap(label, device_id, app_pub, wrapped): + """Security::unwrap, byte for byte.""" + if len(wrapped) != 60: + raise ValueError("wrapped token must be 60 bytes") + shared = DEVICE_EPH.exchange(X25519PublicKey.from_public_bytes(app_pub)) + key = HKDF(hashes.SHA256(), 32, NONCE, label + device_id).derive(shared) + iv, ciphertext, tag = wrapped[:12], wrapped[12:44], wrapped[44:60] + return AESGCM(key).decrypt(iv, ciphertext + tag, device_id) + + +def app_wrap(label, device_id, token): + shared = APP_EPH.exchange(DEVICE_EPH.public_key()) + key = HKDF(hashes.SHA256(), 32, NONCE, label + device_id).derive(shared) + return IV + AESGCM(key).encrypt(IV, token, device_id) + + +def main(): + device_id = bytes.fromhex(DEVICE_ID_HEX) + token = hmac.new(K_PHONE, b"og-unlock-v1" + device_id, hashlib.sha256).digest() + app_pub = APP_EPH.public_key().public_bytes(**RAW) + print("device_id ", DEVICE_ID_HEX) + print("k_phone ", K_PHONE.hex()) + print("token ", token.hex()) + print("device_eph_pub ", base64.b64encode(DEVICE_EPH.public_key().public_bytes(**RAW)).decode()) + print("nonce ", base64.b64encode(NONCE).decode()) + print("app_eph_pub ", base64.b64encode(app_pub).decode()) + for name, label in (("unlock", b"og-unlock-wrap-v1"), ("reset", b"og-reset-wrap-v1")): + wrapped = app_wrap(label, device_id, token) + assert device_unwrap(label, device_id, app_pub, wrapped) == token + print(f"{name:6} wrapped ", base64.b64encode(wrapped).decode()) + # A normal unlock envelope must not authorize a reset, and the other way round (spec 6.11). + unlock = app_wrap(b"og-unlock-wrap-v1", device_id, token) + try: + device_unwrap(b"og-reset-wrap-v1", device_id, app_pub, unlock) + raise SystemExit("unlock envelope accepted as reset") + except InvalidTag: + print("unlock envelope rejected by the reset label: ok") + + +if __name__ == "__main__": + main()