Skip to content

armgit / bento

Public Imported from GitHub
0

Bento, the office suite that fits in a file

home/desktop: the identity agent core and its Linux TPM key store (bento/id H1, part 1) (#771)

nyblnet1a6635fcdf59
diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml
index 5ac80ae8..eab1d783 100644
--- a/.github/workflows/ci.yml
+++ b/.github/workflows/ci.yml
@@ -2802,3 +2802,30 @@ jobs:
# the focus ring, measured on twelve real surfaces, plus a planted
# browser-default field that must be flagged.
run: node scripts/test-type-fields-browser.mjs
+
+ home-desktop-agent:
+ runs-on: ubuntu-24.04
+ timeout-minutes: 20
+ steps:
+ - uses: actions/checkout@v4
+ - name: Desktop agent against the bento/id vectors
+ # home/desktop/agent is the Windows/Linux identity agent core. Its
+ # statements port must reach every verdict AND reason in
+ # kernel/fixtures/identity-v1.json (re-read every run, never pinned), plus
+ # builder round-trips, three tamperings per accepted row, spendCalled
+ # on every cns row, and the frozen display table. A missing fixture
+ # fails; it never skips.
+ working-directory: home/desktop/agent
+ run: cargo test
+ - name: Desktop agent TPM rigs (two software TPMs)
+ # The Linux key store against a real TPM 2.0 (swtpm): the routine key
+ # signs inside the TPM; the consent key and the sealed account key need
+ # the PIN on every use (a wrong PIN is the TPM's own AUTH_FAIL); the key
+ # files are useless on a SECOND TPM (cannot be copied off the machine);
+ # and a second connection without the PIN gets neither, while the
+ # routine key stays usable, which is the stated desktop residual.
+ working-directory: home/desktop/agent
+ run: |
+ sudo apt-get update -qq
+ sudo apt-get install -y -qq libtss2-dev swtpm swtpm-tools >/dev/null
+ ./tpm-rig.sh
diff --git a/docs/DECISIONS.md b/docs/DECISIONS.md
index 3122b389..b4b34d68 100644
--- a/docs/DECISIONS.md
+++ b/docs/DECISIONS.md
@@ -11036,6 +11036,66 @@ with a Cyrillic А passes. So no surface ever shows a name WITHOUT the verified
address beside it, and the ✓ always belongs to the address, never to the name.
(security, #764)
+## 2026-10-18 — bento/id: the desktop agent core and its Linux key store (home/desktop/agent)
+
+The Windows/Linux identity agent is a Rust library crate, `home/desktop/agent`.
+The Tauri host will call it after its own checks. Settled here, so the host and
+other zones build on the same ground:
+
+- **The statements are a PORT, and the vectors are the contract.**
+ `kernel/fixtures/identity-v1.json` is re-read on every run, never pinned.
+ Every row must reach the reference's verdict AND reason. Accepted rows must
+ round-trip through the builders and refuse three kinds of tampering. Every
+ `cns.` row must spend its challenge when `spendCalled` says so. The display
+ refusal set is embedded as the fixture's frozen Unicode 17.0 ranges, and a
+ test fails if the two ever differ. JavaScript string semantics that change
+ verdicts (`trim()`'s whitespace set, UTF-16 `length`) are reproduced on
+ purpose.
+- **One way in.** The agent answers only a `Caller` the host built after its
+ per-webview capability check, on a verified shell, carrying the docId the
+ host read from the file itself. It never takes a docId or a caller name from
+ the page.
+- **Routine signing** (`frame`, `prove`, `delegate`, `show`) uses the device
+ key, unprompted, inside a session: 1 h idle and 24 h overall by default, or
+ 15 min and 12 h for organisations at AAL3. Past either limit, even routine
+ signatures are refused until the person re-authenticates.
+- **Consent is host-stamped.** The rp (`bento`), the audience (`dir`, phase 1's
+ only one), the docId and a 2-minute expiry are chosen by the host. The page
+ supplies only the statement and the directory's challenge. The consent key
+ signs, and prompts every time.
+- **`sign('invite' | 'revoke')` is refused** with `unavailable`. Those are signed
+ by the room's owner key, which the kernel holds in phase 1.
+- **The Linux key store** is the TPM, and the TPM counts only if this user can
+ open it:
+ - the routine key is created in the TPM, non-exportable, and needs no prompt;
+ - the consent key is created in the TPM with the person's PIN as its
+ authValue, so every use needs the PIN and the TPM's lockout limits guessing;
+ - the account key is shared across devices, so it can't be created inside
+ one TPM. It is sealed under the same PIN and unsealed only for a prompted
+ use, then zeroized.
+ What sits on disk are TPM-wrapped blobs that only this TPM can load.
+- **Two desktop-specific residuals, stated rather than hidden.**
+ - On a phone, other apps can't use our keys at all. On a desktop, any process
+ running as the same user can ask the TPM to sign with the routine key, so it
+ can edit as the person in rooms they already belong to. It can't copy the
+ key off the machine, and it can't use the consent or account key without
+ the PIN.
+ - The session timers bind the genuine agent only. A process calling the TPM
+ directly bypasses them.
+ Both are accepted: same-user malware can already edit the person's files and
+ drive the app.
+- **No key-agreement key** anywhere until its placement is ruled.
+
+Rigs:
+- `home/desktop/agent/tests/conformance.rs`, the vectors plus the mutations
+ that showed each check bites: accepting high-S, a late spend, and a dropped
+ display range;
+- `tests/tpm_linux.rs` via `tpm-rig.sh`, against two independent swtpm TPMs:
+ the routine key signs and verifies; a wrong PIN is the TPM's own AUTH_FAIL;
+ the sealed account key unseals only with the PIN; the key files fail on a
+ second TPM; and a second connection without the PIN gets neither the consent
+ key nor the account key, while the routine residual is asserted so it stays
+ visible.
## 2026-10-18 — bento/id: the recovery code and key blobs (kernel/src/recovery.ts)
The bytes behind identity-design §2f, signed by security §28, with
diff --git a/home/desktop/agent/.gitignore b/home/desktop/agent/.gitignore
new file mode 100644
index 00000000..2f7896d1
--- /dev/null
+++ b/home/desktop/agent/.gitignore
@@ -0,0 +1 @@
+target/
diff --git a/home/desktop/agent/Cargo.lock b/home/desktop/agent/Cargo.lock
new file mode 100644
index 00000000..f663923b
--- /dev/null
+++ b/home/desktop/agent/Cargo.lock
@@ -0,0 +1,725 @@
+# This file is automatically @generated by Cargo.
+# It is not intended for manual editing.
+version = 4
+
+[[package]]
+name = "aho-corasick"
+version = "1.1.5"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "c982642fa9e8606056828ee9a8505737230110bb1099153c79efe865c59d12ba"
+dependencies = [
+ "memchr",
+]
+
+[[package]]
+name = "autocfg"
+version = "1.5.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "f2032f911046de80f0a198e0901378627c33f59ea0ac00e363d481118bd70a53"
+
+[[package]]
+name = "base16ct"
+version = "0.2.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "4c7f02d4ea65f2c1853089ffd8d2787bdbc63de2f0d29dedbcf8ccdfa0ccd4cf"
+
+[[package]]
+name = "base64"
+version = "0.22.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "72b3254f16251a8381aa12e40e3c4d2f0199f8c6508fbecb9d91f575e0fbb8c6"
+
+[[package]]
+name = "base64"
+version = "0.23.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "ac07cdecf99051d9a5238b80f35af32cdeba5b336e55d957b318b50137e18da5"
+
+[[package]]
+name = "base64ct"
+version = "1.8.3"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "2af50177e190e07a26ab74f8b1efbfe2ef87da2116221318cb1c2e82baf7de06"
+
+[[package]]
+name = "bento-id-agent"
+version = "0.1.0"
+dependencies = [
+ "base64 0.22.1",
+ "p256",
+ "serde_json",
+ "sha2",
+ "tss-esapi",
+ "unicode-normalization",
+ "zeroize",
+]
+
+[[package]]
+name = "bitfield"
+version = "0.19.5"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "b45721c9db4c7a20899d05efb7ad9235f50b256e980db30ffb229abf732934c3"
+dependencies = [
+ "bitfield-macros",
+]
+
+[[package]]
+name = "bitfield-macros"
+version = "0.19.5"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "c0cb6f3d4773a2107b94cbeccaa5b5f0b35a88389b5d522d13d659f64317b22d"
+dependencies = [
+ "proc-macro2",
+ "quote",
+ "syn 3.0.9",
+]
+
+[[package]]
+name = "block-buffer"
+version = "0.10.4"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "3078c7629b62d3f0439517fa394996acacc5cbc91c5a20d8c658e77abd503a71"
+dependencies = [
+ "generic-array",
+]
+
+[[package]]
+name = "cfg-if"
+version = "1.0.5"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "4e7648175b45a9a48536d676f68d918270699102aa8dab5496df06904c914600"
+
+[[package]]
+name = "const-oid"
+version = "0.9.6"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "c2459377285ad874054d797f3ccebf984978aa39129f6eafde5cdc8315b612f8"
+
+[[package]]
+name = "cpufeatures"
+version = "0.2.17"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "59ed5838eebb26a2bb2e58f6d5b5316989ae9d08bab10e0e6d103e656d1b0280"
+dependencies = [
+ "libc",
+]
+
+[[package]]
+name = "crypto-bigint"
+version = "0.5.5"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "0dc92fb57ca44df6db8059111ab3af99a63d5d0f8375d9972e319a379c6bab76"
+dependencies = [
+ "generic-array",
+ "rand_core",
+ "subtle",
+ "zeroize",
+]
+
+[[package]]
+name = "crypto-common"
+version = "0.1.6"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "1bfb12502f3fc46cca1bb51ac28df9d618d813cdc3d2f25b9fe775a34af26bb3"
+dependencies = [
+ "generic-array",
+ "typenum",
+]
+
+[[package]]
+name = "der"
+version = "0.7.10"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "e7c1832837b905bbfb5101e07cc24c8deddf52f93225eee6ead5f4d63d53ddcb"
+dependencies = [
+ "const-oid",
+ "pem-rfc7468",
+ "zeroize",
+]
+
+[[package]]
+name = "digest"
+version = "0.10.7"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "9ed9a281f7bc9b7576e61468ba615a66a5c8cfdff42420a70aa82701a3b1e292"
+dependencies = [
+ "block-buffer",
+ "const-oid",
+ "crypto-common",
+ "subtle",
+]
+
+[[package]]
+name = "ecdsa"
+version = "0.16.9"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "ee27f32b5c5292967d2d4a9d7f1e0b0aed2c15daded5a60300e4abb9d8020bca"
+dependencies = [
+ "der",
+ "digest",
+ "elliptic-curve",
+ "rfc6979",
+ "signature",
+ "spki",
+]
+
+[[package]]
+name = "elliptic-curve"
+version = "0.13.8"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "b5e6043086bf7973472e0c7dff2142ea0b680d30e18d9cc40f267efbf222bd47"
+dependencies = [
+ "base16ct",
+ "crypto-bigint",
+ "digest",
+ "ff",
+ "generic-array",
+ "group",
+ "pem-rfc7468",
+ "pkcs8",
+ "rand_core",
+ "sec1",
+ "subtle",
+ "zeroize",
+]
+
+[[package]]
+name = "enumflags2"
+version = "0.7.12"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "1027f7680c853e056ebcec683615fb6fbbc07dbaa13b4d5d9442b146ded4ecef"
+dependencies = [
+ "enumflags2_derive",
+]
+
+[[package]]
+name = "enumflags2_derive"
+version = "0.7.12"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "67c78a4d8fdf9953a5c9d458f9efe940fd97a0cab0941c075a813ac594733827"
+dependencies = [
+ "proc-macro2",
+ "quote",
+ "syn 2.0.119",
+]
+
+[[package]]
+name = "ff"
+version = "0.13.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "c0b50bfb653653f9ca9095b427bed08ab8d75a137839d9ad64eb11810d5b6393"
+dependencies = [
+ "rand_core",
+ "subtle",
+]
+
+[[package]]
+name = "generic-array"
+version = "0.14.9"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "4bb6743198531e02858aeaea5398fcc883e71851fcbcb5a2f773e2fb6cb1edf2"
+dependencies = [
+ "typenum",
+ "version_check",
+ "zeroize",
+]
+
+[[package]]
+name = "getrandom"
+version = "0.2.17"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "ff2abc00be7fca6ebc474524697ae276ad847ad0a6b3faa4bcb027e9a4614ad0"
+dependencies = [
+ "cfg-if",
+ "libc",
+ "wasi",
+]
+
+[[package]]
+name = "getrandom"
+version = "0.4.3"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "300e883d756b2e4ec94e02791f39b04b522276138852cfc41d9fb7e904106099"
+dependencies = [
+ "cfg-if",
+ "libc",
+ "r-efi",
+]
+
+[[package]]
+name = "group"
+version = "0.13.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "f0f9ef7462f7c099f518d754361858f86d8a07af53ba9af0fe635bbccb151a63"
+dependencies = [
+ "ff",
+ "rand_core",
+ "subtle",
+]
+
+[[package]]
+name = "hmac"
+version = "0.12.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "6c49c37c09c17a53d937dfbb742eb3a961d65a994e6bcdcf37e7399d0cc8ab5e"
+dependencies = [
+ "digest",
+]
+
+[[package]]
+name = "hostname-validator"
+version = "1.1.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "f558a64ac9af88b5ba400d99b579451af0d39c6d360980045b91aac966d705e2"
+
+[[package]]
+name = "itoa"
+version = "1.0.18"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "8f42a60cbdf9a97f5d2305f08a87dc4e09308d1276d28c869c684d7777685682"
+
+[[package]]
+name = "libc"
+version = "0.2.191"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "65cd87c9a6d60536580b316ad985726104730a5151c99845f2490428ef91240a"
+
+[[package]]
+name = "log"
+version = "0.4.34"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "f9f8bd3e56ce4dfc153cf470fffbfa98c7620958b312ca5c3a4b8d5181fd13c6"
+
+[[package]]
+name = "mbox"
+version = "0.7.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "26d142aeadbc4e8c679fc6d93fbe7efe1c021fa7d80629e615915b519e3bc6de"
+dependencies = [
+ "libc",
+ "stable_deref_trait",
+]
+
+[[package]]
+name = "memchr"
+version = "2.8.3"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "cf8baf1c55e62ffcace7a9f06f4bd9cd3f0c4beb022d3b367256b91b87513d98"
+
+[[package]]
+name = "num-derive"
+version = "0.4.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "ed3955f1a9c7c0c15e092f9c887db08b1fc683305fdf6eb6684f22555355e202"
+dependencies = [
+ "proc-macro2",
+ "quote",
+ "syn 2.0.119",
+]
+
+[[package]]
+name = "num-traits"
+version = "0.2.19"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "071dfc062690e90b734c0b2273ce72ad0ffa95f0c74596bc250dcfd960262841"
+dependencies = [
+ "autocfg",
+]
+
+[[package]]
+name = "oid"
+version = "0.2.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "9c19903c598813dba001b53beeae59bb77ad4892c5c1b9b3500ce4293a0d06c2"
+dependencies = [
+ "serde",
+]
+
+[[package]]
+name = "p256"
+version = "0.13.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "c9863ad85fa8f4460f9c48cb909d38a0d689dba1f6f6988a5e3e0d31071bcd4b"
+dependencies = [
+ "ecdsa",
+ "elliptic-curve",
+ "primeorder",
+ "sha2",
+]
+
+[[package]]
+name = "pem-rfc7468"
+version = "0.7.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "88b39c9bfcfc231068454382784bb460aae594343fb030d46e9f50a645418412"
+dependencies = [
+ "base64ct",
+]
+
+[[package]]
+name = "picky-asn1"
+version = "0.10.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "2ff038f9360b934342fb3c0a1d6e82c438a2624b51c3c6e3e6d7cf252b6f3ee3"
+dependencies = [
+ "oid",
+ "serde",
+ "serde_bytes",
+]
+
+[[package]]
+name = "picky-asn1-der"
+version = "0.5.7"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "b4467118a2c640f4040aea27d01293620984b0b3f3ef0c53577c3bbf6bab4256"
+dependencies = [
+ "picky-asn1",
+ "serde",
+ "serde_bytes",
+]
+
+[[package]]
+name = "picky-asn1-x509"
+version = "0.15.5"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "3f110226d163cea4380b0e5ef698a107061d198b279cc27d2b2c1e95c08cd9b0"
+dependencies = [
+ "base64 0.23.1",
+ "oid",
+ "picky-asn1",
+ "picky-asn1-der",
+ "serde",
+]
+
+[[package]]
+name = "pkcs8"
+version = "0.10.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "f950b2377845cebe5cf8b5165cb3cc1a5e0fa5cfa3e1f7f55707d8fd82e0a7b7"
+dependencies = [
+ "der",
+ "spki",
+]
+
+[[package]]
+name = "pkg-config"
+version = "0.3.34"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "f6b464fbc74e149a392436b17d523f769e057cb6877f6a5c4618bc6f11800548"
+
+[[package]]
+name = "primeorder"
+version = "0.13.6"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "353e1ca18966c16d9deb1c69278edbc5f194139612772bd9537af60ac231e1e6"
+dependencies = [
+ "elliptic-curve",
+]
+
+[[package]]
+name = "proc-macro2"
+version = "1.0.107"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "985e7ec9bb745e6ce6535b544d84d6cd6f7ad8bd711c398938ae983b91a766d9"
+dependencies = [
+ "unicode-ident",
+]
+
+[[package]]
+name = "quote"
+version = "1.0.47"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "1fbf4db142a473a8d80c26bbf18454ed458bf8d26c8219c331daecfdbd079001"
+dependencies = [
+ "proc-macro2",
+]
+
+[[package]]
+name = "r-efi"
+version = "6.0.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "f8dcc9c7d52a811697d2151c701e0d08956f92b0e24136cf4cf27b57a6a0d9bf"
+
+[[package]]
+name = "rand_core"
+version = "0.6.4"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "ec0be4795e2f6a28069bec0b5ff3e2ac9bafc99e6a9a7dc3547996c5c816922c"
+dependencies = [
+ "getrandom 0.2.17",
+]
+
+[[package]]
+name = "regex"
+version = "1.13.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "f020237b6c8eed93db2e2cb53c00c60a8e1bc73da7d073199a1180401450218d"
+dependencies = [
+ "aho-corasick",
+ "memchr",
+ "regex-automata",
+ "regex-syntax",
+]
+
+[[package]]
+name = "regex-automata"
+version = "0.4.18"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "ad8553b9b26413251cbf30e620595c7a41b3887f03da04579c0e6b0d6a06b4b2"
+dependencies = [
+ "aho-corasick",
+ "memchr",
+ "regex-syntax",
+]
+
+[[package]]
+name = "regex-syntax"
+version = "0.8.11"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "d6f6ff9a378485b298a5286656da665ba74413d36db0979633275d2e708145d4"
+
+[[package]]
+name = "rfc6979"
+version = "0.4.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "f8dd2a808d456c4a54e300a23e9f5a67e122c3024119acbfd73e3bf664491cb2"
+dependencies = [
+ "hmac",
+ "subtle",
+]
+
+[[package]]
+name = "sec1"
+version = "0.7.3"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "d3e97a565f76233a6003f9f5c54be1d9c5bdfa3eccfb189469f11ec4901c47dc"
+dependencies = [
+ "base16ct",
+ "der",
+ "generic-array",
+ "pkcs8",
+ "subtle",
+ "zeroize",
+]
+
+[[package]]
+name = "serde"
+version = "1.0.229"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "4148590afebada386688f18773da617792bf2ef03ffc1e4cbd2b1d45b023e0ba"
+dependencies = [
+ "serde_core",
+ "serde_derive",
+]
+
+[[package]]
+name = "serde_bytes"
+version = "0.11.19"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "a5d440709e79d88e51ac01c4b72fc6cb7314017bb7da9eeff678aa94c10e3ea8"
+dependencies = [
+ "serde",
+ "serde_core",
+]
+
+[[package]]
+name = "serde_core"
+version = "1.0.229"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "67dca2c9c51e58a4791a4b1ed58308b39c64224d349a935ab5039aa360942a48"
+dependencies = [
+ "serde_derive",
+]
+
+[[package]]
+name = "serde_derive"
+version = "1.0.229"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "e7a5d71263a5a7d47b41f6b3f06ba276f10cc18b0931f1799f710578e2309348"
+dependencies = [
+ "proc-macro2",
+ "quote",
+ "syn 3.0.9",
+]
+
+[[package]]
+name = "serde_json"
+version = "1.0.154"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "e7e9cc8b1b85264074fbcc02a88680c4096b1e47df8f739dceb03bf482f04bd6"
+dependencies = [
+ "itoa",
+ "memchr",
+ "serde",
+ "serde_core",
+ "zmij",
+]
+
+[[package]]
+name = "sha2"
+version = "0.10.9"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "a7507d819769d01a365ab707794a4084392c824f54a7a6a7862f8c3d0892b283"
+dependencies = [
+ "cfg-if",
+ "cpufeatures",
+ "digest",
+]
+
+[[package]]
+name = "signature"
+version = "2.2.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "77549399552de45a898a580c1b41d445bf730df867cc44e6c0233bbc4b8329de"
+dependencies = [
+ "digest",
+ "rand_core",
+]
+
+[[package]]
+name = "spki"
+version = "0.7.3"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "d91ed6c858b01f942cd56b37a94b3e0a1798290327d1236e4d9cf4eaca44d29d"
+dependencies = [
+ "base64ct",
+ "der",
+]
+
+[[package]]
+name = "stable_deref_trait"
+version = "1.2.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "6ce2be8dc25455e1f91df71bfa12ad37d7af1092ae736f3a6cd0e37bc7810596"
+
+[[package]]
+name = "subtle"
+version = "2.6.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "13c2bddecc57b384dee18652358fb23172facb8a2c51ccc10d74c157bdea3292"
+
+[[package]]
+name = "syn"
+version = "2.0.119"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "872831b642d1a07999a962a351ed35b955ea2cfc8f3862091e2a240a84f17297"
+dependencies = [
+ "proc-macro2",
+ "quote",
+ "unicode-ident",
+]
+
+[[package]]
+name = "syn"
+version = "3.0.9"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "d78c8dee4c7bf0e14673097256fed6142ce9d3b85a408189d07482442145823b"
+dependencies = [
+ "proc-macro2",
+ "quote",
+ "unicode-ident",
+]
+
+[[package]]
+name = "target-lexicon"
+version = "0.12.16"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "61c41af27dd6d1e27b1b16b489db798443478cef1f06a660c96db617ba5de3b1"
+
+[[package]]
+name = "tinyvec"
+version = "1.13.3"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "fd3ca314f692efd6c868f8408f53fe444634a845f96c028b97d35f6a1f79f0ee"
+
+[[package]]
+name = "tss-esapi"
+version = "7.7.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "3f10b25a84912b894d0e6d68f4a3771c923e9c44ddaaed7920cde92ed28aa84e"
+dependencies = [
+ "bitfield",
+ "enumflags2",
+ "getrandom 0.4.3",
+ "hostname-validator",
+ "log",
+ "mbox",
+ "num-derive",
+ "num-traits",
+ "oid",
+ "picky-asn1",
+ "picky-asn1-x509",
+ "regex",
+ "serde",
+ "tss-esapi-sys",
+ "zeroize",
+]
+
+[[package]]
+name = "tss-esapi-sys"
+version = "0.6.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "a7f972672926a3d3d18ecc04524720e4d20b7d1664a3fb73dbf7d4274196dbd9"
+dependencies = [
+ "pkg-config",
+ "target-lexicon",
+]
+
+[[package]]
+name = "typenum"
+version = "1.20.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "b6f5e870be6c3b371b77fe0ee0bafb859fa4964b4404c27de1d380043c4dda20"
+
+[[package]]
+name = "unicode-ident"
+version = "1.0.27"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "a2c754d6c33795a1c324727428e5a7dedb5b06195f9890bdbcba760d3e246563"
+
+[[package]]
+name = "unicode-normalization"
+version = "0.1.26"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "75cd3fb03d5288b3ba9a1ee103ac7e9cbb59f0b03d64f8ddfcc04dd42758a85d"
+dependencies = [
+ "tinyvec",
+]
+
+[[package]]
+name = "version_check"
+version = "0.9.5"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "0b928f33d975fc6ad9f86c8f283853ad26bdd5b10b7f1542aa2fa15e2289105a"
+
+[[package]]
+name = "wasi"
+version = "0.11.1+wasi-snapshot-preview1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "ccf3ec651a847eb01de73ccad15eb7d99f80485de043efb2f370cd654f4ea44b"
+
+[[package]]
+name = "zeroize"
+version = "1.9.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "e13084392c5e4bc371903e2935a5eaeed24905a7511356b883835e18a78f6879"
+dependencies = [
+ "zeroize_derive",
+]
+
+[[package]]
+name = "zeroize_derive"
+version = "1.5.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "3c50655cbb0fe3fc43170059e702f1ce5e19b84cec58dc87b037a09935c2f328"
+dependencies = [
+ "proc-macro2",
+ "quote",
+ "syn 2.0.119",
+]
+
+[[package]]
+name = "zmij"
+version = "1.0.23"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "29666d0abbfad1e3dc4dcf6144730dd3a3ab225bbbdac83319345b1b44ccfc1b"
diff --git a/home/desktop/agent/Cargo.toml b/home/desktop/agent/Cargo.toml
new file mode 100644
index 00000000..8e24c365
--- /dev/null
+++ b/home/desktop/agent/Cargo.toml
@@ -0,0 +1,26 @@
+[package]
+name = "bento-id-agent"
+version = "0.1.0"
+edition = "2021"
+license = "MIT"
+publish = false
+description = "bento/id agent core for the desktop host (Windows, Linux): the signed statements, key storage and the agent contract"
+
+[dependencies]
+p256 = { version = "0.13", features = ["ecdsa"] }
+sha2 = "0.10"
+base64 = "0.22"
+zeroize = "1"
+unicode-normalization = "0.1"
+
+[target.'cfg(target_os = "linux")'.dependencies]
+tss-esapi = { version = "7", optional = true }
+
+[features]
+# the Linux TPM key store (needs libtss2)
+tpm = ["dep:tss-esapi"]
+# the in-memory software key store: tests and rigs only, never a shipped path
+test-store = []
+
+[dev-dependencies]
+serde_json = "1"
diff --git a/home/desktop/agent/gen-display-table.mjs b/home/desktop/agent/gen-display-table.mjs
new file mode 100644
index 00000000..739f9789
--- /dev/null
+++ b/home/desktop/agent/gen-display-table.mjs
@@ -0,0 +1,27 @@
+#!/usr/bin/env node
+// Regenerates src/display_table.rs from kernel/fixtures/identity-v1.json's
+// frozen `displayForbidden` table. Run after the fixture is regenerated; the
+// conformance test fails until the two agree.
+import { readFileSync, writeFileSync } from 'node:fs'
+const here = new URL('.', import.meta.url).pathname
+const d = JSON.parse(readFileSync(here + '../../../kernel/fixtures/identity-v1.json', 'utf8')).displayForbidden
+const hex = (n) => '0x' + n.toString(16).padStart(4, '0')
+const rows = []
+for (let i = 0; i < d.ranges.length; i += 6) rows.push(' ' + d.ranges.slice(i, i + 6).map(([a, b]) => `(${hex(a)}, ${hex(b)})`).join(', ') + ',')
+writeFileSync(here + 'src/display_table.rs', `// SPDX-License-Identifier: MIT
+// Copyright (c) 2026 The Bento authors
+//
+// GENERATED by gen-display-table.mjs from kernel/fixtures/identity-v1.json
+// (\`displayForbidden\`, Unicode ${d.unicode}). Do not edit by hand.
+//
+// The display refusal set, frozen as explicit code-point ranges so every host
+// refuses the same characters whatever Unicode tables its platform ships.
+
+pub const UNICODE: &str = "${d.unicode}";
+
+/// Sorted, non-overlapping, inclusive.
+pub const DISPLAY_FORBIDDEN_RANGES: [(u32, u32); ${d.ranges.length}] = [
+${rows.join('\n')}
+];
+`)
+console.log(`${d.ranges.length} ranges, Unicode ${d.unicode}`)
diff --git a/home/desktop/agent/src/address.rs b/home/desktop/agent/src/address.rs
new file mode 100644
index 00000000..8df86a83
--- /dev/null
+++ b/home/desktop/agent/src/address.rs
@@ -0,0 +1,94 @@
+// SPDX-License-Identifier: MIT
+// Copyright (c) 2026 The Bento authors
+//
+// The ONE definition of "which mailbox is this address" — a port of
+// kernel/src/address.ts. The vectors are the contract; two JS semantics are
+// reproduced on purpose because they change verdicts:
+// - `String.prototype.trim` strips a different set than Rust's `str::trim`
+// (it includes U+FEFF, which Unicode's White_Space does not);
+// - `s.length` counts UTF-16 code units, and the length check runs BEFORE
+// the ASCII check, so an over-long non-ASCII input is `too-long`.
+
+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
+pub enum Refusal {
+ TooLong,
+ NotAscii,
+ AtSign,
+ LocalPart,
+ Domain,
+ NumericTld,
+}
+
+impl Refusal {
+ pub fn as_str(self) -> &'static str {
+ match self {
+ Refusal::TooLong => "too-long",
+ Refusal::NotAscii => "not-ascii",
+ Refusal::AtSign => "at-sign",
+ Refusal::LocalPart => "local-part",
+ Refusal::Domain => "domain",
+ Refusal::NumericTld => "numeric-tld",
+ }
+ }
+}
+
+const MAX_ADDRESS: usize = 254;
+const MAX_LOCAL: usize = 64;
+const MAX_LABEL: usize = 63;
+
+/// ECMAScript WhiteSpace + LineTerminator (what `trim()` removes).
+fn js_space(c: char) -> bool {
+ matches!(c,
+ '\u{0009}' | '\u{000A}' | '\u{000B}' | '\u{000C}' | '\u{000D}' | '\u{0020}' | '\u{00A0}'
+ | '\u{1680}' | '\u{2000}'..='\u{200A}' | '\u{2028}' | '\u{2029}' | '\u{202F}' | '\u{205F}'
+ | '\u{3000}' | '\u{FEFF}')
+}
+
+/// RFC 5322 atext, lower-cased.
+fn atext(c: u8) -> bool {
+ c.is_ascii_lowercase() || c.is_ascii_digit() || b"!#$%&'*+/=?^_`{|}~-".contains(&c)
+}
+
+pub fn normalize(input: &str) -> Result<String, Refusal> {
+ let s = input.trim_matches(js_space);
+ if s.encode_utf16().count() > MAX_ADDRESS {
+ return Err(Refusal::TooLong);
+ }
+ if !s.bytes().all(|c| (0x21..=0x7e).contains(&c)) {
+ return Err(Refusal::NotAscii);
+ }
+ // ASCII from here on, so byte indices are character indices.
+ let at = match s.find('@') {
+ Some(at) if at > 0 && Some(at) == s.rfind('@') && at != s.len() - 1 => at,
+ _ => return Err(Refusal::AtSign),
+ };
+ let local = s[..at].to_ascii_lowercase();
+ let domain = s[at + 1..].to_ascii_lowercase();
+ if local.len() > MAX_LOCAL {
+ return Err(Refusal::TooLong);
+ }
+ if !local.split('.').all(|atom| !atom.is_empty() && atom.bytes().all(atext)) {
+ return Err(Refusal::LocalPart);
+ }
+ let labels: Vec<&str> = domain.split('.').collect();
+ if labels.len() < 2 {
+ return Err(Refusal::Domain);
+ }
+ for label in &labels {
+ if label.is_empty() || label.len() > MAX_LABEL
+ || !label.bytes().all(|c| c.is_ascii_lowercase() || c.is_ascii_digit() || c == b'-')
+ || label.starts_with('-') || label.ends_with('-')
+ {
+ return Err(Refusal::Domain);
+ }
+ }
+ if labels[labels.len() - 1].bytes().all(|c| c.is_ascii_digit()) {
+ return Err(Refusal::NumericTld);
+ }
+ Ok(format!("{local}@{domain}"))
+}
+
+/// True when `s` is already in normal form (what a signed statement carries).
+pub fn is_normal(s: &str) -> bool {
+ normalize(s).map(|a| a == s).unwrap_or(false)
+}
diff --git a/home/desktop/agent/src/agent.rs b/home/desktop/agent/src/agent.rs
new file mode 100644
index 00000000..ea18e205
--- /dev/null
+++ b/home/desktop/agent/src/agent.rs
@@ -0,0 +1,414 @@
+// SPDX-License-Identifier: MIT
+// Copyright (c) 2026 The Bento authors
+//
+// The agent: what a verified document may ask (kernel/src/identity.ts, K1),
+// answered from keys the document never sees.
+//
+// - The ONLY way in is a `Caller`, which the host builds after its capability
+// check (security §19d (a)) and gate 1 (a verified shell). The agent never
+// takes a docId or a caller name from the page.
+// - Routine signing (frame/prove/delegate/show) uses the device ROUTINE key,
+// unprompted, inside a session bounded by the idle and overall timers
+// (§2e (B)): past either, even routine signatures are refused until the person
+// re-authenticates. These timers bind the GENUINE agent only — a same-user
+// process can call the OS key store directly (security, H1 key table).
+// - Consent (`cns.`) is host-STAMPED (§2e (A)): the rp, audience, docId and
+// expiry are chosen here; the page supplies only the statement and the
+// verifier's challenge. Signed by the CONSENT key, which prompts every use.
+// - kx: none. Its placement is unruled (§6b).
+
+use crate::{b64u, statements as st};
+
+/// Which key. The account key is handled by the account flows (link, rotate,
+/// unbind), not by `sign`.
+#[derive(Debug, Clone, PartialEq, Eq)]
+pub enum KeyRole {
+ Account,
+ /// the device ROUTINE key (`devicePub` in `dev.`)
+ Device,
+ /// the hardware CONSENT key (`consentPub` in `dev.`), UV on every use
+ Consent,
+}
+
+/// What the host shows when a key store needs the person (the consent key's
+/// per-use prompt). Drawn by the HOST or the OS, never by the page.
+#[derive(Debug, Clone)]
+pub struct Prompt {
+ pub purpose: String,
+ pub doc_id: Option<String>,
+}
+
+#[derive(Debug, Clone, PartialEq, Eq)]
+pub enum StoreError {
+ /// the person said no at the OS/host prompt
+ Declined,
+ /// no such key on this device
+ NoKey,
+ /// the store cannot act right now (locked, no TPM, busy)
+ Unavailable(String),
+}
+
+/// The OS key store: Windows NCrypt (TPM + Hello), Linux TPM, or Secret
+/// Service. Private keys never leave it through this trait.
+pub trait KeyStore {
+ /// The raw uncompressed P-256 public point, or None if the key does not exist.
+ fn public_key(&self, role: &KeyRole) -> Result<Option<[u8; 65]>, StoreError>;
+ /// ECDSA P-256 / SHA-256 over `msg`, raw r‖s (either S; the agent folds).
+ /// A store whose key needs the person (the consent key) shows `prompt`.
+ fn sign(&mut self, role: &KeyRole, msg: &[u8], prompt: Option<&Prompt>) -> Result<[u8; 64], StoreError>;
+ /// True when this store holds a hardware consent key (false: Linux without
+ /// a TPM → AAL3 refused and routed elsewhere, §2e (E)).
+ fn has_consent_key(&self) -> bool;
+}
+
+pub trait Clock {
+ fn now_ms(&self) -> u64;
+}
+
+/// The routine session (§2e (B)). Defaults are the AAL2 SHOULDs; an org may
+/// set the AAL3 ones (15 min / 12 h).
+#[derive(Debug, Clone, Copy)]
+pub struct Policy {
+ pub idle_ms: u64,
+ pub overall_ms: u64,
+}
+impl Default for Policy {
+ fn default() -> Self {
+ Policy { idle_ms: 60 * 60_000, overall_ms: 24 * 60 * 60_000 }
+ }
+}
+
+/// Who is asking, as the HOST established it: after the per-webview capability
+/// check, on a verified shell, with the docId the host read from the file it
+/// opened. Not constructible from page input by design: the host builds it.
+#[derive(Debug, Clone)]
+pub struct Caller {
+ pub verified: bool,
+ pub doc_id: Option<String>,
+}
+
+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
+pub enum Refusal {
+ Declined,
+ Reauth,
+ Purpose,
+ NoIdentity,
+ Unavailable,
+}
+impl Refusal {
+ /// The K1 `SignRefusal` word.
+ pub fn as_str(self) -> &'static str {
+ match self {
+ Refusal::Declined => "declined",
+ Refusal::Reauth => "reauth",
+ Refusal::Purpose => "purpose",
+ Refusal::NoIdentity => "no-identity",
+ Refusal::Unavailable => "unavailable",
+ }
+ }
+}
+
+#[derive(Debug, Clone, PartialEq, Eq)]
+pub struct Signed {
+ /// raw r‖s, low-S, base64url
+ pub sig: String,
+ /// the key that signed, raw point base64url
+ pub pub_key: String,
+}
+
+#[derive(Debug, Clone, PartialEq, Eq)]
+pub struct ConsentSigned {
+ /// the exact `cns.` text the consent key signed
+ pub cns: String,
+ pub sig: String,
+ pub consent_pub: String,
+}
+
+/// bento's relying party in a `cns.` (a vault id when there is one).
+pub const RP: &str = "bento";
+/// Phase 1's only consent audience: the directory (security §24).
+pub const AUDIENCE: &str = "dir";
+/// Stamped consent lifetime: under CONSENT_MAX_TTL_MS (5 min), as Android.
+pub const CONSENT_TTL_MS: u64 = 2 * 60_000;
+
+const ROUTINE: [&str; 4] = ["frame", "prove", "delegate", "show"];
+
+pub struct Agent<S: KeyStore, C: Clock> {
+ store: S,
+ clock: C,
+ policy: Policy,
+ /// (session start, last routine use), None = must re-authenticate
+ session: Option<(u64, u64)>,
+}
+
+fn store_refusal(e: StoreError) -> Refusal {
+ match e {
+ StoreError::Declined => Refusal::Declined,
+ StoreError::NoKey => Refusal::NoIdentity,
+ StoreError::Unavailable(_) => Refusal::Unavailable,
+ }
+}
+
+impl<S: KeyStore, C: Clock> Agent<S, C> {
+ pub fn new(store: S, clock: C, policy: Policy) -> Self {
+ Agent { store, clock, policy, session: None }
+ }
+
+ /// Open (or renew) the routine session. The host calls this only after the
+ /// person has re-authenticated (Windows Hello / the TPM PIN / unlock).
+ pub fn begin_session(&mut self) {
+ let now = self.clock.now_ms();
+ self.session = Some((now, now));
+ }
+
+ /// Lock: idle lock, sleep, session lock. Routine signing is refused after.
+ pub fn lock(&mut self) {
+ self.session = None;
+ }
+
+ fn session_live(&mut self) -> bool {
+ let now = self.clock.now_ms();
+ match self.session {
+ Some((start, last))
+ if now.saturating_sub(last) <= self.policy.idle_ms && now.saturating_sub(start) <= self.policy.overall_ms =>
+ {
+ true
+ }
+ _ => {
+ self.session = None;
+ false
+ }
+ }
+ }
+
+ /// K1 `sign(purpose, payload)`.
+ pub fn sign(&mut self, caller: &Caller, purpose: &str, payload: &str) -> Result<Signed, Refusal> {
+ if !caller.verified {
+ return Err(Refusal::Unavailable);
+ }
+ if !st::payload_matches_purpose(purpose, payload) {
+ return Err(Refusal::Purpose);
+ }
+ if !ROUTINE.contains(&purpose) {
+ // invite/revoke are signed by the room's OWNER key (the relay's `o`),
+ // which in phase 1 lives in the document and is signed by the kernel
+ // directly. No phase-1 agent holds an owner key, so it refuses
+ // (kernel, 2026-10-18). Phase 2: the owner key moves into the agent,
+ // signs after the host's prompt, and a cns. travels beside it.
+ return Err(Refusal::Unavailable);
+ }
+ let pub_key = self.store.public_key(&KeyRole::Device).map_err(store_refusal)?.ok_or(Refusal::NoIdentity)?;
+ if !self.session_live() {
+ return Err(Refusal::Reauth);
+ }
+ let raw = self.store.sign(&KeyRole::Device, payload.as_bytes(), None).map_err(store_refusal)?;
+ if let Some((start, _)) = self.session {
+ self.session = Some((start, self.clock.now_ms()));
+ }
+ Ok(Signed { sig: b64u::enc(&st::low_s(&raw)), pub_key: b64u::enc(&pub_key) })
+ }
+
+ /// A host-stamped consent (`cns.`) for `statement`, bound to the
+ /// directory's single-use `challenge`. The page chooses neither the rp, the
+ /// audience, the docId nor the expiry. Prompts every time (consent key).
+ pub fn consent(&mut self, caller: &Caller, purpose: &str, statement: &str, challenge: &str) -> Result<ConsentSigned, Refusal> {
+ if !caller.verified {
+ return Err(Refusal::Unavailable);
+ }
+ if !self.store.has_consent_key() {
+ // AAL3 refused on a machine with no consent key; routed elsewhere (§2e (E)).
+ return Err(Refusal::Unavailable);
+ }
+ let family = match purpose {
+ "invite" => "inv.",
+ "revoke" => "rev.",
+ "link" => "dev.",
+ "rotate" => "bind.",
+ "unbind" => "del.",
+ _ => return Err(Refusal::Purpose),
+ };
+ if !statement.starts_with(family) {
+ return Err(Refusal::Purpose);
+ }
+ let doc_id = if matches!(purpose, "invite" | "revoke") {
+ match caller.doc_id.as_deref() {
+ Some(d) if st::is_doc_id(d) => Some(d.to_string()),
+ _ => return Err(Refusal::Purpose),
+ }
+ } else {
+ None
+ };
+ let transcript = st::consent_transcript(AUDIENCE, challenge, statement).ok_or(Refusal::Purpose)?;
+ let consent_pub =
+ self.store.public_key(&KeyRole::Consent).map_err(store_refusal)?.ok_or(Refusal::NoIdentity)?;
+ let cns = st::build_consent(&st::Consent {
+ rp: RP.into(),
+ purpose: purpose.into(),
+ doc_id: doc_id.clone(),
+ transcript,
+ exp: self.clock.now_ms() + CONSENT_TTL_MS,
+ });
+ let prompt = Prompt { purpose: purpose.into(), doc_id };
+ let raw = self.store.sign(&KeyRole::Consent, cns.as_bytes(), Some(&prompt)).map_err(store_refusal)?;
+ Ok(ConsentSigned { cns, sig: b64u::enc(&st::low_s(&raw)), consent_pub: b64u::enc(&consent_pub) })
+ }
+}
+
+// ----------------------------------------------------------------- test store
+
+/// An in-memory software store. TESTS ONLY: it holds private keys in process
+/// memory, which no shipped path may do (security §26).
+#[cfg(any(test, feature = "test-store"))]
+pub mod memory {
+ use super::*;
+ use p256::ecdsa::{signature::Signer, Signature, SigningKey};
+ use std::collections::HashMap;
+
+ #[derive(Default)]
+ pub struct MemoryStore {
+ pub keys: HashMap<String, SigningKey>,
+ /// what the next prompted signature answers
+ pub decline: bool,
+ pub prompts: Vec<Prompt>,
+ pub consent_capable: bool,
+ }
+ fn k(role: &KeyRole) -> String {
+ format!("{role:?}")
+ }
+ impl MemoryStore {
+ pub fn with_keys() -> Self {
+ let mut s = MemoryStore { consent_capable: true, ..Default::default() };
+ for (i, r) in [KeyRole::Account, KeyRole::Device, KeyRole::Consent].iter().enumerate() {
+ s.keys.insert(k(r), SigningKey::from_slice(&[i as u8 + 11; 32]).unwrap());
+ }
+ s
+ }
+ }
+ impl KeyStore for MemoryStore {
+ fn public_key(&self, role: &KeyRole) -> Result<Option<[u8; 65]>, StoreError> {
+ Ok(self.keys.get(&k(role)).map(|s| s.verifying_key().to_encoded_point(false).as_bytes().try_into().unwrap()))
+ }
+ fn sign(&mut self, role: &KeyRole, msg: &[u8], prompt: Option<&Prompt>) -> Result<[u8; 64], StoreError> {
+ if let Some(p) = prompt {
+ self.prompts.push(p.clone());
+ if self.decline {
+ return Err(StoreError::Declined);
+ }
+ }
+ let key = self.keys.get(&k(role)).ok_or(StoreError::NoKey)?;
+ let sig: Signature = key.sign(msg);
+ Ok(sig.to_bytes().into())
+ }
+ fn has_consent_key(&self) -> bool {
+ self.consent_capable
+ }
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use super::memory::MemoryStore;
+ use super::*;
+ use std::cell::Cell;
+ use std::rc::Rc;
+
+ #[derive(Clone)]
+ struct FakeClock(Rc<Cell<u64>>);
+ impl Clock for FakeClock {
+ fn now_ms(&self) -> u64 {
+ self.0.get()
+ }
+ }
+ fn agent() -> (Agent<MemoryStore, FakeClock>, Rc<Cell<u64>>) {
+ let t = Rc::new(Cell::new(1_800_000_000_000));
+ (Agent::new(MemoryStore::with_keys(), FakeClock(t.clone()), Policy::default()), t)
+ }
+ const OK: Caller = Caller { verified: true, doc_id: None };
+ fn frame() -> String {
+ format!("{}.{}", b64u::enc(&[1; 12]), b64u::enc(&[2; 32]))
+ }
+
+ #[test]
+ fn routine_sign_low_s_and_verifies() {
+ let (mut a, _) = agent();
+ a.begin_session();
+ let p = frame();
+ let s = a.sign(&OK, "frame", &p).unwrap();
+ assert!(st::verify_statement_sig(&s.pub_key, &s.sig, &p));
+ }
+
+ #[test]
+ fn timers_gate_the_key_idle_and_overall() {
+ let (mut a, t) = agent();
+ assert_eq!(a.sign(&OK, "frame", &frame()), Err(Refusal::Reauth), "no session yet");
+ a.begin_session();
+ t.set(t.get() + 60 * 60_000 + 1);
+ assert_eq!(a.sign(&OK, "frame", &frame()), Err(Refusal::Reauth), "idle > 1 h");
+ a.begin_session();
+ // keep it busy every 30 min for 24 h: never idle, but past overall
+ for _ in 0..48 {
+ t.set(t.get() + 30 * 60_000);
+ assert!(a.sign(&OK, "frame", &frame()).is_ok());
+ }
+ t.set(t.get() + 30 * 60_000);
+ assert_eq!(a.sign(&OK, "frame", &frame()), Err(Refusal::Reauth), "overall > 24 h");
+ a.begin_session();
+ a.lock();
+ assert_eq!(a.sign(&OK, "frame", &frame()), Err(Refusal::Reauth), "locked");
+ }
+
+ #[test]
+ fn purpose_and_caller_gates() {
+ let (mut a, _) = agent();
+ a.begin_session();
+ assert_eq!(a.sign(&OK, "frame", "live"), Err(Refusal::Purpose), "a show payload is not a frame");
+ assert_eq!(a.sign(&OK, "show", "live").map(|_| ()), Ok(()));
+ assert_eq!(a.sign(&Caller { verified: false, doc_id: None }, "show", "live"), Err(Refusal::Unavailable));
+ // invite/revoke: the owner key's job (the kernel, phase 1), never the agent's
+ let rev_pub = a.store.public_key(&KeyRole::Device).unwrap().unwrap();
+ assert_eq!(a.sign(&OK, "revoke", &format!("rev.{}", b64u::enc(&rev_pub))), Err(Refusal::Unavailable));
+ }
+
+ #[test]
+ fn consent_is_host_stamped_and_verifies_under_k2() {
+ let (mut a, t) = agent();
+ let challenge = b64u::enc(&[9u8; 24]);
+ let caller = Caller { verified: true, doc_id: Some("doc-lq3k9z-8f2h1x".into()) };
+ let dev_pub = b64u::enc(&a.store.public_key(&KeyRole::Device).unwrap().unwrap());
+ let statement = format!("rev.{dev_pub}");
+ let c = a.consent(&caller, "revoke", &statement, &challenge).unwrap();
+ assert_eq!(a.store.prompts.len(), 1, "the consent key prompted");
+ let check = st::ConsentCheck {
+ consent_pub: &c.consent_pub,
+ rp: RP,
+ audience: AUDIENCE,
+ challenge: &challenge,
+ payload_text: &statement,
+ doc_id: Some("doc-lq3k9z-8f2h1x"),
+ now: t.get(),
+ };
+ assert!(st::verify_consent(&c.cns, &c.sig, &check, |_| true).is_ok(), "{}", c.cns);
+ // relayed to a room audience: refused
+ let room = format!("room:w{}", "A".repeat(43));
+ let relayed = st::ConsentCheck { audience: &room, ..check };
+ assert_eq!(st::verify_consent(&c.cns, &c.sig, &relayed, |_| true).unwrap_err(), "transcript");
+ // a different document: refused
+ let other = st::ConsentCheck { doc_id: Some("another-doc"), audience: AUDIENCE, ..relayed };
+ assert_eq!(st::verify_consent(&c.cns, &c.sig, &other, |_| true).unwrap_err(), "docid");
+ }
+
+ #[test]
+ fn consent_refusals() {
+ let (mut a, _) = agent();
+ let ch = b64u::enc(&[9u8; 24]);
+ let doc = Caller { verified: true, doc_id: Some("d1".into()) };
+ assert_eq!(a.consent(&doc, "grant", "inv.x", &ch).unwrap_err(), Refusal::Purpose, "reserved purpose");
+ assert_eq!(a.consent(&doc, "revoke", "inv.x", &ch).unwrap_err(), Refusal::Purpose, "wrong family");
+ assert_eq!(a.consent(&OK, "revoke", "rev.x", &ch).unwrap_err(), Refusal::Purpose, "doc-scoped without a docId");
+ assert_eq!(a.consent(&doc, "revoke", "rev.x", "short").unwrap_err(), Refusal::Purpose, "challenge under 16 bytes");
+ a.store.decline = true;
+ assert_eq!(a.consent(&doc, "revoke", "rev.x", &ch).unwrap_err(), Refusal::Declined);
+ a.store.consent_capable = false;
+ assert_eq!(a.consent(&doc, "revoke", "rev.x", &ch).unwrap_err(), Refusal::Unavailable, "no consent key: AAL3 refused");
+ }
+}
diff --git a/home/desktop/agent/src/b64u.rs b/home/desktop/agent/src/b64u.rs
new file mode 100644
index 00000000..379916b8
--- /dev/null
+++ b/home/desktop/agent/src/b64u.rs
@@ -0,0 +1,20 @@
+// SPDX-License-Identifier: MIT
+// Copyright (c) 2026 The Bento authors
+//
+// Strict base64url (statements.ts b64uEnc / b64uDec): the alphabet only, no
+// padding, and the input must re-encode to exactly the same string, so a
+// non-canonical spelling (non-zero trailing bits) is refused.
+
+use base64::{engine::general_purpose::URL_SAFE_NO_PAD, Engine};
+
+pub fn enc(bytes: &[u8]) -> String {
+ URL_SAFE_NO_PAD.encode(bytes)
+}
+
+pub fn dec(s: &str) -> Option<Vec<u8>> {
+ if !s.bytes().all(|c| c.is_ascii_alphanumeric() || c == b'-' || c == b'_') || s.len() % 4 == 1 {
+ return None;
+ }
+ let out = URL_SAFE_NO_PAD.decode(s).ok()?;
+ (enc(&out) == s).then_some(out)
+}
diff --git a/home/desktop/agent/src/device_list.rs b/home/desktop/agent/src/device_list.rs
new file mode 100644
index 00000000..ff0607ce
--- /dev/null
+++ b/home/desktop/agent/src/device_list.rs
@@ -0,0 +1,76 @@
+// SPDX-License-Identifier: MIT
+// Copyright (c) 2026 The Bento authors
+//
+// The RECEIVER-side removal check (security §29a.5–6).
+//
+// A device-list change must notify the list as it was BEFORE the change, and
+// the publishing agent waits until that notice is durably queued. But on a
+// desktop the account key that publishes the list can be used OUTSIDE the
+// genuine agent — on a machine without a TPM, or in the window while it is
+// unsealed for a prompted use — so the publisher's gate can be skipped. So
+// every agent also checks what it RECEIVES: whenever a fetched list drops a
+// device this agent did not remove itself, it raises its own local alert,
+// whatever any notice said.
+//
+// Devices are identified by their routine key (`devicePub`). The synced list's
+// format comes with the directory work; this is the pure check it must feed.
+
+use std::collections::BTreeSet;
+
+#[derive(Debug, Clone, PartialEq, Eq)]
+pub struct Removal {
+ /// the removed device's routine key
+ pub device_pub: String,
+ /// true when it is THIS device: "this device was removed from your account"
+ pub is_self: bool,
+ /// who published the list that dropped it, when the list names a publisher
+ pub by: Option<String>,
+}
+
+/// Compare the last list this agent saw with a freshly fetched one.
+/// `own_removals` are the devices this agent removed itself (a confirmed
+/// removal it published), which raise no alert. Additions are not alerts here:
+/// a new device is announced by the §2f fetch notice and the linking flow.
+pub fn removals(
+ last_seen: &[String],
+ fetched: &[String],
+ own_removals: &BTreeSet<String>,
+ this_device: &str,
+ publisher: Option<&str>,
+) -> Vec<Removal> {
+ let now: BTreeSet<&str> = fetched.iter().map(String::as_str).collect();
+ last_seen
+ .iter()
+ .filter(|d| !now.contains(d.as_str()) && !own_removals.contains(*d))
+ .map(|d| Removal { device_pub: d.clone(), is_self: d == this_device, by: publisher.map(str::to_string) })
+ .collect()
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+ fn v(xs: &[&str]) -> Vec<String> {
+ xs.iter().map(|s| s.to_string()).collect()
+ }
+
+ #[test]
+ fn a_list_shrunk_behind_the_gates_back_raises_the_alert_on_the_next_fetch() {
+ // A,B,C published; then A alone, published by A without the notice gate.
+ // B's next fetch must alert for itself AND for C.
+ let r = removals(&v(&["A", "B", "C"]), &v(&["A"]), &BTreeSet::new(), "B", Some("A"));
+ assert_eq!(r.len(), 2);
+ assert!(r.iter().any(|x| x.device_pub == "B" && x.is_self && x.by.as_deref() == Some("A")));
+ assert!(r.iter().any(|x| x.device_pub == "C" && !x.is_self));
+ }
+
+ #[test]
+ fn control_a_removal_this_agent_made_itself_raises_nothing() {
+ let own: BTreeSet<String> = ["C".to_string()].into();
+ assert!(removals(&v(&["A", "B", "C"]), &v(&["A", "B"]), &own, "B", Some("B")).is_empty());
+ }
+
+ #[test]
+ fn additions_and_reorders_are_not_removals() {
+ assert!(removals(&v(&["A", "B"]), &v(&["B", "A", "D"]), &BTreeSet::new(), "B", None).is_empty());
+ }
+}
diff --git a/home/desktop/agent/src/display_table.rs b/home/desktop/agent/src/display_table.rs
new file mode 100644
index 00000000..3c8899fe
--- /dev/null
+++ b/home/desktop/agent/src/display_table.rs
@@ -0,0 +1,139 @@
+// SPDX-License-Identifier: MIT
+// Copyright (c) 2026 The Bento authors
+//
+// GENERATED by gen-display-table.mjs from kernel/fixtures/identity-v1.json
+// (`displayForbidden`, Unicode 17.0). Do not edit by hand.
+//
+// The display refusal set, frozen as explicit code-point ranges so every host
+// refuses the same characters whatever Unicode tables its platform ships.
+
+pub const UNICODE: &str = "17.0";
+
+/// Sorted, non-overlapping, inclusive.
+pub const DISPLAY_FORBIDDEN_RANGES: [(u32, u32); 746] = [
+ (0x0000, 0x001f), (0x007f, 0x009f), (0x00ad, 0x00ad), (0x0378, 0x0379), (0x0380, 0x0383), (0x038b, 0x038b),
+ (0x038d, 0x038d), (0x03a2, 0x03a2), (0x0530, 0x0530), (0x0557, 0x0558), (0x058b, 0x058c), (0x0590, 0x0590),
+ (0x05c8, 0x05cf), (0x05eb, 0x05ee), (0x05f5, 0x0605), (0x061c, 0x061c), (0x06dd, 0x06dd), (0x070e, 0x070f),
+ (0x074b, 0x074c), (0x07b2, 0x07bf), (0x07fb, 0x07fc), (0x082e, 0x082f), (0x083f, 0x083f), (0x085c, 0x085d),
+ (0x085f, 0x085f), (0x086b, 0x086f), (0x0890, 0x0896), (0x08e2, 0x08e2), (0x0984, 0x0984), (0x098d, 0x098e),
+ (0x0991, 0x0992), (0x09a9, 0x09a9), (0x09b1, 0x09b1), (0x09b3, 0x09b5), (0x09ba, 0x09bb), (0x09c5, 0x09c6),
+ (0x09c9, 0x09ca), (0x09cf, 0x09d6), (0x09d8, 0x09db), (0x09de, 0x09de), (0x09e4, 0x09e5), (0x09ff, 0x0a00),
+ (0x0a04, 0x0a04), (0x0a0b, 0x0a0e), (0x0a11, 0x0a12), (0x0a29, 0x0a29), (0x0a31, 0x0a31), (0x0a34, 0x0a34),
+ (0x0a37, 0x0a37), (0x0a3a, 0x0a3b), (0x0a3d, 0x0a3d), (0x0a43, 0x0a46), (0x0a49, 0x0a4a), (0x0a4e, 0x0a50),
+ (0x0a52, 0x0a58), (0x0a5d, 0x0a5d), (0x0a5f, 0x0a65), (0x0a77, 0x0a80), (0x0a84, 0x0a84), (0x0a8e, 0x0a8e),
+ (0x0a92, 0x0a92), (0x0aa9, 0x0aa9), (0x0ab1, 0x0ab1), (0x0ab4, 0x0ab4), (0x0aba, 0x0abb), (0x0ac6, 0x0ac6),
+ (0x0aca, 0x0aca), (0x0ace, 0x0acf), (0x0ad1, 0x0adf), (0x0ae4, 0x0ae5), (0x0af2, 0x0af8), (0x0b00, 0x0b00),
+ (0x0b04, 0x0b04), (0x0b0d, 0x0b0e), (0x0b11, 0x0b12), (0x0b29, 0x0b29), (0x0b31, 0x0b31), (0x0b34, 0x0b34),
+ (0x0b3a, 0x0b3b), (0x0b45, 0x0b46), (0x0b49, 0x0b4a), (0x0b4e, 0x0b54), (0x0b58, 0x0b5b), (0x0b5e, 0x0b5e),
+ (0x0b64, 0x0b65), (0x0b78, 0x0b81), (0x0b84, 0x0b84), (0x0b8b, 0x0b8d), (0x0b91, 0x0b91), (0x0b96, 0x0b98),
+ (0x0b9b, 0x0b9b), (0x0b9d, 0x0b9d), (0x0ba0, 0x0ba2), (0x0ba5, 0x0ba7), (0x0bab, 0x0bad), (0x0bba, 0x0bbd),
+ (0x0bc3, 0x0bc5), (0x0bc9, 0x0bc9), (0x0bce, 0x0bcf), (0x0bd1, 0x0bd6), (0x0bd8, 0x0be5), (0x0bfb, 0x0bff),
+ (0x0c0d, 0x0c0d), (0x0c11, 0x0c11), (0x0c29, 0x0c29), (0x0c3a, 0x0c3b), (0x0c45, 0x0c45), (0x0c49, 0x0c49),
+ (0x0c4e, 0x0c54), (0x0c57, 0x0c57), (0x0c5b, 0x0c5b), (0x0c5e, 0x0c5f), (0x0c64, 0x0c65), (0x0c70, 0x0c76),
+ (0x0c8d, 0x0c8d), (0x0c91, 0x0c91), (0x0ca9, 0x0ca9), (0x0cb4, 0x0cb4), (0x0cba, 0x0cbb), (0x0cc5, 0x0cc5),
+ (0x0cc9, 0x0cc9), (0x0cce, 0x0cd4), (0x0cd7, 0x0cdb), (0x0cdf, 0x0cdf), (0x0ce4, 0x0ce5), (0x0cf0, 0x0cf0),
+ (0x0cf4, 0x0cff), (0x0d0d, 0x0d0d), (0x0d11, 0x0d11), (0x0d45, 0x0d45), (0x0d49, 0x0d49), (0x0d50, 0x0d53),
+ (0x0d64, 0x0d65), (0x0d80, 0x0d80), (0x0d84, 0x0d84), (0x0d97, 0x0d99), (0x0db2, 0x0db2), (0x0dbc, 0x0dbc),
+ (0x0dbe, 0x0dbf), (0x0dc7, 0x0dc9), (0x0dcb, 0x0dce), (0x0dd5, 0x0dd5), (0x0dd7, 0x0dd7), (0x0de0, 0x0de5),
+ (0x0df0, 0x0df1), (0x0df5, 0x0e00), (0x0e3b, 0x0e3e), (0x0e5c, 0x0e80), (0x0e83, 0x0e83), (0x0e85, 0x0e85),
+ (0x0e8b, 0x0e8b), (0x0ea4, 0x0ea4), (0x0ea6, 0x0ea6), (0x0ebe, 0x0ebf), (0x0ec5, 0x0ec5), (0x0ec7, 0x0ec7),
+ (0x0ecf, 0x0ecf), (0x0eda, 0x0edb), (0x0ee0, 0x0eff), (0x0f48, 0x0f48), (0x0f6d, 0x0f70), (0x0f98, 0x0f98),
+ (0x0fbd, 0x0fbd), (0x0fcd, 0x0fcd), (0x0fdb, 0x0fff), (0x10c6, 0x10c6), (0x10c8, 0x10cc), (0x10ce, 0x10cf),
+ (0x115f, 0x1160), (0x1249, 0x1249), (0x124e, 0x124f), (0x1257, 0x1257), (0x1259, 0x1259), (0x125e, 0x125f),
+ (0x1289, 0x1289), (0x128e, 0x128f), (0x12b1, 0x12b1), (0x12b6, 0x12b7), (0x12bf, 0x12bf), (0x12c1, 0x12c1),
+ (0x12c6, 0x12c7), (0x12d7, 0x12d7), (0x1311, 0x1311), (0x1316, 0x1317), (0x135b, 0x135c), (0x137d, 0x137f),
+ (0x139a, 0x139f), (0x13f6, 0x13f7), (0x13fe, 0x13ff), (0x169d, 0x169f), (0x16f9, 0x16ff), (0x1716, 0x171e),
+ (0x1737, 0x173f), (0x1754, 0x175f), (0x176d, 0x176d), (0x1771, 0x1771), (0x1774, 0x177f), (0x17de, 0x17df),
+ (0x17ea, 0x17ef), (0x17fa, 0x17ff), (0x180e, 0x180e), (0x181a, 0x181f), (0x1879, 0x187f), (0x18ab, 0x18af),
+ (0x18f6, 0x18ff), (0x191f, 0x191f), (0x192c, 0x192f), (0x193c, 0x193f), (0x1941, 0x1943), (0x196e, 0x196f),
+ (0x1975, 0x197f), (0x19ac, 0x19af), (0x19ca, 0x19cf), (0x19db, 0x19dd), (0x1a1c, 0x1a1d), (0x1a5f, 0x1a5f),
+ (0x1a7d, 0x1a7e), (0x1a8a, 0x1a8f), (0x1a9a, 0x1a9f), (0x1aae, 0x1aaf), (0x1ade, 0x1adf), (0x1aec, 0x1aff),
+ (0x1b4d, 0x1b4d), (0x1bf4, 0x1bfb), (0x1c38, 0x1c3a), (0x1c4a, 0x1c4c), (0x1c8b, 0x1c8f), (0x1cbb, 0x1cbc),
+ (0x1cc8, 0x1ccf), (0x1cfb, 0x1cff), (0x1f16, 0x1f17), (0x1f1e, 0x1f1f), (0x1f46, 0x1f47), (0x1f4e, 0x1f4f),
+ (0x1f58, 0x1f58), (0x1f5a, 0x1f5a), (0x1f5c, 0x1f5c), (0x1f5e, 0x1f5e), (0x1f7e, 0x1f7f), (0x1fb5, 0x1fb5),
+ (0x1fc5, 0x1fc5), (0x1fd4, 0x1fd5), (0x1fdc, 0x1fdc), (0x1ff0, 0x1ff1), (0x1ff5, 0x1ff5), (0x1fff, 0x1fff),
+ (0x200b, 0x200b), (0x200e, 0x200f), (0x2028, 0x202e), (0x2060, 0x206f), (0x2072, 0x2073), (0x208f, 0x208f),
+ (0x209d, 0x209f), (0x20c2, 0x20cf), (0x20f1, 0x20ff), (0x218c, 0x218f), (0x242a, 0x243f), (0x244b, 0x245f),
+ (0x2b74, 0x2b75), (0x2cf4, 0x2cf8), (0x2d26, 0x2d26), (0x2d28, 0x2d2c), (0x2d2e, 0x2d2f), (0x2d68, 0x2d6e),
+ (0x2d71, 0x2d7e), (0x2d97, 0x2d9f), (0x2da7, 0x2da7), (0x2daf, 0x2daf), (0x2db7, 0x2db7), (0x2dbf, 0x2dbf),
+ (0x2dc7, 0x2dc7), (0x2dcf, 0x2dcf), (0x2dd7, 0x2dd7), (0x2ddf, 0x2ddf), (0x2e5e, 0x2e7f), (0x2e9a, 0x2e9a),
+ (0x2ef4, 0x2eff), (0x2fd6, 0x2fef), (0x3040, 0x3040), (0x3097, 0x3098), (0x3100, 0x3104), (0x3130, 0x3130),
+ (0x3164, 0x3164), (0x318f, 0x318f), (0x31e6, 0x31ee), (0x321f, 0x321f), (0xa48d, 0xa48f), (0xa4c7, 0xa4cf),
+ (0xa62c, 0xa63f), (0xa6f8, 0xa6ff), (0xa7dd, 0xa7f0), (0xa82d, 0xa82f), (0xa83a, 0xa83f), (0xa878, 0xa87f),
+ (0xa8c6, 0xa8cd), (0xa8da, 0xa8df), (0xa954, 0xa95e), (0xa97d, 0xa97f), (0xa9ce, 0xa9ce), (0xa9da, 0xa9dd),
+ (0xa9ff, 0xa9ff), (0xaa37, 0xaa3f), (0xaa4e, 0xaa4f), (0xaa5a, 0xaa5b), (0xaac3, 0xaada), (0xaaf7, 0xab00),
+ (0xab07, 0xab08), (0xab0f, 0xab10), (0xab17, 0xab1f), (0xab27, 0xab27), (0xab2f, 0xab2f), (0xab6c, 0xab6f),
+ (0xabee, 0xabef), (0xabfa, 0xabff), (0xd7a4, 0xd7af), (0xd7c7, 0xd7ca), (0xd7fc, 0xd7ff), (0xe000, 0xf8ff),
+ (0xfa6e, 0xfa6f), (0xfada, 0xfaff), (0xfb07, 0xfb12), (0xfb18, 0xfb1c), (0xfb37, 0xfb37), (0xfb3d, 0xfb3d),
+ (0xfb3f, 0xfb3f), (0xfb42, 0xfb42), (0xfb45, 0xfb45), (0xfdd0, 0xfdef), (0xfe1a, 0xfe1f), (0xfe53, 0xfe53),
+ (0xfe67, 0xfe67), (0xfe6c, 0xfe6f), (0xfe75, 0xfe75), (0xfefd, 0xff00), (0xffa0, 0xffa0), (0xffbf, 0xffc1),
+ (0xffc8, 0xffc9), (0xffd0, 0xffd1), (0xffd8, 0xffd9), (0xffdd, 0xffdf), (0xffe7, 0xffe7), (0xffef, 0xfffb),
+ (0xfffe, 0xffff), (0x1000c, 0x1000c), (0x10027, 0x10027), (0x1003b, 0x1003b), (0x1003e, 0x1003e), (0x1004e, 0x1004f),
+ (0x1005e, 0x1007f), (0x100fb, 0x100ff), (0x10103, 0x10106), (0x10134, 0x10136), (0x1018f, 0x1018f), (0x1019d, 0x1019f),
+ (0x101a1, 0x101cf), (0x101fe, 0x1027f), (0x1029d, 0x1029f), (0x102d1, 0x102df), (0x102fc, 0x102ff), (0x10324, 0x1032c),
+ (0x1034b, 0x1034f), (0x1037b, 0x1037f), (0x1039e, 0x1039e), (0x103c4, 0x103c7), (0x103d6, 0x103ff), (0x1049e, 0x1049f),
+ (0x104aa, 0x104af), (0x104d4, 0x104d7), (0x104fc, 0x104ff), (0x10528, 0x1052f), (0x10564, 0x1056e), (0x1057b, 0x1057b),
+ (0x1058b, 0x1058b), (0x10593, 0x10593), (0x10596, 0x10596), (0x105a2, 0x105a2), (0x105b2, 0x105b2), (0x105ba, 0x105ba),
+ (0x105bd, 0x105bf), (0x105f4, 0x105ff), (0x10737, 0x1073f), (0x10756, 0x1075f), (0x10768, 0x1077f), (0x10786, 0x10786),
+ (0x107b1, 0x107b1), (0x107bb, 0x107ff), (0x10806, 0x10807), (0x10809, 0x10809), (0x10836, 0x10836), (0x10839, 0x1083b),
+ (0x1083d, 0x1083e), (0x10856, 0x10856), (0x1089f, 0x108a6), (0x108b0, 0x108df), (0x108f3, 0x108f3), (0x108f6, 0x108fa),
+ (0x1091c, 0x1091e), (0x1093a, 0x1093e), (0x1095a, 0x1097f), (0x109b8, 0x109bb), (0x109d0, 0x109d1), (0x10a04, 0x10a04),
+ (0x10a07, 0x10a0b), (0x10a14, 0x10a14), (0x10a18, 0x10a18), (0x10a36, 0x10a37), (0x10a3b, 0x10a3e), (0x10a49, 0x10a4f),
+ (0x10a59, 0x10a5f), (0x10aa0, 0x10abf), (0x10ae7, 0x10aea), (0x10af7, 0x10aff), (0x10b36, 0x10b38), (0x10b56, 0x10b57),
+ (0x10b73, 0x10b77), (0x10b92, 0x10b98), (0x10b9d, 0x10ba8), (0x10bb0, 0x10bff), (0x10c49, 0x10c7f), (0x10cb3, 0x10cbf),
+ (0x10cf3, 0x10cf9), (0x10d28, 0x10d2f), (0x10d3a, 0x10d3f), (0x10d66, 0x10d68), (0x10d86, 0x10d8d), (0x10d90, 0x10e5f),
+ (0x10e7f, 0x10e7f), (0x10eaa, 0x10eaa), (0x10eae, 0x10eaf), (0x10eb2, 0x10ec1), (0x10ec8, 0x10ecf), (0x10ed9, 0x10ef9),
+ (0x10f28, 0x10f2f), (0x10f5a, 0x10f6f), (0x10f8a, 0x10faf), (0x10fcc, 0x10fdf), (0x10ff7, 0x10fff), (0x1104e, 0x11051),
+ (0x11076, 0x1107e), (0x110bd, 0x110bd), (0x110c3, 0x110cf), (0x110e9, 0x110ef), (0x110fa, 0x110ff), (0x11135, 0x11135),
+ (0x11148, 0x1114f), (0x11177, 0x1117f), (0x111e0, 0x111e0), (0x111f5, 0x111ff), (0x11212, 0x11212), (0x11242, 0x1127f),
+ (0x11287, 0x11287), (0x11289, 0x11289), (0x1128e, 0x1128e), (0x1129e, 0x1129e), (0x112aa, 0x112af), (0x112eb, 0x112ef),
+ (0x112fa, 0x112ff), (0x11304, 0x11304), (0x1130d, 0x1130e), (0x11311, 0x11312), (0x11329, 0x11329), (0x11331, 0x11331),
+ (0x11334, 0x11334), (0x1133a, 0x1133a), (0x11345, 0x11346), (0x11349, 0x1134a), (0x1134e, 0x1134f), (0x11351, 0x11356),
+ (0x11358, 0x1135c), (0x11364, 0x11365), (0x1136d, 0x1136f), (0x11375, 0x1137f), (0x1138a, 0x1138a), (0x1138c, 0x1138d),
+ (0x1138f, 0x1138f), (0x113b6, 0x113b6), (0x113c1, 0x113c1), (0x113c3, 0x113c4), (0x113c6, 0x113c6), (0x113cb, 0x113cb),
+ (0x113d6, 0x113d6), (0x113d9, 0x113e0), (0x113e3, 0x113ff), (0x1145c, 0x1145c), (0x11462, 0x1147f), (0x114c8, 0x114cf),
+ (0x114da, 0x1157f), (0x115b6, 0x115b7), (0x115de, 0x115ff), (0x11645, 0x1164f), (0x1165a, 0x1165f), (0x1166d, 0x1167f),
+ (0x116ba, 0x116bf), (0x116ca, 0x116cf), (0x116e4, 0x116ff), (0x1171b, 0x1171c), (0x1172c, 0x1172f), (0x11747, 0x117ff),
+ (0x1183c, 0x1189f), (0x118f3, 0x118fe), (0x11907, 0x11908), (0x1190a, 0x1190b), (0x11914, 0x11914), (0x11917, 0x11917),
+ (0x11936, 0x11936), (0x11939, 0x1193a), (0x11947, 0x1194f), (0x1195a, 0x1199f), (0x119a8, 0x119a9), (0x119d8, 0x119d9),
+ (0x119e5, 0x119ff), (0x11a48, 0x11a4f), (0x11aa3, 0x11aaf), (0x11af9, 0x11aff), (0x11b0a, 0x11b5f), (0x11b68, 0x11bbf),
+ (0x11be2, 0x11bef), (0x11bfa, 0x11bff), (0x11c09, 0x11c09), (0x11c37, 0x11c37), (0x11c46, 0x11c4f), (0x11c6d, 0x11c6f),
+ (0x11c90, 0x11c91), (0x11ca8, 0x11ca8), (0x11cb7, 0x11cff), (0x11d07, 0x11d07), (0x11d0a, 0x11d0a), (0x11d37, 0x11d39),
+ (0x11d3b, 0x11d3b), (0x11d3e, 0x11d3e), (0x11d48, 0x11d4f), (0x11d5a, 0x11d5f), (0x11d66, 0x11d66), (0x11d69, 0x11d69),
+ (0x11d8f, 0x11d8f), (0x11d92, 0x11d92), (0x11d99, 0x11d9f), (0x11daa, 0x11daf), (0x11ddc, 0x11ddf), (0x11dea, 0x11edf),
+ (0x11ef9, 0x11eff), (0x11f11, 0x11f11), (0x11f3b, 0x11f3d), (0x11f5b, 0x11faf), (0x11fb1, 0x11fbf), (0x11ff2, 0x11ffe),
+ (0x1239a, 0x123ff), (0x1246f, 0x1246f), (0x12475, 0x1247f), (0x12544, 0x12f8f), (0x12ff3, 0x12fff), (0x13430, 0x1343f),
+ (0x13456, 0x1345f), (0x143fb, 0x143ff), (0x14647, 0x160ff), (0x1613a, 0x167ff), (0x16a39, 0x16a3f), (0x16a5f, 0x16a5f),
+ (0x16a6a, 0x16a6d), (0x16abf, 0x16abf), (0x16aca, 0x16acf), (0x16aee, 0x16aef), (0x16af6, 0x16aff), (0x16b46, 0x16b4f),
+ (0x16b5a, 0x16b5a), (0x16b62, 0x16b62), (0x16b78, 0x16b7c), (0x16b90, 0x16d3f), (0x16d7a, 0x16e3f), (0x16e9b, 0x16e9f),
+ (0x16eb9, 0x16eba), (0x16ed4, 0x16eff), (0x16f4b, 0x16f4e), (0x16f88, 0x16f8e), (0x16fa0, 0x16fdf), (0x16fe5, 0x16fef),
+ (0x16ff7, 0x16fff), (0x18cd6, 0x18cfe), (0x18d1f, 0x18d7f), (0x18df3, 0x1afef), (0x1aff4, 0x1aff4), (0x1affc, 0x1affc),
+ (0x1afff, 0x1afff), (0x1b123, 0x1b131), (0x1b133, 0x1b14f), (0x1b153, 0x1b154), (0x1b156, 0x1b163), (0x1b168, 0x1b16f),
+ (0x1b2fc, 0x1bbff), (0x1bc6b, 0x1bc6f), (0x1bc7d, 0x1bc7f), (0x1bc89, 0x1bc8f), (0x1bc9a, 0x1bc9b), (0x1bca0, 0x1cbff),
+ (0x1ccfd, 0x1ccff), (0x1ceb4, 0x1ceb9), (0x1ced1, 0x1cedf), (0x1cef1, 0x1ceff), (0x1cf2e, 0x1cf2f), (0x1cf47, 0x1cf4f),
+ (0x1cfc4, 0x1cfff), (0x1d0f6, 0x1d0ff), (0x1d127, 0x1d128), (0x1d173, 0x1d17a), (0x1d1eb, 0x1d1ff), (0x1d246, 0x1d2bf),
+ (0x1d2d4, 0x1d2df), (0x1d2f4, 0x1d2ff), (0x1d357, 0x1d35f), (0x1d379, 0x1d3ff), (0x1d455, 0x1d455), (0x1d49d, 0x1d49d),
+ (0x1d4a0, 0x1d4a1), (0x1d4a3, 0x1d4a4), (0x1d4a7, 0x1d4a8), (0x1d4ad, 0x1d4ad), (0x1d4ba, 0x1d4ba), (0x1d4bc, 0x1d4bc),
+ (0x1d4c4, 0x1d4c4), (0x1d506, 0x1d506), (0x1d50b, 0x1d50c), (0x1d515, 0x1d515), (0x1d51d, 0x1d51d), (0x1d53a, 0x1d53a),
+ (0x1d53f, 0x1d53f), (0x1d545, 0x1d545), (0x1d547, 0x1d549), (0x1d551, 0x1d551), (0x1d6a6, 0x1d6a7), (0x1d7cc, 0x1d7cd),
+ (0x1da8c, 0x1da9a), (0x1daa0, 0x1daa0), (0x1dab0, 0x1deff), (0x1df1f, 0x1df24), (0x1df2b, 0x1dfff), (0x1e007, 0x1e007),
+ (0x1e019, 0x1e01a), (0x1e022, 0x1e022), (0x1e025, 0x1e025), (0x1e02b, 0x1e02f), (0x1e06e, 0x1e08e), (0x1e090, 0x1e0ff),
+ (0x1e12d, 0x1e12f), (0x1e13e, 0x1e13f), (0x1e14a, 0x1e14d), (0x1e150, 0x1e28f), (0x1e2af, 0x1e2bf), (0x1e2fa, 0x1e2fe),
+ (0x1e300, 0x1e4cf), (0x1e4fa, 0x1e5cf), (0x1e5fb, 0x1e5fe), (0x1e600, 0x1e6bf), (0x1e6df, 0x1e6df), (0x1e6f6, 0x1e6fd),
+ (0x1e700, 0x1e7df), (0x1e7e7, 0x1e7e7), (0x1e7ec, 0x1e7ec), (0x1e7ef, 0x1e7ef), (0x1e7ff, 0x1e7ff), (0x1e8c5, 0x1e8c6),
+ (0x1e8d7, 0x1e8ff), (0x1e94c, 0x1e94f), (0x1e95a, 0x1e95d), (0x1e960, 0x1ec70), (0x1ecb5, 0x1ed00), (0x1ed3e, 0x1edff),
+ (0x1ee04, 0x1ee04), (0x1ee20, 0x1ee20), (0x1ee23, 0x1ee23), (0x1ee25, 0x1ee26), (0x1ee28, 0x1ee28), (0x1ee33, 0x1ee33),
+ (0x1ee38, 0x1ee38), (0x1ee3a, 0x1ee3a), (0x1ee3c, 0x1ee41), (0x1ee43, 0x1ee46), (0x1ee48, 0x1ee48), (0x1ee4a, 0x1ee4a),
+ (0x1ee4c, 0x1ee4c), (0x1ee50, 0x1ee50), (0x1ee53, 0x1ee53), (0x1ee55, 0x1ee56), (0x1ee58, 0x1ee58), (0x1ee5a, 0x1ee5a),
+ (0x1ee5c, 0x1ee5c), (0x1ee5e, 0x1ee5e), (0x1ee60, 0x1ee60), (0x1ee63, 0x1ee63), (0x1ee65, 0x1ee66), (0x1ee6b, 0x1ee6b),
+ (0x1ee73, 0x1ee73), (0x1ee78, 0x1ee78), (0x1ee7d, 0x1ee7d), (0x1ee7f, 0x1ee7f), (0x1ee8a, 0x1ee8a), (0x1ee9c, 0x1eea0),
+ (0x1eea4, 0x1eea4), (0x1eeaa, 0x1eeaa), (0x1eebc, 0x1eeef), (0x1eef2, 0x1efff), (0x1f02c, 0x1f02f), (0x1f094, 0x1f09f),
+ (0x1f0af, 0x1f0b0), (0x1f0c0, 0x1f0c0), (0x1f0d0, 0x1f0d0), (0x1f0f6, 0x1f0ff), (0x1f1ae, 0x1f1e5), (0x1f203, 0x1f20f),
+ (0x1f23c, 0x1f23f), (0x1f249, 0x1f24f), (0x1f252, 0x1f25f), (0x1f266, 0x1f2ff), (0x1f6d9, 0x1f6db), (0x1f6ed, 0x1f6ef),
+ (0x1f6fd, 0x1f6ff), (0x1f7da, 0x1f7df), (0x1f7ec, 0x1f7ef), (0x1f7f1, 0x1f7ff), (0x1f80c, 0x1f80f), (0x1f848, 0x1f84f),
+ (0x1f85a, 0x1f85f), (0x1f888, 0x1f88f), (0x1f8ae, 0x1f8af), (0x1f8bc, 0x1f8bf), (0x1f8c2, 0x1f8cf), (0x1f8d9, 0x1f8ff),
+ (0x1fa58, 0x1fa5f), (0x1fa6e, 0x1fa6f), (0x1fa7d, 0x1fa7f), (0x1fa8b, 0x1fa8d), (0x1fac7, 0x1fac7), (0x1fac9, 0x1facc),
+ (0x1fadd, 0x1fade), (0x1faeb, 0x1faee), (0x1faf9, 0x1faff), (0x1fb93, 0x1fb93), (0x1fbfb, 0x1ffff), (0x2a6e0, 0x2a6ff),
+ (0x2b81e, 0x2b81f), (0x2ceae, 0x2ceaf), (0x2ebe1, 0x2ebef), (0x2ee5e, 0x2f7ff), (0x2fa1e, 0x2ffff), (0x3134b, 0x3134f),
+ (0x3347a, 0xe00ff), (0xe01f0, 0x10ffff),
+];
diff --git a/home/desktop/agent/src/lib.rs b/home/desktop/agent/src/lib.rs
new file mode 100644
index 00000000..4014889e
--- /dev/null
+++ b/home/desktop/agent/src/lib.rs
@@ -0,0 +1,20 @@
+// SPDX-License-Identifier: MIT
+// Copyright (c) 2026 The Bento authors
+//
+// bento/id — the desktop agent core (Windows, Linux).
+//
+// The reference for every byte is kernel/src/statements.ts and
+// kernel/src/address.ts; the CONTRACT is kernel/fixtures/identity-v1.json,
+// which tests/conformance.rs runs row by row. This crate never re-derives a
+// rule from prose: where the reference makes a choice (an order of checks, a
+// JS string semantic), it is mirrored here and commented.
+
+pub mod address;
+pub mod agent;
+pub mod b64u;
+pub mod device_list;
+mod display_table;
+pub mod statements;
+
+#[cfg(all(target_os = "linux", feature = "tpm"))]
+pub mod tpm_linux;
diff --git a/home/desktop/agent/src/statements.rs b/home/desktop/agent/src/statements.rs
new file mode 100644
index 00000000..a3d12f4c
--- /dev/null
+++ b/home/desktop/agent/src/statements.rs
@@ -0,0 +1,708 @@
+// SPDX-License-Identifier: MIT
+// Copyright (c) 2026 The Bento authors
+//
+// bento/id — the signed statements, a port of kernel/src/statements.ts.
+//
+// The family rules (from the reference, unchanged): dot-joined printable-ASCII
+// text signed over its EXACT bytes; every field is a closed dot-free token or
+// base64url free text; split on '.', KEEP empty fields, require the exact
+// count; times are epoch milliseconds; keys are raw uncompressed P-256 points;
+// signatures are raw r‖s, LOW-S, base64url — never DER.
+//
+// Every check runs in the reference's ORDER, so a refused row is refused for
+// the same reason the reference gives. The vectors compare reasons too.
+
+use crate::{address, b64u};
+use p256::ecdsa::{signature::Verifier, Signature, VerifyingKey};
+use p256::elliptic_curve::PrimeField;
+use sha2::{Digest, Sha256};
+use std::collections::HashMap;
+
+pub type Verdict<T> = Result<T, &'static str>;
+
+// --- free text ---------------------------------------------------------------
+
+/// base64url-of-UTF-8 → text, canonical both ways.
+fn free_text(f: &str) -> Option<String> {
+ let b = b64u::dec(f)?;
+ let t = String::from_utf8(b).ok()?;
+ (b64u::enc(t.as_bytes()) == f).then_some(t)
+}
+
+const MAX_DISPLAY: usize = 64;
+
+pub use crate::display_table::{DISPLAY_FORBIDDEN_RANGES, UNICODE as DISPLAY_UNICODE};
+
+/// statements.ts displayForbidden: the frozen ranges (display_table.rs,
+/// generated from the fixture), binary-searched like the reference.
+fn display_forbidden(c: char) -> bool {
+ let cp = c as u32;
+ DISPLAY_FORBIDDEN_RANGES
+ .binary_search_by(|&(a, b)| {
+ if cp < a {
+ std::cmp::Ordering::Greater
+ } else if cp > b {
+ std::cmp::Ordering::Less
+ } else {
+ std::cmp::Ordering::Equal
+ }
+ })
+ .is_ok()
+}
+fn is_joiner(c: char) -> bool {
+ matches!(c, '\u{200C}' | '\u{200D}')
+}
+
+/// A name or device label a person sees. `[...t].length` in JS counts code
+/// points (`chars().count()`); the text must already be NFC.
+fn display_text(f: &str) -> Option<String> {
+ use unicode_normalization::UnicodeNormalization;
+ let t = free_text(f)?;
+ if t.is_empty() || t.chars().count() > MAX_DISPLAY {
+ return None;
+ }
+ if t.nfc().collect::<String>() != t {
+ return None;
+ }
+ if t.chars().any(display_forbidden)
+ || t.chars().next().is_some_and(is_joiner)
+ || t.chars().last().is_some_and(is_joiner)
+ {
+ return None;
+ }
+ Some(t)
+}
+
+pub fn sha256_b64u(text: &str) -> String {
+ b64u::enc(&Sha256::digest(text.as_bytes()))
+}
+
+// --- keys and signatures ---------------------------------------------------------
+
+/// The P-256 group order, big-endian.
+const N: [u8; 32] = [
+ 0xff, 0xff, 0xff, 0xff, 0x00, 0x00, 0x00, 0x00, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
+ 0xbc, 0xe6, 0xfa, 0xad, 0xa7, 0x17, 0x9e, 0x84, 0xf3, 0xb9, 0xca, 0xc2, 0xfc, 0x63, 0x25, 0x51,
+];
+/// N >> 1, big-endian.
+const HALF_N: [u8; 32] = [
+ 0x7f, 0xff, 0xff, 0xff, 0x80, 0x00, 0x00, 0x00, 0x7f, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
+ 0xde, 0x73, 0x7d, 0x56, 0xd3, 0x8b, 0xcf, 0x42, 0x79, 0xdc, 0xe5, 0x61, 0x7e, 0x31, 0x92, 0xa8,
+];
+const ZERO: [u8; 32] = [0; 32];
+
+/// A raw r‖s signature in range, with s in the lower half (r, s > 0; r < N; s ≤ N/2).
+/// Big-endian byte arrays of equal length compare like the integers they hold.
+fn sig_in_range(sig: &[u8]) -> bool {
+ if sig.len() != 64 {
+ return false;
+ }
+ let (r, s) = (&sig[..32], &sig[32..]);
+ r > &ZERO[..] && r < &N[..] && s > &ZERO[..] && s <= &HALF_N[..]
+}
+
+/// The low-S form of a raw r‖s signature: every signer must emit this.
+pub fn low_s(sig: &[u8; 64]) -> [u8; 64] {
+ if sig[32..] <= HALF_N[..] {
+ return *sig;
+ }
+ let mut repr = p256::FieldBytes::default();
+ repr.copy_from_slice(&sig[32..]);
+ let s = p256::Scalar::from_repr(repr);
+ let mut out = *sig;
+ if bool::from(s.is_some()) {
+ out[32..].copy_from_slice(&(-s.unwrap()).to_repr());
+ }
+ out
+}
+
+/// A raw uncompressed P-256 point that is actually on the curve. The same
+/// check serves a signing key and a kx (ECDH) key: WebCrypto's importKey
+/// accepts exactly the valid points for both.
+fn point(b64: &str) -> Option<VerifyingKey> {
+ let raw = b64u::dec(b64)?;
+ if raw.len() != 65 || raw[0] != 0x04 {
+ return None;
+ }
+ VerifyingKey::from_sec1_bytes(&raw).ok()
+}
+pub fn is_signing_key(b64: &str) -> bool {
+ point(b64).is_some()
+}
+pub fn is_kx_key(b64: &str) -> bool {
+ point(b64).is_some()
+}
+
+/// Verify `sig_b64` (raw r‖s, low-S) by `pub_b64` over the exact UTF-8 of `text`.
+pub fn verify_statement_sig(pub_b64: &str, sig_b64: &str, text: &str) -> bool {
+ let Some(sig) = b64u::dec(sig_b64) else { return false };
+ if !sig_in_range(&sig) {
+ return false;
+ }
+ let Some(key) = point(pub_b64) else { return false };
+ let Ok(sig) = Signature::from_slice(&sig) else { return false };
+ key.verify(text.as_bytes(), &sig).is_ok()
+}
+
+/// Sign `text`, emitting the low-S raw form base64url. For tests and software
+/// keys; hardware key stores produce the same bytes and fold through `low_s`.
+pub fn sign_statement(key: &p256::ecdsa::SigningKey, text: &str) -> String {
+ use p256::ecdsa::signature::Signer;
+ let sig: Signature = key.sign(text.as_bytes());
+ let raw: [u8; 64] = sig.to_bytes().into();
+ b64u::enc(&low_s(&raw))
+}
+
+// --- strict parsing --------------------------------------------------------------
+
+const MAX_STATEMENT: usize = 4096;
+
+/// Printable ASCII only, exact prefix and field count, empty fields kept.
+/// `count` includes the prefix.
+fn fields<'a>(text: &'a str, prefix: &str, count: usize) -> Option<Vec<&'a str>> {
+ if text.is_empty() || text.len() > MAX_STATEMENT || !text.bytes().all(|c| (0x21..=0x7e).contains(&c)) {
+ return None;
+ }
+ let parts: Vec<&str> = text.split('.').collect();
+ (parts.len() == count && parts[0] == prefix).then_some(parts)
+}
+
+/// INT_RE ^(0|[1-9][0-9]{0,15})$, and a JS safe integer.
+fn is_int_text(f: &str) -> bool {
+ let b = f.as_bytes();
+ f == "0" || (!b.is_empty() && b.len() <= 16 && b[0] != b'0' && b.iter().all(u8::is_ascii_digit))
+}
+fn int(f: &str) -> Option<u64> {
+ if !is_int_text(f) {
+ return None;
+ }
+ let n: u64 = f.parse().ok()?;
+ (n <= (1u64 << 53) - 1).then_some(n)
+}
+fn ms(f: &str) -> Option<u64> {
+ int(f).filter(|n| *n > 0)
+}
+fn is_hash(f: &str) -> bool {
+ b64u::dec(f).map(|b| b.len() == 32).unwrap_or(false)
+}
+
+fn lower_digit(c: u8) -> bool {
+ c.is_ascii_lowercase() || c.is_ascii_digit()
+}
+/// KID_RE ^[a-z0-9][a-z0-9-]{0,62}$
+fn is_kid(f: &str) -> bool {
+ let b = f.as_bytes();
+ !b.is_empty() && b.len() <= 63 && lower_digit(b[0]) && b.iter().all(|c| lower_digit(*c) || *c == b'-')
+}
+/// RP_RE ^(bento|vault-[a-z0-9][a-z0-9-]{0,62})$
+fn is_rp(f: &str) -> bool {
+ f == "bento" || f.strip_prefix("vault-").map(is_kid).unwrap_or(false)
+}
+fn b64_char(c: u8) -> bool {
+ c.is_ascii_alphanumeric() || c == b'_' || c == b'-'
+}
+/// DOCID_RE ^[A-Za-z0-9_-]{1,128}$ (security §19i)
+pub fn is_doc_id(f: &str) -> bool {
+ (1..=128).contains(&f.len()) && f.bytes().all(b64_char)
+}
+/// ROOM_RE ^w[A-Za-z0-9_-]{43}$
+fn is_room(f: &str) -> bool {
+ f.len() == 44 && f.as_bytes()[0] == b'w' && f.bytes().all(b64_char)
+}
+/// CODE_RE ^[23456789ABCDEFGHJKMNPQRSTUVWXYZ]{8}$
+fn is_code(f: &str) -> bool {
+ f.len() == 8 && f.bytes().all(|c| b"23456789ABCDEFGHJKMNPQRSTUVWXYZ".contains(&c))
+}
+
+pub const SKEW_MS: u64 = 5 * 60_000;
+const DAY: u64 = 86_400_000;
+/// 13 × 30.5 days + 1 = 397.5 days, exactly.
+pub const CERT_MAX_MS: u64 = 397 * DAY + DAY / 2;
+
+fn lifetime(created: u64, expires: u64, now: u64) -> Option<&'static str> {
+ if expires <= created || expires - created > CERT_MAX_MS {
+ return Some("lifetime");
+ }
+ if created > now + SKEW_MS {
+ return Some("not-yet-valid");
+ }
+ if now >= expires {
+ return Some("expired");
+ }
+ None
+}
+
+// --- kx placement (unruled: both slots empty) ------------------------------------
+
+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
+pub enum KxMode {
+ Unruled,
+ A,
+ B,
+ C,
+}
+impl KxMode {
+ pub fn parse(s: &str) -> Option<KxMode> {
+ Some(match s {
+ "unruled" => KxMode::Unruled,
+ "A" => KxMode::A,
+ "B" => KxMode::B,
+ "C" => KxMode::C,
+ _ => return None,
+ })
+ }
+ /// (bind slot required, dev slot required)
+ fn slots(self) -> (bool, bool) {
+ match self {
+ KxMode::Unruled => (false, false),
+ KxMode::A => (true, false),
+ KxMode::B => (false, true),
+ KxMode::C => (true, true),
+ }
+ }
+}
+/// The mode this build runs in. The maintainer has not ruled (§6b), so both
+/// slots must be empty and nothing accepts a placement nobody chose.
+pub const KX_MODE: KxMode = KxMode::Unruled;
+
+/// Ok(None) = empty and allowed; Ok(Some(kx)) = present and valid; Err = refuse.
+fn kx_slot(f: &str, required: bool, others: &[&str]) -> Result<Option<String>, ()> {
+ if !required {
+ return if f.is_empty() { Ok(None) } else { Err(()) };
+ }
+ if f.is_empty() || !is_kx_key(f) || others.contains(&f) {
+ return Err(());
+ }
+ Ok(Some(f.to_string()))
+}
+
+// --- dev. ------------------------------------------------------------------------
+
+/// `dev.<devicePub>.<consentPub|empty>.<accountPub>.<kx|empty>.<b64u(label)|empty>.<created>.<expires>`
+#[derive(Debug, Clone, PartialEq, Eq)]
+pub struct DeviceCert {
+ pub device_pub: String,
+ pub consent_pub: Option<String>,
+ pub account_pub: String,
+ pub kx: Option<String>,
+ pub label: Option<String>,
+ pub created: u64,
+ pub expires: u64,
+}
+
+pub fn build_dev(c: &DeviceCert) -> String {
+ [
+ "dev".into(),
+ c.device_pub.clone(),
+ c.consent_pub.clone().unwrap_or_default(),
+ c.account_pub.clone(),
+ c.kx.clone().unwrap_or_default(),
+ c.label.as_deref().filter(|l| !l.is_empty()).map(|l| b64u::enc(l.as_bytes())).unwrap_or_default(),
+ c.created.to_string(),
+ c.expires.to_string(),
+ ]
+ .join(".")
+}
+
+pub fn verify_dev(text: &str, sig: &str, now: u64, kx_mode: KxMode) -> Verdict<DeviceCert> {
+ let p = fields(text, "dev", 8).ok_or("grammar")?;
+ let (device_pub, consent_f, account_pub, kx_f, label_f, created_f, expires_f) =
+ (p[1], p[2], p[3], p[4], p[5], p[6], p[7]);
+ if !is_signing_key(device_pub) || !is_signing_key(account_pub) || device_pub == account_pub {
+ return Err("key");
+ }
+ let mut consent_pub = None;
+ if !consent_f.is_empty() {
+ if !is_signing_key(consent_f) || consent_f == device_pub || consent_f == account_pub {
+ return Err("consent-key");
+ }
+ consent_pub = Some(consent_f.to_string());
+ }
+ let kx = kx_slot(kx_f, kx_mode.slots().1, &[device_pub, account_pub, consent_f]).map_err(|_| "kx")?;
+ let mut label = None;
+ if !label_f.is_empty() {
+ label = Some(display_text(label_f).ok_or("label")?);
+ }
+ let (created, expires) = (ms(created_f).ok_or("grammar")?, ms(expires_f).ok_or("grammar")?);
+ if let Some(l) = lifetime(created, expires, now) {
+ return Err(l);
+ }
+ if !verify_statement_sig(account_pub, sig, text) {
+ return Err("signature");
+ }
+ Ok(DeviceCert { device_pub: device_pub.into(), consent_pub, account_pub: account_pub.into(), kx, label, created, expires })
+}
+
+// --- bind. -----------------------------------------------------------------------
+
+/// `bind.<b64u(address)>.<accountPub>.<kx|empty>.<b64u(name)|empty>.<seq>.<prev|empty>.<created>.<expires>`
+#[derive(Debug, Clone, PartialEq, Eq)]
+pub struct BindCert {
+ pub address: String,
+ pub account_pub: String,
+ pub kx: Option<String>,
+ pub name: Option<String>,
+ pub seq: u64,
+ pub prev: Option<String>,
+ pub created: u64,
+ pub expires: u64,
+}
+
+pub fn build_bind(c: &BindCert) -> String {
+ [
+ "bind".into(),
+ b64u::enc(c.address.as_bytes()),
+ c.account_pub.clone(),
+ c.kx.clone().unwrap_or_default(),
+ c.name.as_deref().filter(|n| !n.is_empty()).map(|n| b64u::enc(n.as_bytes())).unwrap_or_default(),
+ c.seq.to_string(),
+ c.prev.clone().unwrap_or_default(),
+ c.created.to_string(),
+ c.expires.to_string(),
+ ]
+ .join(".")
+}
+
+pub fn verify_bind(text: &str, sig: &str, now: u64, kx_mode: KxMode) -> Verdict<BindCert> {
+ let p = fields(text, "bind", 9).ok_or("grammar")?;
+ let (address_f, account_pub, kx_f, name_f, seq_f, prev_f, created_f, expires_f) =
+ (p[1], p[2], p[3], p[4], p[5], p[6], p[7], p[8]);
+ let address = free_text(address_f).filter(|a| address::is_normal(a)).ok_or("address")?;
+ if !is_signing_key(account_pub) {
+ return Err("key");
+ }
+ let kx = kx_slot(kx_f, kx_mode.slots().0, &[account_pub]).map_err(|_| "kx")?;
+ let mut name = None;
+ if !name_f.is_empty() {
+ name = Some(display_text(name_f).ok_or("name")?);
+ }
+ let seq = int(seq_f).filter(|s| *s >= 1).ok_or("seq")?;
+ if (seq == 1) != prev_f.is_empty() || (!prev_f.is_empty() && !is_hash(prev_f)) {
+ return Err("prev");
+ }
+ let (created, expires) = (ms(created_f).ok_or("grammar")?, ms(expires_f).ok_or("grammar")?);
+ if let Some(l) = lifetime(created, expires, now) {
+ return Err(l);
+ }
+ if !verify_statement_sig(account_pub, sig, text) {
+ return Err("signature");
+ }
+ Ok(BindCert {
+ address,
+ account_pub: account_pub.into(),
+ kx,
+ name,
+ seq,
+ prev: (!prev_f.is_empty()).then(|| prev_f.to_string()),
+ created,
+ expires,
+ })
+}
+
+// --- att. ------------------------------------------------------------------------
+
+/// `att.<sha256(bind text)>.<verifiedAt>.<issuedAt>.<kid>.<active|pending|frozen>`
+#[derive(Debug, Clone, PartialEq, Eq)]
+pub struct Attestation {
+ pub bind_hash: String,
+ pub verified_at: u64,
+ pub issued_at: u64,
+ pub kid: String,
+ pub state: String,
+}
+
+pub fn build_att(a: &Attestation) -> String {
+ format!("att.{}.{}.{}.{}.{}", a.bind_hash, a.verified_at, a.issued_at, a.kid, a.state)
+}
+
+pub fn verify_att(
+ text: &str,
+ sig: &str,
+ directory_keys: &HashMap<String, String>,
+ bind_text: &str,
+ now: u64,
+ max_age_ms: u64,
+) -> Verdict<Attestation> {
+ let p = fields(text, "att", 6).ok_or("grammar")?;
+ let (bind_hash, verified_f, issued_f, kid, state) = (p[1], p[2], p[3], p[4], p[5]);
+ if !is_hash(bind_hash) || !is_kid(kid) || !matches!(state, "active" | "pending" | "frozen") {
+ return Err("grammar");
+ }
+ let (verified_at, issued_at) = (ms(verified_f).ok_or("grammar")?, ms(issued_f).ok_or("grammar")?);
+ if verified_at > issued_at {
+ return Err("grammar");
+ }
+ if issued_at > now + SKEW_MS {
+ return Err("not-yet-valid");
+ }
+ // `now - issuedAt > maxAgeMs` in JS, with issuedAt possibly ahead of now
+ // (within the skew): signed arithmetic.
+ if now as i128 - issued_at as i128 > max_age_ms as i128 {
+ return Err("stale");
+ }
+ if bind_hash != sha256_b64u(bind_text) {
+ return Err("bind-mismatch");
+ }
+ let key = directory_keys.get(kid).ok_or("unknown-kid")?;
+ if !verify_statement_sig(key, sig, text) {
+ return Err("signature");
+ }
+ Ok(Attestation { bind_hash: bind_hash.into(), verified_at, issued_at, kid: kid.into(), state: state.into() })
+}
+
+// --- tomb. -----------------------------------------------------------------------
+
+/// `tomb.<sha256(last bind text)|empty>.<seq>.<deletedAt>.<holder|mailbox|operator>.<kid>`
+#[derive(Debug, Clone, PartialEq, Eq)]
+pub struct Tombstone {
+ pub last_bind_hash: Option<String>,
+ pub seq: u64,
+ pub deleted_at: u64,
+ pub by: String,
+ pub kid: String,
+}
+
+pub fn build_tomb(t: &Tombstone) -> String {
+ format!("tomb.{}.{}.{}.{}.{}", t.last_bind_hash.clone().unwrap_or_default(), t.seq, t.deleted_at, t.by, t.kid)
+}
+
+pub fn verify_tomb(text: &str, sig: &str, directory_keys: &HashMap<String, String>, now: u64) -> Verdict<Tombstone> {
+ let p = fields(text, "tomb", 6).ok_or("grammar")?;
+ let (hash_f, seq_f, deleted_f, by, kid) = (p[1], p[2], p[3], p[4], p[5]);
+ if !hash_f.is_empty() && !is_hash(hash_f) {
+ return Err("grammar");
+ }
+ let seq = int(seq_f).filter(|s| *s >= 1).ok_or("grammar")?;
+ let deleted_at = ms(deleted_f).ok_or("grammar")?;
+ if !matches!(by, "holder" | "mailbox" | "operator") || !is_kid(kid) {
+ return Err("grammar");
+ }
+ if deleted_at > now + SKEW_MS {
+ return Err("not-yet-valid");
+ }
+ let key = directory_keys.get(kid).ok_or("unknown-kid")?;
+ if !verify_statement_sig(key, sig, text) {
+ return Err("signature");
+ }
+ Ok(Tombstone {
+ last_bind_hash: (!hash_f.is_empty()).then(|| hash_f.to_string()),
+ seq,
+ deleted_at,
+ by: by.into(),
+ kid: kid.into(),
+ })
+}
+
+// --- del. ------------------------------------------------------------------------
+
+pub const DELETE_WINDOW_MS: u64 = 5 * 60_000;
+
+pub fn build_del(address: &str, ts: u64) -> String {
+ format!("del.{}.{}", b64u::enc(address.as_bytes()), ts)
+}
+
+pub fn verify_del(text: &str, sig: &str, account_pub: &str, now: u64) -> Verdict<(String, u64)> {
+ let p = fields(text, "del", 3).ok_or("grammar")?;
+ let address = free_text(p[1]).filter(|a| address::is_normal(a)).ok_or("address")?;
+ let ts = ms(p[2]).ok_or("grammar")?;
+ if now.abs_diff(ts) > DELETE_WINDOW_MS {
+ return Err("expired");
+ }
+ if !verify_statement_sig(account_pub, sig, text) {
+ return Err("signature");
+ }
+ Ok((address, ts))
+}
+
+// --- cmp. ------------------------------------------------------------------------
+
+pub fn build_cmp(bind_hash: &str, code: &str) -> String {
+ format!("cmp.{bind_hash}.{code}")
+}
+
+pub fn verify_cmp(text: &str, sig: &str, account_pub: &str, bind_text: &str) -> Verdict<(String, String)> {
+ let p = fields(text, "cmp", 3).ok_or("grammar")?;
+ let (bind_hash, code) = (p[1], p[2]);
+ if !is_hash(bind_hash) || !is_code(code) {
+ return Err("grammar");
+ }
+ if bind_hash != sha256_b64u(bind_text) {
+ return Err("bind-mismatch");
+ }
+ if !verify_statement_sig(account_pub, sig, text) {
+ return Err("signature");
+ }
+ Ok((bind_hash.into(), code.into()))
+}
+
+// --- cns. ------------------------------------------------------------------------
+
+/// The consent purposes, a CLOSED set, and the statement family each authorises.
+fn consent_family(purpose: &str) -> Option<&'static str> {
+ Some(match purpose {
+ "invite" => "inv.",
+ "revoke" => "rev.",
+ "link" => "dev.",
+ "rotate" => "bind.",
+ "unbind" => "del.",
+ _ => return None,
+ })
+}
+const RESERVED_PURPOSES: [&str; 2] = ["grant", "role"];
+fn doc_scoped(purpose: &str) -> bool {
+ matches!(purpose, "invite" | "revoke")
+}
+
+pub const CONSENT_MAX_TTL_MS: u64 = 5 * 60_000;
+
+/// AUDIENCE_RE ^(dir|room:<room>)$
+fn is_audience(a: &str) -> bool {
+ a == "dir" || a.strip_prefix("room:").map(is_room).unwrap_or(false)
+}
+
+/// The channel binding (security §24):
+/// b64u(SHA-256("cnst.v1." ‖ audience ‖ "." ‖ challenge ‖ "." ‖ b64u(SHA-256(payload)))).
+/// None if a part breaks its grammar.
+pub fn consent_transcript(audience: &str, challenge: &str, payload_text: &str) -> Option<String> {
+ if !is_audience(audience) {
+ return None;
+ }
+ let c = b64u::dec(challenge)?;
+ if !(16..=64).contains(&c.len()) {
+ return None;
+ }
+ Some(sha256_b64u(&format!("cnst.v1.{audience}.{challenge}.{}", sha256_b64u(payload_text))))
+}
+
+#[derive(Debug, Clone, PartialEq, Eq)]
+pub struct Consent {
+ pub rp: String,
+ pub purpose: String,
+ pub doc_id: Option<String>,
+ pub transcript: String,
+ pub exp: u64,
+}
+
+/// `cns.<rp>.<purpose>.<docId|empty>.<transcript>.<exp>`, every field host-stamped.
+pub fn build_consent(c: &Consent) -> String {
+ format!("cns.{}.{}.{}.{}.{}", c.rp, c.purpose, c.doc_id.clone().unwrap_or_default(), c.transcript, c.exp)
+}
+
+pub struct ConsentCheck<'a> {
+ /// from a VERIFIED dev. certificate's consentPub
+ pub consent_pub: &'a str,
+ pub rp: &'a str,
+ pub audience: &'a str,
+ pub challenge: &'a str,
+ pub payload_text: &'a str,
+ pub doc_id: Option<&'a str>,
+ pub now: u64,
+}
+
+/// Verify a consent signature. The transcript is RECOMPUTED from the verifier's
+/// own audience, challenge and payload. `spend` must mark the challenge used and
+/// return false if it was already spent or expired; it runs right after the
+/// grammar check, so any attempt consumes the challenge.
+pub fn verify_consent(text: &str, sig: &str, o: &ConsentCheck, spend: impl FnOnce(&str) -> bool) -> Verdict<Consent> {
+ let p = fields(text, "cns", 6).ok_or("grammar")?;
+ if !spend(o.challenge) {
+ return Err("replay");
+ }
+ let (rp, purpose, doc_id_f, transcript, exp_f) = (p[1], p[2], p[3], p[4], p[5]);
+ if !is_rp(rp) || !is_hash(transcript) {
+ return Err("grammar");
+ }
+ if RESERVED_PURPOSES.contains(&purpose) {
+ return Err("reserved-purpose");
+ }
+ let family = consent_family(purpose).ok_or("grammar")?;
+ let exp = ms(exp_f).ok_or("grammar")?;
+ if rp != o.rp {
+ return Err("rp");
+ }
+ if !o.payload_text.starts_with(family) {
+ return Err("payload-family");
+ }
+ if doc_scoped(purpose) {
+ if !is_doc_id(doc_id_f) || Some(doc_id_f) != o.doc_id {
+ return Err("docid");
+ }
+ } else if !doc_id_f.is_empty() || o.doc_id.is_some() {
+ return Err("docid");
+ }
+ match consent_transcript(o.audience, o.challenge, o.payload_text) {
+ Some(t) if t == transcript => {}
+ _ => return Err("transcript"),
+ }
+ if o.now >= exp {
+ return Err("expired");
+ }
+ if exp - o.now > CONSENT_MAX_TTL_MS {
+ return Err("lifetime");
+ }
+ if !verify_statement_sig(o.consent_pub, sig, text) {
+ return Err("signature");
+ }
+ Ok(Consent {
+ rp: rp.into(),
+ purpose: purpose.into(),
+ doc_id: (!doc_id_f.is_empty()).then(|| doc_id_f.to_string()),
+ transcript: transcript.into(),
+ exp,
+ })
+}
+
+/// The light tier's clientDataJSON.challenge for a cns. (security §27).
+pub fn webauthn_challenge_for(cns_text: &str) -> String {
+ sha256_b64u(cns_text)
+}
+
+/// Prefixes reserved for statements not defined yet.
+pub const RESERVED_PREFIXES: [&str; 1] = ["pk"];
+
+// --- routine signing: which payload each SignPurpose may sign ---------------------
+
+fn b64_len(f: &str, min: usize, exact: Option<usize>) -> bool {
+ match b64u::dec(f) {
+ Some(b) => exact.map(|e| b.len() == e).unwrap_or(b.len() >= min),
+ None => false,
+ }
+}
+fn is_pub_field(f: &str) -> bool {
+ b64u::dec(f).map(|b| b.len() == 65 && b[0] == 0x04).unwrap_or(false)
+}
+fn iv(f: &str) -> bool {
+ b64_len(f, 0, Some(12))
+}
+fn ct(f: &str) -> bool {
+ b64_len(f, 16, None)
+}
+/// ^[rw][A-Za-z0-9_-]{1,64}$
+fn is_room_name(f: &str) -> bool {
+ let b = f.as_bytes();
+ (2..=65).contains(&b.len()) && (b[0] == b'r' || b[0] == b'w') && b[1..].iter().all(|c| b64_char(*c))
+}
+
+/// Does `payload` have the exact shape of the statement `purpose` names?
+/// The agent signs only a matching payload.
+pub fn payload_matches_purpose(purpose: &str, payload: &str) -> bool {
+ if payload.len() > MAX_STATEMENT {
+ return false;
+ }
+ let p: Vec<&str> = payload.split('.').collect();
+ match purpose {
+ "frame" => p.len() == 2 && iv(p[0]) && ct(p[1]),
+ "prove" => p.len() == 3 && p[0] == "prove" && b64_len(p[1], 16, None) && is_room_name(p[2]),
+ "delegate" => p.len() == 2 && p[0] == "dlg" && is_pub_field(p[1]),
+ "show" => {
+ (p.len() == 1 && (p[0] == "live" || p[0] == "end"))
+ || (p.len() == 4 && (p[0] == "nav" || p[0] == "black") && p[1] == "aud" && iv(p[2]) && ct(p[3]))
+ }
+ "invite" => {
+ p.len() == 4 && p[0] == "inv" && is_pub_field(p[1])
+ && matches!(p[2], "writer" | "commenter" | "audience") && is_int_text(p[3])
+ }
+ "revoke" => p.len() == 2 && p[0] == "rev" && is_pub_field(p[1]),
+ _ => false,
+ }
+}
diff --git a/home/desktop/agent/src/tpm_linux.rs b/home/desktop/agent/src/tpm_linux.rs
new file mode 100644
index 00000000..ac9606f2
--- /dev/null
+++ b/home/desktop/agent/src/tpm_linux.rs
@@ -0,0 +1,307 @@
+// SPDX-License-Identifier: MIT
+// Copyright (c) 2026 The Bento authors
+//
+// The Linux TPM key store (H1b), per security §26 / §26a / §26b and the H1 key
+// table:
+//
+// - DEVICE (routine) key: an ECC P-256 signing key CREATED IN the TPM,
+// non-exportable (fixedTPM | fixedParent | sensitiveDataOrigin), with an empty
+// authValue — no per-use prompt; the agent's session timers gate the genuine
+// agent. Residual (security): a same-user process that can open the TPM can
+// ALSO sign routine frames with it; it can never copy it off the machine.
+// - CONSENT key: the same, with the person's PIN as its authValue, so EVERY
+// signature needs the PIN, and the TPM's dictionary-attack lockout limits
+// guessing. A same-user process cannot use it without the PIN.
+// - ACCOUNT key (shared across devices, so it cannot be born in one TPM): a
+// sealed data object under the same PIN, unsealed only for a prompted use and
+// zeroized at once (§26b).
+//
+// What is stored on disk is only the TPM-WRAPPED public/private blob pair: it
+// loads on THIS TPM and nowhere else, so copying the files copies nothing usable.
+//
+// "TPM present" means this user can open it (tss group / /dev/tpmrm0); otherwise
+// the host uses the no-TPM store and says so. tss-group access is per user, so it
+// adds no isolation between that user's processes.
+
+use crate::agent::{KeyRole, KeyStore, Prompt, StoreError};
+use sha2::{Digest, Sha256};
+use std::path::PathBuf;
+use tss_esapi::{
+ attributes::ObjectAttributesBuilder,
+ constants::tss::{TPM2_RH_NULL, TPM2_ST_HASHCHECK},
+ handles::KeyHandle,
+ interface_types::{
+ algorithm::{HashingAlgorithm, PublicAlgorithm},
+ ecc::EccCurve,
+ key_bits::RsaKeyBits,
+ resource_handles::Hierarchy,
+ session_handles::AuthSession,
+ },
+ structures::{
+ Auth, Digest as TpmDigest, EccPoint, EccScheme, HashScheme, HashcheckTicket, KeyedHashScheme, Private, Public,
+ PublicBuilder, PublicEccParametersBuilder, PublicKeyedHashParameters, SensitiveData, Signature, SignatureScheme,
+ SymmetricDefinitionObject,
+ },
+ tss2_esys::TPMT_TK_HASHCHECK,
+ traits::{Marshall, UnMarshall},
+ utils::create_restricted_decryption_rsa_public,
+ Context, TctiNameConf,
+};
+use zeroize::Zeroizing;
+
+/// Asks the person for their TPM PIN, drawn by the HOST (never the page).
+/// None = they declined.
+pub type PinPrompt = Box<dyn FnMut(&Prompt) -> Option<Zeroizing<String>>>;
+
+pub struct TpmStore {
+ ctx: Context,
+ dir: PathBuf,
+ pin: PinPrompt,
+}
+
+fn tpm_err(e: impl std::fmt::Display) -> StoreError {
+ StoreError::Unavailable(e.to_string())
+}
+
+fn name(role: &KeyRole) -> &'static str {
+ match role {
+ KeyRole::Account => "account",
+ KeyRole::Device => "device",
+ KeyRole::Consent => "consent",
+ }
+}
+
+fn ecc_signing_public(with_auth: bool) -> Result<Public, StoreError> {
+ let attrs = ObjectAttributesBuilder::new()
+ .with_fixed_tpm(true)
+ .with_fixed_parent(true)
+ .with_sensitive_data_origin(true)
+ .with_user_with_auth(true)
+ .with_sign_encrypt(true)
+ .with_decrypt(false)
+ .with_restricted(false)
+ .build()
+ .map_err(tpm_err)?;
+ let _ = with_auth; // the authValue is set at create; userWithAuth applies to both
+ PublicBuilder::new()
+ .with_public_algorithm(PublicAlgorithm::Ecc)
+ .with_name_hashing_algorithm(HashingAlgorithm::Sha256)
+ .with_object_attributes(attrs)
+ .with_ecc_parameters(
+ PublicEccParametersBuilder::new_unrestricted_signing_key(
+ EccScheme::EcDsa(HashScheme::new(HashingAlgorithm::Sha256)),
+ EccCurve::NistP256,
+ )
+ .build()
+ .map_err(tpm_err)?,
+ )
+ .with_ecc_unique_identifier(EccPoint::default())
+ .build()
+ .map_err(tpm_err)
+}
+
+fn sealed_public() -> Result<Public, StoreError> {
+ let attrs = ObjectAttributesBuilder::new()
+ .with_fixed_tpm(true)
+ .with_fixed_parent(true)
+ .with_user_with_auth(true)
+ .build()
+ .map_err(tpm_err)?;
+ PublicBuilder::new()
+ .with_public_algorithm(PublicAlgorithm::KeyedHash)
+ .with_name_hashing_algorithm(HashingAlgorithm::Sha256)
+ .with_object_attributes(attrs)
+ .with_keyed_hash_parameters(PublicKeyedHashParameters::new(KeyedHashScheme::Null))
+ .with_keyed_hash_unique_identifier(TpmDigest::default())
+ .build()
+ .map_err(tpm_err)
+}
+
+/// Raw uncompressed point from a TPM ECC public area.
+fn point(public: &Public) -> Result<[u8; 65], StoreError> {
+ match public {
+ Public::Ecc { unique, .. } => {
+ let (x, y) = (unique.x().value(), unique.y().value());
+ if x.len() > 32 || y.len() > 32 {
+ return Err(StoreError::Unavailable("bad point".into()));
+ }
+ let mut out = [0u8; 65];
+ out[0] = 4;
+ out[1 + 32 - x.len()..33].copy_from_slice(x);
+ out[33 + 32 - y.len()..].copy_from_slice(y);
+ Ok(out)
+ }
+ _ => Err(StoreError::Unavailable("not an ECC key".into())),
+ }
+}
+
+impl TpmStore {
+ /// Open the TPM named by `tcti` (e.g. "device:/dev/tpmrm0", "swtpm:port=2321")
+ /// and keep blobs in `dir`.
+ pub fn open(tcti: &str, dir: PathBuf, pin: PinPrompt) -> Result<TpmStore, StoreError> {
+ let conf: TctiNameConf = tcti.parse().map_err(tpm_err)?;
+ let ctx = Context::new(conf).map_err(tpm_err)?;
+ std::fs::create_dir_all(&dir).map_err(tpm_err)?;
+ Ok(TpmStore { ctx, dir, pin })
+ }
+
+ /// The storage primary key, re-derived from its template each time (same
+ /// seed + same template = same key), so no persistent handle is needed.
+ fn primary(&mut self) -> Result<KeyHandle, StoreError> {
+ let public = create_restricted_decryption_rsa_public(
+ SymmetricDefinitionObject::AES_128_CFB,
+ RsaKeyBits::Rsa2048,
+ Default::default(),
+ )
+ .map_err(tpm_err)?;
+ let r = self
+ .ctx
+ .execute_with_session(Some(AuthSession::Password), |c| {
+ c.create_primary(Hierarchy::Owner, public, None, None, None, None)
+ })
+ .map_err(tpm_err)?;
+ Ok(r.key_handle)
+ }
+
+ fn paths(&self, role: &KeyRole) -> (PathBuf, PathBuf) {
+ (self.dir.join(format!("{}.pub", name(role))), self.dir.join(format!("{}.priv", name(role))))
+ }
+
+ fn stored(&self, role: &KeyRole) -> Result<Option<(Public, Private)>, StoreError> {
+ let (pp, pv) = self.paths(role);
+ if !pp.exists() {
+ return Ok(None);
+ }
+ let public = Public::unmarshall(&std::fs::read(pp).map_err(tpm_err)?).map_err(tpm_err)?;
+ let private = Private::try_from(std::fs::read(pv).map_err(tpm_err)?).map_err(tpm_err)?;
+ Ok(Some((public, private)))
+ }
+
+ fn save(&self, role: &KeyRole, public: &Public, private: &Private) -> Result<(), StoreError> {
+ let (pp, pv) = self.paths(role);
+ std::fs::write(pp, public.marshall().map_err(tpm_err)?).map_err(tpm_err)?;
+ std::fs::write(pv, private.value()).map_err(tpm_err)
+ }
+
+ /// Create the device (no auth) or consent (PIN) key in the TPM.
+ pub fn create_signing_key(&mut self, role: &KeyRole, pin: Option<&str>) -> Result<[u8; 65], StoreError> {
+ let parent = self.primary()?;
+ let public = ecc_signing_public(pin.is_some())?;
+ let auth = pin.map(|p| Auth::try_from(p.as_bytes().to_vec())).transpose().map_err(tpm_err)?;
+ let r = self
+ .ctx
+ .execute_with_session(Some(AuthSession::Password), |c| c.create(parent, public, auth, None, None, None))
+ .map_err(tpm_err)?;
+ self.ctx.flush_context(parent.into()).map_err(tpm_err)?;
+ self.save(role, &r.out_public, &r.out_private)?;
+ point(&r.out_public)
+ }
+
+ /// Seal `secret` (the account key) under the PIN.
+ pub fn seal_account(&mut self, secret: &[u8], pin: &str) -> Result<(), StoreError> {
+ let parent = self.primary()?;
+ let data = SensitiveData::try_from(secret.to_vec()).map_err(tpm_err)?;
+ let auth = Auth::try_from(pin.as_bytes().to_vec()).map_err(tpm_err)?;
+ let public = sealed_public()?;
+ let r = self
+ .ctx
+ .execute_with_session(Some(AuthSession::Password), |c| c.create(parent, public, Some(auth), Some(data), None, None))
+ .map_err(tpm_err)?;
+ self.ctx.flush_context(parent.into()).map_err(tpm_err)?;
+ self.save(&KeyRole::Account, &r.out_public, &r.out_private)
+ }
+
+ /// Unseal the account key for ONE prompted use; the caller zeroizes it.
+ pub fn unseal_account(&mut self, prompt: &Prompt) -> Result<Zeroizing<Vec<u8>>, StoreError> {
+ let (public, private) = self.stored(&KeyRole::Account)?.ok_or(StoreError::NoKey)?;
+ let pin = (self.pin)(prompt).ok_or(StoreError::Declined)?;
+ let parent = self.primary()?;
+ let h = self
+ .ctx
+ .execute_with_session(Some(AuthSession::Password), |c| c.load(parent, private, public))
+ .map_err(tpm_err);
+ self.ctx.flush_context(parent.into()).map_err(tpm_err)?;
+ let h = h?;
+ self.ctx.tr_set_auth(h.into(), Auth::try_from(pin.as_bytes().to_vec()).map_err(tpm_err)?).map_err(tpm_err)?;
+ let out = self.ctx.execute_with_session(Some(AuthSession::Password), |c| c.unseal(h.into()));
+ let _ = self.ctx.flush_context(h.into());
+ let data = out.map_err(|e| auth_failure(e.to_string()))?;
+ Ok(Zeroizing::new(data.value().to_vec()))
+ }
+}
+
+/// A wrong PIN is a refusal the person can retry, not an outage. Matched on the
+/// TPM's OWN authorization failures only (measured on swtpm: a wrong PIN on
+/// Sign and on Unseal both return TPM_RC_AUTH_FAIL, "the authorization HMAC
+/// check failed and DA counter incremented"), so an unrelated error can never
+/// masquerade as "the person said no".
+fn auth_failure(msg: String) -> StoreError {
+ const AUTH: [&str; 3] = [
+ "the authorization HMAC check failed", // TPM_RC_AUTH_FAIL (counts toward DA lockout)
+ "authorization failure without DA implications", // TPM_RC_BAD_AUTH
+ "authorizations for objects subject to DA protection are not allowed at this time", // TPM_RC_LOCKOUT
+ ];
+ if AUTH.iter().any(|a| msg.contains(a)) {
+ StoreError::Declined
+ } else {
+ StoreError::Unavailable(msg)
+ }
+}
+
+impl KeyStore for TpmStore {
+ fn public_key(&self, role: &KeyRole) -> Result<Option<[u8; 65]>, StoreError> {
+ match self.stored(role)? {
+ Some((public, _)) if *role != KeyRole::Account => Ok(Some(point(&public)?)),
+ _ => Ok(None),
+ }
+ }
+
+ fn sign(&mut self, role: &KeyRole, msg: &[u8], prompt: Option<&Prompt>) -> Result<[u8; 64], StoreError> {
+ if *role == KeyRole::Account {
+ return Err(StoreError::Unavailable("the account key signs via unseal_account".into()));
+ }
+ let (public, private) = self.stored(role)?.ok_or(StoreError::NoKey)?;
+ // The consent key needs the PIN on EVERY use; the device key needs none.
+ let pin = if *role == KeyRole::Consent {
+ let p = prompt.ok_or(StoreError::Unavailable("consent needs a prompt".into()))?;
+ Some((self.pin)(p).ok_or(StoreError::Declined)?)
+ } else {
+ None
+ };
+ let parent = self.primary()?;
+ let h = self.ctx.execute_with_session(Some(AuthSession::Password), |c| c.load(parent, private, public)).map_err(tpm_err);
+ self.ctx.flush_context(parent.into()).map_err(tpm_err)?;
+ let h = h?;
+ if let Some(pin) = &pin {
+ self.ctx.tr_set_auth(h.into(), Auth::try_from(pin.as_bytes().to_vec()).map_err(tpm_err)?).map_err(tpm_err)?;
+ }
+ let digest = TpmDigest::try_from(Sha256::digest(msg).to_vec()).map_err(tpm_err)?;
+ let ticket = HashcheckTicket::try_from(TPMT_TK_HASHCHECK {
+ tag: TPM2_ST_HASHCHECK,
+ hierarchy: TPM2_RH_NULL,
+ digest: Default::default(),
+ })
+ .map_err(tpm_err)?;
+ let sig = self
+ .ctx
+ .execute_with_session(Some(AuthSession::Password), |c| c.sign(h, digest, SignatureScheme::Null, ticket));
+ let _ = self.ctx.flush_context(h.into());
+ match sig.map_err(|e| auth_failure(e.to_string()))? {
+ Signature::EcDsa(s) => {
+ let (r, s) = (s.signature_r().value(), s.signature_s().value());
+ if r.len() > 32 || s.len() > 32 {
+ return Err(StoreError::Unavailable("bad signature".into()));
+ }
+ let mut out = [0u8; 64];
+ out[32 - r.len()..32].copy_from_slice(r);
+ out[64 - s.len()..].copy_from_slice(s);
+ Ok(out)
+ }
+ _ => Err(StoreError::Unavailable("unexpected signature scheme".into())),
+ }
+ }
+
+ fn has_consent_key(&self) -> bool {
+ self.paths(&KeyRole::Consent).0.exists()
+ }
+}
diff --git a/home/desktop/agent/tests/conformance.rs b/home/desktop/agent/tests/conformance.rs
new file mode 100644
index 00000000..f3a9e37a
--- /dev/null
+++ b/home/desktop/agent/tests/conformance.rs
@@ -0,0 +1,294 @@
+// SPDX-License-Identifier: MIT
+// Copyright (c) 2026 The Bento authors
+//
+// The desktop agent against the bento/id conformance vectors
+// (kernel/fixtures/identity-v1.json), mirroring scripts/test-statements.ts:
+// every row's verdict AND reason, the builder round-trip and three tamperings of
+// every accepted row, the attack rows' presence, the derivations, low-S, the
+// purpose matcher, addresses and strict base64url.
+//
+// The fixture is RE-READ every run, never pinned: a regeneration changes the
+// signatures, not the verdicts. A missing fixture is a FAILURE, never a skip.
+// Override the path with BENTO_ID_FIXTURE.
+
+use bento_id_agent::{address, b64u, statements as st};
+use serde_json::Value;
+use std::collections::HashMap;
+
+fn fixture() -> Value {
+ let path = std::env::var("BENTO_ID_FIXTURE").unwrap_or_else(|_| {
+ format!("{}/../../../kernel/fixtures/identity-v1.json", env!("CARGO_MANIFEST_DIR"))
+ });
+ let text = std::fs::read_to_string(&path)
+ .unwrap_or_else(|e| panic!("the conformance fixture is required ({path}): {e}"));
+ serde_json::from_str(&text).expect("fixture is JSON")
+}
+
+fn s<'a>(r: &'a Value, k: &str) -> &'a str {
+ r[k].as_str().unwrap_or_else(|| panic!("row field {k} missing: {r}"))
+}
+
+struct Ctx {
+ now: u64,
+ kx_default: st::KxMode,
+ dir_keys: HashMap<String, String>,
+ account: String,
+ consent: String,
+}
+
+#[derive(Debug)]
+enum Parsed {
+ Dev(st::DeviceCert),
+ Bind(st::BindCert),
+ Att(st::Attestation),
+ Tomb(st::Tombstone),
+ Del(String, u64),
+ Cmp(String, String),
+ Cns(st::Consent),
+}
+
+fn check(c: &Ctx, r: &Value, text: &str, sig: &str) -> Result<Parsed, &'static str> {
+ let now = r["now"].as_u64().unwrap_or(c.now);
+ let kx = r["kxMode"].as_str().map(|m| st::KxMode::parse(m).expect("kxMode")).unwrap_or(c.kx_default);
+ match s(r, "type") {
+ "dev" => st::verify_dev(text, sig, now, kx).map(Parsed::Dev),
+ "bind" => st::verify_bind(text, sig, now, kx).map(Parsed::Bind),
+ "att" => st::verify_att(text, sig, &c.dir_keys, s(r, "bindText"), now, r["maxAgeMs"].as_u64().expect("maxAgeMs"))
+ .map(Parsed::Att),
+ "tomb" => st::verify_tomb(text, sig, &c.dir_keys, now).map(Parsed::Tomb),
+ "del" => st::verify_del(text, sig, &c.account, now).map(|(a, t)| Parsed::Del(a, t)),
+ "cmp" => st::verify_cmp(text, sig, &c.account, s(r, "bindText")).map(|(h, k)| Parsed::Cmp(h, k)),
+ "cns" => {
+ let o = st::ConsentCheck {
+ consent_pub: &c.consent,
+ rp: s(r, "rp"),
+ audience: s(r, "audience"),
+ challenge: s(r, "challenge"),
+ payload_text: s(r, "payloadText"),
+ doc_id: r["docId"].as_str(),
+ now,
+ };
+ let spent = r["challengeSpent"].as_bool().unwrap_or(false);
+ let called = std::cell::Cell::new(false);
+ let v = st::verify_consent(text, sig, &o, |_| { called.set(true); !spent }).map(Parsed::Cns);
+ // The verdict cannot show WHEN spend runs; the fixture says whether
+ // it must have been called (spend FIRST, after the grammar check).
+ // Only on the fixture's own text: a tampered text may fail grammar.
+ if text == s(r, "text") {
+ if let Some(want) = r["spendCalled"].as_bool() {
+ assert_eq!(called.get(), want, "spendCalled: {}", s(r, "name"));
+ }
+ }
+ v
+ }
+ t => panic!("unknown row type {t}"),
+ }
+}
+
+fn rebuild(p: &Parsed) -> String {
+ match p {
+ Parsed::Dev(c) => st::build_dev(c),
+ Parsed::Bind(c) => st::build_bind(c),
+ Parsed::Att(a) => st::build_att(a),
+ Parsed::Tomb(t) => st::build_tomb(t),
+ Parsed::Del(a, t) => st::build_del(a, *t),
+ Parsed::Cmp(h, k) => st::build_cmp(h, k),
+ Parsed::Cns(c) => st::build_consent(c),
+ }
+}
+
+fn ctx(f: &Value) -> Ctx {
+ Ctx {
+ now: f["now"].as_u64().unwrap(),
+ kx_default: st::KxMode::parse(f["kxModeDefault"].as_str().unwrap()).unwrap(),
+ dir_keys: f["directoryKeys"].as_object().unwrap().iter().map(|(k, v)| (k.clone(), v.as_str().unwrap().into())).collect(),
+ account: f["keys"]["account"].as_str().unwrap().into(),
+ consent: f["keys"]["consent"].as_str().unwrap().into(),
+ }
+}
+
+#[test]
+fn every_statement_row_reaches_its_verdict_and_reason() {
+ let f = fixture();
+ let c = ctx(&f);
+ let mut bad = vec![];
+ let rows = f["statements"].as_array().unwrap();
+ assert!(rows.len() >= 60, "the statement rows shrank: {}", rows.len());
+ let cns = rows.iter().filter(|r| r["type"] == "cns").count();
+ assert_eq!(rows.iter().filter(|r| r["type"] == "cns" && r["spendCalled"].is_boolean()).count(), cns,
+ "every cns row carries spendCalled");
+ for r in rows {
+ let got = match check(&c, r, s(r, "text"), s(r, "sig")) {
+ Ok(_) => "accept".to_string(),
+ Err(e) => format!("reject:{e}"),
+ };
+ let want = if s(r, "expect") == "accept" { "accept".to_string() } else { format!("reject:{}", s(r, "reason")) };
+ if got != want {
+ bad.push(format!("{}: want {want}, got {got}", s(r, "name")));
+ }
+ }
+ assert!(bad.is_empty(), "{} rows differ:\n{}", bad.len(), bad.join("\n"));
+}
+
+#[test]
+fn accepted_rows_round_trip_and_refuse_tampering() {
+ let f = fixture();
+ let c = ctx(&f);
+ let mut n = 0;
+ for r in f["statements"].as_array().unwrap().iter().filter(|r| r["expect"] == "accept") {
+ let (text, sig) = (s(r, "text"), s(r, "sig"));
+ let p = check(&c, r, text, sig).unwrap_or_else(|e| panic!("{}: {e}", s(r, "name")));
+ assert_eq!(rebuild(&p), text, "builder reproduces the exact text: {}", s(r, "name"));
+ let mut raw = b64u::dec(sig).unwrap();
+ raw[10] ^= 1;
+ assert!(check(&c, r, text, &b64u::enc(&raw)).is_err(), "flipped signature bit refused: {}", s(r, "name"));
+ assert!(check(&c, r, &format!("{text}.x"), sig).is_err(), "extra field refused: {}", s(r, "name"));
+ let i = text.len() - 2;
+ let flipped = format!("{}{}{}", &text[..i], if &text[i..i + 1] == "1" { "2" } else { "1" }, &text[i + 1..]);
+ assert!(check(&c, r, &flipped, sig).is_err(), "one changed byte refused: {}", s(r, "name"));
+ n += 1;
+ }
+ assert!(n > 0);
+}
+
+#[test]
+fn the_contract_cannot_quietly_shrink() {
+ let f = fixture();
+ let rows = f["statements"].as_array().unwrap();
+ let has = |needle: &str| rows.iter().any(|r| s(r, "name").contains(needle));
+ for a in ["REPLAY", "RELAY", "PAYLOAD SWAP", "DOCID SWAP", "EXPIRED"] {
+ assert!(has(a), "cns attack row present: {a}");
+ }
+ for g in ["high-S", "DER", "an extra field", "a field missing", "raw (unencoded) email", "dotted rp", "padded base64url"] {
+ assert!(has(g), "grammar/signature row present: {g}");
+ }
+ for t in ["dev", "bind", "att", "tomb", "del", "cmp", "cns"] {
+ assert!(rows.iter().any(|r| r["type"] == t && r["expect"] == "accept"), "{t} has an accept row");
+ assert!(rows.iter().any(|r| r["type"] == t && r["expect"] == "reject"), "{t} has a reject row");
+ }
+ assert_eq!(f["kxModeDefault"], "unruled");
+ assert_eq!(st::KX_MODE, st::KxMode::Unruled, "kx placement is unruled: both slots empty");
+}
+
+#[test]
+fn consent_transcript_and_webauthn_challenge() {
+ let f = fixture();
+ for t in f["transcripts"].as_array().unwrap() {
+ let got = st::consent_transcript(s(t, "audience"), s(t, "challenge"), s(t, "payload"));
+ assert_eq!(got.as_deref(), t["transcript"].as_str(), "transcript {t}");
+ }
+ for w in f["webauthn"].as_array().unwrap() {
+ assert_eq!(st::webauthn_challenge_for(s(w, "cns")), s(w, "challenge"));
+ }
+}
+
+#[test]
+fn low_s_verifiers_refuse_high_signers_fold() {
+ let f = fixture();
+ let account = f["keys"]["account"].as_str().unwrap();
+ for (i, p) in f["lowS"].as_array().unwrap().iter().enumerate() {
+ let text = format!("dev.lows.{i}");
+ assert!(st::verify_statement_sig(account, s(p, "low"), &text), "pair {i}: low-S verifies");
+ assert!(!st::verify_statement_sig(account, s(p, "high"), &text), "pair {i}: high-S refused");
+ let fold = |x: &str| -> String {
+ let raw: [u8; 64] = b64u::dec(x).unwrap().try_into().unwrap();
+ b64u::enc(&st::low_s(&raw))
+ };
+ assert_eq!(fold(s(p, "high")), s(p, "low"), "pair {i}: folds high to low");
+ assert_eq!(fold(s(p, "low")), s(p, "low"), "pair {i}: leaves low alone");
+ }
+}
+
+#[test]
+fn each_purpose_signs_only_its_own_shape() {
+ let f = fixture();
+ for p in f["purposes"].as_array().unwrap() {
+ assert_eq!(
+ st::payload_matches_purpose(s(p, "purpose"), s(p, "payload")),
+ p["match"].as_bool().unwrap(),
+ "{p}"
+ );
+ }
+}
+
+#[test]
+fn one_normal_form_for_addresses() {
+ let f = fixture();
+ let mut bad = vec![];
+ for a in f["addresses"].as_array().unwrap() {
+ let want = match a["address"].as_str() {
+ Some(x) => format!("ok:{x}"),
+ None => format!("refused:{}", s(a, "reason")),
+ };
+ let got = match address::normalize(s(a, "input")) {
+ Ok(x) => format!("ok:{x}"),
+ Err(e) => format!("refused:{}", e.as_str()),
+ };
+ if got != want {
+ bad.push(format!("{:?}: want {want}, got {got}", s(a, "input")));
+ }
+ }
+ assert!(bad.is_empty(), "{}", bad.join("\n"));
+}
+
+#[test]
+fn strict_base64url() {
+ assert!(b64u::dec("QQ").is_some() && b64u::dec("QQ==").is_none(), "padding refused");
+ assert!(b64u::dec("QR").is_none(), "non-zero trailing bits refused");
+ assert!(b64u::dec("Q").is_none(), "impossible length refused");
+ assert!(b64u::dec("Q+8").is_none() && b64u::dec("Q/8").is_none(), "standard alphabet refused");
+ assert_eq!(b64u::dec("").map(|b| b.len()), Some(0), "empty is zero bytes");
+}
+
+#[test]
+fn signing_emits_low_s_that_the_verifier_accepts() {
+ // A software key round-trip: 64 signatures, every one low-S and accepted.
+ let key = p256::ecdsa::SigningKey::from_slice(&[7u8; 32]).unwrap();
+ let pubkey = b64u::enc(key.verifying_key().to_encoded_point(false).as_bytes());
+ for i in 0..64 {
+ let text = format!("dev.test.{i}");
+ let sig = st::sign_statement(&key, &text);
+ assert!(st::verify_statement_sig(&pubkey, &sig, &text), "round-trip {i}");
+ }
+}
+
+#[test]
+fn reserved_prefixes() {
+ assert!(st::RESERVED_PREFIXES.contains(&"pk"));
+}
+
+#[test]
+fn every_consent_attempt_spends_its_challenge_even_one_refused_for_another_reason() {
+ // The fixture's `spend` is a stub (challengeSpent true/false), so it cannot
+ // tell WHEN the verifier spends. The reference spends right after the
+ // grammar check: an attempt refused for ANY later reason must still burn the
+ // challenge, or a refused attempt leaves it live to be retried. Mutation
+ // check: moving `spend` after the transcript check passed every vector row.
+ let f = fixture();
+ let c = ctx(&f);
+ let row = f["statements"].as_array().unwrap().iter()
+ .find(|r| r["type"] == "cns" && r["expect"] == "accept").expect("an accepted cns row");
+ let mut spent = false;
+ let o = st::ConsentCheck {
+ consent_pub: &c.consent,
+ rp: "vault-not-this-one",
+ audience: s(row, "audience"),
+ challenge: s(row, "challenge"),
+ payload_text: s(row, "payloadText"),
+ doc_id: row["docId"].as_str(),
+ now: row["now"].as_u64().unwrap_or(c.now),
+ };
+ let v = st::verify_consent(s(row, "text"), s(row, "sig"), &o, |_| { spent = true; true });
+ assert_eq!(v.unwrap_err(), "rp");
+ assert!(spent, "a consent refused for its rp still spent the challenge");
+}
+
+#[test]
+fn the_display_table_is_the_fixtures_frozen_table() {
+ let f = fixture();
+ let d = &f["displayForbidden"];
+ assert_eq!(d["unicode"].as_str(), Some(bento_id_agent::statements::DISPLAY_UNICODE), "regenerate with gen-display-table.mjs");
+ let want: Vec<(u32, u32)> = d["ranges"].as_array().unwrap().iter()
+ .map(|r| (r[0].as_u64().unwrap() as u32, r[1].as_u64().unwrap() as u32)).collect();
+ assert_eq!(st::DISPLAY_FORBIDDEN_RANGES.to_vec(), want, "the embedded table drifted from the fixture");
+}
diff --git a/home/desktop/agent/tests/tpm_linux.rs b/home/desktop/agent/tests/tpm_linux.rs
new file mode 100644
index 00000000..a37fb556
--- /dev/null
+++ b/home/desktop/agent/tests/tpm_linux.rs
@@ -0,0 +1,137 @@
+// SPDX-License-Identifier: MIT
+// Copyright (c) 2026 The Bento authors
+//
+// H1b rigs: the Linux TPM key store against a real TPM 2.0 (swtpm in CI and
+// development). Run with the `tpm` feature and BENTO_TPM_TCTI (the TPM under
+// test) and BENTO_TPM_TCTI_OTHER (a SECOND, unrelated TPM, for the copy-off rig).
+// Missing env is a FAILURE, never a skip.
+#![cfg(all(target_os = "linux", feature = "tpm"))]
+
+use bento_id_agent::agent::{Agent, Caller, Clock, KeyRole, KeyStore, Policy, Prompt, StoreError};
+use bento_id_agent::tpm_linux::{PinPrompt, TpmStore};
+use bento_id_agent::{b64u, statements as st};
+use std::cell::RefCell;
+use std::rc::Rc;
+use zeroize::Zeroizing;
+
+fn tcti(var: &str) -> String {
+ std::env::var(var).unwrap_or_else(|_| panic!("{var} is required for the TPM rigs"))
+}
+fn dir(tag: &str) -> std::path::PathBuf {
+ let d = std::env::temp_dir().join(format!("bento-tpm-{tag}-{}", std::process::id()));
+ let _ = std::fs::remove_dir_all(&d);
+ d
+}
+/// A PIN prompt that answers from a queue and records every prompt it was shown.
+fn pins(answers: Vec<Option<&str>>, seen: Rc<RefCell<Vec<Prompt>>>) -> PinPrompt {
+ let q = RefCell::new(answers.into_iter().map(|a| a.map(|s| s.to_string())).collect::<Vec<_>>());
+ Box::new(move |p: &Prompt| {
+ seen.borrow_mut().push(p.clone());
+ let mut q = q.borrow_mut();
+ if q.is_empty() { None } else { q.remove(0).map(Zeroizing::new) }
+ })
+}
+struct Now;
+impl Clock for Now {
+ fn now_ms(&self) -> u64 {
+ std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).unwrap().as_millis() as u64
+ }
+}
+const PIN: &str = "4711-bento";
+
+#[test]
+fn routine_key_signs_in_the_tpm_and_verifies_under_k2() {
+ let d = dir("routine");
+ let mut s = TpmStore::open(&tcti("BENTO_TPM_TCTI"), d, pins(vec![], Default::default())).unwrap();
+ let pubk = s.create_signing_key(&KeyRole::Device, None).unwrap();
+ let pub_b64 = b64u::enc(&pubk);
+ for i in 0..8 {
+ let text = format!("{}.{}", b64u::enc(&[i; 12]), b64u::enc(&[i; 40]));
+ let raw = s.sign(&KeyRole::Device, text.as_bytes(), None).unwrap();
+ let sig = b64u::enc(&st::low_s(&raw));
+ assert!(st::verify_statement_sig(&pub_b64, &sig, &text), "TPM signature {i} verifies (low-S folded)");
+ }
+}
+
+#[test]
+fn consent_key_needs_the_pin_every_time() {
+ let d = dir("consent");
+ let seen = Rc::new(RefCell::new(vec![]));
+ let mut s = TpmStore::open(&tcti("BENTO_TPM_TCTI"), d,
+ pins(vec![Some("wrong-pin"), None, Some(PIN), Some(PIN)], seen.clone())).unwrap();
+ s.create_signing_key(&KeyRole::Consent, Some(PIN)).unwrap();
+ let p = Prompt { purpose: "revoke".into(), doc_id: Some("d1".into()) };
+ assert_eq!(s.sign(&KeyRole::Consent, b"x", Some(&p)), Err(StoreError::Declined), "a wrong PIN is refused by the TPM");
+ assert_eq!(s.sign(&KeyRole::Consent, b"x", Some(&p)), Err(StoreError::Declined), "a declined prompt signs nothing");
+ assert!(s.sign(&KeyRole::Consent, b"x", Some(&p)).is_ok(), "the right PIN signs");
+ assert!(s.sign(&KeyRole::Consent, b"y", Some(&p)).is_ok(), "and again: one PIN per signature");
+ assert_eq!(seen.borrow().len(), 4, "every consent signature prompted");
+ assert!(s.sign(&KeyRole::Consent, b"x", None).is_err(), "no prompt, no consent signature");
+}
+
+#[test]
+fn agent_consent_on_the_tpm_verifies_under_k2() {
+ let d = dir("agent");
+ let mut s = TpmStore::open(&tcti("BENTO_TPM_TCTI"), d, pins(vec![Some(PIN)], Default::default())).unwrap();
+ let dev = s.create_signing_key(&KeyRole::Device, None).unwrap();
+ s.create_signing_key(&KeyRole::Consent, Some(PIN)).unwrap();
+ let mut a = Agent::new(s, Now, Policy::default());
+ let caller = Caller { verified: true, doc_id: Some("doc-lq3k9z-8f2h1x".into()) };
+ let challenge = b64u::enc(&[5u8; 32]);
+ let statement = format!("rev.{}", b64u::enc(&dev));
+ let c = a.consent(&caller, "revoke", &statement, &challenge).unwrap();
+ let check = st::ConsentCheck {
+ consent_pub: &c.consent_pub, rp: "bento", audience: "dir", challenge: &challenge,
+ payload_text: &statement, doc_id: Some("doc-lq3k9z-8f2h1x"), now: Now.now_ms(),
+ };
+ assert!(st::verify_consent(&c.cns, &c.sig, &check, |_| true).is_ok(), "{}", c.cns);
+ // routine signing through the agent, inside a session
+ a.begin_session();
+ let r = a.sign(&caller, "show", "live").unwrap();
+ assert!(st::verify_statement_sig(&r.pub_key, &r.sig, "live"));
+}
+
+#[test]
+fn sealed_account_key_unseals_only_with_the_pin() {
+ let d = dir("account");
+ let mut s = TpmStore::open(&tcti("BENTO_TPM_TCTI"), d,
+ pins(vec![Some("nope"), Some(PIN)], Default::default())).unwrap();
+ let secret = [0x5au8; 32];
+ s.seal_account(&secret, PIN).unwrap();
+ let p = Prompt { purpose: "link".into(), doc_id: None };
+ assert!(matches!(s.unseal_account(&p), Err(StoreError::Declined)), "wrong PIN refused");
+ assert_eq!(&s.unseal_account(&p).unwrap()[..], &secret[..], "right PIN unseals");
+ assert_eq!(s.public_key(&KeyRole::Account).unwrap(), None, "the account key has no TPM public point");
+}
+
+#[test]
+fn key_files_are_useless_on_another_tpm() {
+ // "Cannot be copied off the machine": the stored blobs are TPM-wrapped, so a
+ // second, unrelated TPM given the very same files cannot load them.
+ let d = dir("copyoff");
+ let mut a = TpmStore::open(&tcti("BENTO_TPM_TCTI"), d.clone(), pins(vec![], Default::default())).unwrap();
+ a.create_signing_key(&KeyRole::Device, None).unwrap();
+ assert!(a.sign(&KeyRole::Device, b"m", None).is_ok(), "control: it signs on its own TPM");
+ let mut b = TpmStore::open(&tcti("BENTO_TPM_TCTI_OTHER"), d, pins(vec![], Default::default())).unwrap();
+ let r = b.sign(&KeyRole::Device, b"m", None);
+ assert!(matches!(r, Err(StoreError::Unavailable(_))), "another TPM cannot use the copied files: {r:?}");
+}
+
+#[test]
+fn a_second_connection_cannot_use_consent_or_account_without_the_pin() {
+ // Stand-in for "a second same-user process": a fresh connection to the same
+ // TPM over the same files, whose prompt answers nothing. The routine key
+ // stays usable — the accepted DESKTOP residual (security), asserted so it
+ // stays visible rather than assumed.
+ let d = dir("second");
+ let mut first = TpmStore::open(&tcti("BENTO_TPM_TCTI"), d.clone(), pins(vec![], Default::default())).unwrap();
+ first.create_signing_key(&KeyRole::Device, None).unwrap();
+ first.create_signing_key(&KeyRole::Consent, Some(PIN)).unwrap();
+ first.seal_account(&[7u8; 32], PIN).unwrap();
+ drop(first);
+ let mut other = TpmStore::open(&tcti("BENTO_TPM_TCTI"), d, pins(vec![None, None], Default::default())).unwrap();
+ let p = Prompt { purpose: "link".into(), doc_id: None };
+ assert_eq!(other.sign(&KeyRole::Consent, b"x", Some(&p)), Err(StoreError::Declined), "consent key: no PIN, no signature");
+ assert!(matches!(other.unseal_account(&p), Err(StoreError::Declined)), "account key: no PIN, no key");
+ assert!(other.sign(&KeyRole::Device, b"x", None).is_ok(), "RESIDUAL: the routine key signs without a prompt");
+}
diff --git a/home/desktop/agent/tpm-rig.sh b/home/desktop/agent/tpm-rig.sh
new file mode 100755
index 00000000..c11b369a
--- /dev/null
+++ b/home/desktop/agent/tpm-rig.sh
@@ -0,0 +1,15 @@
+#!/usr/bin/env bash
+# The H1b TPM rigs against two independent software TPMs (swtpm). Linux only.
+set -euo pipefail
+for n in A:2321 B:2331; do
+ t=${n%%:*}; p=${n##*:}; d=$(mktemp -d)
+ swtpm_setup --tpm2 --tpmstate "$d" --create-ek-cert --create-platform-cert --overwrite >/dev/null 2>&1 || true
+ swtpm socket --tpm2 --tpmstate dir="$d" --server type=tcp,port=$p --ctrl type=tcp,port=$((p+1)) \
+ --flags not-need-init,startup-clear --daemon
+done
+export BENTO_TPM_TCTI="swtpm:host=127.0.0.1,port=2321" BENTO_TPM_TCTI_OTHER="swtpm:host=127.0.0.1,port=2331"
+out=$(cargo test --features tpm --test tpm_linux -- --test-threads=1 "$@" 2>&1) || { echo "$out"; exit 1; }
+echo "$out"
+# A green run with nothing in it proves nothing: if the tpm feature ever stopped
+# compiling the rigs, cargo would report "0 passed" and exit 0.
+echo "$out" | grep -qE "test result: ok\. [1-9][0-9]* passed" || { echo "FAIL: no TPM rig ran"; exit 1; }