Skip to content

armgit / bento

Public Imported from GitHub
0

Bento, the office suite that fits in a file

home/android: bento/connect agent core (A1): two Keystore keys, the routine session, host-stamped consent, the enrolment canary (#765)

nyblnetca8e64028b39
diff --git a/docs/DECISIONS.md b/docs/DECISIONS.md
index ffc19ab0..21504a30 100644
--- a/docs/DECISIONS.md
+++ b/docs/DECISIONS.md
@@ -11200,3 +11200,95 @@ Follows the desktop agent core entry above.
Rigs: `tests/recovery.rs`, where each of these mutations turns a test red: the
old pepper labels, losing O→0 when reading a code, and skipping the range
check. Also `tests/secret_linux.rs` via `keyring-rig.sh`.
+
+## 2026-10-18 — bento/connect on Android (Bento ID): the agent's two keys, the routine session, and host-stamped consent
+
+The Android agent core (phase-1 plan A1). It isn't wired to any page yet: the
+`__bentoIdentity` global goes in only after the Android host verifies the
+shell it serves (gate 1, A2).
+
+- **Two Keystore keys.** The ROUTINE key signs collaboration traffic without a
+ prompt. The CONSENT key needs an authentication for every use: a
+ BiometricPrompt authorises exactly one signature (a CryptoObject), and the
+ Keystore, not the UI, refuses a second (measured on the emulator). The
+ consent key lives in StrongBox where the device has one. A `dev.`
+ certificate names it as `consentPub`, and it is a different key from the
+ routine one.
+- **The consent key accepts the device credential as well as a strong
+ biometric (API 30+), as security ruled (threat model §29).** People without
+ biometrics aren't excluded, matching iOS's `.userPresence`. An organisation
+ setting, "biometric-only consent", is OFF by default and not built yet. The
+ residual risk, stated plainly: a thief holding the phone AND its passcode
+ passes user verification. Notification to every device, the contest/freeze
+ and the recovery code catch that, not the key. On API 26–29, a per-use key
+ accepts biometrics only, so a phone without one gets no consent key: it can
+ do routine work but not consent (security §29, option a). A time-windowed
+ PIN key was rejected: it breaks "one prompt, one signature". Requiring API
+ 30 was rejected too: it excludes people for no gain. In phase 1 that device
+ can't authorise link, rotate or unbind. Invite and revoke are unaffected,
+ since they are still owner-key statements the kernel signs (§24b). It can
+ still BE linked, because the consenting device or the passkey authorises
+ that. Its message reads: "Approving new devices or account changes needs a
+ fingerprint on this Android version. Do it from another device."
+- **§2e (B) is enforced in two layers, each with its own bound.** The routine
+ key carries a Keystore validity window of the OVERALL timeout (24 h). That is
+ the hardware floor, and it means "since the device was last unlocked": a
+ lock-screen unlock reopens it with no app prompt (measured, with a control).
+ `RoutineGate` enforces "since Bento was last used": idle 1 h, overall 24 h,
+ tightenable by an organisation (15 min / 12 h) but never loosened. A clock
+ that goes backwards locks the session.
+- **Enrolling a fingerprint doesn't destroy the routine key**
+ (`setInvalidatedByBiometricEnrollment(false)`). It carries no consent, and
+ losing it would drop the device from every room it is in.
+- **Nor does it invalidate the consent key, so a CANARY is the tripwire
+ (threat model §29b).** Measured on the emulator with a positive control:
+ a per-use key that also accepts the device credential survives new
+ fingerprints. Only a biometric-ONLY key is invalidated, and a control key
+ read `KeyPermanentlyInvalidatedException` after a new finger. Removing a
+ fingerprint invalidates neither (measured). So a biometric-only canary key
+ stands beside the consent key. It never signs: before every consent it is
+ read with `initSign`, which needs no prompt. A missing or invalidated canary,
+ biometrics gone under a "bio" record, biometrics present under a "none"
+ record, or no record at all reads CHANGED. A Keystore error reads UNKNOWN
+ and refuses. On CHANGED the gate is home/ios's: the notice "biometrics
+ changed on <device>" goes to the durable outbox FIRST, then the person
+ re-confirms, then the canary is re-minted under the new enrolment. There is
+ no forced re-link; that rested on an invalidation that doesn't happen. The
+ canary and the baseline are made WITH the consent key, so a brand-new
+ identity's first consent reads unchanged and sends no false notice. A busy
+ sensor (`HW_UNAVAILABLE`, often transient) doesn't block a consent the PIN
+ could complete: under a "bio" record the canary, a Keystore check, decides
+ alone. Under a "none" record it can't tell whether biometrics were added,
+ so it refuses, as does any answer the platform can't name. No baseline is
+ ever recorded under a state the platform can't name.
+- **Notices follow §29a, ported from home/ios** (`Notices.kt`). Recipients are
+ snapshotted when a notice is queued: the devices then, plus the address.
+ Removed devices still receive it and still hold it back. It never clears
+ without the address. A silent device stops holding it back after 7 days,
+ and only once the address has confirmed. A device-list change sends its own
+ notice to the list as it was BEFORE the change, and may not be published
+ until that notice is queued. Every device also checks each fetched list
+ itself and raises a local alert if it, or a device it didn't remove, is
+ gone. The alert is written before the new list becomes the baseline.
+- **Signatures leave as raw r‖s, low-S.** The Keystore emits DER and doesn't
+ normalise, so the host converts and folds s.
+- **The host stamps every field of a `cns.`.** The relying party is the app's
+ own (`bento`). The audience is phase 1's only one (`dir`). The docId is the
+ one the host read from the file it opened (#755's rule), never one the page
+ names. The expiry is 2 minutes. A page supplies only the statement and the
+ verifier's challenge. The host refuses to stamp a request a verifier would
+ refuse: wrong family, a document-scoped purpose without a docId, or a
+ malformed challenge.
+- **Conformance is kernel's fixture, re-read on every run.** `ConsentTest`
+ reaches the stated verdict on every `cns` row, rebuilds every accepted row's
+ text byte for byte, and passes the transcript, purpose and low-S rows. It
+ never pins a signature.
+- **Measured end to end on the emulator.** A consent signed inside a
+ BiometricPrompt by the real Keystore key is accepted by kernel's reference
+ `verifyConsent`. Re-presenting it is rejected as `replay`; presenting it to
+ a room verifier, or applying it to another statement, as `transcript`;
+ checking it against another relying party as `rp`; checking it against the
+ routine key as `signature`; and presenting it after expiry as `expired`.
+
+Still for a real phone: TEE and StrongBox residency (the emulator reports
+software keys), and the API 26–29 consent path, which allows biometrics only.
diff --git a/home/android/app/build.gradle.kts b/home/android/app/build.gradle.kts
index f4262e64..ab1fcc17 100644
--- a/home/android/app/build.gradle.kts
+++ b/home/android/app/build.gradle.kts
@@ -137,6 +137,10 @@ dependencies {
// nothing from Material and would only inherit the inflation requirements.
implementation("com.google.android.material:material:1.12.0")
+ // bento/connect (phase-1 plan A1): BiometricPrompt with a CryptoObject, so the
+ // consent key signs only inside an authentication the person just gave.
+ implementation("androidx.biometric:biometric:1.1.0")
+
// Test-only. The indexer is held to the shared corpus in home/fixtures/ by
// a plain JVM test — no emulator, so there is no excuse not to run it.
//
diff --git a/home/android/app/src/debug/AndroidManifest.xml b/home/android/app/src/debug/AndroidManifest.xml
new file mode 100644
index 00000000..011d53ce
--- /dev/null
+++ b/home/android/app/src/debug/AndroidManifest.xml
@@ -0,0 +1,8 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!-- DEBUG BUILDS ONLY. Never in a release: src/debug is not compiled into one. -->
+<manifest xmlns:android="http://schemas.android.com/apk/res/android">
+ <application>
+ <activity android:name=".AgentProbeActivity" android:exported="true"
+ android:theme="@style/Theme.Tray" />
+ </application>
+</manifest>
diff --git a/home/android/app/src/debug/java/page/bento/home/AgentProbeActivity.kt b/home/android/app/src/debug/java/page/bento/home/AgentProbeActivity.kt
new file mode 100644
index 00000000..67eab750
--- /dev/null
+++ b/home/android/app/src/debug/java/page/bento/home/AgentProbeActivity.kt
@@ -0,0 +1,200 @@
+// SPDX-License-Identifier: MIT
+// Copyright (c) 2026 The Bento authors
+
+package page.bento.home
+
+import android.os.Build
+import android.os.Bundle
+import android.util.Base64
+import android.util.Log
+import androidx.appcompat.app.AppCompatActivity
+import androidx.biometric.BiometricManager.Authenticators
+import androidx.biometric.BiometricPrompt
+import androidx.core.content.ContextCompat
+import java.security.KeyFactory
+import java.security.Signature
+import java.security.spec.X509EncodedKeySpec
+
+/**
+ * DEBUG ONLY — exercises AgentKeys on a device before any bridge exists.
+ * Every result goes to logcat under "BentoAgentProbe". Launch with
+ * adb shell am start -n page.bento.home/.AgentProbeActivity
+ * and answer the prompt with a fingerprint (emulator: `adb emu finger touch 1`).
+ */
+class AgentProbeActivity : AppCompatActivity() {
+ private fun log(m: String) = Log.i("BentoAgentProbe", m)
+ private val msg = "bento/connect probe".toByteArray()
+
+ override fun onCreate(savedInstanceState: Bundle?) {
+ super.onCreate(savedInstanceState)
+ if (intent.getStringExtra("mode") == "window") { windowProbe(); return }
+ if (intent.getStringExtra("mode") == "consent") { consentProbe(); return }
+ if (intent.getStringExtra("mode") == "keystate") { keyState(); return }
+ if (intent.getStringExtra("mode") == "gate") { gateProbe(); return }
+ AgentKeys.ensure(this)
+ log("sdk=${Build.VERSION.SDK_INT} routine=${AgentKeys.strength(AgentKeys.ROUTINE)} consent=${AgentKeys.strength(AgentKeys.CONSENT)}")
+ val routineSig = AgentKeys.signRoutine(msg)
+ log("routine: ${routineSig.size}-byte raw signature, verifies=${verifyRaw(AgentKeys.ROUTINE, routineSig)}")
+ log("routine pub (raw, ${AgentKeys.publicRaw(AgentKeys.ROUTINE).size} B): ${Base64.encodeToString(AgentKeys.publicRaw(AgentKeys.ROUTINE), Base64.NO_WRAP)}")
+
+ // Consent WITHOUT authenticating: the Keystore must refuse to sign.
+ val unauth = try {
+ AgentKeys.consentSignature().run { update(msg); sign() }; "SIGNED (WRONG)"
+ } catch (e: Exception) { "refused: ${e.javaClass.simpleName}" }
+ log("consent without auth: $unauth")
+
+ // Consent WITH a prompt that authorises exactly this Signature.
+ val sig = AgentKeys.consentSignature()
+ val allowed = if (Build.VERSION.SDK_INT >= 30) Authenticators.BIOMETRIC_STRONG or Authenticators.DEVICE_CREDENTIAL
+ else Authenticators.BIOMETRIC_STRONG
+ val info = BiometricPrompt.PromptInfo.Builder()
+ .setTitle("bento/connect probe").setSubtitle("Approve a consent signature")
+ .setAllowedAuthenticators(allowed)
+ .apply { if (Build.VERSION.SDK_INT < 30) setNegativeButtonText("Cancel") }
+ .build()
+ BiometricPrompt(this, ContextCompat.getMainExecutor(this), object : BiometricPrompt.AuthenticationCallback() {
+ override fun onAuthenticationSucceeded(result: BiometricPrompt.AuthenticationResult) {
+ val s = result.cryptoObject!!.signature!!
+ s.update(msg)
+ val raw = Ecdsa.derToRaw(s.sign())
+ log("consent after auth: ${raw.size}-byte raw signature, verifies=${verifyRaw(AgentKeys.CONSENT, raw)}")
+ // The authorisation covered ONE operation. A second, fresh Signature must be refused.
+ val again = try { AgentKeys.consentSignature().run { update(msg); sign() }; "SIGNED (WRONG)" }
+ catch (e: Exception) { "refused: ${e.javaClass.simpleName}" }
+ log("consent second use without a new prompt: $again")
+ log("DONE")
+ }
+ override fun onAuthenticationError(code: Int, err: CharSequence) { log("prompt error $code: $err"); log("DONE") }
+ }).authenticate(info, BiometricPrompt.CryptoObject(sig))
+ }
+
+ /**
+ * Does a DEVICE UNLOCK open a Keystore auth-validity window? A throwaway key
+ * valid for 300 s after the user authenticates; sign with it and report.
+ * Run right after unlocking the screen (no app prompt in between).
+ */
+ private fun windowProbe() {
+ val alias = "bento-probe-window"
+ val ks = java.security.KeyStore.getInstance("AndroidKeyStore").apply { load(null) }
+ if (!ks.containsAlias(alias)) {
+ java.security.KeyPairGenerator.getInstance(android.security.keystore.KeyProperties.KEY_ALGORITHM_EC, "AndroidKeyStore").apply {
+ initialize(android.security.keystore.KeyGenParameterSpec.Builder(alias, android.security.keystore.KeyProperties.PURPOSE_SIGN)
+ .setAlgorithmParameterSpec(java.security.spec.ECGenParameterSpec("secp256r1"))
+ .setDigests(android.security.keystore.KeyProperties.DIGEST_SHA256)
+ .setUserAuthenticationRequired(true)
+ .setUserAuthenticationParameters(300,
+ android.security.keystore.KeyProperties.AUTH_BIOMETRIC_STRONG or android.security.keystore.KeyProperties.AUTH_DEVICE_CREDENTIAL)
+ .build())
+ }.generateKeyPair()
+ log("window: key created")
+ }
+ val r = try {
+ Signature.getInstance("SHA256withECDSA").run { initSign(ks.getKey(alias, null) as java.security.PrivateKey); update(msg); sign() }
+ "SIGNED without an app prompt"
+ } catch (e: Exception) { "refused: ${e.javaClass.simpleName}" }
+ log("window: $r")
+ log("DONE")
+ finish()
+ }
+
+ /**
+ * A host-stamped consent end to end: stamp a `cns.` for the given challenge
+ * and statement, sign it with the consent key inside a BiometricPrompt, and
+ * log text, signature and keys for kernel's reference verifier to judge.
+ */
+ private fun consentProbe() {
+ AgentKeys.ensure(this)
+ val challenge = intent.getStringExtra("challenge")!!
+ val payload = intent.getStringExtra("payload")!!
+ val purpose = Consent.Purpose.of(intent.getStringExtra("purpose") ?: "link")!!
+ val text = Consent.stamp(purpose, intent.getStringExtra("docId"), challenge, payload, System.currentTimeMillis())
+ if (text == null) { log("consent: host REFUSED to stamp"); log("DONE"); return }
+ val info = BiometricPrompt.PromptInfo.Builder()
+ .setTitle("Link a new device?").setSubtitle("bento/connect probe")
+ .setAllowedAuthenticators(Authenticators.BIOMETRIC_STRONG or Authenticators.DEVICE_CREDENTIAL)
+ .build()
+ BiometricPrompt(this, ContextCompat.getMainExecutor(this), object : BiometricPrompt.AuthenticationCallback() {
+ override fun onAuthenticationSucceeded(result: BiometricPrompt.AuthenticationResult) {
+ val s = result.cryptoObject!!.signature!!
+ s.update(text.toByteArray(Charsets.UTF_8))
+ val sig = Ecdsa.lowS(Ecdsa.derToRaw(s.sign()))
+ log("CNS text=$text")
+ log("CNS sig=${Consent.b64uEnc(sig)}")
+ log("CNS consentPub=${Consent.b64uEnc(AgentKeys.publicRaw(AgentKeys.CONSENT))}")
+ log("CNS routinePub=${Consent.b64uEnc(AgentKeys.publicRaw(AgentKeys.ROUTINE))}")
+ log("DONE")
+ }
+ override fun onAuthenticationError(code: Int, err: CharSequence) { log("prompt error $code: $err"); log("DONE") }
+ }).authenticate(info, BiometricPrompt.CryptoObject(AgentKeys.consentSignature()))
+ }
+
+ /**
+ * Is each key still usable? Initialising a Signature needs no
+ * authentication, but throws KeyPermanentlyInvalidatedException for a key
+ * the platform invalidated — the enrolment tripwire, observed directly.
+ * "fresh" first deletes both keys and mints them anew.
+ */
+ private fun keyState() {
+ val ks = java.security.KeyStore.getInstance("AndroidKeyStore").apply { load(null) }
+ if (intent.getBooleanExtra("fresh", false)) { ks.deleteEntry(AgentKeys.ROUTINE); ks.deleteEntry(AgentKeys.CONSENT) }
+ try { AgentKeys.ensure(this) } catch (e: Exception) { log("ensure threw ${e.javaClass.simpleName}: ${e.message}") }
+ // POSITIVE CONTROL: a biometric-ONLY per-use key, which the platform
+ // documents as invalidated by a new enrolment. If this one never reads
+ // INVALIDATED either, the probe cannot see invalidation at all.
+ if (intent.getBooleanExtra("canary", false)) {
+ ks.deleteEntry("bento-probe-canary")
+ java.security.KeyPairGenerator.getInstance(android.security.keystore.KeyProperties.KEY_ALGORITHM_EC, "AndroidKeyStore").apply {
+ initialize(android.security.keystore.KeyGenParameterSpec.Builder("bento-probe-canary", android.security.keystore.KeyProperties.PURPOSE_SIGN)
+ .setAlgorithmParameterSpec(java.security.spec.ECGenParameterSpec("secp256r1"))
+ .setDigests(android.security.keystore.KeyProperties.DIGEST_SHA256)
+ .setUserAuthenticationRequired(true)
+ .setUserAuthenticationParameters(0, android.security.keystore.KeyProperties.AUTH_BIOMETRIC_STRONG)
+ .build())
+ }.generateKeyPair()
+ log("keystate: canary minted")
+ }
+ val bm = androidx.biometric.BiometricManager.from(this)
+ log("keystate: biometricStrong=${bm.canAuthenticate(Authenticators.BIOMETRIC_STRONG)} (0=enrolled)")
+ for (alias in listOf(AgentKeys.ROUTINE, AgentKeys.CONSENT, "bento-probe-canary")) {
+ val r = if (!ks.containsAlias(alias)) "ABSENT" else try {
+ Signature.getInstance("SHA256withECDSA").initSign(ks.getKey(alias, null) as java.security.PrivateKey); "usable"
+ } catch (e: android.security.keystore.KeyPermanentlyInvalidatedException) { "INVALIDATED" }
+ catch (e: Exception) { "error ${e.javaClass.simpleName}" }
+ log("keystate: $alias $r")
+ }
+ log("DONE"); finish()
+ }
+
+ /**
+ * The §29b gate on real keys. "fresh" deletes everything and starts a new
+ * identity; "accept" re-confirms. Logs the gate, the canary and the outbox.
+ */
+ private fun gateProbe() {
+ val ks = java.security.KeyStore.getInstance("AndroidKeyStore").apply { load(null) }
+ if (intent.getBooleanExtra("fresh", false)) {
+ for (a in listOf(AgentKeys.ROUTINE, AgentKeys.CONSENT, AgentKeys.CANARY)) ks.deleteEntry(a)
+ java.io.File(noBackupFilesDir, "identity").deleteRecursively()
+ }
+ AgentKeys.ensure(this)
+ val devices = setOf("devA", "devB", "devC")
+ if (intent.getBooleanExtra("accept", false)) log("gate: accept=${AgentKeys.acceptEnrolment(this)}")
+ log("gate: canary=${AgentKeys.canary()} biometrics=${AgentKeys.biometrics(this)}")
+ log("gate: ${AgentKeys.enrolmentGate(this, "devA", devices, System.currentTimeMillis())}")
+ val st = AgentKeys.store(this)
+ log("gate: outbox=${Notices.pending(st)?.map { it.kind + "->" + it.recipients.sorted() }}")
+ log("gate: record=${(st.get(Notices.ENROLMENT) as? Notices.Read.Found)?.text?.substringBefore('.')}")
+ log("DONE"); finish()
+ }
+
+ /** Verify a raw r‖s signature against the key's certificate, as a verifier elsewhere would. */
+ private fun verifyRaw(alias: String, raw: ByteArray): Boolean {
+ val ks = java.security.KeyStore.getInstance("AndroidKeyStore").apply { load(null) }
+ val pub = KeyFactory.getInstance("EC").generatePublic(X509EncodedKeySpec(ks.getCertificate(alias).publicKey.encoded))
+ fun int(b: ByteArray): ByteArray { var i = 0; while (i < b.size - 1 && b[i] == 0.toByte()) i++
+ var v = b.copyOfRange(i, b.size); if (v[0].toInt() and 0x80 != 0) v = byteArrayOf(0) + v
+ return byteArrayOf(0x02, v.size.toByte()) + v }
+ val body = int(raw.copyOfRange(0, 32)) + int(raw.copyOfRange(32, 64))
+ val der = byteArrayOf(0x30, body.size.toByte()) + body
+ return Signature.getInstance("SHA256withECDSA").run { initVerify(pub); update(msg); verify(der) }
+ }
+}
diff --git a/home/android/app/src/main/java/page/bento/home/AgentKeys.kt b/home/android/app/src/main/java/page/bento/home/AgentKeys.kt
new file mode 100644
index 00000000..1330d014
--- /dev/null
+++ b/home/android/app/src/main/java/page/bento/home/AgentKeys.kt
@@ -0,0 +1,263 @@
+// SPDX-License-Identifier: MIT
+// Copyright (c) 2026 The Bento authors
+
+package page.bento.home
+
+import android.content.Context
+import android.content.pm.PackageManager
+import android.os.Build
+import android.security.keystore.KeyGenParameterSpec
+import android.security.keystore.KeyInfo
+import android.security.keystore.KeyProperties
+import android.security.keystore.StrongBoxUnavailableException
+import java.math.BigInteger
+import java.security.KeyFactory
+import java.security.KeyPairGenerator
+import java.security.KeyStore
+import java.security.PrivateKey
+import java.security.Signature
+import java.security.interfaces.ECPublicKey
+import java.security.spec.ECGenParameterSpec
+
+/**
+ * The device's bento/connect keys (phase-1 plan A1). Two keys, because the Keystore
+ * attaches user authentication to a KEY, not to a call:
+ *
+ * - **routine** — signs edit batches and presence many times a minute; never
+ * prompts. TEE-backed, non-exportable.
+ * - **consent** — signs shares, role changes, revocations and device links;
+ * every use needs the person, through a BiometricPrompt that authorises THIS
+ * signature (a CryptoObject), so the prompt is cryptographic, not cosmetic.
+ * StrongBox where the device has one: slower, and only used rarely.
+ *
+ * Nothing here decides WHAT is signed. The consent statement — origin-bound,
+ * with bento's relying-party identity, the purpose, the docId and a channel
+ * binding (identity-design §2e (A)) — is kernel's K2 format and its vectors;
+ * this only produces raw signatures over the bytes it is given.
+ */
+object AgentKeys {
+ const val ROUTINE = "bento-agent-routine"
+ const val CONSENT = "bento-agent-consent"
+ /** Biometric-only, never signs: the enrolment tripwire (Notices, §29b). */
+ const val CANARY = "bento-agent-canary"
+
+ /** The agent's identity records (enrolment baseline, notice outbox, alerts). */
+ fun store(context: Context): Notices.Store = Notices.FileStore(java.io.File(context.noBackupFilesDir, "identity"))
+
+ private fun keystore() = KeyStore.getInstance("AndroidKeyStore").apply { load(null) }
+
+ /** Where a key actually lives, as the Keystore reports it — for the probe and logs. */
+ enum class Strength { STRONGBOX, TEE, SOFTWARE, UNKNOWN }
+
+ fun ensure(context: Context) {
+ val ks = keystore()
+ if (!ks.containsAlias(ROUTINE)) generate(ROUTINE, consent = false, strongBox = false)
+ // (Requires a secure lock screen: without one, generation throws and
+ // the caller reports no identity. A Bento ID key on a phone anyone can
+ // pick up and use would vouch for nobody.)
+ if (!ks.containsAlias(CONSENT)) {
+ // The canary and the enrolment baseline are made WITH the consent
+ // key, before any consent can run the gate: otherwise a brand-new
+ // identity reads "changed" and its first consent sends every device
+ // a false "biometrics changed" (home-ios hit exactly this).
+ val sb = Build.VERSION.SDK_INT >= 28 &&
+ context.packageManager.hasSystemFeature(PackageManager.FEATURE_STRONGBOX_KEYSTORE)
+ try {
+ try {
+ generate(CONSENT, consent = true, strongBox = sb)
+ } catch (e: StrongBoxUnavailableException) {
+ generate(CONSENT, consent = true, strongBox = false)
+ }
+ } catch (e: java.security.GeneralSecurityException) {
+ // API 26–29 has no per-use key that accepts the device PIN: with
+ // no enrolled biometric there is no consent key (security §29,
+ // option a). The routine key above still stands, so the device
+ // does everyday work. A later ensure() mints the consent key
+ // once a fingerprint is enrolled. From 30 on this is a real fault.
+ if (Build.VERSION.SDK_INT >= 30) throw e
+ }
+ if (ks.containsAlias(CONSENT)) {
+ val bio = biometrics(context)
+ // A canary that fails to mint, or a state the platform can't
+ // name, leaves no baseline: the first consent then reads
+ // CHANGED (or refuses) — never a baseline nothing backs.
+ if (bio == Notices.Biometrics.NONE || (bio == Notices.Biometrics.ENROLLED && remintCanary()))
+ Notices.recordEnrolment(bio == Notices.Biometrics.ENROLLED, generation(), store(context))
+ }
+ }
+ }
+
+ /** The platform's answer, mapped once. Anything unrecognised is UNKNOWN, which refuses. */
+ fun biometrics(context: Context): Notices.Biometrics =
+ when (androidx.biometric.BiometricManager.from(context)
+ .canAuthenticate(androidx.biometric.BiometricManager.Authenticators.BIOMETRIC_STRONG)) {
+ androidx.biometric.BiometricManager.BIOMETRIC_SUCCESS -> Notices.Biometrics.ENROLLED
+ androidx.biometric.BiometricManager.BIOMETRIC_ERROR_NONE_ENROLLED,
+ androidx.biometric.BiometricManager.BIOMETRIC_ERROR_NO_HARDWARE -> Notices.Biometrics.NONE
+ androidx.biometric.BiometricManager.BIOMETRIC_ERROR_HW_UNAVAILABLE -> Notices.Biometrics.SENSOR_BUSY
+ else -> Notices.Biometrics.UNKNOWN
+ }
+
+ /** Read the canary with initSign: no prompt, no signature. Invalidated by a new enrolment (measured). */
+ fun canary(): Notices.Canary = try {
+ val ks = keystore()
+ if (!ks.containsAlias(CANARY)) Notices.Canary.ABSENT
+ else { Signature.getInstance("SHA256withECDSA").initSign(ks.getKey(CANARY, null) as PrivateKey); Notices.Canary.USABLE }
+ } catch (e: android.security.keystore.KeyPermanentlyInvalidatedException) { Notices.Canary.INVALIDATED }
+ catch (e: Exception) { Notices.Canary.ERROR }
+
+ /** Replace the canary under the enrolment as it is now. Biometric-only and per-use, so any new enrolment voids it. */
+ fun remintCanary(): Boolean = try {
+ keystore().deleteEntry(CANARY)
+ val b = KeyGenParameterSpec.Builder(CANARY, KeyProperties.PURPOSE_SIGN)
+ .setAlgorithmParameterSpec(ECGenParameterSpec("secp256r1"))
+ .setDigests(KeyProperties.DIGEST_SHA256)
+ .setUserAuthenticationRequired(true)
+ .setInvalidatedByBiometricEnrollment(true)
+ if (Build.VERSION.SDK_INT >= 30) b.setUserAuthenticationParameters(0, KeyProperties.AUTH_BIOMETRIC_STRONG)
+ else @Suppress("DEPRECATION") b.setUserAuthenticationValidityDurationSeconds(-1)
+ KeyPairGenerator.getInstance(KeyProperties.KEY_ALGORITHM_EC, "AndroidKeyStore").apply { initialize(b.build()) }.generateKeyPair()
+ true
+ } catch (e: Exception) { false }
+
+ fun generation(): String = Consent.b64uEnc(ByteArray(12).also { java.security.SecureRandom().nextBytes(it) })
+
+ /**
+ * The gate before EVERY consent (§29b): the notice is queued first on a
+ * change. `devices` is the account's device list now.
+ */
+ fun enrolmentGate(context: Context, device: String, devices: Set<String>, now: Long): Notices.Gate =
+ Notices.enrolmentGate(biometrics(context), canary(), device, devices, now, store(context))
+
+ /** After re-confirmation: accept the new enrolment (only once its notice is queued) and re-mint the canary. */
+ fun acceptEnrolment(context: Context): Boolean {
+ return Notices.acceptEnrolment(biometrics(context), canary(), generation(), store(context)) { remintCanary() }
+ }
+
+ /** False on API 26–29 with no enrolled biometric: this device cannot consent. */
+ fun hasConsentKey(): Boolean = keystore().containsAlias(CONSENT)
+
+ private fun generate(alias: String, consent: Boolean, strongBox: Boolean) {
+ val b = KeyGenParameterSpec.Builder(alias, KeyProperties.PURPOSE_SIGN)
+ .setAlgorithmParameterSpec(ECGenParameterSpec("secp256r1"))
+ .setDigests(KeyProperties.DIGEST_SHA256)
+ if (!consent) {
+ // The HARDWARE floor of §2e (B): no device authentication in the
+ // overall period and the Keystore itself refuses, whatever the app
+ // believes. It is only a floor — a lock-screen unlock reopens it
+ // (measured), so the idle and overall timeouts proper are RoutineGate's.
+ b.setUserAuthenticationRequired(true)
+ if (Build.VERSION.SDK_INT >= 30) {
+ b.setUserAuthenticationParameters(RoutineGate.OVERALL_SECONDS,
+ KeyProperties.AUTH_BIOMETRIC_STRONG or KeyProperties.AUTH_DEVICE_CREDENTIAL)
+ } else {
+ @Suppress("DEPRECATION") b.setUserAuthenticationValidityDurationSeconds(RoutineGate.OVERALL_SECONDS)
+ }
+ // Enrolling a new fingerprint must not destroy the device's identity:
+ // the routine key carries no consent, and losing it would orphan every
+ // room this device is in. (Android 7+; the default would invalidate.)
+ b.setInvalidatedByBiometricEnrollment(false)
+ } else {
+ b.setUserAuthenticationRequired(true)
+ // Per-use: a BiometricPrompt must authorise each signature. On 30+
+ // the device PIN/pattern also qualifies; before 30 a 0-second
+ // per-use key accepts strong biometrics only (plan A1: per-use on
+ // 26–29, never a time window).
+ if (Build.VERSION.SDK_INT >= 30) {
+ b.setUserAuthenticationParameters(0,
+ KeyProperties.AUTH_BIOMETRIC_STRONG or KeyProperties.AUTH_DEVICE_CREDENTIAL)
+ } else {
+ @Suppress("DEPRECATION") b.setUserAuthenticationValidityDurationSeconds(-1)
+ }
+ }
+ if (strongBox && Build.VERSION.SDK_INT >= 28) b.setIsStrongBoxBacked(true)
+ KeyPairGenerator.getInstance(KeyProperties.KEY_ALGORITHM_EC, "AndroidKeyStore").apply {
+ initialize(b.build())
+ }.generateKeyPair()
+ }
+
+ fun strength(alias: String): Strength = try {
+ val key = keystore().getKey(alias, null) as PrivateKey
+ val info = KeyFactory.getInstance(key.algorithm, "AndroidKeyStore").getKeySpec(key, KeyInfo::class.java)
+ if (Build.VERSION.SDK_INT >= 31) when (info.securityLevel) {
+ KeyProperties.SECURITY_LEVEL_STRONGBOX -> Strength.STRONGBOX
+ KeyProperties.SECURITY_LEVEL_TRUSTED_ENVIRONMENT -> Strength.TEE
+ KeyProperties.SECURITY_LEVEL_SOFTWARE -> Strength.SOFTWARE
+ else -> Strength.UNKNOWN
+ } else @Suppress("DEPRECATION") if (info.isInsideSecureHardware) Strength.TEE else Strength.SOFTWARE
+ } catch (e: Exception) { Strength.UNKNOWN }
+
+ /** The public key as WebCrypto imports it with format "raw": 0x04 ‖ X ‖ Y (65 bytes). */
+ fun publicRaw(alias: String): ByteArray {
+ val pub = keystore().getCertificate(alias).publicKey as ECPublicKey
+ return byteArrayOf(4) + fixed(pub.w.affineX, 32) + fixed(pub.w.affineY, 32)
+ }
+
+ /** Sign with the routine key. Returns raw r ‖ s, as WebCrypto verifies. */
+ fun signRoutine(message: ByteArray): ByteArray {
+ val s = Signature.getInstance("SHA256withECDSA")
+ s.initSign(keystore().getKey(ROUTINE, null) as PrivateKey)
+ s.update(message)
+ return Ecdsa.lowS(Ecdsa.derToRaw(s.sign()))
+ }
+
+ /**
+ * A Signature over the consent key, initialised for ONE signing operation.
+ * Wrap it in a BiometricPrompt.CryptoObject; only after the prompt succeeds
+ * will `sign()` work, and then for that one operation.
+ */
+ fun consentSignature(): Signature = Signature.getInstance("SHA256withECDSA").apply {
+ initSign(keystore().getKey(CONSENT, null) as PrivateKey)
+ }
+
+ private fun fixed(n: BigInteger, len: Int): ByteArray {
+ val b = n.toByteArray()
+ return when {
+ b.size == len -> b
+ b.size > len -> b.copyOfRange(b.size - len, b.size) // drop the sign byte
+ else -> ByteArray(len - b.size) + b // left-pad
+ }
+ }
+}
+
+/** ECDSA signature encodings: the Keystore emits DER; WebCrypto wants raw r ‖ s. */
+object Ecdsa {
+ /**
+ * DER `SEQUENCE { INTEGER r, INTEGER s }` → 64-byte raw `r ‖ s` for P-256.
+ * Unconverted, a valid signature is rejected by WebCrypto as if tampered —
+ * the same silent failure Releases.kt guards against in the other direction.
+ */
+ fun derToRaw(der: ByteArray): ByteArray {
+ require(der.size >= 8 && der[0] == 0x30.toByte()) { "not a DER ECDSA signature" }
+ var i = 2
+ if (der[1].toInt() and 0x80 != 0) i = 2 + (der[1].toInt() and 0x7f) // long-form length
+ fun int(): ByteArray {
+ require(der[i] == 0x02.toByte()) { "expected INTEGER" }
+ val len = der[i + 1].toInt() and 0xff
+ val v = der.copyOfRange(i + 2, i + 2 + len)
+ i += 2 + len
+ val trimmed = v.dropWhile { it == 0.toByte() }.toByteArray()
+ require(trimmed.size <= 32) { "integer longer than 32 bytes" }
+ return ByteArray(32 - trimmed.size) + trimmed
+ }
+ return int() + int()
+ }
+
+ /** P-256's group order n. */
+ private val N = BigInteger("FFFFFFFF00000000FFFFFFFFFFFFFFFFBCE6FAADA7179E84F3B9CAC2FC632551", 16)
+ private val HALF_N = N.shiftRight(1)
+
+ /**
+ * Low-S normalisation (K1's SignResult contract): if s > n/2, replace it
+ * with n − s. Both verify; only the low one is accepted, so a signature
+ * cannot be re-minted into a second valid byte string by a third party.
+ * The Keystore does not normalise, so about half its signatures need this.
+ */
+ fun lowS(raw: ByteArray): ByteArray {
+ require(raw.size == 64) { "raw P-256 signature is 64 bytes" }
+ val s = BigInteger(1, raw.copyOfRange(32, 64))
+ if (s <= HALF_N) return raw
+ val t = N.subtract(s).toByteArray().let { if (it.size > 32) it.copyOfRange(it.size - 32, it.size) else it }
+ return raw.copyOfRange(0, 32) + ByteArray(32 - t.size) + t
+ }
+}
diff --git a/home/android/app/src/main/java/page/bento/home/Consent.kt b/home/android/app/src/main/java/page/bento/home/Consent.kt
new file mode 100644
index 00000000..0beb0339
--- /dev/null
+++ b/home/android/app/src/main/java/page/bento/home/Consent.kt
@@ -0,0 +1,118 @@
+// SPDX-License-Identifier: MIT
+// Copyright (c) 2026 The Bento authors
+
+package page.bento.home
+
+import java.security.MessageDigest
+import java.util.Base64
+
+/**
+ * The host-stamped consent statement (`cns.`, kernel/src/statements.ts) and the
+ * routine payload shapes, in Kotlin. kernel/fixtures/identity-v1.json is the
+ * contract: ConsentTest re-reads it, so this file can never drift from the
+ * reference without a failing test.
+ *
+ * Every field of a `cns.` is chosen HERE, never by the page (identity-design
+ * §2e (A)): the relying party is this app's, the docId is the one the host read
+ * from the file it opened, the audience is phase 1's only one (`dir`), and the
+ * transcript binds the verifier's challenge to the exact statement being
+ * authorised. A page asking for consent supplies only the statement and the
+ * challenge — so it cannot aim a signature at another verifier (relay), reuse
+ * one (replay: the challenge is single-use), or swap what it authorises.
+ */
+object Consent {
+ /** bento's relying-party identity in a `cns.` (a vault id when there is one). */
+ const val RP = "bento"
+ /** Phase 1's only consent audience: the directory (security §24). No relay change. */
+ const val AUDIENCE = "dir"
+ /** A consent is good for at most five minutes (CONSENT_MAX_TTL_MS); stamp two. */
+ const val TTL_MS = 2 * 60_000L
+
+ enum class Purpose(val word: String, val family: String, val docScoped: Boolean) {
+ INVITE("invite", "inv.", true),
+ REVOKE("revoke", "rev.", true),
+ LINK("link", "dev.", false),
+ ROTATE("rotate", "bind.", false),
+ UNBIND("unbind", "del.", false);
+ companion object { fun of(w: String) = values().firstOrNull { it.word == w } }
+ }
+
+ // ---- strict base64url ------------------------------------------------------
+
+ fun b64uEnc(b: ByteArray): String = Base64.getUrlEncoder().withoutPadding().encodeToString(b)
+
+ /** Canonical base64url only: alphabet, no padding, re-encodes to the same text. */
+ fun b64uDec(s: String): ByteArray? {
+ if (!B64U.matches(s) || s.length % 4 == 1) return null
+ val b = try { Base64.getUrlDecoder().decode(s) } catch (e: IllegalArgumentException) { return null }
+ return if (b64uEnc(b) == s) b else null
+ }
+ private val B64U = Regex("^[A-Za-z0-9_-]*$")
+
+ fun sha256b64u(text: String): String =
+ b64uEnc(MessageDigest.getInstance("SHA-256").digest(text.toByteArray(Charsets.UTF_8)))
+
+ // ---- the channel binding ---------------------------------------------------
+
+ private val ROOM = "w[A-Za-z0-9_-]{43}"
+ private val AUDIENCE_RE = Regex("^(dir|room:$ROOM)$")
+
+ /**
+ * b64u(SHA-256("cnst.v1." ‖ audience ‖ "." ‖ challenge ‖ "." ‖ b64u(SHA-256(payload)))),
+ * or null if the audience or challenge breaks its grammar.
+ */
+ fun transcript(audience: String, challenge: String, payloadText: String): String? {
+ if (!AUDIENCE_RE.matches(audience)) return null
+ val c = b64uDec(challenge) ?: return null
+ if (c.size < 16 || c.size > 64) return null
+ return sha256b64u("cnst.v1.$audience.$challenge.${sha256b64u(payloadText)}")
+ }
+
+ fun build(rp: String, purpose: Purpose, docId: String?, transcript: String, exp: Long): String =
+ listOf("cns", rp, purpose.word, docId ?: "", transcript, exp.toString()).joinToString(".")
+
+ private val DOC_ID = Regex("^[A-Za-z0-9_-]{1,128}$")
+
+ /**
+ * The statement this host will sign for a consent request, or null when the
+ * request does not hold together — the host refuses to stamp what a verifier
+ * would refuse to accept. `docId` is the HOST's: the one it read from the
+ * file it opened (DocumentOrigin.extractDocId), never one the page names.
+ */
+ fun stamp(purpose: Purpose, hostDocId: String?, challenge: String, payloadText: String, now: Long): String? {
+ if (!payloadText.startsWith(purpose.family)) return null
+ val docId = if (purpose.docScoped) hostDocId?.takeIf { DOC_ID.matches(it) } ?: return null else null
+ val t = transcript(AUDIENCE, challenge, payloadText) ?: return null
+ return build(RP, purpose, docId, t, now + TTL_MS)
+ }
+
+ // ---- routine signing: what payload each identity.ts SignPurpose may sign ---
+
+ private const val MAX_STATEMENT = 4096
+ private val INT = Regex("^(0|[1-9][0-9]{0,15})$")
+ private val PROVE_ROOM = Regex("^[rw][A-Za-z0-9_-]{1,64}$")
+ private fun len(f: String, min: Int, exact: Int? = null): Boolean {
+ val b = b64uDec(f) ?: return false
+ return if (exact == null) b.size >= min else b.size == exact
+ }
+ private fun pub(f: String): Boolean { val b = b64uDec(f); return b != null && b.size == 65 && b[0] == 4.toByte() }
+ private fun iv(f: String) = len(f, 0, 12)
+ private fun ct(f: String) = len(f, 16)
+
+ /** Does `payload` have the exact shape `purpose` names? Mirrors payloadMatchesPurpose. */
+ fun payloadMatchesPurpose(purpose: String, payload: String): Boolean {
+ if (payload.length > MAX_STATEMENT) return false
+ val p = payload.split(".") // Kotlin's split keeps empty fields, like JS
+ return when (purpose) {
+ "frame" -> p.size == 2 && iv(p[0]) && ct(p[1])
+ "prove" -> p.size == 3 && p[0] == "prove" && len(p[1], 16) && PROVE_ROOM.matches(p[2])
+ "delegate" -> p.size == 2 && p[0] == "dlg" && pub(p[1])
+ "show" -> (p.size == 1 && (p[0] == "live" || p[0] == "end")) ||
+ (p.size == 4 && (p[0] == "nav" || p[0] == "black") && p[1] == "aud" && iv(p[2]) && ct(p[3]))
+ "invite" -> p.size == 4 && p[0] == "inv" && pub(p[1]) &&
+ (p[2] == "writer" || p[2] == "commenter" || p[2] == "audience") && INT.matches(p[3])
+ "revoke" -> p.size == 2 && p[0] == "rev" && pub(p[1])
+ else -> false
+ }
+ }
+}
diff --git a/home/android/app/src/main/java/page/bento/home/Notices.kt b/home/android/app/src/main/java/page/bento/home/Notices.kt
new file mode 100644
index 00000000..bbbf850a
--- /dev/null
+++ b/home/android/app/src/main/java/page/bento/home/Notices.kt
@@ -0,0 +1,300 @@
+// SPDX-License-Identifier: MIT
+// Copyright (c) 2026 The Bento authors
+
+package page.bento.home
+
+import java.io.File
+
+/**
+ * The agent's security notices and its own checks (threat model §29, §29a,
+ * §29b), the Android twin of home/ios IdentityKeys.swift. Pure over a [Store],
+ * so every rule is a JVM test.
+ *
+ * - **The enrolment tripwire.** The consent key accepts the device PIN, and
+ * Android then does NOT invalidate it when a fingerprint is added (measured:
+ * only a biometric-ONLY key is). So a biometric-only CANARY key stands beside
+ * it, signs nothing, and is read with initSign before every consent: that
+ * throws KeyPermanentlyInvalidatedException with no prompt. A change sends
+ * "biometrics changed on <device>" to every device and the address, queued
+ * durably BEFORE the consent can go on, then asks for re-confirmation.
+ * - **Recipients are snapshotted when a notice is queued**: the devices listed
+ * then, plus the address. A device removed later still receives it and still
+ * holds it back. It never clears without the address. A silent device stops
+ * holding it back after 7 days, and only once the address has confirmed.
+ * - **A device-list change sends its own notice** to the list as it was BEFORE
+ * the change. The publisher may not publish until it is queued.
+ * - **Every device checks each fetched list itself** and raises a local alert
+ * if it, or a device it didn't remove, is gone — whatever the publisher did.
+ * The alert is written before the new list becomes the baseline.
+ */
+object Notices {
+
+ // ---- storage -----------------------------------------------------------------
+
+ sealed class Read {
+ class Found(val text: String) : Read()
+ object Absent : Read()
+ object Unavailable : Read()
+ }
+
+ interface Store {
+ fun get(name: String): Read
+ fun set(name: String, text: String): Boolean
+ }
+
+ /** The app's identity records, in no-backup storage, each written by atomic rename. */
+ class FileStore(private val dir: File) : Store {
+ private fun f(name: String) = File(dir, name.replace('/', '_'))
+ override fun get(name: String): Read = try {
+ val file = f(name)
+ if (!file.exists()) Read.Absent else Read.Found(file.readText())
+ } catch (e: Exception) { Read.Unavailable }
+ override fun set(name: String, text: String): Boolean = try {
+ dir.mkdirs()
+ val tmp = File(dir, f(name).name + ".tmp")
+ tmp.writeText(text)
+ tmp.renameTo(f(name))
+ } catch (e: Exception) { false }
+ }
+
+ // ---- the record format: tokens only, so nothing needs escaping ---------------
+
+ private val TOKEN = Regex("^[A-Za-z0-9_-]+$")
+ private fun tok(s: String) = s.also { require(TOKEN.matches(it)) { "not a token: $it" } }
+ private fun set(s: String): Set<String> = if (s.isEmpty()) emptySet() else s.split(",").toSet()
+ private fun join(s: Set<String>) = s.sorted().joinToString(",") { tok(it) }
+
+ data class Notice(
+ val kind: String,
+ val device: String,
+ /** which change it is about (a hash) */
+ val state: String,
+ val at: Long,
+ /** WHO it goes to, fixed when it was queued */
+ val recipients: Set<String>,
+ /** who has confirmed receiving it */
+ val deliveredTo: Set<String> = emptySet(),
+ ) {
+ fun line() = listOf(tok(kind), tok(device), tok(state), at.toString(), join(recipients), join(deliveredTo)).joinToString("\t")
+ companion object {
+ fun parse(l: String): Notice? {
+ val p = l.split("\t")
+ if (p.size != 6) return null
+ val at = p[3].toLongOrNull() ?: return null
+ return Notice(p[0], p[1], p[2], at, set(p[4]), set(p[5]))
+ }
+ }
+ }
+
+ private fun decode(text: String): List<Notice>? =
+ text.lines().filter { it.isNotEmpty() }.map { Notice.parse(it) ?: return null }
+
+ const val OUTBOX = "identity/notice-outbox"
+ const val ADDRESS = "address"
+ const val SILENT_DEVICE_TIMEOUT_MS = 7 * 86_400_000L
+
+ /** The notices still to deliver, or null if the outbox can't be read. */
+ fun pending(store: Store): List<Notice>? = when (val r = store.get(OUTBOX)) {
+ is Read.Found -> decode(r.text)
+ Read.Absent -> emptyList()
+ Read.Unavailable -> null
+ }
+
+ private fun save(l: List<Notice>, store: Store) = store.set(OUTBOX, l.joinToString("\n") { it.line() })
+
+ /** Everyone confirmed; or the address did and every silent device has timed out. Never without the address. */
+ fun isDone(n: Notice, now: Long): Boolean {
+ if (ADDRESS !in n.deliveredTo) return false
+ if (n.deliveredTo.containsAll(n.recipients)) return true
+ return now - n.at >= SILENT_DEVICE_TIMEOUT_MS
+ }
+
+ private fun queue(n: Notice, store: Store): Boolean {
+ val l = pending(store) ?: return false
+ if (l.any { it.state == n.state && it.kind == n.kind }) return true // idempotent per change
+ return save(l + n, store)
+ }
+
+ /** Counts only for a recipient in the notice's own snapshot (removed devices included). */
+ fun markDelivered(n: Notice, recipient: String, now: Long, store: Store): Boolean {
+ val l = pending(store)?.toMutableList() ?: return false
+ val i = l.indexOfFirst { it.state == n.state && it.device == n.device && it.kind == n.kind }
+ if (i < 0 || recipient !in l[i].recipients) return false
+ l[i] = l[i].copy(deliveredTo = l[i].deliveredTo + recipient)
+ return save(l.filterNot { isDone(it, now) }, store)
+ }
+
+ fun sweep(now: Long, store: Store): Boolean {
+ val l = pending(store) ?: return false
+ return save(l.filterNot { isDone(it, now) }, store)
+ }
+
+ // ---- the enrolment tripwire ----------------------------------------------------
+
+ enum class Enrolment { UNCHANGED, CHANGED, UNKNOWN }
+
+ /**
+ * What the platform says about enrolled biometrics. SENSOR_BUSY
+ * (HW_UNAVAILABLE) is often transient; under a "bio" record the canary — a
+ * Keystore check, no sensor needed — decides alone (security §29b). Under a
+ * "none" record it can't tell whether biometrics were added, so UNKNOWN.
+ */
+ enum class Biometrics { ENROLLED, NONE, SENSOR_BUSY, UNKNOWN }
+
+ /** What the Keystore says about the canary, read with initSign: never a prompt, never a signature. */
+ enum class Canary { USABLE, INVALIDATED, ABSENT, ERROR }
+
+ const val ENROLMENT = "identity/enrolment"
+
+ /**
+ * The record is "bio.<generation>" (a canary was minted under the enrolment
+ * then) or "none.<generation>" (no biometrics then). A new generation is
+ * chosen at every acceptance, so successive changes are distinct notices.
+ */
+ fun check(record: Read, bio: Biometrics, canary: Canary): Enrolment {
+ if (canary == Canary.ERROR || bio == Biometrics.UNKNOWN) return Enrolment.UNKNOWN
+ val r = when (record) {
+ is Read.Found -> record.text
+ Read.Absent -> return Enrolment.CHANGED // made before the check: re-confirm once
+ Read.Unavailable -> return Enrolment.UNKNOWN
+ }
+ return when {
+ r.startsWith("bio.") -> when {
+ bio == Biometrics.NONE -> Enrolment.CHANGED
+ canary == Canary.USABLE -> Enrolment.UNCHANGED // ENROLLED, or SENSOR_BUSY: the canary alone
+ else -> Enrolment.CHANGED
+ }
+ r.startsWith("none.") -> when (bio) {
+ Biometrics.NONE -> Enrolment.UNCHANGED
+ Biometrics.ENROLLED -> Enrolment.CHANGED
+ else -> Enrolment.UNKNOWN // SENSOR_BUSY: were biometrics added? can't tell
+ }
+ else -> Enrolment.UNKNOWN
+ }
+ }
+
+ /** Which change this is: the record it departs from, and what was observed. */
+ fun changeTag(record: Read, bio: Biometrics, canary: Canary): String {
+ val from = (record as? Read.Found)?.text ?: "-"
+ // SENSOR_BUSY under a "bio" record is decided by the canary: tag it as ENROLLED,
+ // so a busy sensor and a ready one name the same change.
+ val seen = if (bio == Biometrics.NONE) "none" else "bio"
+ return Consent.sha256b64u("enrol.$from>$seen.${canary.name}")
+ }
+
+ enum class Gate { PROCEED, RECONFIRM, REFUSE }
+
+ /**
+ * Run before EVERY consent. On a change the notice is written to the durable
+ * outbox FIRST, whether the consent then completes or is cancelled; a
+ * restart neither drops nor repeats it. Nothing here takes input from the
+ * page. `devices` is the account's device list now, snapshotted with the address.
+ */
+ fun enrolmentGate(bio: Biometrics, canary: Canary, device: String, devices: Set<String>, now: Long, store: Store): Gate {
+ val record = store.get(ENROLMENT)
+ return when (check(record, bio, canary)) {
+ Enrolment.UNCHANGED -> Gate.PROCEED
+ Enrolment.UNKNOWN -> Gate.REFUSE
+ Enrolment.CHANGED -> {
+ val n = Notice("biometrics-changed", device, changeTag(record, bio, canary), now, devices + ADDRESS)
+ if (queue(n, store)) Gate.RECONFIRM else Gate.REFUSE
+ }
+ }
+ }
+
+ /**
+ * After the person re-confirmed a consent under a changed enrolment. Refused
+ * unless that change's notice is durably queued: the protection is the
+ * NOTICE (someone who added their own finger re-confirms trivially).
+ * `remint` replaces the canary under the enrolment as it is now and returns
+ * true, or false if it couldn't; with no biometrics it mints nothing.
+ */
+ fun acceptEnrolment(bio: Biometrics, canary: Canary, generation: String, store: Store, remint: () -> Boolean): Boolean {
+ // a new baseline is only ever recorded under a state the platform could name
+ if (bio != Biometrics.ENROLLED && bio != Biometrics.NONE) return false
+ val biometricsNow = bio == Biometrics.ENROLLED
+ val record = store.get(ENROLMENT)
+ val tag = changeTag(record, bio, canary)
+ if (pending(store)?.any { it.kind == "biometrics-changed" && it.state == tag } != true) return false
+ if (biometricsNow && !remint()) return false
+ return store.set(ENROLMENT, (if (biometricsNow) "bio." else "none.") + tok(generation))
+ }
+
+ /** At consent-key creation: the enrolment it was born under (the canary is minted with it). */
+ fun recordEnrolment(biometricsNow: Boolean, generation: String, store: Store): Boolean =
+ store.set(ENROLMENT, (if (biometricsNow) "bio." else "none.") + tok(generation))
+
+ // ---- a device-list change's own notice -------------------------------------------
+
+ private fun listTag(before: Set<String>, after: Set<String>) =
+ Consent.sha256b64u("devices.${before.sorted().joinToString(",")}>${after.sorted().joinToString(",")}")
+
+ /** Queue the notice for a device-list change, to the list BEFORE it. Idempotent per change. */
+ fun queueDeviceListChange(before: Set<String>, after: Set<String>, by: String, now: Long, store: Store): Boolean {
+ if (before == after) return true
+ return queue(Notice("devices-changed", by, listTag(before, after), now, before + ADDRESS), store)
+ }
+
+ /** True only once the notice for exactly this change is durably queued. */
+ fun mayPublishDeviceList(before: Set<String>, after: Set<String>, store: Store): Boolean {
+ if (before == after) return true
+ val tag = listTag(before, after)
+ return pending(store)?.any { it.kind == "devices-changed" && it.state == tag } ?: false
+ }
+
+ // ---- the receiver's own check ---------------------------------------------------
+
+ data class Alert(val kind: String, val device: String, val by: String, val at: Long) {
+ fun line() = listOf(tok(kind), tok(device), tok(by), at.toString()).joinToString("\t")
+ }
+
+ const val LAST_LIST = "identity/last-device-list"
+ const val ALERTS = "identity/local-alerts"
+
+ /**
+ * Run on every fetch of the synced device list. Returns the alerts raised, or
+ * null if the check couldn't be made; the caller must then not treat the list
+ * as checked. `removedHere` is what this device itself removed.
+ */
+ fun observeDeviceList(current: Set<String>, signedBy: String, me: String, removedHere: Set<String>, now: Long, store: Store): List<Alert>? {
+ val last: Set<String>? = when (val r = store.get(LAST_LIST)) {
+ is Read.Found -> {
+ if (r.text.isNotEmpty() && r.text.split(",").any { !TOKEN.matches(it) }) {
+ raise(listOf(Alert("unknown", me, signedBy, now)), store) // never adopt a list blind
+ return null
+ }
+ set(r.text)
+ }
+ Read.Absent -> null // the first fetch sets the baseline
+ Read.Unavailable -> return null
+ }
+ val alerts = mutableListOf<Alert>()
+ if (last != null) {
+ if (me in last && me !in current) alerts += Alert("this-device-removed", me, signedBy, now)
+ for (gone in (last - current - me - removedHere).sorted()) alerts += Alert("device-removed", gone, signedBy, now)
+ }
+ // the alert first, then the new baseline
+ if (alerts.isNotEmpty() && !raise(alerts, store)) return null
+ if (!store.set(LAST_LIST, join(current))) return null
+ return alerts
+ }
+
+ private fun raise(new: List<Alert>, store: Store): Boolean {
+ val prior = when (val r = store.get(ALERTS)) {
+ is Read.Found -> r.text.lines().filter { it.isNotEmpty() }
+ Read.Absent -> emptyList()
+ Read.Unavailable -> return false
+ }
+ return store.set(ALERTS, (prior + new.map { it.line() }).joinToString("\n"))
+ }
+
+ /** The alerts raised and not yet shown and dismissed, or null if unreadable. */
+ fun localAlerts(store: Store): List<Alert>? = when (val r = store.get(ALERTS)) {
+ is Read.Found -> r.text.lines().filter { it.isNotEmpty() }.map {
+ val p = it.split("\t"); if (p.size != 4) return null
+ Alert(p[0], p[1], p[2], p[3].toLongOrNull() ?: return null)
+ }
+ Read.Absent -> emptyList()
+ Read.Unavailable -> null
+ }
+}
diff --git a/home/android/app/src/main/java/page/bento/home/RoutineGate.kt b/home/android/app/src/main/java/page/bento/home/RoutineGate.kt
new file mode 100644
index 00000000..235c5970
--- /dev/null
+++ b/home/android/app/src/main/java/page/bento/home/RoutineGate.kt
@@ -0,0 +1,50 @@
+// SPDX-License-Identifier: MIT
+// Copyright (c) 2026 The Bento authors
+
+package page.bento.home
+
+/**
+ * The session around the ROUTINE key (identity-design §2e (B)): past the idle
+ * or the overall timeout the agent refuses even routine signatures — `reauth`
+ * in the identity contract — until the person authenticates again.
+ *
+ * Two layers, each enforcing a different bound:
+ * - the Keystore's validity window on the key (AgentKeys) is the HARDWARE
+ * floor: no device authentication in OVERALL_SECONDS and the key will not
+ * sign. A lock-screen unlock reopens it, so it means "since the device was
+ * last unlocked", never "since Bento was last used";
+ * - this gate is "since Bento was last used": idle since the last routine
+ * signature, overall since the person last authenticated TO BENTO.
+ *
+ * Pure and clock-injected so the rules are testable on the JVM. Defaults are
+ * the AAL2 SHOULDs; an organisation may tighten them (AAL3: 15 min / 12 h),
+ * never loosen them.
+ */
+class RoutineGate(
+ private val idleMs: Long = IDLE_SECONDS * 1000L,
+ private val overallMs: Long = OVERALL_SECONDS * 1000L,
+) {
+ init { require(idleMs in 1..IDLE_SECONDS * 1000L && overallMs in 1..OVERALL_SECONDS * 1000L) { "timeouts may only tighten" } }
+
+ private var authenticatedAt = -1L
+ private var lastUse = -1L
+
+ /** The person just authenticated to Bento (a BiometricPrompt that succeeded). */
+ fun authenticated(now: Long) { authenticatedAt = now; lastUse = now }
+
+ /** May the routine key sign now? A yes counts as use and refreshes the idle clock. */
+ fun allow(now: Long): Boolean {
+ if (authenticatedAt < 0) return false
+ if (now < lastUse || now < authenticatedAt) { lock(); return false } // clock went backwards: fail closed
+ if (now - lastUse >= idleMs || now - authenticatedAt >= overallMs) { lock(); return false }
+ lastUse = now
+ return true
+ }
+
+ fun lock() { authenticatedAt = -1L; lastUse = -1L }
+
+ companion object {
+ const val IDLE_SECONDS = 60 * 60
+ const val OVERALL_SECONDS = 24 * 60 * 60
+ }
+}
diff --git a/home/android/app/src/test/java/page/bento/home/ConsentTest.kt b/home/android/app/src/test/java/page/bento/home/ConsentTest.kt
new file mode 100644
index 00000000..dd6e446f
--- /dev/null
+++ b/home/android/app/src/test/java/page/bento/home/ConsentTest.kt
@@ -0,0 +1,166 @@
+// SPDX-License-Identifier: MIT
+// Copyright (c) 2026 The Bento authors
+
+package page.bento.home
+
+import com.google.gson.JsonObject
+import com.google.gson.JsonParser
+import org.junit.Assert.assertEquals
+import org.junit.Assert.assertFalse
+import org.junit.Assert.assertNotNull
+import org.junit.Assert.assertNull
+import org.junit.Assert.assertTrue
+import org.junit.Test
+import java.io.File
+import java.math.BigInteger
+import java.security.KeyFactory
+import java.security.Signature
+import java.security.spec.ECGenParameterSpec
+import java.security.spec.ECParameterSpec
+import java.security.spec.ECPoint
+import java.security.spec.ECPublicKeySpec
+import java.security.AlgorithmParameters
+
+/**
+ * Consent.kt against kernel/fixtures/identity-v1.json — RE-READ every run, never
+ * pinned, so a regenerated fixture is still the contract.
+ *
+ * The verifier below is a test-side port of statements.ts verifyConsent. Its
+ * job is to show that the bytes THIS host stamps are the bytes the reference
+ * verifies: every cns row reaches its stated verdict through Consent's own
+ * transcript and encoding, and every accepted row's text is rebuilt exactly by
+ * Consent.build.
+ */
+class ConsentTest {
+ private val fx: JsonObject = JsonParser.parseString(
+ File("../../../kernel/fixtures/identity-v1.json").readText()).asJsonObject
+
+ private fun JsonObject.str(k: String): String? = get(k)?.takeIf { !it.isJsonNull }?.asString
+
+ // --- a raw r‖s, low-S P-256 verifier (what K2's verifyStatementSig does) ---
+
+ private val n = BigInteger("FFFFFFFF00000000FFFFFFFFFFFFFFFFBCE6FAADA7179E84F3B9CAC2FC632551", 16)
+ private val p256: ECParameterSpec = AlgorithmParameters.getInstance("EC").run {
+ init(ECGenParameterSpec("secp256r1")); getParameterSpec(ECParameterSpec::class.java) }
+
+ private fun verifySig(pubB64: String, sigB64: String, text: String): Boolean {
+ val pub = Consent.b64uDec(pubB64) ?: return false
+ val sig = Consent.b64uDec(sigB64) ?: return false
+ if (pub.size != 65 || pub[0] != 4.toByte() || sig.size != 64) return false
+ val r = BigInteger(1, sig.copyOfRange(0, 32)); val s = BigInteger(1, sig.copyOfRange(32, 64))
+ if (r.signum() == 0 || s.signum() == 0 || r >= n || s > n.shiftRight(1)) return false // low-S only
+ val key = KeyFactory.getInstance("EC").generatePublic(ECPublicKeySpec(
+ ECPoint(BigInteger(1, pub.copyOfRange(1, 33)), BigInteger(1, pub.copyOfRange(33, 65))), p256))
+ fun int(v: BigInteger): ByteArray { val b = v.toByteArray(); return byteArrayOf(2, b.size.toByte()) + b }
+ val body = int(r) + int(s)
+ return try {
+ Signature.getInstance("SHA256withECDSA").run { initVerify(key); update(text.toByteArray()); verify(byteArrayOf(0x30, body.size.toByte()) + body) }
+ } catch (e: Exception) { false }
+ }
+
+ private val RP_RE = Regex("^(bento|vault-[a-z0-9][a-z0-9-]{0,62})$")
+ private val DOCID_RE = Regex("^[A-Za-z0-9_-]{1,128}$")
+
+ private fun verifyConsent(row: JsonObject, consentPub: String, now: Long): String? {
+ val text = row.str("text")!!
+ if (text.isEmpty() || text.length > 4096 || text.any { it.code < 0x21 || it.code > 0x7e }) return "grammar"
+ val p = text.split(".")
+ if (p.size != 6 || p[0] != "cns") return "grammar"
+ if (row.get("challengeSpent")?.asBoolean == true) return "replay"
+ val (_, rp, purposeF, docIdF, transcript, expF) = p
+ if (!RP_RE.matches(rp) || Consent.b64uDec(transcript)?.size != 32) return "grammar"
+ if (purposeF == "grant" || purposeF == "role") return "reserved-purpose"
+ val purpose = Consent.Purpose.of(purposeF) ?: return "grammar"
+ val exp = expF.takeIf { Regex("^(0|[1-9][0-9]{0,15})$").matches(it) }?.toLong()?.takeIf { it > 0 } ?: return "grammar"
+ if (rp != row.str("rp")) return "rp"
+ val payload = row.str("payloadText")!!
+ if (!payload.startsWith(purpose.family)) return "payload-family"
+ val docId = row.str("docId")
+ if (purpose.docScoped) { if (!DOCID_RE.matches(docIdF) || docIdF != docId) return "docid" }
+ else if (docIdF != "" || docId != null) return "docid"
+ val expected = Consent.transcript(row.str("audience")!!, row.str("challenge")!!, payload)
+ if (expected == null || transcript != expected) return "transcript"
+ if (now >= exp) return "expired"
+ if (exp - now > 5 * 60_000) return "lifetime"
+ if (!verifySig(consentPub, row.str("sig")!!, text)) return "signature"
+ return null
+ }
+ private operator fun <T> List<T>.component6() = this[5]
+
+ @Test fun `every cns row reaches its stated verdict`() {
+ val now = fx.get("now").asLong
+ val consentPub = fx.getAsJsonObject("keys").str("consent")!!
+ val rows = fx.getAsJsonArray("statements").map { it.asJsonObject }.filter { it.str("type") == "cns" }
+ assertTrue("the fixture has cns rows", rows.size >= 10)
+ val seen = mutableSetOf<String>()
+ for (row in rows) {
+ val reason = verifyConsent(row, consentPub, row.get("now")?.asLong ?: now)
+ val name = row.str("name")
+ if (row.str("expect") == "accept") assertNull("$name: accepted by the reference, refused here ($reason)", reason)
+ else {
+ assertNotNull("$name: refused by the reference, accepted here", reason)
+ assertEquals("$name: reason", row.str("reason"), reason)
+ seen += reason!!
+ }
+ }
+ // security's run-it check for A1: relayed and replayed consents are REJECTED
+ assertTrue("the fixture exercises replay", "replay" in seen)
+ assertTrue("the fixture exercises relay (transcript)", "transcript" in seen)
+ }
+
+ @Test fun `the host stamps byte-identical statements for every accepted row`() {
+ val rows = fx.getAsJsonArray("statements").map { it.asJsonObject }
+ .filter { it.str("type") == "cns" && it.str("expect") == "accept" }
+ assertTrue(rows.isNotEmpty())
+ for (row in rows) {
+ val p = row.str("text")!!.split(".")
+ val t = Consent.transcript(row.str("audience")!!, row.str("challenge")!!, row.str("payloadText")!!)!!
+ val rebuilt = Consent.build(p[1], Consent.Purpose.of(p[2])!!, row.str("docId"), t, p[5].toLong())
+ assertEquals(row.str("name"), row.str("text"), rebuilt)
+ }
+ }
+
+ @Test fun `transcripts, including the refusals`() {
+ for (r in fx.getAsJsonArray("transcripts").map { it.asJsonObject })
+ assertEquals(r.toString(), r.str("transcript"),
+ Consent.transcript(r.str("audience")!!, r.str("challenge")!!, r.str("payload")!!))
+ }
+
+ @Test fun `routine purposes match exactly the payloads the reference matches`() {
+ for (r in fx.getAsJsonArray("purposes").map { it.asJsonObject })
+ assertEquals(r.toString(), r.get("match").asBoolean, Consent.payloadMatchesPurpose(r.str("purpose")!!, r.str("payload")!!))
+ }
+
+ @Test fun `low-S - the signer folds every high-S signature to the low one`() {
+ for (r in fx.getAsJsonArray("lowS").map { it.asJsonObject }) {
+ val low = Consent.b64uDec(r.str("low")!!)!!; val high = Consent.b64uDec(r.str("high")!!)!!
+ assertEquals(Consent.b64uEnc(low), Consent.b64uEnc(Ecdsa.lowS(high)))
+ assertEquals(Consent.b64uEnc(low), Consent.b64uEnc(Ecdsa.lowS(low)))
+ }
+ }
+
+ // --- stamping: what the host refuses to sign, whatever the page asks --------
+
+ private val challenge = "Aw4ZJC86RVBbZnF8h5KdqLO-ydTf6vUA"
+
+ @Test fun `stamp fixes the rp, the audience and a short expiry`() {
+ val text = Consent.stamp(Consent.Purpose.LINK, null, challenge, "dev.x", 1_000)!!
+ val p = text.split(".")
+ assertEquals(listOf("cns", "bento", "link", ""), p.subList(0, 4))
+ assertEquals(Consent.transcript("dir", challenge, "dev.x"), p[4])
+ assertEquals("1000${""}".toLong() + Consent.TTL_MS, p[5].toLong())
+ assertTrue(Consent.TTL_MS <= 5 * 60_000)
+ }
+
+ @Test fun `stamp refuses a mismatched family, a missing docId and a bad challenge`() {
+ assertNull("link over an inv. payload", Consent.stamp(Consent.Purpose.LINK, null, challenge, "inv.x", 0))
+ assertNull("invite with no host docId", Consent.stamp(Consent.Purpose.INVITE, null, challenge, "inv.x", 0))
+ assertNull("invite with a malformed docId", Consent.stamp(Consent.Purpose.INVITE, "a.b", challenge, "inv.x", 0))
+ assertNull("short challenge", Consent.stamp(Consent.Purpose.LINK, null, "AAAAAAAAAAA", "dev.x", 0))
+ assertNull("padded challenge", Consent.stamp(Consent.Purpose.LINK, null, "$challenge=", "dev.x", 0))
+ val inv = Consent.stamp(Consent.Purpose.INVITE, "doc-abc_123", challenge, "inv.x", 0)!!
+ assertEquals("doc-abc_123", inv.split(".")[3])
+ assertFalse("account-scoped purposes never carry the docId",
+ Consent.stamp(Consent.Purpose.LINK, "doc-abc_123", challenge, "dev.x", 0)!!.contains("doc-abc_123"))
+ }
+}
diff --git a/home/android/app/src/test/java/page/bento/home/EcdsaTest.kt b/home/android/app/src/test/java/page/bento/home/EcdsaTest.kt
new file mode 100644
index 00000000..86ca9c4b
--- /dev/null
+++ b/home/android/app/src/test/java/page/bento/home/EcdsaTest.kt
@@ -0,0 +1,75 @@
+// SPDX-License-Identifier: MIT
+// Copyright (c) 2026 The Bento authors
+
+package page.bento.home
+
+import org.junit.Assert.assertArrayEquals
+import org.junit.Assert.assertEquals
+import org.junit.Assert.assertTrue
+import org.junit.Test
+import java.security.KeyPairGenerator
+import java.security.Signature
+import java.security.spec.ECGenParameterSpec
+
+/**
+ * DER → raw conversion for the agent's signatures. Real signatures from the
+ * JVM's own ECDSA (DER, like the Keystore's) are converted and must verify
+ * again after converting back — and must be exactly 64 bytes, including the
+ * cases where r or s has a leading zero (31 bytes) or a sign byte (33 bytes),
+ * which a sloppy conversion gets wrong about one time in 256.
+ */
+class EcdsaTest {
+ private fun rawToDer(raw: ByteArray): ByteArray {
+ fun int(b: ByteArray): ByteArray {
+ var i = 0
+ while (i < b.size - 1 && b[i] == 0.toByte()) i++
+ var v = b.copyOfRange(i, b.size)
+ if (v[0].toInt() and 0x80 != 0) v = byteArrayOf(0) + v
+ return byteArrayOf(0x02, v.size.toByte()) + v
+ }
+ val body = int(raw.copyOfRange(0, 32)) + int(raw.copyOfRange(32, 64))
+ return byteArrayOf(0x30, body.size.toByte()) + body
+ }
+
+ @Test fun `two thousand real signatures convert to 64 bytes and verify both ways`() {
+ val kp = KeyPairGenerator.getInstance("EC").apply { initialize(ECGenParameterSpec("secp256r1")) }.generateKeyPair()
+ var sawShort = false; var sawSignByte = false
+ repeat(2000) { n ->
+ val msg = "message $n".toByteArray()
+ val der = Signature.getInstance("SHA256withECDSA").run { initSign(kp.private); update(msg); sign() }
+ val rLen = der[3].toInt(); val sLen = der[5 + rLen].toInt()
+ if (rLen < 32 || sLen < 32) sawShort = true
+ if (rLen == 33 || sLen == 33) sawSignByte = true
+ val raw = Ecdsa.derToRaw(der)
+ assertEquals(64, raw.size)
+ val ok = Signature.getInstance("SHA256withECDSA").run { initVerify(kp.public); update(msg); verify(rawToDer(raw)) }
+ assertTrue("signature $n must verify after DER→raw→DER", ok)
+ }
+ assertTrue("the run must include a short integer (leading zero dropped)", sawShort)
+ assertTrue("the run must include a sign-byte integer (33 bytes)", sawSignByte)
+ }
+
+ @Test fun `low-S normalisation keeps the signature valid and always lands at or below n over 2`() {
+ val n = java.math.BigInteger("FFFFFFFF00000000FFFFFFFFFFFFFFFFBCE6FAADA7179E84F3B9CAC2FC632551", 16)
+ val kp = KeyPairGenerator.getInstance("EC").apply { initialize(ECGenParameterSpec("secp256r1")) }.generateKeyPair()
+ var flipped = 0
+ repeat(500) { k ->
+ val msg = "low-s $k".toByteArray()
+ val raw = Ecdsa.derToRaw(Signature.getInstance("SHA256withECDSA").run { initSign(kp.private); update(msg); sign() })
+ val low = Ecdsa.lowS(raw)
+ val s = java.math.BigInteger(1, low.copyOfRange(32, 64))
+ assertTrue("s must be low", s <= n.shiftRight(1))
+ if (!low.contentEquals(raw)) flipped++
+ val ok = Signature.getInstance("SHA256withECDSA").run { initVerify(kp.public); update(msg); verify(rawToDer(low)) }
+ assertTrue("normalised signature $k must still verify", ok)
+ assertArrayEquals("normalising twice changes nothing", low, Ecdsa.lowS(low))
+ }
+ assertTrue("about half need flipping; got $flipped of 500", flipped in 150..350)
+ }
+
+ @Test fun `a hand-built signature with a short r is left-padded`() {
+ val r = ByteArray(31) { 0x11 }; val s = ByteArray(32) { 0x7f }
+ val der = byteArrayOf(0x30, (2 + 31 + 2 + 32).toByte(), 0x02, 31) + r + byteArrayOf(0x02, 32) + s
+ assertArrayEquals(byteArrayOf(0) + r + s, Ecdsa.derToRaw(der))
+ }
+}
diff --git a/home/android/app/src/test/java/page/bento/home/NoticesTest.kt b/home/android/app/src/test/java/page/bento/home/NoticesTest.kt
new file mode 100644
index 00000000..cc165e2c
--- /dev/null
+++ b/home/android/app/src/test/java/page/bento/home/NoticesTest.kt
@@ -0,0 +1,234 @@
+// SPDX-License-Identifier: MIT
+// Copyright (c) 2026 The Bento authors
+
+package page.bento.home
+
+import org.junit.Assert.assertEquals
+import org.junit.Assert.assertFalse
+import org.junit.Assert.assertNull
+import org.junit.Assert.assertTrue
+import org.junit.Test
+import page.bento.home.Notices.Canary
+import page.bento.home.Notices.Enrolment
+import page.bento.home.Notices.Gate
+import page.bento.home.Notices.Read
+import page.bento.home.Notices.Biometrics
+
+/**
+ * Threat model §29 / §29a / §29b, the same cases as home/ios's
+ * test-home-id-keys.mjs, against Notices.kt. The store is in memory; a
+ * "restart" is a fresh read of the same map, and a blind store refuses reads.
+ */
+class NoticesTest {
+ private class Mem(var blind: Boolean = false) : Notices.Store {
+ val m = HashMap<String, String>()
+ override fun get(name: String): Read = if (blind) Read.Unavailable else m[name]?.let { Read.Found(it) } ?: Read.Absent
+ override fun set(name: String, text: String): Boolean { if (blind) return false; m[name] = text; return true }
+ }
+ private val day = 86_400_000L
+ private val me = "devA"
+ private val list = setOf("devA", "devB", "devC")
+
+ // ---- the tripwire ----
+
+ @Test fun `the enrolment the consent key was made under reads unchanged`() {
+ val s = Mem(); Notices.recordEnrolment(true, "g1", s)
+ assertEquals(Enrolment.UNCHANGED, Notices.check(s.get(Notices.ENROLMENT), Biometrics.ENROLLED, Canary.USABLE))
+ }
+
+ @Test fun `a new finger invalidates the canary - CHANGED`() {
+ val s = Mem(); Notices.recordEnrolment(true, "g1", s)
+ assertEquals(Enrolment.CHANGED, Notices.check(s.get(Notices.ENROLMENT), Biometrics.ENROLLED, Canary.INVALIDATED))
+ assertEquals("a missing canary is a change too", Enrolment.CHANGED, Notices.check(s.get(Notices.ENROLMENT), Biometrics.ENROLLED, Canary.ABSENT))
+ }
+
+ @Test fun `biometrics removed, or gained where there were none, is CHANGED`() {
+ val s = Mem(); Notices.recordEnrolment(true, "g1", s)
+ assertEquals(Enrolment.CHANGED, Notices.check(s.get(Notices.ENROLMENT), Biometrics.NONE, Canary.USABLE))
+ Notices.recordEnrolment(false, "g2", s)
+ assertEquals(Enrolment.UNCHANGED, Notices.check(s.get(Notices.ENROLMENT), Biometrics.NONE, Canary.ABSENT))
+ assertEquals(Enrolment.CHANGED, Notices.check(s.get(Notices.ENROLMENT), Biometrics.ENROLLED, Canary.ABSENT))
+ }
+
+ @Test fun `no record is CHANGED once, an unreadable record or a Keystore error is UNKNOWN`() {
+ assertEquals(Enrolment.CHANGED, Notices.check(Read.Absent, Biometrics.ENROLLED, Canary.USABLE))
+ assertEquals(Enrolment.UNKNOWN, Notices.check(Read.Unavailable, Biometrics.ENROLLED, Canary.USABLE))
+ assertEquals(Enrolment.UNKNOWN, Notices.check(Read.Found("bio.g1"), Biometrics.ENROLLED, Canary.ERROR))
+ assertEquals(Enrolment.UNKNOWN, Notices.check(Read.Found("garbage"), Biometrics.ENROLLED, Canary.USABLE))
+ }
+
+ // ---- the notice comes first ----
+
+ @Test fun `an unchanged enrolment proceeds and queues nothing`() {
+ val s = Mem(); Notices.recordEnrolment(true, "g1", s)
+ assertEquals(Gate.PROCEED, Notices.enrolmentGate(Biometrics.ENROLLED, Canary.USABLE, me, list, 0, s))
+ assertEquals(0, Notices.pending(s)!!.size)
+ }
+
+ @Test fun `a third finger - the notice is queued BEFORE re-confirmation, and survives a kill`() {
+ val s = Mem(); Notices.recordEnrolment(true, "g1", s)
+ assertFalse("cannot be accepted before its notice is queued",
+ Notices.acceptEnrolment(Biometrics.ENROLLED, Canary.INVALIDATED, "g2", s) { true })
+ assertEquals(Gate.RECONFIRM, Notices.enrolmentGate(Biometrics.ENROLLED, Canary.INVALIDATED, me, list, 0, s))
+ val q = Notices.pending(s)!!
+ assertEquals(1, q.size); assertEquals("biometrics-changed", q[0].kind)
+ // killed here, before acceptance: a restart reads the same store
+ val restarted = Mem().also { it.m.putAll(s.m) }
+ assertEquals("still queued after the kill", 1, Notices.pending(restarted)!!.size)
+ assertEquals("and still not accepted", Enrolment.CHANGED,
+ Notices.check(restarted.get(Notices.ENROLMENT), Biometrics.ENROLLED, Canary.INVALIDATED))
+ assertEquals(Gate.RECONFIRM, Notices.enrolmentGate(Biometrics.ENROLLED, Canary.INVALIDATED, me, list, 5, restarted))
+ assertEquals("the gate after a restart neither drops nor repeats it", 1, Notices.pending(restarted)!!.size)
+ }
+
+ @Test fun `after acceptance a fresh canary under the new enrolment is UNCHANGED, and the notice stays until sent`() {
+ val s = Mem(); Notices.recordEnrolment(true, "g1", s)
+ Notices.enrolmentGate(Biometrics.ENROLLED, Canary.INVALIDATED, me, list, 0, s)
+ var reminted = false
+ assertTrue(Notices.acceptEnrolment(Biometrics.ENROLLED, Canary.INVALIDATED, "g2", s) { reminted = true; true })
+ assertTrue("the canary was re-minted", reminted)
+ assertEquals(Gate.PROCEED, Notices.enrolmentGate(Biometrics.ENROLLED, Canary.USABLE, me, list, 10, s))
+ assertEquals("accepting doesn't send it", 1, Notices.pending(s)!!.size)
+ assertEquals("a later finger is a NEW change", Gate.RECONFIRM, Notices.enrolmentGate(Biometrics.ENROLLED, Canary.INVALIDATED, me, list, 20, s))
+ assertEquals(2, Notices.pending(s)!!.size)
+ }
+
+ @Test fun `a failed re-mint is not an acceptance`() {
+ val s = Mem(); Notices.recordEnrolment(true, "g1", s)
+ Notices.enrolmentGate(Biometrics.ENROLLED, Canary.INVALIDATED, me, list, 0, s)
+ assertFalse(Notices.acceptEnrolment(Biometrics.ENROLLED, Canary.INVALIDATED, "g2", s) { false })
+ assertEquals(Enrolment.CHANGED, Notices.check(s.get(Notices.ENROLMENT), Biometrics.ENROLLED, Canary.INVALIDATED))
+ }
+
+ @Test fun `a store that cannot be read refuses the consent`() {
+ assertEquals(Gate.REFUSE, Notices.enrolmentGate(Biometrics.ENROLLED, Canary.USABLE, me, list, 0, Mem(blind = true)))
+ val s = Mem(); Notices.recordEnrolment(true, "g1", s)
+ assertEquals("a Keystore error refuses", Gate.REFUSE, Notices.enrolmentGate(Biometrics.ENROLLED, Canary.ERROR, me, list, 0, s))
+ }
+
+ // ---- recipients and the anchor ----
+
+ private fun queued(s: Mem): Notices.Notice {
+ Notices.recordEnrolment(true, "g1", s)
+ Notices.enrolmentGate(Biometrics.ENROLLED, Canary.INVALIDATED, me, list, 0, s)
+ return Notices.pending(s)!!.single()
+ }
+
+ @Test fun `recipients are snapshotted at queue time - the devices then, plus the address`() {
+ val s = Mem(); val n = queued(s)
+ assertEquals(list + Notices.ADDRESS, n.recipients)
+ }
+
+ @Test fun `partial delivery keeps it, strangers are ignored, removed devices still hold it back`() {
+ val s = Mem(); val n = queued(s)
+ assertTrue(Notices.markDelivered(n, Notices.ADDRESS, 1, s))
+ assertTrue(Notices.markDelivered(n, "devB", 1, s))
+ assertEquals("partial", 1, Notices.pending(s)!!.size)
+ assertFalse("a stranger's confirmation is ignored", Notices.markDelivered(n, "devZ", 1, s))
+ // devC is dropped from the account now; it is still in the snapshot
+ assertEquals("removed devC still holds it back at 6 days", 1, Notices.apply { sweep(6 * day, s) }.pending(s)!!.size)
+ assertTrue(Notices.sweep(7 * day, s))
+ assertEquals("and stops at 7 days, the address having confirmed", 0, Notices.pending(s)!!.size)
+ }
+
+ @Test fun `everyone confirming clears it at once`() {
+ val s = Mem(); val n = queued(s)
+ for (r in n.recipients) Notices.markDelivered(n, r, 1, s)
+ assertEquals(0, Notices.pending(s)!!.size)
+ }
+
+ @Test fun `without the ADDRESS a notice never clears`() {
+ val s = Mem(); val n = queued(s)
+ for (r in list) Notices.markDelivered(n, r, 1, s)
+ Notices.sweep(365 * day, s)
+ assertEquals(1, Notices.pending(s)!!.size)
+ Notices.markDelivered(n, Notices.ADDRESS, 365 * day, s)
+ assertEquals(0, Notices.pending(s)!!.size)
+ }
+
+ // ---- device-list changes ----
+
+ @Test fun `remove-then-enrol - the list notice goes to the BEFORE list, publish waits for it`() {
+ val s = Mem(); Notices.recordEnrolment(true, "g1", s)
+ val after = setOf("devA")
+ assertFalse("not publishable before its notice is queued", Notices.mayPublishDeviceList(list, after, s))
+ assertTrue(Notices.queueDeviceListChange(list, after, me, 0, s))
+ assertTrue(Notices.mayPublishDeviceList(list, after, s))
+ // then a finger: that notice is snapshotted from the SHRUNK list…
+ Notices.enrolmentGate(Biometrics.ENROLLED, Canary.INVALIDATED, me, after, 1, s)
+ val bio = Notices.pending(s)!!.single { it.kind == "biometrics-changed" }
+ assertFalse("the finger notice excludes the dropped devices", "devB" in bio.recipients)
+ // …but the list notice reaches them and waits for them
+ val dl = Notices.pending(s)!!.single { it.kind == "devices-changed" }
+ assertEquals(list + Notices.ADDRESS, dl.recipients)
+ Notices.markDelivered(dl, Notices.ADDRESS, 2, s); Notices.markDelivered(dl, "devA", 2, s)
+ assertTrue("waits for the removed devices", Notices.pending(s)!!.any { it.kind == "devices-changed" })
+ assertTrue(Notices.queueDeviceListChange(list, after, me, 3, s))
+ assertEquals("queuing the same change twice queues one", 1, Notices.pending(s)!!.count { it.kind == "devices-changed" })
+ }
+
+ @Test fun `enrol-then-remove - the finger notice keeps the devices removed after it`() {
+ val s = Mem(); val n = queued(s)
+ Notices.queueDeviceListChange(list, setOf("devA"), me, 1, s)
+ assertEquals(list + Notices.ADDRESS, Notices.pending(s)!!.single { it.kind == "biometrics-changed" }.recipients)
+ assertEquals(n.recipients, Notices.pending(s)!!.first().recipients)
+ }
+
+ // ---- the receiver's own check ----
+
+ @Test fun `a publish that skipped the gate is caught by the receiver`() {
+ val b = Mem() // device B's own store
+ assertEquals(emptyList<Notices.Alert>(), Notices.observeDeviceList(list, "devA", "devB", emptySet(), 0, b))
+ // a hostile devA publishes {devA} without ever queuing a notice
+ val alerts = Notices.observeDeviceList(setOf("devA"), "devA", "devB", emptySet(), 1, b)!!
+ assertEquals(listOf("this-device-removed", "device-removed"), alerts.map { it.kind })
+ assertEquals("devC", alerts[1].device)
+ assertEquals("recorded durably", 2, Notices.localAlerts(b)!!.size)
+ }
+
+ @Test fun `removals made here raise nothing, and an unreadable baseline is never adopted blind`() {
+ val a = Mem()
+ Notices.observeDeviceList(list, "devA", "devA", emptySet(), 0, a)
+ assertEquals(0, Notices.observeDeviceList(setOf("devA", "devB"), "devA", "devA", setOf("devC"), 1, a)!!.size)
+ val blind = Mem(blind = true)
+ assertNull(Notices.observeDeviceList(list, "devA", "devB", emptySet(), 0, blind))
+ val bad = Mem().also { it.m[Notices.LAST_LIST] = "devA,de vB" }
+ assertNull(Notices.observeDeviceList(list, "devA", "devB", emptySet(), 0, bad))
+ assertEquals("unknown", Notices.localAlerts(bad)!!.single().kind)
+ assertEquals("the bad baseline was not replaced", "devA,de vB", bad.m[Notices.LAST_LIST])
+ }
+
+ @Test fun `the alert is written before the baseline`() {
+ val order = mutableListOf<String>()
+ val s = object : Notices.Store {
+ val m = HashMap<String, String>()
+ override fun get(name: String): Read = m[name]?.let { Read.Found(it) } ?: Read.Absent
+ override fun set(name: String, text: String): Boolean { order += name; m[name] = text; return true }
+ }
+ Notices.observeDeviceList(list, "devA", "devB", emptySet(), 0, s); order.clear()
+ Notices.observeDeviceList(setOf("devA"), "devA", "devB", emptySet(), 1, s)
+ assertEquals(listOf(Notices.ALERTS, Notices.LAST_LIST), order)
+ }
+
+ // ---- a busy sensor (security §29b refinement) ----
+
+ @Test fun `a busy sensor under a bio record is decided by the canary alone`() {
+ val s = Mem(); Notices.recordEnrolment(true, "g1", s)
+ assertEquals(Gate.PROCEED, Notices.enrolmentGate(Biometrics.SENSOR_BUSY, Canary.USABLE, me, list, 0, s))
+ assertEquals(Gate.RECONFIRM, Notices.enrolmentGate(Biometrics.SENSOR_BUSY, Canary.INVALIDATED, me, list, 0, s))
+ assertEquals("busy and ready name the same change: one notice", Gate.RECONFIRM,
+ Notices.enrolmentGate(Biometrics.ENROLLED, Canary.INVALIDATED, me, list, 1, s))
+ assertEquals(1, Notices.pending(s)!!.size)
+ }
+
+ @Test fun `a busy sensor under a none record, or an unknown answer, refuses and records nothing`() {
+ val s = Mem(); Notices.recordEnrolment(false, "g1", s)
+ assertEquals(Gate.REFUSE, Notices.enrolmentGate(Biometrics.SENSOR_BUSY, Canary.ABSENT, me, list, 0, s))
+ val b = Mem(); Notices.recordEnrolment(true, "g1", b)
+ assertEquals(Gate.REFUSE, Notices.enrolmentGate(Biometrics.UNKNOWN, Canary.USABLE, me, list, 0, b))
+ assertEquals(0, Notices.pending(s)!!.size + Notices.pending(b)!!.size)
+ Notices.enrolmentGate(Biometrics.SENSOR_BUSY, Canary.INVALIDATED, me, list, 0, b)
+ assertFalse("never a new baseline under a state the platform can't name",
+ Notices.acceptEnrolment(Biometrics.SENSOR_BUSY, Canary.INVALIDATED, "g2", b) { true })
+ }
+}
diff --git a/home/android/app/src/test/java/page/bento/home/RoutineGateTest.kt b/home/android/app/src/test/java/page/bento/home/RoutineGateTest.kt
new file mode 100644
index 00000000..d7051c5e
--- /dev/null
+++ b/home/android/app/src/test/java/page/bento/home/RoutineGateTest.kt
@@ -0,0 +1,45 @@
+// SPDX-License-Identifier: MIT
+// Copyright (c) 2026 The Bento authors
+
+package page.bento.home
+
+import org.junit.Assert.assertFalse
+import org.junit.Assert.assertTrue
+import org.junit.Test
+
+/** §2e (B): the routine key's app-side session — idle and overall timeouts. */
+class RoutineGateTest {
+ private val H = 3_600_000L
+
+ @Test fun `nothing signs before the person has authenticated`() {
+ assertFalse(RoutineGate().allow(0))
+ }
+
+ @Test fun `steady use keeps the session open until the overall timeout`() {
+ val g = RoutineGate(); g.authenticated(0)
+ var t = 0L
+ while (t < 24 * H - 30 * 60_000) { t += 30 * 60_000; assertTrue("use at ${t / 60_000} min", g.allow(t)) }
+ assertFalse("24 h after authenticating, even steady use is refused", g.allow(24 * H))
+ }
+
+ @Test fun `an hour idle locks it, and it stays locked until re-authentication`() {
+ val g = RoutineGate(); g.authenticated(0)
+ assertTrue(g.allow(59 * 60_000))
+ assertFalse(g.allow(59 * 60_000 + H))
+ assertFalse("a refusal is not a use: it must not reopen the session", g.allow(59 * 60_000 + H + 1))
+ g.authenticated(3 * H)
+ assertTrue(g.allow(3 * H + 1))
+ }
+
+ @Test fun `a clock that goes backwards fails closed`() {
+ val g = RoutineGate(); g.authenticated(10 * H)
+ assertFalse(g.allow(9 * H))
+ assertFalse(g.allow(10 * H + 1))
+ }
+
+ @Test fun `an organisation may tighten the timeouts but never loosen them`() {
+ val g = RoutineGate(idleMs = 15 * 60_000, overallMs = 12 * H); g.authenticated(0)
+ assertFalse(g.allow(15 * 60_000))
+ assertTrue(runCatching { RoutineGate(idleMs = 2 * H) }.isFailure)
+ }
+}