Skip to content

fix(native-android): App arbeitet mit Nils' Firmware 0.3.0 (Heartbeat, Koppeln, Reset, Sicherheit) - #22

Open
arturict wants to merge 17 commits into
OffGridCH:mainfrom
arturict:compat/nils-030
Open

arturict wants to merge 17 commits into
OffGridCH:mainfrom
arturict:compat/nils-030

Conversation

@arturict

Copy link
Copy Markdown
Contributor

Problem

Die native App in native-android/ (#15) stammt aus der Zeit vor Nils' Firmware 0.3.0 mit echter Sicherheit (OffGridCH/firmware main 47bb2d9). Mit dieser Firmware geht Folgendes schief:

  • Heartbeat: Die App pingt nur alle 5 s, die Firmware sperrt nach 15 s ohne Kommando. Zwei verlorene Pings reichen, damit die Antenne mitten im Chat sperrt. Die Spec (docs/offgrid-link.md §2, §14.4) verlangt etwa 1 s.
  • Koppeln: Bei jedem Öffnen des Kopplungs-Screens ruft die App pair.begin auf. Firmware 0.3.0 zieht dabei jedes Mal ein neues Salt. Öffnet eine Seite den Screen nach dem Scan noch einmal, rechnen die beiden Boards mit verschiedenen Schlüsseln, und danach kommt keine Nachricht an. Auf Hardware mit main 47bb2d9 nachgestellt (Koppeln in App-Reihenfolge: 6 von 11 Prüfungen, keine Nachricht in beide Richtungen; siehe fix(pairing): ein Salt pro 5-Minuten-Kopplungsfenster firmware#11).
  • Werkseinstellungen: Die App kennt das Wrap-Label og-reset-wrap-v1 nicht und kann sys.factory_reset mit Methode app nicht autorisieren.
  • Nebenläufige Anfragen: Die App schickt bis zu 4 Anfragen gleichzeitig. Die Spec empfiehlt eine (§1).
  • Weitere Lücken: Entsperr-Fehler, Rate-Limit und Backoff, neu geflashte Antennen, die Kommandonamen und -argumente aus Commands.cpp und der Abgleich mit msg.pending nach einem Reconnect sind nicht so umgesetzt, wie die Firmware antwortet.

Erwartet ist, dass die App mit Nils' unverändertem main einrichtet, entsperrt, offen bleibt, koppelt, sendet, empfängt und zurücksetzt.

Change

Diese Commits haben wir auf Hardware mit 0.3.0 entwickelt; sie fehlten in #15. Sie liegen unverändert unter native-android/:

  • 68f4ad8 Token-Wrap mit Reset-Label und den Testvektoren aus der Firmware
  • 6d2115c, 91f39d6 Simulator nach Nils' 0.3.0-Serial-API (plus die Lab-Erweiterungen, nur wenn die Antenne lab_radio meldet)
  • d18cd94 Outbox nach jedem Connect mit msg.pending abgleichen
  • f3b380c Echte Sicherheit: Entsperr-Fehler, autorisierter Reset, neu geflashte Antennen
  • d30c36e Kommandos und Argumente wie in Commands.cpp
  • 5628a36 Version und Hinweise zum Lab-Image
  • e680014 Setup und Entsperren: alle Gerätezustände, Countdown bei Rate-Limit, Heartbeat 1 s
  • 69466b6 Koppeln: Der angezeigte Code bleibt an die Session der Antenne gebunden. Erneutes Öffnen ruft kein neues pair.begin auf, solange die Session gilt.
  • 3d610b1 Eine Anfrage gleichzeitig, wie es die Spec empfiehlt
  • bbd1504 Zustelldetails pro Nachricht
  • 15e77c0 Texte über 83 Bytes werden auf mehrere Nachrichten verteilt (die Firmware fragmentiert nicht)
  • b667d6c Release-Signierung nur über Umgebungsvariablen, nie mit dem Debug-Key; kein Schlüssel im Repo
  • a9e57c2 Bereich «Erweitert»: Firmware-Info, Mesh- und Funkeinstellungen, Statistik. Lab-Einstellungen nur bei lab_radio.
  • 85a4364 Token-Rotation nach einem Backup-Import (sec.rotate_token)
  • f2de17f Hinweistext zur Ignorierliste
  • 8f52c6d Neuer Hardware-Test TeamFirmwareTest (siehe Verification)

Lab-Funktionen (OGZ1, Ignorierliste, recent, waiting) blendet die App nur ein, wenn sys.hello lab_radio meldet. Mit Nils' Firmware ruft sie keine lab.*-Kommandos auf.

Scope

  • Der PR ist gross (49 Dateien, +5142/−425), weil er den Stand nachreicht, der nach Kein Ticket: Native Android-App (Kotlin) als native-android/ #15 auf Hardware entstanden ist. Alles betrifft dasselbe Ziel: Die App arbeitet mit Firmware 0.3.0.
  • Nur native-android/ ist betroffen. Ionic-App, Doku-Site und CI bleiben unverändert.
  • Keine Änderung an Firmware oder Protokoll.
  • Die Release-Signierung braucht vier Umgebungsvariablen (OFFGRID_RELEASE_*). Ohne sie entsteht wie bisher nur ein Debug-Build.

Verification

  • ./gradlew testDebugUnitTest lintDebug assembleDebug in native-android/: 133 Tests, 0 Fehler, 7 übersprungen (die Hardware-Tests ohne Boards). Lint ohne Fehler, 2 Warnungen, die schon vorher bestanden.

  • Emulator (API 35) mit simulierter Antenne nach 0.3.0-API, Release-Build dieses Stands zusammen mit den zwei Feature-PRs (Links, Werkseinstellungen): Einrichtung bis zur Kontaktliste, Chat, Zustellstatus; kein Absturz.

  • Hardware: Der Kopplungsfehler oben ist am 24.10. auf drei Heltec V3 mit main 47bb2d9 reproduziert (Serial-API-Skript in App-Reihenfolge). Einen dokumentierten Lauf dieses App-Codes gegen Nils' unverändertes main gibt es noch nicht.

  • Hardware-Test mit Nils' main ausstehend. Der Test TeamFirmwareTest liegt bei (app/src/test/java/ch/offgrid/android/link/hw/). Er fährt AntennaManager und Pairing der App gegen zwei Boards mit unverändertem main und prüft:

    • Einrichtung, Heartbeat über 20 s, Koppeln mit mehrfachem Öffnen;
    • Text mit Umlauten und Emoji, Standort, Reaktion;
    • Fehlzustellung an ein gesperrtes Board, Sperren und Entsperren;
    • falscher Token mit Backoff, Token-Rotation, Werkseinstellungen.

    Die Boards sind gerade beim Team im Einsatz. Das Ergebnis reiche ich als Kommentar nach.

  • Nicht geprüft: echte Handys über USB-C (USB-Reset beim Öffnen, Berechtigungsdialog, Hintergrundbetrieb).


Erstellt mit Claude Opus 5.5 in Claude Code via T3 Code, im Auftrag von Artur. Vor dem Merge braucht es ein menschliches Review.

🤖 Generated with Claude Code

arturict and others added 17 commits October 24, 2026 09:19
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.
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.
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
<Name> 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.
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.
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.
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.
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.
…beat

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.
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.
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.
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.
…e 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.
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.
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.
@arturict

Copy link
Copy Markdown
Contributor Author

Bitte um Review. Dieser PR macht die native App mit Nils' unverändertem Firmware-main (47bb2d9) lauffähig; #23 (Links) und #24 (Werkseinstellungen) bauen darauf auf.

Der Hardware-Test mit Nils' main steht noch aus, weil die Boards gerade beim Team sind. TeamFirmwareTest liegt bei, das Ergebnis kommt als Kommentar nach. Die CI baut native-android/ nicht; Tests, Lint und Build liefen lokal.

Geschrieben von Claude Opus 5.5 (KI) im Auftrag von Artur.

@arturict arturict left a comment

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Ergebnis: FAIL. Die nativen Basisprüfungen sind grün; Gerätezuordnung, Wiederverbindung und Sicherheitsabläufe haben belegte Fehler.

Befunde

Kotlin-Pfade relativ zu native-android/app/src/main/java/ch/offgrid/android/.

  1. Blocker: domain/Messaging.kt:215, :261–263. Der Vorbefund aus #15 bleibt offen: Slot-Befehle prüfen nicht die Geräte-ID des Kontakts. A/Slot 1 = Anna, B/Slot 1 = Bob: Annas wartender Text kann an Bob gehen; Annas Löschen kann Bobs Schlüssel löschen. Vor Senden, Reaktion, Umbenennen und Löschen Geräteidentität und erfolgreichen Kontaktabgleich prüfen. Fremde Antennen nicht bedienen.
  2. Wichtig: domain/OutboxReconciler.kt:128–129. Für Zeilen mit refSession genügt dieselbe msg_ref; abweichende Zähler werden ignoriert. Die App-UUID belegt keinen Geräte-Boot, und die Firmware beginnt Referenzen nach Neustart wieder bei 1. Zusätzliche Regressionstests scheitern: alte ref 7/ctr 41 wird an pending ref 7/ctr 99 gebunden; ein fremder Endstatus kann sie als zugestellt markieren. Beim Sitzungswechsel Zähler und Gegenstelle prüfen; Endstände ohne eindeutige Boot-Zuordnung nicht übernehmen.
  3. Wichtig: domain/Pairing.kt:105, :118. Nach 241 s wird beim erneuten Öffnen ein noch gültiger QR ersetzt, aber codeRenewed bleibt false. Mit tatsächlicher Pairing-Klasse und kontrollierter Uhr reproduziert: zwei pair.begin, neuer Code, keine Erneuerungswarnung. Nils' Firmware erzeugt dabei ein neues Salz. Hat das Gegenüber den alten Code bereits gescannt, unterscheiden sich die Schlüssel. Jede Ersetzung eines gezeigten Codes anzeigen und den erneuten Scan vor Fortsetzung berücksichtigen.
  4. Wichtig: domain/AntennaManager.kt:463. unlocked -> return überspringt eine ausstehende Tokenübernahme nach Backup-Import. Regressionstest: neues Handy erreicht READY, das alte Transfertoken bleibt gespeichert und gültig; der neue Keystore allein scheitert nach Neustart mit UNLOCK_FAILED. Auch bei bereits entsperrter Antenne die Rotation abschliessen und das Transfertoken erst nach Bestätigung entfernen. Der gespeicherte alte Token ermöglicht derzeit einen späteren Fallback; die Übernahme ist bei READY noch nicht abgeschlossen.
  5. Wichtig: ui/screens/SettingsScreen.kt:259, domain/Messaging.kt:278. Der Hintergrundauftrag übernimmt den bestätigten Löschumfang nicht. Wird bei noch laufender Verbindung „nur Handydaten“ bestätigt und die Antenne vor Ausführung READY, ruft deleteAll() zusätzlich factoryReset() auf und löscht deren Identität/Schlüssel. Umfang und gegebenenfalls Geräte-ID bei Bestätigung festhalten, explizit übergeben und vor Ausführung prüfen.

Ticket-Abdeckung

Kein Ticket verlinkt; gegen den beschriebenen Kompatibilitätsumfang geprüft. Nur native-android/ geändert. Reset-Wrap-Label und Testvektoren passen zur Firmware; Release verwendet keinen Debug-Signierschlüssel mehr. Queue-Nachschub und Behandlung beobachteter Neustarts sind verbessert. Ein Lauf dieses App-Codes gegen unveränderte Team-Boards sowie echte USB-Handys bleibt ausstehend.

CI

app-checks und docs-check grün, prüfen die native App nicht. Auf hack-b am unveränderten Head: testDebugUnitTest lintDebug assembleDebug erfolgreich, 133 Tests, 7 Hardware-Skips. Danach drei zusätzliche Outbox-/Token-Regressionsfälle im isolierten Checkout: alle drei schlagen wegen der beschriebenen Fehler fehl. Pairing zusätzlich mit kontrollierter Uhr reproduziert. Kein Hardwaretest.

— Automatisches Review mit GPT-6.1 Sol (Codex) im Auftrag von @arturict; ersetzt kein menschliches Review.

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant