From 68f4ad8b8ae5382d2278e8ffac403b3e0674cdb4 Mon Sep 17 00:00:00 2001 From: arturict Date: Sat, 24 Oct 2026 03:59:00 +0200 Subject: [PATCH 01/17] Token wrap: reset label and firmware vectors TokenWrap takes a WrapPurpose so the factory reset can use the og-reset-wrap-v1 label of link spec 6.11. A new JVM test checks the unlock and reset envelopes against vectors that tools/wrap_vectors.py computes with Python cryptography from Security::unwrap, and checks that an envelope for one purpose or device never verifies for another. --- .../ch/offgrid/android/crypto/UnlockToken.kt | 48 ++++++++--- .../crypto/TokenWrapFirmwareVectorTest.kt | 69 ++++++++++++++++ native-android/tools/wrap_vectors.py | 79 +++++++++++++++++++ 3 files changed, 185 insertions(+), 11 deletions(-) create mode 100644 native-android/app/src/test/java/ch/offgrid/android/crypto/TokenWrapFirmwareVectorTest.kt create mode 100644 native-android/tools/wrap_vectors.py 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/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/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() From 6d2115c5d5f7436992b2fe1700d2b493e35186a2 Mon Sep 17 00:00:00 2001 From: arturict Date: Sat, 24 Oct 2026 04:07:41 +0200 Subject: [PATCH 02/17] Simulator: behave like the lab.3 image The simulated antenna now follows the lab.3 host contract the app is written against: msg_ref starts at a random value per boot, msg.pending lists the queue with its states plus the last 16 final outcomes as recent, and a message without ACK after its retries reports waiting (no_ack), is sent again when its contact is heard or every resend interval, and fails with timeout after the park time. msg.cancel and contact.delete end pending messages as the firmware does, a restart drops queue and recent without events, and sys.factory_reset needs the reset envelope, locks, answers pending and restarts unprovisioned with the same device_id. sys.hello announces lab_radio and the text codec, lab.get and lab.set switch OGZ1, and RSSI values are floats as on the board. Timings are a constructor parameter so tests run fast. --- .../ch/offgrid/android/link/sim/SimState.kt | 2 + .../android/link/sim/SimulatedHeltec.kt | 351 +++++++++++++----- .../android/link/SimulatedHeltecLab3Test.kt | 216 +++++++++++ 3 files changed, 485 insertions(+), 84 deletions(-) create mode 100644 native-android/app/src/test/java/ch/offgrid/android/link/SimulatedHeltecLab3Test.kt 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..fab01b6 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,8 @@ 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", ) @Serializable 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..5c797e8 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,10 +30,35 @@ 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 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) { + 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 @@ -43,6 +71,7 @@ class SimulatedHeltec( private val store: SimFlashStore, private val scope: CoroutineScope, private val clock: () -> Long = System::currentTimeMillis, + private val timing: SimTiming = SimTiming(), ) { private var flash: SimFlash = store.load() ?: SimFlash(deviceId = OgCrypto.hex(OgCrypto.randomBytes(6))) .also(store::save) @@ -55,8 +84,15 @@ class SimulatedHeltec( 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 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 @@ -109,7 +145,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 +161,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 +189,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,20 +226,34 @@ 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) } } + "radio.stats" -> { requireUnlocked(); buildJsonObject { put("tx_packets", txPackets); put("rx_packets", 0) } } + "lab.get" -> { requireUnlocked(); labJson() } + "lab.set" -> { + requireUnlocked() + 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") + } + save(flash.copy(textCodec = codec)) + labJson() + } "mesh.get" -> buildJsonObject { put("hop_default", 3); put("relay_enabled", true); put("relay_when_locked", false) put("cad_enabled", true); put("retries", 3) @@ -214,6 +269,7 @@ class SimulatedHeltec( private fun afterResponse(r: Request) { when (r.cmd) { "sys.reboot" -> reboot("software") + "sys.factory_reset" -> if (resetAuthorized) eraseAndRestart() } } @@ -224,15 +280,47 @@ class SimulatedHeltec( 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 + 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) @@ -241,6 +329,7 @@ class SimulatedHeltec( 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) + 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,6 +337,7 @@ 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_text_input_bytes", maxTextInputBytes()) } } } @@ -257,25 +347,48 @@ class SimulatedHeltec( put("heap_free", 172304); put("battery_mv", JsonNull) putJsonObject("radio") { put("running", state == "unlocked"); put("relay_only", false) } if (state == "unlocked") { - putJsonObject("queue") { put("pending", pendingJobs.size); put("capacity", 8) } + putJsonObject("queue") { put("pending", pending.size); put("capacity", 8) } putJsonObject("contacts") { put("used", flash.contacts.size); put("capacity", 32) } } 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))) @@ -298,18 +411,7 @@ 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() @@ -339,6 +441,7 @@ class SimulatedHeltec( 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) }) @@ -440,7 +543,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 +559,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 item 3: with ogz1 up to 160 bytes are accepted when the compressed body fits. + val max = maxTextInputBytes() + val onAir = MessageLimits.onAirTextBytes(text, flash.textCodec, 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 +581,129 @@ 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 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) } } - 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?): SimPending { + val p = SimPending(nextRef++, to, type, ctr, clock()) + pending[p.ref] = p + return p + } + + private fun statusData(p: SimPending, reason: String?, extra: JsonObjectBuilder.() -> Unit = {}) = buildJsonObject { + put("msg_ref", p.ref); put("to", p.to); put("state", p.state); put("retry", p.retry) + if (reason != null) put("reason", reason) + extra() + } + + /** 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" || state == "retrying") txPackets++ + 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); put("to", p.to); put("type", p.type); put("ctr", p.ctr) + put("state", p.state); put("retry", p.retry) + }) + } + } + putJsonArray("recent") { + recent.forEach { r -> + add(buildJsonObject { put("msg_ref", r.ref); put("state", r.state); if (r.reason != null) put("reason", r.reason) }) + } + } + } - 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) } + /** + * 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 (!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 && peer.inRange) 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 (!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++ } + 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 || !peer.inRange || !peer.scansBack || state != "unlocked") return false + finish(p, "delivered", null) { put("hops", 1); put("rtt_ms", 842) } + activate(p.to, peer) + peer } + reactTo(peer, p.to, args, p.type) + return true } /** Virtual peers answer questions and share their position back. */ @@ -557,9 +738,11 @@ class SimulatedHeltec( 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) + put("ctr", ctr); put("hops", 1); 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. */ @@ -584,13 +767,7 @@ class SimulatedHeltec( } 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 @@ -645,12 +822,12 @@ class SimulatedHeltec( 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 { + val p = enqueue(0, "text", null) + p.job = scope.launch { delay(400) synchronized(lock) { - status(ref, 0, "sent", 0) { put("group", gid) } - pendingJobs.remove(ref) + txPackets++ + finish(p, "sent", null) { put("group", gid) } } if (text.contains('?')) { val replier = synchronized(lock) { @@ -666,7 +843,7 @@ class SimulatedHeltec( } } } - return buildJsonObject { put("msg_ref", ref); put("ack_requested", false); put("state", "queued") } + return buildJsonObject { put("msg_ref", p.ref); put("ack_requested", false); put("state", "queued") } } // ---------------------------------------------------------------- test harness API (not part of the protocol) @@ -701,14 +878,14 @@ class SimulatedHeltec( 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 maxTextInputBytes(): Int = + if (flash.textCodec == 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()) } private fun emitLater(name: String, data: JsonObject) { @@ -724,7 +901,13 @@ class SimulatedHeltec( } companion object { - const val FW_VERSION = "0.1.0-sim" + /** Behaves like the lab image 0.2.0-lab.3 (lab contract of 2026-10-24). */ + const val FW_VERSION = "0.2.0-lab.3-sim" const val PROTO = "1.0" + 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/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..944ef5c --- /dev/null +++ b/native-android/app/src/test/java/ch/offgrid/android/link/SimulatedHeltecLab3Test.kt @@ -0,0 +1,216 @@ +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.buildJsonObject +import kotlinx.serialization.json.put +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.2.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) + c.close() + } +} From d18cd94fa14b2a9863dcc97ee31d680357145511 Mon Sep 17 00:00:00 2001 From: arturict Date: Sat, 24 Oct 2026 04:12:39 +0200 Subject: [PATCH 03/17] Reconcile the outbox with msg.pending on every connect Messages could stay at gesendet for good: msg.status events are lost while the phone is not connected, and a restart of the antenna cleared the refs of sent messages so nothing could settle them later. Every message the antenna accepts now records the link session its msg_ref was confirmed in (messages.refSession, Room migration 1 to 2). msg.status events only update messages of the current session. After the antenna is ready and the contacts are synced, messages of earlier sessions are settled against msg.pending: still queued takes over the antenna state and the new session, an entry in recent applies its final state, and anything else fails with reason lost. Final states drop ref and session, so a ref from an earlier boot can never reach a newer message. Open states only move forward. The app does not resend on its own; the user can retry. The lab image's waiting state is a new status: a clock and Wartet auf instead of a check mark, until delivered or failed. Failures after the antenna had the message read Nicht zugestellt, refusals by the antenna keep Nicht gesendet. The migration marks version 1 direct messages that lost their ref at gesendet as lost. --- .../2.json | 387 ++++++++++++++++++ .../java/ch/offgrid/android/AppContainer.kt | 5 +- .../main/java/ch/offgrid/android/data/Daos.kt | 18 +- .../java/ch/offgrid/android/data/Entities.kt | 21 +- .../ch/offgrid/android/data/Migrations.kt | 22 + .../ch/offgrid/android/domain/Messaging.kt | 82 +++- .../android/domain/OutboxReconciler.kt | 127 ++++++ .../android/ui/components/ChatComponents.kt | 17 +- .../offgrid/android/ui/components/OgIcons.kt | 1 + .../offgrid/android/ui/screens/ChatScreen.kt | 20 +- .../android/domain/OutboxReconcilerTest.kt | 148 +++++++ 11 files changed, 805 insertions(+), 43 deletions(-) create mode 100644 native-android/app/schemas/ch.offgrid.android.data.OffGridDatabase/2.json create mode 100644 native-android/app/src/main/java/ch/offgrid/android/data/Migrations.kt create mode 100644 native-android/app/src/main/java/ch/offgrid/android/domain/OutboxReconciler.kt create mode 100644 native-android/app/src/test/java/ch/offgrid/android/domain/OutboxReconcilerTest.kt 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/src/main/java/ch/offgrid/android/AppContainer.kt b/native-android/app/src/main/java/ch/offgrid/android/AppContainer.kt index 8a8edae..1a60627 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,7 @@ 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.OffGridDatabase import ch.offgrid.android.domain.AntennaManager import ch.offgrid.android.domain.BackupService @@ -37,7 +38,9 @@ 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) + .build() val settings = Settings(db.settings(), scope) val simDevice = SimulatedHeltec(SimFlashStore(File(context.filesDir, "sim-heltec.json")), scope) 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..2816d96 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,13 +107,6 @@ 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) @@ -210,7 +208,7 @@ interface MaintenanceDao { @Database( entities = [ContactEntity::class, MessageEntity::class, GroupEntity::class, GroupMemberEntity::class, SettingEntity::class], - version = 1, + version = 2, 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..3639aa6 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 @@ -45,8 +45,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,8 +79,16 @@ 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. */ 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..53532bf --- /dev/null +++ b/native-android/app/src/main/java/ch/offgrid/android/data/Migrations.kt @@ -0,0 +1,22 @@ +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)", + ) + } +} 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..4be155b 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 @@ -58,8 +58,15 @@ class Messaging( 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(), @@ -118,7 +125,8 @@ class Messaging( 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)) flushQueue() } } @@ -134,26 +142,31 @@ class Messaging( } } - /** 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 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")) 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), + ) + } true } catch (e: LinkCommandException) { when (e.error.code) { @@ -259,12 +272,40 @@ class Messaging( override suspend fun onReady(antenna: AntennaManager, deviceId: String) { currentDevice = deviceId syncContacts(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) } + } + } + + /** 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) } + currentSession = session } /** @@ -333,19 +374,16 @@ 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 + val m = db.messages().byMsgRef(ref, session) ?: return + OutboxReconciler.applyEvent(m, state, d.str("reason"))?.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())) } } } 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..e8996f3 --- /dev/null +++ b/native-android/app/src/main/java/ch/offgrid/android/domain/OutboxReconciler.kt @@ -0,0 +1,127 @@ +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) + +/** + * 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")) + } + 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; + * - 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. + */ + fun applyEvent(m: MessageEntity, state: String, reason: String?): 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 finished(m, status, state, reason) + if (rank(status) <= rank(m.status)) return null + return m.copy(status = status, failReason = null) + } + + 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, + 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) ?: m + if (next.msgRef == null) next else next.copy(refSession = session) + } + done != null -> statusFor(done.state)?.let { finished(m, it, done.state, done.reason) } ?: 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/ui/components/ChatComponents.kt b/native-android/app/src/main/java/ch/offgrid/android/ui/components/ChatComponents.kt index 7e50317..9aa9d77 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) + } } } } 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/ChatScreen.kt b/native-android/app/src/main/java/ch/offgrid/android/ui/screens/ChatScreen.kt index 4ab79e7..8f6462f 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 @@ -119,7 +119,7 @@ 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, @@ -231,18 +231,30 @@ 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", "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.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 (reason != null && (reason.startsWith("E_") || reason == "no_contact")) "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 +270,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, 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..98c46d5 --- /dev/null +++ b/native-android/app/src/test/java/ch/offgrid/android/domain/OutboxReconcilerTest.kt @@ -0,0 +1,148 @@ +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 }) + } + + @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) + 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)), 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()) + } +} From f3b380ce2ca7e9106475fdd61b2291176a7c8be6 Mon Sep 17 00:00:00 2001 From: arturict Date: Sat, 24 Oct 2026 04:19:26 +0200 Subject: [PATCH 04/17] Real security: unlock errors, authenticated reset, reflashed antennas MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Unlock and provisioning now follow Security.cpp: every attempt uses a fresh sys.hello session, a state that changed in between gets one more try, E_ALREADY_UNLOCKED counts as open, and E_UNLOCK_FAILED, E_RATE_LIMITED, E_NO_SESSION and E_INTERNAL end the session with their own German text instead of Die Antenne antwortet nicht. Other codes are shown with the code. The reason of a sec.state lock is kept for the connect screen, and a failed re-unlock after an auto-lock now ends the session with its reason instead of leaving a locked antenna marked ready. Alle Daten löschen erases a connected antenna with sys.factory_reset (method app, token wrapped with og-reset-wrap-v1, the transfer token from a backup as fallback). Local data is only deleted once the antenna confirmed; a refusal keeps everything and says why. After the restart the app provisions the empty antenna again for this phone. Without an antenna only the phone is cleared, and the dialog says so. A known antenna that reports unprovisioned (reflashed or reset) is set up again; a backup transfer token for it is dropped because it can never open the new vault (the token itself is derived, not stored). Contacts it no longer lists become unpaired: Neu koppeln in the list and the chat, a banner with the number on the contact list, and no sending until they are paired again. --- .../java/ch/offgrid/android/AppContainer.kt | 2 +- .../offgrid/android/domain/AntennaManager.kt | 296 +++++++++++++++--- .../ch/offgrid/android/domain/Messaging.kt | 52 ++- .../ch/offgrid/android/domain/Settings.kt | 3 + .../offgrid/android/ui/screens/ChatScreen.kt | 8 + .../ch/offgrid/android/ui/screens/Common.kt | 26 +- .../android/ui/screens/ConnectScreen.kt | 3 +- .../android/ui/screens/ContactsScreen.kt | 22 +- .../android/ui/screens/SettingsScreen.kt | 31 +- .../android/domain/AntennaSecurityTest.kt | 166 ++++++++++ 10 files changed, 529 insertions(+), 80 deletions(-) create mode 100644 native-android/app/src/test/java/ch/offgrid/android/domain/AntennaSecurityTest.kt 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 1a60627..aeb89eb 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 @@ -69,7 +69,7 @@ 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) 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..802c674 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,14 +32,32 @@ 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.JsonObject import kotlinx.serialization.json.buildJsonObject 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 } +/** 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, + + /** Any other error code; [AntennaState.errorCode] has it. */ + REJECTED, +} data class AntennaState( val phase: AntennaPhase = AntennaPhase.DISCONNECTED, @@ -53,11 +73,18 @@ data class AntennaState( /** 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, 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, ) { val ready: Boolean get() = phase == AntennaPhase.READY 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,6 +92,9 @@ 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. @@ -85,6 +115,10 @@ class AntennaManager( private var client: LinkClient? = null private val unlockMutex = Mutex() + /** 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 val previous = sessionJob @@ -98,7 +132,7 @@ class AntennaManager( 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) } } /** Sends a command on the open link. Throws [LinkClosedException] when the antenna is not ready. */ @@ -132,43 +166,59 @@ 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) + 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}") + fail(e.error, e.code) } 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 radio and identity, + * 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('-') + _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) + } + unlock(c, hello) + 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, errorCode = null, lockReason = null) + } + listener.onReady(this, deviceId) + } + + private fun fail(error: AntennaError?, code: String? = 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) + } } /** Link spec 3.3: commands sent during boot are lost, so retry `sys.hello` every 500 ms. */ @@ -197,34 +247,73 @@ 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 6.5 to 6.10). 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 6.10). + */ + 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 + c.call("sec.unlock", wrapArgs(hello, tokenSource.token(deviceBytes), deviceBytes)) + 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)) + c.call("sec.unlock", wrapArgs(c.call("sys.hello", HELLO_ARGS), transfer, deviceBytes)) c.call("sec.rotate_token", wrapArgs(c.call("sys.hello", HELLO_ARGS), tokenSource.token(deviceBytes), deviceBytes)) + clearTransferToken() + } + + /** + * 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) + c.call("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 +334,20 @@ class AntennaManager( } } - private fun wrapArgs(hello: JsonObject, token: ByteArray, deviceId: ByteArray, name: String? = null): JsonObject { + 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,25 +359,112 @@ 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 6.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 { + c.call("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, 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) { + fail(e.error, e.code) + } 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. + listener.onDeviceRebooted() + relock() + } + } + "sec.state" -> if (event.data.str("state") == "locked") { + _state.update { it.copy(lockReason = event.data.str("reason")) } + if (reset == null && state.value.ready) relock() } - "sec.state" -> if (event.data.str("state") == "locked" && state.value.ready) relock() else -> listener.onEvent(event) } } + /** Opens the vault again after an auto-lock or restart; ends the session with the reason when that fails. */ private suspend fun relock() { val c = client ?: 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}") + bringUp(c, c.call("sys.hello", HELLO_ARGS)) + } catch (e: UnlockFailure) { + log("re-unlock failed: ${e.code}") + fail(e.error, e.code) + } 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 } } @@ -290,6 +473,17 @@ class AntennaManager( // 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 + const val RESET_BOOT_TIMEOUT_MS = 15_000L val HELLO_ARGS = buildJsonObject { put("app", "offgrid-android"); put("app_proto", "1.0") } + val RETRY_WITH_NEW_HELLO = setOf("E_NO_SESSION", "E_NOT_PROVISIONED", "E_ALREADY_PROVISIONED") + + 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/Messaging.kt b/native-android/app/src/main/java/ch/offgrid/android/domain/Messaging.kt index 4be155b..f34711f 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 @@ -53,6 +53,7 @@ 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, @@ -89,9 +90,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 }, ) } @@ -188,7 +196,8 @@ class Messaging( val g = db.groups().all().firstOrNull { it.id == m.groupId } ?: return null return buildJsonObject { put("group_id", g.deviceGroupId); 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) @@ -240,16 +249,19 @@ class Messaging( } /** - * "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`. */ @@ -310,9 +322,9 @@ class Messaging( /** * 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 @@ -329,9 +341,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. */ @@ -426,6 +441,9 @@ class Messaging( /** Slot of a contact the device no longer holds (device slots are 1 to 32). */ const val NO_SLOT = 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/Settings.kt b/native-android/app/src/main/java/ch/offgrid/android/domain/Settings.kt index 0509482..8251813 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 @@ -33,6 +33,9 @@ class Settings(private val dao: SettingDao, scope: CoroutineScope) { 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/ui/screens/ChatScreen.kt b/native-android/app/src/main/java/ch/offgrid/android/ui/screens/ChatScreen.kt index 8f6462f..e6bb9d9 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 @@ -53,6 +53,7 @@ import ch.offgrid.android.domain.Formats import ch.offgrid.android.domain.Geo import ch.offgrid.android.domain.GeoFix import ch.offgrid.android.domain.MessageLimits +import ch.offgrid.android.domain.Messaging import ch.offgrid.android.domain.REACTIONS import ch.offgrid.android.ui.LocalApp import ch.offgrid.android.ui.Routes @@ -110,6 +111,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") { 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..d83fe59 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 @@ -21,6 +21,7 @@ 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 @@ -50,7 +51,8 @@ fun rememberNow(): Long { fun patternFor(fingerprint: String): BooleanArray = KeyPattern.fromSeed(KeyPattern.contactSeed(fingerprint)) /** Texts from the screen spec table "Fehlertexte". */ -fun AntennaError.text(): String = when (this) { +/** [code] is the link error code behind [AntennaError.REJECTED]. */ +fun AntennaError.text(code: 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." @@ -58,6 +60,28 @@ fun AntennaError.text(): String = when (this) { AntennaError.PROTO_MISMATCH -> "Die Firmware der Antenne passt nicht zu dieser App-Version." AntennaError.LOST -> "Verbindung zur Antenne verloren." 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 wartet bis zu einer Minute, bevor sie es wieder zulässt." + 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. Steck sie neu ein. Hilft das nicht, muss sie zurückgesetzt werden." + AntennaError.REJECTED -> "Die Antenne hat die Verbindung abgelehnt" + (code?.let { " ($it)." } ?: ".") +} + +/** Why the antenna locked itself (`sec.state` reason), for the connect screen while it is not open again. */ +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." + else -> "Die Antenne ist gesperrt." +} + +/** 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. Warte eine Minute und 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) { 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..b1a4935 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 @@ -125,7 +125,8 @@ fun ConnectScreen(onNext: (onboardingDone: Boolean) -> Unit) { ), ), ) - state.error?.let { OgNote(it.text()) } + state.lockReason?.takeIf { !state.ready }?.let { OgNote(lockReasonText(it)) } + state.error?.let { OgNote(it.text(state.errorCode)) } 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..3349a9f 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 @@ -43,6 +43,7 @@ import ch.offgrid.android.data.MessageEntity 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 +52,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 +60,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) @@ -106,6 +109,15 @@ fun ContactsScreen(nav: NavHostController) { } } AntennaStatusLine(antenna.ready, antenna.kind, antenna.freqMhz) { 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) { @@ -164,6 +176,8 @@ fun AntennaStatusLine(ready: Boolean, kind: LinkKind, freqMhz: Double?, onClick: 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 +187,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 +195,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/SettingsScreen.kt b/native-android/app/src/main/java/ch/offgrid/android/ui/screens/SettingsScreen.kt index af1edd5..5e45e41 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 @@ -62,6 +62,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 +93,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 ?: "") @@ -199,8 +202,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 +222,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)) } }, 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..d7e18e5 --- /dev/null +++ b/native-android/app/src/test/java/ch/offgrid/android/domain/AntennaSecurityTest.kt @@ -0,0 +1,166 @@ +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.runBlocking +import kotlinx.coroutines.withTimeout +import kotlinx.serialization.json.buildJsonObject +import kotlinx.serialization.json.put +import org.junit.After +import org.junit.Assert.assertEquals +import org.junit.Assert.assertNotEquals +import org.junit.Assert.assertNull +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 autoLockIsReopenedAndTheReasonCleared() = 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) + } + + @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 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 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 } + } +} From d30c36ed8fd226d68aab83b605a0fd0b09ecd54a Mon Sep 17 00:00:00 2001 From: arturict Date: Sat, 24 Oct 2026 04:22:01 +0200 Subject: [PATCH 05/17] Match the commands to Commands.cpp Checked every command the app sends against Commands.cpp on feature/mesh-direct and fixed what differed: - RSSI is a float in msg.received and contact views; the app read it as an integer and dropped every fractional value. It is now rounded. - E_BUSY from msg.send means the counter is exhausted (re-pair), not a passing state; it no longer blocks the local queue forever. - contact.rename and contact.delete are not sent for contacts without a slot (contact_id must be 1 to 32). - A final msg.status frees a queue slot, so messages that met E_QUEUE_FULL are handed over then instead of at the next connect. The hardware test accepts the lab.3 waiting state and checks msg.pending, msg.cancel and recent there. --- .../ch/offgrid/android/domain/Messaging.kt | 24 ++++++++++++----- .../java/ch/offgrid/android/link/LinkCodec.kt | 6 +++++ .../ch/offgrid/android/link/LinkCodecTest.kt | 12 +++++++++ .../android/link/hw/RealAntennaTest.kt | 26 ++++++++++++++----- 4 files changed, 54 insertions(+), 14 deletions(-) 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 f34711f..4a6dbbd 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 @@ -11,6 +11,7 @@ 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.dbm import ch.offgrid.android.link.double import ch.offgrid.android.link.int import ch.offgrid.android.link.isNull @@ -178,7 +179,10 @@ class Messaging( 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 @@ -234,15 +238,19 @@ 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) @@ -365,7 +373,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) } @@ -400,11 +408,13 @@ class Messaging( 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) } } 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/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/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") From 5628a36bbdae94a17365a69fd46fd6016302f003 Mon Sep 17 00:00:00 2001 From: arturict Date: Sat, 24 Oct 2026 04:25:47 +0200 Subject: [PATCH 06/17] Version 0.1.0-lab3 and the lab.3 notes versionCode 2 (database version 2), versionName 0.1.0-lab3. README, STATUS and docs/hardware.md describe the security handling, the factory reset, reflashed antennas, the reconnect reconciliation and the command fixes, how the lab test APK is built, and that all of it was checked against firmware source, vectors and the simulator, not on a board. --- native-android/README.md | 57 ++++++++++++++++++++++------- native-android/STATUS.md | 9 +++++ native-android/app/build.gradle.kts | 5 ++- native-android/docs/hardware.md | 41 +++++++++++++++++++-- 4 files changed, 94 insertions(+), 18 deletions(-) diff --git a/native-android/README.md b/native-android/README.md index a4e00f2..54ad24d 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` @@ -31,6 +32,10 @@ POSTHOG_KEY=phc_... | 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. | +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 1. Enable USB debugging on the phone (Settings, About phone, tap "Build number" seven times, @@ -47,9 +52,13 @@ 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 @@ -150,7 +159,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 +204,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 +213,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, a release signing key, 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..28dde68 100644 --- a/native-android/STATUS.md +++ b/native-android/STATUS.md @@ -10,6 +10,15 @@ Install with `adb install -r `; details in the [README](README.md). Everyth 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, diff --git a/native-android/app/build.gradle.kts b/native-android/app/build.gradle.kts index d17d1e6..fb69d8c 100644 --- a/native-android/app/build.gradle.kts +++ b/native-android/app/build.gradle.kts @@ -16,8 +16,9 @@ android { applicationId = "ch.offgrid.android" minSdk = 26 targetSdk = 35 - versionCode = 1 - versionName = "0.1.0" + // 2: database version 2 (messages.refSession) and the lab.3 security and delivery handling. + versionCode = 2 + versionName = "0.1.0-lab3" // 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. 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 From 91f39d6e2878ba5fd7a9a7c2133cd6653c4ed10a Mon Sep 17 00:00:00 2001 From: arturict Date: Sat, 24 Oct 2026 06:37:30 +0200 Subject: [PATCH 07/17] Simulator: Nils' 0.3.0 serial API and the lab.3 extras The simulated antenna now follows the link spec of firmware 0.3.0 (feature/firmware-hardening) and, with labRadio (default), the lab image 0.3.0-lab.3 on top: - sys.hello and sys.boot report mock:false, recovery and storage fields; sys.status has radio, storage and security in every state; sec.provision, sec.unlock and sec.rotate_token return the spec shapes. - mesh.get in every state, mesh.set (hop_default, relay_enabled, relay_when_locked, retries, cad_enabled) persisted and validated; msg.send uses hop_default. - radio.stats with the spec counters, the lab extras (resends, locked buffer) and reset. - Lab: pair.begin keeps one salt per 5-minute window, lab.get/lab.set with fw and ignore_nodes (up to 8 NodeIDs, persisted; an ignored peer is out of reach, there are no relays to simulate), compressed in msg.send and msg.received. - Team mode (labRadio = false): a new salt on every pair.begin and completion ends the session, failed timeout after the retries, no recent, lab.* answers E_UNKNOWN_CMD. OGZ1 counting follows the lab image: texts that fit 83 bytes raw stay raw so team boards can read them, only longer ones are compressed. --- .../java/ch/offgrid/android/domain/Limits.kt | 13 +- .../ch/offgrid/android/link/sim/SimState.kt | 8 + .../android/link/sim/SimulatedHeltec.kt | 262 ++++++++++++++---- .../android/domain/MessageLimitsTest.kt | 7 + .../android/link/SimulatedHeltecLab3Test.kt | 85 +++++- .../android/link/SimulatedHeltecTeamTest.kt | 97 +++++++ 6 files changed, 412 insertions(+), 60 deletions(-) create mode 100644 native-android/app/src/test/java/ch/offgrid/android/link/SimulatedHeltecTeamTest.kt 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..2991bc2 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,15 +26,16 @@ 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. */ 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 fab01b6..773c381 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 @@ -24,6 +24,14 @@ data class SimFlash( 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 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 5c797e8..4773e9a 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 @@ -64,14 +64,20 @@ private data class SimRecent(val ref: Int, val state: String, val reason: String * 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) @@ -89,6 +95,10 @@ class SimulatedHeltec( private val pending = LinkedHashMap() private val recent = ArrayDeque() private var txPackets = 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. */ @@ -125,6 +135,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) { @@ -243,21 +254,11 @@ class SimulatedHeltec( "msg.pending" -> { requireUnlocked(); pendingJson() } "radio.get" -> radioJson() "radio.set" -> { requireUnlocked(); radioSet(a) } - "radio.stats" -> { requireUnlocked(); buildJsonObject { put("tx_packets", txPackets); put("rx_packets", 0) } } - "lab.get" -> { requireUnlocked(); labJson() } - "lab.set" -> { - requireUnlocked() - 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") - } - save(flash.copy(textCodec = codec)) - labJson() - } - "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.send" -> groupSend(a) @@ -275,9 +276,11 @@ class SimulatedHeltec( // ---------------------------------------------------------------- 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`. */ @@ -327,9 +330,12 @@ class SimulatedHeltec( 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) - put("lab_radio", true); put("text_codec", flash.textCodec) + putJsonObject("fw") { put("version", fwVersion); put("build", "simulator") } + put("proto", PROTO); put("state", state); put("mock", mockImage); put("radio_diagnostics", false) + 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)) @@ -337,20 +343,29 @@ 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_text_input_bytes", maxTextInputBytes()) + 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", pending.size); put("capacity", 8) } putJsonObject("contacts") { put("used", flash.contacts.size); put("capacity", 32) } + 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). */ @@ -403,7 +418,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 { @@ -416,10 +437,7 @@ class SimulatedHeltec( 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() { @@ -435,7 +453,7 @@ 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) { @@ -447,6 +465,11 @@ class SimulatedHeltec( 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") @@ -471,14 +494,30 @@ 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. 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") @@ -499,6 +538,8 @@ class SimulatedHeltec( fingerprint = OgCrypto.fingerprint(publicKey(), peerPub), ) save(flash.copy(contacts = flash.contacts.filter { it.contactId != id } + contact)) + // Team firmware: success ends the pairing session. The lab image keeps the salt for its window. + if (!labRadio) pairing = null 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. @@ -559,9 +600,9 @@ 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") - // Lab.3 item 3: with ogz1 up to 160 bytes are accepted when the compressed body fits. + // 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, flash.textCodec, max) + 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") } @@ -583,7 +624,8 @@ class SimulatedHeltec( } 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 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) @@ -592,6 +634,7 @@ class SimulatedHeltec( return buildJsonObject { 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) } } @@ -611,7 +654,11 @@ class SimulatedHeltec( private fun progress(p: SimPending, state: String, reason: String? = null): Boolean { if (pending[p.ref] !== p) return false p.state = state - if (state == "sent" || state == "retrying") txPackets++ + if (state == "sent") txPackets++ + if (state == "retrying") { + txPackets++ + retriesScheduled++ + } emitEvent("msg.status", statusData(p, reason)) return true } @@ -646,9 +693,11 @@ class SimulatedHeltec( }) } } - putJsonArray("recent") { - recent.forEach { r -> - add(buildJsonObject { put("msg_ref", r.ref); put("state", r.state); if (r.reason != null) put("reason", r.reason) }) + 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) }) + } } } } @@ -666,7 +715,7 @@ class SimulatedHeltec( finish(p, "sent", null) peerFor(p.to) } - if (peer != null && peer.inRange) reactTo(peer, p.to, args, p.type) + if (peer != null && reachable(peer)) reactTo(peer, p.to, args, p.type) return } for (retry in 0..timing.retries) { @@ -680,6 +729,11 @@ class SimulatedHeltec( 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() @@ -688,7 +742,12 @@ class SimulatedHeltec( return } withTimeoutOrNull(minOf(timing.resendMs, left)) { p.wake.receive() } - synchronized(lock) { if (pending[p.ref] === p) txPackets++ } + synchronized(lock) { + if (pending[p.ref] === p) { + txPackets++ + resends++ + } + } if (tryDeliver(p, args)) return } } @@ -697,8 +756,10 @@ class SimulatedHeltec( 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 || !peer.inRange || !peer.scansBack || state != "unlocked") return false - finish(p, "delivered", null) { put("hops", 1); put("rtt_ms", 842) } + 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 } @@ -730,15 +791,17 @@ 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 + 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.toDouble()); 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. @@ -761,6 +824,10 @@ 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 } @@ -772,6 +839,77 @@ class SimulatedHeltec( // ---------------------------------------------------------------- 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) @@ -831,7 +969,7 @@ class SimulatedHeltec( } if (text.contains('?')) { val replier = synchronized(lock) { - group.members.firstNotNullOfOrNull { id -> peerFor(id)?.takeIf { it.inRange }?.let { id to it } } + group.members.firstNotNullOfOrNull { id -> peerFor(id)?.takeIf { reachable(it) }?.let { id to it } } } if (replier != null) { delay(3_000) @@ -848,6 +986,14 @@ class SimulatedHeltec( // ---------------------------------------------------------------- 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, @@ -881,11 +1027,15 @@ class SimulatedHeltec( /** 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 (flash.textCodec == MessageLimits.CODEC_OGZ1) OGZ1_MAX_TEXT_INPUT_BYTES else MessageLimits.DEFAULT_MAX_TEXT_BYTES + 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) { @@ -901,8 +1051,14 @@ class SimulatedHeltec( } companion object { - /** Behaves like the lab image 0.2.0-lab.3 (lab contract of 2026-10-24). */ - const val FW_VERSION = "0.2.0-lab.3-sim" + /** 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.0" private const val RECENT_CAPACITY = 16 private const val OGZ1_MAX_TEXT_INPUT_BYTES = 160 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..fbe4b1e 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")) 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 index 944ef5c..c720394 100644 --- 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 @@ -17,8 +17,10 @@ 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 @@ -89,7 +91,7 @@ class SimulatedHeltecLab3Test { val h = c.call("sys.hello", hello) assertEquals(true, h.bool("lab_radio")) assertEquals("raw", h.str("text_codec")) - assertEquals("0.2.0-lab.3-sim", h.obj("fw")!!.str("version")) + 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)) @@ -211,6 +213,87 @@ class SimulatedHeltecLab3Test { 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) + val qr = device.addVirtualPeer("Anna", -80) + c.call("pair.complete", buildJsonObject { put("qr", qr) }) + // The lab image keeps the salt after a completion; cancel wipes it. + assertEquals(first.str("qr"), c.call("pair.begin").str("qr")) + c.call("pair.cancel") + assertNotEquals(first.str("qr"), c.call("pair.begin").str("qr")) + 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() + } +} From e6800144db719e83c6ef7b8481b5ce0b7bc91fec Mon Sep 17 00:00:00 2001 From: arturict Date: Sat, 24 Oct 2026 06:37:40 +0200 Subject: [PATCH 08/17] Setup and unlock: every device state, rate-limit countdown, 1 s heartbeat Checked against the state machine, error codes and app checklist of the 0.3.0 link spec: - sys.hello with mock:true is refused (old image without real authentication). - The connect screen says what the session does: antenna starting, new antenna being set up (unprovisioned), unlocking, unlocking again after an auto-lock or restart, factory reset. The contact list status line shows locked, connecting and error states instead of only verbunden/getrennt. - E_RATE_LIMITED has no remaining time, so the app estimates it from its own failures like Security::failure (2 s from the third, doubling to 60 s), shows a countdown and tries once more when it ends. - sys.ping every second as the spec asks (was 5 s); three unanswered pings while open end the session as "antwortet nicht mehr". - An E_LOCKED answer while the app thinks the antenna is open (lost sec.state) opens it again; one relock at a time, skipped when a fresh hello says it is still open. A restart seen through sys.boot and every lock are kept as lastLock with reason and time. - After unlocking the app reads sys.status (radio running and last error, vault status, secure boot), mesh.get, sec.get_policy and on lab images lab.get. An unlocked antenna whose radio does not run is shown as "Funkmodul nicht bereit"; E_INTERNAL during unlock names the vault_status. - Commands that write NVS or the vault get the 5 s timeout. --- .../offgrid/android/domain/AntennaManager.kt | 347 +++++++++++++++--- .../ch/offgrid/android/domain/DeviceInfo.kt | 125 +++++++ .../ch/offgrid/android/link/LinkClient.kt | 8 +- .../ch/offgrid/android/ui/screens/Common.kt | 62 +++- .../android/ui/screens/ConnectScreen.kt | 15 +- .../android/ui/screens/ContactsScreen.kt | 30 +- .../android/domain/AntennaSecurityTest.kt | 133 ++++++- 7 files changed, 656 insertions(+), 64 deletions(-) create mode 100644 native-android/app/src/main/java/ch/offgrid/android/domain/DeviceInfo.kt 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 802c674..8c7577c 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 @@ -39,6 +39,24 @@ import kotlinx.serialization.json.put enum class AntennaPhase { DISCONNECTED, SEARCHING, DEVICE_FOUND, CONNECTING, READY, ERROR } +/** 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, @@ -55,18 +73,30 @@ enum class AntennaError { /** `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) + 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, @@ -77,8 +107,40 @@ data class AntennaState( 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, + 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 every successful unlock or provisioning; a change means the antenna's RAM state (pairing salt, refs) is new. */ + 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 } @@ -96,8 +158,27 @@ interface AntennaListener { 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, @@ -105,6 +186,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() @@ -112,8 +194,15 @@ 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 @@ -121,6 +210,7 @@ class AntennaManager( fun connect() { if (state.value.busy || state.value.ready) return + retryJob?.cancel() val previous = sessionJob sessionJob = scope.launch { previous?.cancelAndJoin() @@ -129,22 +219,33 @@ class AntennaManager( } fun disconnect() { + retryJob?.cancel() sessionJob?.cancel() client?.close() client = null - _state.update { it.copy(phase = AntennaPhase.DISCONNECTED, error = null, errorCode = 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 { @@ -158,7 +259,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) } @@ -167,6 +268,8 @@ class AntennaManager( val proto = hello.str("proto") ?: "0.0" if (proto.substringBefore('.') != PROTO_MAJOR) return fail(AntennaError.PROTO_MISMATCH) 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() @@ -175,7 +278,7 @@ class AntennaManager( if (state.value.phase != AntennaPhase.ERROR) fail(if (cause != null) AntennaError.LOST else null) } catch (e: UnlockFailure) { log("unlock failed: ${e.code}") - fail(e.error, e.code) + failUnlock(c, e) } catch (_: LinkTimeoutException) { fail(AntennaError.NO_INFO) } catch (_: LinkClosedException) { @@ -189,35 +292,95 @@ class AntennaManager( } /** - * From a `sys.hello` answer to "ready": open the vault, apply the text codec, read radio and identity, - * then tell the listener. Used on connect, after an auto-lock or restart, and after a factory reset. + * 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, 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) + 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 (hello.bool("lab_radio") == true) selectTextCodec(c) + 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, freqMhz = radio.double("freq_mhz"), nodeId = identity.str("node_id"), - error = null, errorCode = null, lockReason = null) + 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"), + 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 = it.unlockCount + 1) } listener.onReady(this, deviceId) } - private fun fail(error: AntennaError?, code: String? = null) { + 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, errorCode = code) + 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) } } @@ -233,13 +396,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 } @@ -247,9 +423,9 @@ class AntennaManager( } /** - * Opens the vault (link spec 6.5 to 6.10). 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]. + * 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) = unlockMutex.withLock { var hello = firstHello @@ -271,7 +447,7 @@ class AntennaManager( /** * 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 6.10). + * 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")!! @@ -281,18 +457,35 @@ class AntennaManager( "unprovisioned" -> return provision(c, hello, deviceId, deviceBytes) } try { - c.call("sec.unlock", wrapArgs(hello, tokenSource.token(deviceBytes), deviceBytes)) + authCall(c, "sec.unlock", wrapArgs(hello, tokenSource.token(deviceBytes), deviceBytes)) return } catch (e: LinkCommandException) { if (e.error.code != "E_UNLOCK_FAILED") throw e } 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), transfer, deviceBytes)) + authCall(c, "sec.unlock", wrapArgs(c.call("sys.hello", HELLO_ARGS), transfer, deviceBytes)) 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 @@ -302,7 +495,7 @@ class AntennaManager( */ private suspend fun provision(c: LinkClient, hello: JsonObject, deviceId: String, deviceBytes: ByteArray) { val name = settings.get(Settings.DISPLAY_NAME)?.takeIf(MessageLimits::isValidName) - c.call("sec.provision", wrapArgs(hello, tokenSource.token(deviceBytes), deviceBytes, name)) + authCall(c, "sec.provision", wrapArgs(hello, tokenSource.token(deviceBytes), deviceBytes, name)) if (settings.get(Settings.TRANSFER_DEVICE) == deviceId) clearTransferToken() } @@ -334,6 +527,44 @@ class AntennaManager( } } + // ------------------------------------------------------------------ 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) + } + } + private fun wrapArgs( hello: JsonObject, token: ByteArray, @@ -360,7 +591,7 @@ class AntennaManager( fun tokenFor(deviceId: String): ByteArray = tokenSource.token(OgCrypto.unhex(deviceId)) /** - * Erases the connected antenna (link spec 6.11, `method: "app"`): vault, identity, contacts and settings + * 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. @@ -381,7 +612,7 @@ class AntennaManager( .forEach { (k, v) -> put(k, v) } } try { - c.call("sys.factory_reset", args) + authCall(c, "sys.factory_reset", args) } catch (e: LinkCommandException) { log("factory reset refused: ${e.error.code}") when (e.error.code) { @@ -393,7 +624,9 @@ class AntennaManager( } } clearTransferToken() - _state.update { it.copy(phase = AntennaPhase.CONNECTING, lockReason = "factory_reset") } + _state.update { + it.copy(phase = AntennaPhase.CONNECTING, activity = AntennaActivity.RESETTING, lockReason = "factory_reset") + } scope.launch { setUpAfterReset(c, boot) } return ResetResult.DONE } @@ -416,7 +649,7 @@ class AntennaManager( resetBoot = null bringUp(c, helloWithRetry(c)) } catch (e: UnlockFailure) { - fail(e.error, e.code) + failUnlock(c, e) } catch (_: LinkTimeoutException) { fail(AntennaError.NO_INFO) } catch (_: LinkClosedException) { @@ -438,26 +671,42 @@ class AntennaManager( } 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" -> if (event.data.str("state") == "locked") { - _state.update { it.copy(lockReason = event.data.str("reason")) } - if (reset == null && state.value.ready) 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) } else -> listener.onEvent(event) } } - /** Opens the vault again after an auto-lock or restart; ends the session with the reason when that fails. */ + /** + * 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 { - bringUp(c, c.call("sys.hello", HELLO_ARGS)) + val hello = c.call("sys.hello", HELLO_ARGS) + 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}") - fail(e.error, e.code) + failUnlock(c, e) } catch (e: LinkCommandException) { log("re-unlock failed: ${e.error.code}") fail(AntennaError.REJECTED, e.error.code) @@ -465,19 +714,27 @@ class AntennaManager( fail(AntennaError.NO_INFO) } catch (_: LinkClosedException) { // runSession reports the lost link + } finally { + relockMutex.unlock() } } - private companion object { - 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 - const val RESET_BOOT_TIMEOUT_MS = 15_000L - val HELLO_ARGS = buildJsonObject { put("app", "offgrid-android"); put("app_proto", "1.0") } - val RETRY_WITH_NEW_HELLO = setOf("E_NO_SESSION", "E_NOT_PROVISIONED", "E_ALREADY_PROVISIONED") + companion object { + /** [LockEvent.reason] for a restart noticed through `sys.boot` (not a `sec.state` reason). */ + const val REASON_RESTART = "restart" - fun errorFor(code: String): AntennaError = when (code) { + private const val PROTO_MAJOR = "1" + // 8 s: an image that plays its OLED boot animation in setup() answers only after it ends. + 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.0") } + 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 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..f116085 --- /dev/null +++ b/native-android/app/src/main/java/ch/offgrid/android/domain/DeviceInfo.kt @@ -0,0 +1,125 @@ +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").uppercase().takeIf { NODE_ID.matches(it) } + } +} + +/** 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/link/LinkClient.kt b/native-android/app/src/main/java/ch/offgrid/android/link/LinkClient.kt index 4d0bf45..3d3b013 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 @@ -24,7 +24,7 @@ class LinkClosedException(cause: Throwable? = null) : Exception("link closed", c * * - 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). + * - 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. */ @@ -105,7 +105,11 @@ class LinkClient( companion object { const val MAX_IN_FLIGHT = 4 - private val VAULT_COMMANDS = setOf("pair.complete", "contact.delete") + /** 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/ui/screens/Common.kt b/native-android/app/src/main/java/ch/offgrid/android/ui/screens/Common.kt index d83fe59..a80022c 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,7 +16,9 @@ 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 @@ -48,38 +50,82 @@ 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". */ -/** [code] is the link error code behind [AntennaError.REJECTED]. */ -fun AntennaError.text(code: String? = null): 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 wartet bis zu einer Minute, bevor sie es wieder zulässt." + 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. Steck sie neu ein. Hilft das nicht, muss sie zurückgesetzt werden." + 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), for the connect screen while it is not open again. */ +/** 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. Warte eine Minute und versuch es dann erneut. Es 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." } 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 b1a4935..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,16 +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.lockReason?.takeIf { !state.ready }?.let { OgNote(lockReasonText(it)) } - state.error?.let { OgNote(it.text(state.errorCode)) } + 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 3349a9f..a7b67f6 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,6 +40,9 @@ 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 @@ -108,7 +111,7 @@ fun ContactsScreen(nav: NavHostController) { } } } - 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( @@ -151,7 +154,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), @@ -160,11 +164,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), ) @@ -172,6 +182,16 @@ 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 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 index d7e18e5..2af38b0 100644 --- 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 @@ -18,14 +18,19 @@ 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 @@ -86,7 +91,45 @@ class AntennaSecurityTest { } @Test - fun autoLockIsReopenedAndTheReasonCleared() = runBlocking { + 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() @@ -96,6 +139,88 @@ class AntennaSecurityTest { 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 @@ -156,6 +281,12 @@ class AntennaSecurityTest { 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) } } From 69466b6f449ab7827cd5ccbc9033cd6483486647 Mon Sep 17 00:00:00 2001 From: arturict Date: Sat, 24 Oct 2026 06:42:25 +0200 Subject: [PATCH 09/17] Pairing: keep the shown code bound to the antenna's session MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Nils' firmware draws a new salt on every pair.begin, so opening "Kontakt hinzufügen" twice gave the peer a code the antenna no longer completes with (the 2026-10-24 field bug, fixed only in the lab image). Pairing now keeps the session of the last pair.begin and shows it again when the screen is opened again; it asks for a new one only when less than a minute is left, after the antenna locked or restarted, or when the antenna answers E_NO_PAIRING. Leaving the screen no longer sends pair.cancel (that wiped the salt); only a finished pairing does. After our own scan the code is never refreshed, the peer may still scan it. E_NO_PAIRING renews the session (pair.cancel, pair.begin), shows the new code with a note that whoever scanned the old one has to scan again, and retries once. A second refusal is the lab image's guard against completing the same peer code twice: "Diesen Code hat die Antenne schon verwendet". E_CONTACT_EXISTS offers "Neu koppeln" with replace:true. The simulator follows the lab fix: a completion ends the session and the same peer code is refused within the window. PairingTest covers both firmwares through a small Pairing.Store seam instead of Room. --- .../java/ch/offgrid/android/AppContainer.kt | 7 +- .../offgrid/android/domain/AntennaManager.kt | 8 +- .../java/ch/offgrid/android/domain/Pairing.kt | 164 +++++++++++++--- .../android/link/sim/SimulatedHeltec.kt | 13 +- .../android/ui/screens/AddContactScreen.kt | 7 + .../android/ui/screens/AddContactViewModel.kt | 24 ++- .../ch/offgrid/android/ui/screens/Common.kt | 3 +- .../ch/offgrid/android/domain/PairingTest.kt | 184 ++++++++++++++++++ .../android/link/SimulatedHeltecLab3Test.kt | 10 +- 9 files changed, 373 insertions(+), 47 deletions(-) create mode 100644 native-android/app/src/test/java/ch/offgrid/android/domain/PairingTest.kt 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 aeb89eb..9e57fd5 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 @@ -30,8 +30,10 @@ 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 @@ -73,7 +75,10 @@ class AppContainer(private val context: Context) { 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/domain/AntennaManager.kt b/native-android/app/src/main/java/ch/offgrid/android/domain/AntennaManager.kt index 8c7577c..7d94292 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 @@ -136,7 +136,10 @@ data class AntennaState( val lastLock: LockEvent? = null, /** Code of the last unsolicited `error` event (storage, RF, lost events). */ val lastDeviceError: String? = null, - /** Counts every successful unlock or provisioning; a change means the antenna's RAM state (pairing salt, refs) is new. */ + /** + * 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 @@ -335,7 +338,8 @@ class AntennaManager( 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 = it.unlockCount + 1) + error = null, errorCode = null, lockReason = null, retryAt = null, + unlockCount = if (deviceState == "unlocked") it.unlockCount else it.unlockCount + 1) } listener.onReady(this, deviceId) } 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/link/sim/SimulatedHeltec.kt b/native-android/app/src/main/java/ch/offgrid/android/link/sim/SimulatedHeltec.kt index 4773e9a..2a23637 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 @@ -87,6 +87,8 @@ 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() @@ -293,6 +295,7 @@ class SimulatedHeltec( identityPrivate = null session = null pairing = null + usedPeerCodes.clear() resetAuthorized = false bootAt = clock() emitEvent("sys.boot", bootData(reason)) @@ -496,7 +499,7 @@ class SimulatedHeltec( /** * `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. Nils' firmware 0.3.0 draws a new salt on + * 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 { @@ -524,6 +527,9 @@ class SimulatedHeltec( 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) @@ -538,8 +544,9 @@ class SimulatedHeltec( fingerprint = OgCrypto.fingerprint(publicKey(), peerPub), ) save(flash.copy(contacts = flash.contacts.filter { it.contactId != id } + contact)) - // Team firmware: success ends the pairing session. The lab image keeps the salt for its window. - if (!labRadio) pairing = null + // 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. 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/Common.kt b/native-android/app/src/main/java/ch/offgrid/android/ui/screens/Common.kt index a80022c..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 @@ -133,7 +133,8 @@ fun ResetResult.text(): String? = when (this) { 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/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/SimulatedHeltecLab3Test.kt b/native-android/app/src/test/java/ch/offgrid/android/link/SimulatedHeltecLab3Test.kt index c720394..e394779 100644 --- 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 @@ -226,12 +226,14 @@ class SimulatedHeltecLab3Test { 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) }) - // The lab image keeps the salt after a completion; cancel wipes it. - assertEquals(first.str("qr"), c.call("pair.begin").str("qr")) - c.call("pair.cancel") - assertNotEquals(first.str("qr"), c.call("pair.begin").str("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() } From 3d610b152ea051f8315d142f9e3f3ff15889ddcc Mon Sep 17 00:00:00 2001 From: arturict Date: Sat, 24 Oct 2026 06:44:24 +0200 Subject: [PATCH 10/17] One request in flight, as the link spec recommends --- native-android/README.md | 2 +- .../app/src/main/java/ch/offgrid/android/link/LinkClient.kt | 5 +++-- 2 files changed, 4 insertions(+), 3 deletions(-) diff --git a/native-android/README.md b/native-android/README.md index 54ad24d..f746bec 100644 --- a/native-android/README.md +++ b/native-android/README.md @@ -65,7 +65,7 @@ formatting and analytics. | 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 | 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 3d3b013..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,7 +23,7 @@ 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). + * - 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,7 +104,8 @@ class LinkClient( } companion object { - const val MAX_IN_FLIGHT = 4 + /** 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", From bbd150409ee19e404d8c0d51841c95811d59ab9b Mon Sep 17 00:00:00 2001 From: arturict Date: Sat, 24 Oct 2026 06:50:03 +0200 Subject: [PATCH 11/17] Delivery details per message and a details sheet MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Messages store hops, RSSI, SNR, retries, the time to the ACK, the OGZ1 flag, bytes on air and the last device state from msg.send, msg.status and msg.received (database version 3). A delivery the reconciliation finds only in msg.pending.recent shows as "zugestellt, während offline". A long press on any bubble opens the details; on a peer's message together with the reactions. --- .../3.json | 442 ++++++++++++++++++ .../java/ch/offgrid/android/AppContainer.kt | 3 +- .../main/java/ch/offgrid/android/data/Daos.kt | 2 +- .../java/ch/offgrid/android/data/Entities.kt | 21 + .../ch/offgrid/android/data/Migrations.kt | 9 + .../offgrid/android/domain/MessageDetails.kt | 81 ++++ .../ch/offgrid/android/domain/Messaging.kt | 13 +- .../android/domain/OutboxReconciler.kt | 39 +- .../android/ui/components/ChatComponents.kt | 3 +- .../offgrid/android/ui/screens/ChatScreen.kt | 45 +- .../android/ui/screens/GroupScreens.kt | 67 +-- .../android/ui/screens/MessageSheet.kt | 79 ++++ .../android/domain/MessageDetailsTest.kt | 54 +++ .../android/domain/OutboxReconcilerTest.kt | 27 +- 14 files changed, 811 insertions(+), 74 deletions(-) create mode 100644 native-android/app/schemas/ch.offgrid.android.data.OffGridDatabase/3.json create mode 100644 native-android/app/src/main/java/ch/offgrid/android/domain/MessageDetails.kt create mode 100644 native-android/app/src/main/java/ch/offgrid/android/ui/screens/MessageSheet.kt create mode 100644 native-android/app/src/test/java/ch/offgrid/android/domain/MessageDetailsTest.kt 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/src/main/java/ch/offgrid/android/AppContainer.kt b/native-android/app/src/main/java/ch/offgrid/android/AppContainer.kt index 9e57fd5..77ec701 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 @@ -9,6 +9,7 @@ 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.OffGridDatabase import ch.offgrid.android.domain.AntennaManager import ch.offgrid.android.domain.BackupService @@ -41,7 +42,7 @@ import java.util.UUID class AppContainer(private val context: Context) { val scope = CoroutineScope(SupervisorJob() + Dispatchers.Default) val db: OffGridDatabase = Room.databaseBuilder(context, OffGridDatabase::class.java, "offgrid.db") - .addMigrations(MIGRATION_1_2) + .addMigrations(MIGRATION_1_2, MIGRATION_2_3) .build() val settings = Settings(db.settings(), scope) 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 2816d96..9ada34b 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 @@ -208,7 +208,7 @@ interface MaintenanceDao { @Database( entities = [ContactEntity::class, MessageEntity::class, GroupEntity::class, GroupMemberEntity::class, SettingEntity::class], - version = 2, + version = 3, 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 3639aa6..00009a7 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 @@ -95,6 +96,26 @@ data class MessageEntity( val senderContactId: Long? = null, val senderName: 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. 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 index 53532bf..4085a50 100644 --- 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 @@ -20,3 +20,12 @@ val MIGRATION_1_2 = object : Migration(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") } + } +} 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..20f9edb --- /dev/null +++ b/native-android/app/src/main/java/ch/offgrid/android/domain/MessageDetails.kt @@ -0,0 +1,81 @@ +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 no contact slot). */ + fun failedBeforeSending(reason: String?): Boolean = reason != null && (reason.startsWith("E_") || reason == "no_contact") + + /** 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" + "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_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 4a6dbbd..66a69aa 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 @@ -11,6 +11,7 @@ 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 @@ -135,7 +136,10 @@ class Messaging( scope.launch { val m = db.messages().byId(messageId) ?: return@launch // 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)) + 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() } } @@ -173,7 +177,9 @@ class Messaging( 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), + 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 @@ -403,7 +409,7 @@ class Messaging( // Only refs of the current session: a ref from an earlier boot must never touch a newer message. val session = currentSession ?: return val m = db.messages().byMsgRef(ref, session) ?: return - OutboxReconciler.applyEvent(m, state, d.str("reason"))?.also { db.messages().update(it) } ?: return + OutboxReconciler.applyEvent(m, state, d.str("reason"), DeliveryDetails.parse(d))?.also { db.messages().update(it) } ?: return } if (updated.status == MessageStatus.DELIVERED) { updated.contactId?.let { db.contacts().byId(it) }?.let { db.contacts().update(it.copy(lastSeenAt = now())) } @@ -424,6 +430,7 @@ class Messaging( senderContactId = if (group != null) c.id else null, senderName = if (group != null) c.displayName else null, 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) 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 index e8996f3..a8193f7 100644 --- 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 @@ -9,7 +9,20 @@ 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) +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 @@ -22,7 +35,8 @@ data class PendingSnapshot(val pending: List, val recent: List 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")) + 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")) } @@ -39,7 +53,8 @@ data class PendingSnapshot(val pending: List, val recent: List { - val next = applyEvent(m, queued.state, queued.reason) ?: m + 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) } ?: lost(m) + 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 } 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 9aa9d77..501ccf1 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 @@ -220,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( @@ -238,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( 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 e6bb9d9..ca7c090 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 @@ -52,6 +52,7 @@ 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.Messaging import ch.offgrid.android.domain.REACTIONS @@ -90,7 +91,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. @@ -132,7 +133,8 @@ fun ChatScreen(nav: NavHostController, contactId: Long) { 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", ) } } @@ -154,25 +156,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) }, + ) } } @@ -240,15 +229,20 @@ fun MessageList( } /** - * Meta line: in → time; out → "14:03 · zugestellt", "Wartet auf Anna", "wartet auf Funk …", + * 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) @@ -260,8 +254,7 @@ fun metaFor(m: MessageEntity, ready: Boolean, recipient: String? = null): String * "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 (reason != null && (reason.startsWith("E_") || reason == "no_contact")) "Nicht gesendet" else "Nicht zugestellt" +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) { 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..83532fa 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,6 +1,8 @@ package ch.offgrid.android.ui.screens +import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.Column +import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.foundation.layout.padding import androidx.compose.foundation.rememberScrollState import androidx.compose.foundation.verticalScroll @@ -127,6 +129,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) @@ -137,37 +140,41 @@ fun GroupChatScreen(nav: NavHostController, groupId: Long) { } val count = members.count { it.groupId == groupId } + 1 - 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) }, + ) + 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) }, + 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, ) } - ChatComposer( - draft = draft, - onDraft = { draft = it }, - target = g.name, - antenna = antenna, - onSend = { - app.messaging.sendGroupText(g.id, draft) - draft = "" - }, - onLocation = null, - ) + MessageSheet(detailsFor?.let { id -> messages.firstOrNull { it.id == id } }, recipient = null, onClose = { detailsFor = null }) } } 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/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/OutboxReconcilerTest.kt b/native-android/app/src/test/java/ch/offgrid/android/domain/OutboxReconcilerTest.kt index 98c46d5..2f20c35 100644 --- 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 @@ -60,6 +60,29 @@ class OutboxReconcilerTest { 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 @@ -112,7 +135,7 @@ class OutboxReconcilerTest { @Test fun eventsNeverMoveAMessageBackAndFinalsClearTheRef() { - val waiting = out(1, 100, MessageStatus.WAITING, session = now) + 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)) @@ -140,7 +163,7 @@ class OutboxReconcilerTest { """"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)), s.pending) + 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()) From 15e77c0d5a66da474a2814125bfbbdf14a026156 Mon Sep 17 00:00:00 2001 From: arturict Date: Sat, 24 Oct 2026 06:53:22 +0200 Subject: [PATCH 12/17] Split texts longer than one packet into several messages The firmware does not fragment (link spec 10). A text that does not fit one packet, also not OGZ1-compressed on a lab image, goes out as up to four raw messages cut at spaces, which boards on the team firmware can read. --- .../java/ch/offgrid/android/domain/Limits.kt | 32 +++++++++++++++++++ .../ch/offgrid/android/domain/Messaging.kt | 21 +++++++----- .../android/ui/components/ChatComponents.kt | 11 +++++-- .../offgrid/android/ui/screens/ChatScreen.kt | 2 ++ .../android/domain/MessageLimitsTest.kt | 23 +++++++++++++ 5 files changed, 79 insertions(+), 10 deletions(-) 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 2991bc2..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 @@ -42,6 +42,38 @@ object MessageLimits { 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/Messaging.kt b/native-android/app/src/main/java/ch/offgrid/android/domain/Messaging.kt index 66a69aa..6a090ea 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 @@ -116,20 +116,23 @@ 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()) + }, ) fun sendGroupText(groupId: Long, text: String) = enqueue( - MessageEntity(groupId = groupId, direction = "out", kind = "text", text = text.trim(), - status = MessageStatus.LOCAL_QUEUED, sentAt = now()), + MessageLimits.split(text, antenna.state.value).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) { @@ -147,10 +150,12 @@ 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() } } 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 501ccf1..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 @@ -360,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. @@ -409,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/screens/ChatScreen.kt b/native-android/app/src/main/java/ch/offgrid/android/ui/screens/ChatScreen.kt index ca7c090..7155163 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 @@ -304,6 +304,8 @@ fun ChatComposer( maxBytes = antenna.maxTextBytes, onSend = onSend, onLocation = onLocation, + parts = MessageLimits.split(draft, antenna).size, + maxParts = MessageLimits.MAX_PARTS, ) } 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 fbe4b1e..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 @@ -70,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) + } } From b667d6cdf274cdeee337bf1a3c79599bc7c94b54 Mon Sep 17 00:00:00 2001 From: arturict Date: Sat, 24 Oct 2026 06:55:05 +0200 Subject: [PATCH 13/17] Release 0.2.0: sign with a release key from the environment, never the debug key The release signingConfig reads OFFGRID_RELEASE_STORE_FILE, _STORE_PASSWORD, _KEY_ALIAS and _KEY_PASSWORD from Gradle properties or the environment. Without them the release APK is unsigned; a partial setup or a missing keystore stops the build. Releases no longer take the TCP bridge or the forced TEXT codec from local.properties. --- native-android/README.md | 21 ++++++++++++--- native-android/STATUS.md | 7 ++--- native-android/app/build.gradle.kts | 41 ++++++++++++++++++++++++----- 3 files changed, 56 insertions(+), 13 deletions(-) diff --git a/native-android/README.md b/native-android/README.md index f746bec..025d31f 100644 --- a/native-android/README.md +++ b/native-android/README.md @@ -30,7 +30,20 @@ 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 @@ -42,8 +55,8 @@ unlocking and counts bytes with the codec, and it uses USB, not the TCP bridge. 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. @@ -218,7 +231,7 @@ image (`lab_radio`) and what only a second board can show. It is kept by the age 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, a release signing key, and a + 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 28dde68..cab6de0 100644 --- a/native-android/STATUS.md +++ b/native-android/STATUS.md @@ -4,7 +4,8 @@ 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`, @@ -73,5 +74,5 @@ the simulator only; see [`docs/hardware.md`](docs/hardware.md), "App against lab 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 fb69d8c..1c63ee5 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,9 +31,9 @@ android { applicationId = "ch.offgrid.android" minSdk = 26 targetSdk = 35 - // 2: database version 2 (messages.refSession) and the lab.3 security and delivery handling. - versionCode = 2 - versionName = "0.1.0-lab3" + // 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. @@ -36,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") } From a9e57c25a17fe70af3acc98344609264fb18bd0f Mon Sep 17 00:00:00 2001 From: arturict Date: Sat, 24 Oct 2026 06:59:44 +0200 Subject: [PATCH 14/17] Erweitert / Lab: firmware info, mesh and lab settings, radio statistics A new screen under Einstellungen shows device id, NodeID, firmware version and build, lab or team firmware, vault and security state, the last lock and device error, lost events and the radio settings. Hop limit, relaying and relaying while locked go to mesh.set; on lab boards the text codec and the ignore list (up to eight NodeIDs, not the own one) go to lab.set. radio.stats can be refreshed and reset. Lab boards always reach it, team boards behind a switch. --- .../offgrid/android/domain/AntennaManager.kt | 6 +- .../ch/offgrid/android/domain/DeviceInfo.kt | 22 +- .../ch/offgrid/android/domain/Settings.kt | 3 + .../java/ch/offgrid/android/ui/AppNavHost.kt | 3 + .../android/ui/screens/AdvancedScreen.kt | 341 ++++++++++++++++++ .../offgrid/android/ui/screens/ChatScreen.kt | 3 - .../android/ui/screens/SettingsScreen.kt | 27 +- .../offgrid/android/domain/DeviceInfoTest.kt | 31 ++ 8 files changed, 427 insertions(+), 9 deletions(-) create mode 100644 native-android/app/src/main/java/ch/offgrid/android/ui/screens/AdvancedScreen.kt create mode 100644 native-android/app/src/test/java/ch/offgrid/android/domain/DeviceInfoTest.kt 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 7d94292..973ff5c 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 @@ -123,6 +123,8 @@ data class AntennaState( 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). */ @@ -335,6 +337,7 @@ class AntennaManager( 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"), @@ -565,7 +568,8 @@ class AntennaManager( 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) + vaultStatus = status?.obj("storage")?.str("vault_status") ?: it.vaultStatus, + droppedEvents = status?.obj("queue")?.int("dropped_events") ?: it.droppedEvents) } } 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 index f116085..b20de25 100644 --- 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 @@ -73,10 +73,30 @@ data class LabConfig( ) /** 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").uppercase().takeIf { NODE_ID.matches(it) } + 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( 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 8251813..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,6 +30,9 @@ 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" 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..39cfdf6 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,6 +28,7 @@ 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 @@ -56,6 +57,7 @@ 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}" @@ -136,6 +138,7 @@ 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")) 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..67073f9 --- /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}. Die NodeID eines Kontakts steht in der Kontaktliste der Antenne.", + 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 7155163..0c11c3e 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 @@ -55,7 +53,6 @@ import ch.offgrid.android.domain.GeoFix import ch.offgrid.android.domain.MessageDetails import ch.offgrid.android.domain.MessageLimits import ch.offgrid.android.domain.Messaging -import ch.offgrid.android.domain.REACTIONS import ch.offgrid.android.ui.LocalApp import ch.offgrid.android.ui.Routes import ch.offgrid.android.ui.back 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 5e45e41..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 @@ -189,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.") { @@ -260,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), @@ -278,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/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) + } +} From 85a43644131de48d090584a27f834e64ea451a07 Mon Sep 17 00:00:00 2001 From: arturict Date: Sat, 24 Oct 2026 07:01:49 +0200 Subject: [PATCH 15/17] Token rotation: drop the old phone's token once ours opens the antenna If the answer to sec.rotate_token is lost, the next connect opens the vault with this phone's token and then forgets the transfer token. Test covers the import, the lost answer and the old phone being locked out. --- .../offgrid/android/domain/AntennaManager.kt | 4 +++ .../android/domain/AntennaSecurityTest.kt | 28 +++++++++++++++++++ 2 files changed, 32 insertions(+) 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 973ff5c..c356723 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 @@ -465,6 +465,8 @@ class AntennaManager( } try { 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 @@ -472,6 +474,8 @@ class AntennaManager( 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. 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() } 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 index 2af38b0..1dc7fe8 100644 --- 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 @@ -235,6 +235,34 @@ class AntennaSecurityTest { 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") From f2de17fa4a4448ccd685a708b71b8922f321e55a Mon Sep 17 00:00:00 2001 From: arturict Date: Sat, 24 Oct 2026 07:05:34 +0200 Subject: [PATCH 16/17] Ignore list hint: point to the board's own NodeID --- .../main/java/ch/offgrid/android/ui/screens/AdvancedScreen.kt | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) 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 index 67073f9..3e984fc 100644 --- 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 @@ -182,7 +182,7 @@ fun AdvancedScreen(nav: NavHostController) { 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}. Die NodeID eines Kontakts steht in der Kontaktliste der Antenne.", + 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, From 8f52c6d641225df87108d3e289c9f3a419a8181b Mon Sep 17 00:00:00 2001 From: arturict Date: Sat, 24 Oct 2026 09:33:43 +0200 Subject: [PATCH 17/17] Hardware test: the app's link, security and pairing code against two boards on the team firmware --- .../android/link/hw/TeamFirmwareTest.kt | 245 ++++++++++++++++++ 1 file changed, 245 insertions(+) create mode 100644 native-android/app/src/test/java/ch/offgrid/android/link/hw/TeamFirmwareTest.kt 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") + } +}