Bento, the office suite that fits in a file
TypeScript mit-licenseofficeoffice-365office-suiteoffice-toolsoffice365open-sourcepowerpointself-hostedsingle-page-appslidesslideshareslideshowslideshow-galleryslideshow-makerslideshows
home/desktop: gate 1 in Rust, held to the K5 conformance corpus (#831)
nyblneta0f7ba962918
diff --git a/.github/workflows/ci-home-desktop.yml b/.github/workflows/ci-home-desktop.ymlindex f0c1a8d1..11857fb8 100644--- a/.github/workflows/ci-home-desktop.yml+++ b/.github/workflows/ci-home-desktop.yml@@ -35,6 +35,15 @@ jobs:# fails; it never skips.working-directory: home/desktop/agentrun: cargo test+ - name: Desktop gate 1 against the conformance corpus+ # home/desktop/gate1 is the desktop host's Rust port of kernel/src/gate1.ts+ # (bento/connect K5): is this file's runtime a genuine Bento release? It+ # must reach every declared verdict in home/fixtures/gate1/ (served,+ # ambiguous, strict file:// and anti-rollback rows), read from the+ # corpus each run. The signed history must verify and a one-byte change+ # to it must not. A corpus file without a row fails.+ working-directory: home/desktop/gate1+ 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 needdiff --git a/home/desktop/gate1/.gitignore b/home/desktop/gate1/.gitignorenew file mode 100644index 00000000..2f7896d1--- /dev/null+++ b/home/desktop/gate1/.gitignore@@ -0,0 +1 @@+target/diff --git a/home/desktop/gate1/Cargo.lock b/home/desktop/gate1/Cargo.locknew file mode 100644index 00000000..19c9d670--- /dev/null+++ b/home/desktop/gate1/Cargo.lock@@ -0,0 +1,457 @@+# This file is automatically @generated by Cargo.+# It is not intended for manual editing.+version = 4++[[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 = "base64ct"+version = "1.8.3"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "2af50177e190e07a26ab74f8b1efbfe2ef87da2116221318cb1c2e82baf7de06"++[[package]]+name = "bento-gate1"+version = "0.1.0"+dependencies = [+ "base64",+ "p256",+ "serde_json",+ "sha2",+]++[[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 = "equivalent"+version = "1.0.3"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "00d174d5400e5e8fd687ad1049e2f578285fa914201b1af7e8b112a4546bd826"++[[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 = "foldhash"+version = "0.2.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "77ce24cb58228fbb8aa041425bb1050850ac19177686ea6e0f41a70416f56fdb"++[[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 = "group"+version = "0.13.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "f0f9ef7462f7c099f518d754361858f86d8a07af53ba9af0fe635bbccb151a63"+dependencies = [+ "ff",+ "rand_core",+ "subtle",+]++[[package]]+name = "hashbrown"+version = "0.17.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "ed5909b6e89a2db4456e54cd5f673791d7eca6732202bbf2a9cc504fe2f9b84a"++[[package]]+name = "hmac"+version = "0.12.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "6c49c37c09c17a53d937dfbb742eb3a961d65a994e6bcdcf37e7399d0cc8ab5e"+dependencies = [+ "digest",+]++[[package]]+name = "indexmap"+version = "2.14.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "cc4e190f5d26ca7051642629da2c52fc03bde85a03197c99408dcd291734c855"+dependencies = [+ "equivalent",+ "hashbrown",+]++[[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 = "memchr"+version = "2.8.3"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "cf8baf1c55e62ffcace7a9f06f4bd9cd3f0c4beb022d3b367256b91b87513d98"++[[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 = "pkcs8"+version = "0.10.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "f950b2377845cebe5cf8b5165cb3cc1a5e0fa5cfa3e1f7f55707d8fd82e0a7b7"+dependencies = [+ "der",+ "spki",+]++[[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 = "rand_core"+version = "0.6.4"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "ec0be4795e2f6a28069bec0b5ff3e2ac9bafc99e6a9a7dc3547996c5c816922c"+dependencies = [+ "getrandom",+]++[[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",+]++[[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",+]++[[package]]+name = "serde_json"+version = "1.0.154"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "e7e9cc8b1b85264074fbcc02a88680c4096b1e47df8f739dceb03bf482f04bd6"+dependencies = [+ "foldhash",+ "indexmap",+ "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 = "subtle"+version = "2.6.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "13c2bddecc57b384dee18652358fb23172facb8a2c51ccc10d74c157bdea3292"++[[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 = "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 = "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"++[[package]]+name = "zmij"+version = "1.0.23"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "29666d0abbfad1e3dc4dcf6144730dd3a3ab225bbbdac83319345b1b44ccfc1b"diff --git a/home/desktop/gate1/Cargo.toml b/home/desktop/gate1/Cargo.tomlnew file mode 100644index 00000000..f95f9f80--- /dev/null+++ b/home/desktop/gate1/Cargo.toml@@ -0,0 +1,15 @@+[package]+name = "bento-gate1"+version = "0.1.0"+edition = "2021"+license = "MIT"+description = "Gate 1 for the desktop host: is this file's runtime a genuine Bento release? A port of kernel/src/gate1.ts, held to home/fixtures/gate1."+publish = false++[dependencies]+p256 = { version = "0.13", features = ["ecdsa"] }+sha2 = "0.10"+base64 = "0.22"+serde_json = { version = "1", features = ["preserve_order"] }++[workspace]diff --git a/home/desktop/gate1/examples/probe.rs b/home/desktop/gate1/examples/probe.rsnew file mode 100644index 00000000..90b75286--- /dev/null+++ b/home/desktop/gate1/examples/probe.rs@@ -0,0 +1,13 @@+// Verdicts for files named on the command line, against the corpus history.+use bento_gate1::*;+fn main() {+ let d = concat!(env!("CARGO_MANIFEST_DIR"), "/../../fixtures/gate1/");+ let key: serde_json::Value = serde_json::from_slice(&std::fs::read(format!("{d}test-public-key.json")).unwrap()).unwrap();+ let h = History::from_signed(&std::fs::read_to_string(format!("{d}history.json")).unwrap(), key["x"].as_str().unwrap(), key["y"].as_str().unwrap()).unwrap();+ for f in std::env::args().skip(1) {+ match verify_served(&std::fs::read(&f).unwrap(), &h, "'none'") {+ ServedVerdict::Genuine { release, .. } => println!("RUST {} genuine {}", f.rsplit('/').next().unwrap(), release.version),+ ServedVerdict::Unknown { reason } => println!("RUST {} unknown {reason}", f.rsplit('/').next().unwrap()),+ }+ }+}diff --git a/home/desktop/gate1/src/lib.rs b/home/desktop/gate1/src/lib.rsnew file mode 100644index 00000000..feb6d5bd--- /dev/null+++ b/home/desktop/gate1/src/lib.rs@@ -0,0 +1,635 @@+// SPDX-License-Identifier: MIT+// Copyright (c) 2026 The Bento authors+//+// GATE 1 for the desktop host: is this file's runtime a genuine Bento release?+// (bento/connect K5, security §13–§18, §36 and the 2026-10-21 grammar ruling.)+//+// A PORT of kernel/src/gate1.ts, the reference. It is held to the conformance+// corpus in home/fixtures/gate1/ (tests/corpus.rs): a row this port reads+// differently is a finding for kernel and security, never something to "fix"+// on one side alone.+//+// Port notes, where Rust and JavaScript could differ:+// - Offsets are BYTES of UTF-8; the reference's are UTF-16 units. Every search+// is for ASCII, and case is folded for ASCII only (as the reference's+// asciiLower does), which never changes a length, so the offsets agree.+// - The tag-name window is 256 UTF-16 units, as in the reference; see+// parse_start_tag for the one place a surrogate pair could split there.+// - `\s` in the <meta http-equiv> rule is JavaScript's set (js_space).+// - The input must be UTF-8; anything else is UNKNOWN.+//+// examples/probe.rs prints this port's verdict for any file against the+// corpus history, for comparing a suspect file with the reference.++use base64::{engine::general_purpose::STANDARD as B64, engine::general_purpose::URL_SAFE_NO_PAD as B64URL, Engine};+use p256::ecdsa::{signature::Verifier, Signature, VerifyingKey};+use serde_json::Value;+use sha2::{Digest, Sha256};++// --- small helpers mirroring JavaScript ------------------------------------------++/// JavaScript's `\s`: WhiteSpace and LineTerminator (ECMA-262 §22.2.2.9).+pub fn js_space(c: char) -> bool {+ matches!(c, '\t' | '\n' | '\u{0B}' | '\u{0C}' | '\r' | ' ' | '\u{A0}' | '\u{1680}' | '\u{2000}'..='\u{200A}' | '\u{2028}' | '\u{2029}' | '\u{202F}' | '\u{205F}' | '\u{3000}' | '\u{FEFF}')+}++fn char_at(s: &str, i: usize) -> Option<char> {+ s.get(i..).and_then(|t| t.chars().next())+}+++fn skip_space(s: &str, mut i: usize) -> usize {+ while let Some(c) = char_at(s, i) {+ if !js_space(c) { break }+ i += c.len_utf8();+ }+ i+}++fn starts_ci(s: &str, i: usize, needle: &str) -> bool {+ s.as_bytes().get(i..i + needle.len()).is_some_and(|b| b.eq_ignore_ascii_case(needle.as_bytes()))+}++fn find_from(h: &str, needle: &str, from: usize) -> Option<usize> {+ h.get(from..)?.find(needle).map(|k| k + from)+}++/// sha256 HEX of a string's UTF-8 bytes: the encoding of every `blocks` pin.+pub fn sha256hex(s: &str) -> String {+ Sha256::digest(s.as_bytes()).iter().map(|b| format!("{b:02x}")).collect()+}++/// 'sha256-' + BASE64: the CSP encoding of every `scriptSrc` pin. Never compare it to a hex pin.+pub fn csp_hash(s: &str) -> String {+ format!("sha256-{}", B64.encode(Sha256::digest(s.as_bytes())))+}++// --- the scanner ---------------------------------------------------------------++#[derive(Debug, Clone)]+pub struct Block<'a> {+ pub tag: &'static str,+ pub attrs: &'a str,+ /// the raw text, ending at the first `</script` / `</style` in any case+ pub text: &'a str,+ /// offset of the start tag's "<"+ pub tag_start: usize,+ /// offset of the text's first character+ pub start: usize,+ /// offset just past the end tag's ">", as the tokenizer ends it+ pub end: usize,+ pub type_: Option<String>,+ pub id: Option<String>,+ pub src: Option<String>,+ pub preview: bool,+ /// the start tag repeats an attribute name, or uses "/" between attributes (Bento writes neither)+ pub duplicate: bool,+ pub slash: bool,+}++/// The HTML tokenizer's whitespace between attributes: tab, LF, FF, CR, space.+fn html_ws(b: u8) -> bool {+ matches!(b, b'\t' | b'\n' | 0x0C | b'\r' | b' ')+}++/// ASCII-only case fold: the HTML spec's, and LENGTH-PRESERVING (the reference's asciiLower).+pub fn ascii_lower(s: &str) -> String {+ s.to_ascii_lowercase()+}++/// A start tag's attributes, read the way the HTML tokenizer reads them.+#[derive(Debug, Clone)]+pub struct StartTag {+ pub name: String,+ /// in source order; the FIRST of duplicate names wins+ pub attrs: Vec<(String, String)>,+ pub duplicate: bool,+ pub slash: bool,+ /// the offset just past the closing '>'+ pub end: usize,+}++impl StartTag {+ pub fn get(&self, n: &str) -> Option<&str> {+ self.attrs.iter().find(|(k, _)| k == n).map(|(_, v)| v.as_str())+ }+}++/// The reference's parseStartTag(). Whitespace OR "/" separates attributes; a+/// quoted value ends one even with no separator after it; a leading "=" is part+/// of a name; names fold ASCII case and NUL becomes U+FFFD; the first duplicate+/// wins. None: not a start tag, or unterminated.+///+/// The tag name is `^([a-zA-Z][^\t\n\f\r />]*)` over 256 UTF-16 units from its first character (read_tag).+/// The port stops the name at the last WHOLE character inside the window; the+/// reference can split a surrogate pair there. Either way the remainder is read+/// as an attribute name starting with a non-ASCII character, which no rule+/// matches, so the verdict is the same.+pub fn parse_start_tag(html: &str, i: usize) -> Option<StartTag> {+ if html.as_bytes().get(i) != Some(&b'<') { return None }+ read_tag(html, i + 1)+}++/// An END tag, read exactly like a start tag: the tokenizer parses attributes+/// in end tags too, quoted values included, so `</p a="><b c='">` ends at its+/// SECOND ">". None if `i` isn't "</" and a letter, or it's unterminated.+pub fn parse_end_tag(html: &str, i: usize) -> Option<StartTag> {+ let b = html.as_bytes();+ if b.get(i) != Some(&b'<') || b.get(i + 1) != Some(&b'/') { return None }+ read_tag(html, i + 2)+}++/// A tag's name and attributes, from its name's first character (the+/// reference's readTag; the name window is 256 UTF-16 units from `at`).+fn read_tag(html: &str, at: usize) -> Option<StartTag> {+ let b = html.as_bytes();+ if !b.get(at).is_some_and(|c| c.is_ascii_alphabetic()) { return None }+ let mut units = 0usize;+ let mut j = at;+ for c in html[at..].chars() {+ if matches!(c, '\t' | '\n' | '\u{0C}' | '\r' | ' ' | '/' | '>') { break }+ if units + c.len_utf16() > 256 { break }+ units += c.len_utf16();+ j += c.len_utf8();+ }+ let name = ascii_lower(&html[at..j]);+ let (mut attrs, mut duplicate, mut slash): (Vec<(String, String)>, bool, bool) = (vec![], false, false);+ while j < b.len() {+ let c = b[j];+ if html_ws(c) { j += 1; continue }+ if c == b'/' { slash = true; j += 1; continue }+ if c == b'>' { return Some(StartTag { name, attrs, duplicate, slash, end: j + 1 }) }+ // the name: a leading "=" is part of it; it ends at whitespace, "/", ">" or "="+ let mut k = j;+ if b[k] == b'=' { k += 1 }+ while k < b.len() && !html_ws(b[k]) && b[k] != b'/' && b[k] != b'>' && b[k] != b'=' { k += 1 }+ let aname = ascii_lower(&html[j..k]).replace('\0', "\u{FFFD}");+ let mut value = String::new();+ let mut p = k;+ while p < b.len() && html_ws(b[p]) { p += 1 }+ if b.get(p) == Some(&b'=') {+ p += 1;+ while p < b.len() && html_ws(b[p]) { p += 1 }+ match b.get(p) {+ Some(&q @ (b'"' | b'\'')) => {+ let close = find_from(html, if q == b'"' { "\"" } else { "'" }, p + 1)?;+ value = html[p + 1..close].to_string();+ k = close + 1;+ }+ _ => {+ let mut e = p;+ while e < b.len() && !html_ws(b[e]) && b[e] != b'>' { e += 1 }+ value = html[p..e].to_string();+ k = e;+ }+ }+ }+ if attrs.iter().any(|(n, _)| *n == aname) { duplicate = true } else { attrs.push((aname, value)) }+ j = k;+ }+ None // unterminated+}++/// Elements whose content is TEXT to a browser, never tags, up to their real end tag.+const RAW_TEXT: [&str; 4] = ["script", "style", "textarea", "title"];++/// `^[a-z][a-z0-9-]*$`: the only tag names Bento writes.+fn plain_tag_name(n: &str) -> bool {+ let b = n.as_bytes();+ !b.is_empty() && b[0].is_ascii_lowercase() && b.iter().all(|c| c.is_ascii_lowercase() || c.is_ascii_digit() || *c == b'-')+}++/// Where a raw-text element really ends: "</name" followed by whitespace, "/",+/// ">" or the end of the file. "</scriptx>" is text, not its end.+fn raw_text_end(lower: &str, name: &str, from: usize) -> Option<usize> {+ let needle = format!("</{name}");+ let mut at = from;+ while let Some(k) = find_from(lower, &needle, at) {+ match lower.as_bytes().get(k + needle.len()) {+ None => return Some(k),+ Some(&c) if html_ws(c) || c == b'/' || c == b'>' => return Some(k),+ _ => at = k + 2,+ }+ }+ None+}++/// ONE walk over the file in document order, tag by tag, as a browser's+/// tokenizer meets them (the reference's walk()). Blocks and markup problems+/// come from the same reading, so a "<style" inside another tag's name (a tag a+/// browser reads as "meta<style") can never be taken for a style element.+fn walk(html: &str) -> (Vec<Block<'_>>, Vec<String>) {+ let (mut blocks, mut problems) = (vec![], vec![]);+ let lower = ascii_lower(html);+ let b = html.as_bytes();+ let mut i = 0;+ while let Some(at) = find_from(html, "<", i) {+ i = at;+ if html[i..].starts_with("<!--") {+ // "<!-->" and "<!--->" are whole (empty) comments to a browser+ if html[i..].starts_with("<!-->") { i += 5; continue }+ if html[i..].starts_with("<!--->") { i += 6; continue }+ let end = find_from(html, "-->", i + 4);+ if lower[i + 4..end.unwrap_or(html.len())].contains("<script") { problems.push("a comment holds a <script>".into()) }+ let Some(end) = end else { problems.push("an unterminated comment".into()); break };+ i = end + 3;+ continue;+ }+ if b.get(i + 1) == Some(&b'/') && b.get(i + 2).is_some_and(|c| c.is_ascii_alphabetic()) {+ // an end tag: tokenized with the start tag's attribute rules (see parse_end_tag)+ let Some(et) = parse_end_tag(html, i) else { problems.push("an unterminated end tag".into()); break };+ if !plain_tag_name(&et.name) { problems.push(format!("an end tag named {}", serde_json::to_string(&et.name).unwrap_or_default())) }+ // a browser drops them, but they move where the tag ends: Bento writes none+ if !et.attrs.is_empty() { problems.push(format!("an end tag </{}> carrying attributes", et.name)) }+ i = et.end;+ continue;+ }+ if html[i..].starts_with("</>") { i += 3; continue } // ignored entirely+ if matches!(b.get(i + 1), Some(b'/' | b'!' | b'?')) {+ // a doctype or a bogus comment: it ends at the first ">", quotes or not+ let Some(end) = find_from(html, ">", i + 2) else { problems.push("an unterminated tag".into()); break };+ i = end + 1;+ continue;+ }+ if !b.get(i + 1).is_some_and(|c| c.is_ascii_alphabetic()) { i += 1; continue } // a "<" that starts no tag is text+ let Some(tag) = parse_start_tag(html, i) else { problems.push("an unterminated start tag".into()); break };+ let name = tag.name.clone();+ if !plain_tag_name(&name) { problems.push(format!("a start tag named {}", serde_json::to_string(&name).unwrap_or_default())) }+ if ["iframe", "object", "embed", "base"].contains(&name.as_str()) { problems.push(format!("a <{name}>")) }+ if name == "meta" && tag.get("http-equiv").is_some_and(meta_kind) { problems.push("a <meta> refresh or CSP".into()) }+ if tag.attrs.iter().any(|(n, _)| n.starts_with("on")) { problems.push(format!("an on*= attribute on <{name}>")) }+ if name == "script" && (tag.duplicate || tag.slash) {+ problems.push(format!("a <script> start tag with a {} (Bento writes neither)", if tag.duplicate { "duplicate attribute" } else { "\"/\" between attributes" }));+ }+ if let Some(raw) = RAW_TEXT.iter().find(|r| **r == name) {+ let Some(close) = raw_text_end(&lower, raw, tag.end) else { problems.push(format!("an unterminated <{name}>")); break };+ if *raw != "script" && lower[tag.end..close].contains("<script") { problems.push(format!("a <{name}> holds a <script>")) }+ if *raw == "script" || *raw == "style" {+ let Some(et) = parse_end_tag(html, close) else { problems.push(format!("an unterminated </{name}>")); break };+ let tagname: &'static str = if *raw == "script" { "script" } else { "style" };+ blocks.push(Block {+ tag: tagname,+ attrs: &html[i..tag.end],+ text: &html[tag.end..close],+ tag_start: i,+ start: tag.end,+ end: et.end,+ type_: tag.get("type").map(str::to_string),+ id: tag.get("id").map(str::to_string),+ src: tag.get("src").map(str::to_string),+ preview: tag.get("data-bento-preview").is_some(),+ duplicate: tag.duplicate,+ slash: tag.slash,+ });+ }+ i = close; // its end tag is judged next, as an end tag+ continue;+ }+ i = tag.end;+ }+ (blocks, problems)+}++/// Every <script> and <style> element in the file, with its raw text, in document order.+pub fn scan_blocks(html: &str) -> Vec<Block<'_>> {+ walk(html).0+}++// --- the grammar (security, 2026-10-21) ------------------------------------------++pub const DATA_TYPES: [&str; 4] = ["application/bento+json", "application/bento+lang", "bento/deflate-b64", "bento/deflate-b86"];++/// A <script> is inert ONLY if its type is exactly one of Bento's data types and it has no src.+pub fn is_data_script(b: &Block) -> bool {+ b.tag == "script" && b.src.is_none() && b.type_.as_deref().is_some_and(|t| DATA_TYPES.contains(&t))+}++/// Every script that isn't one of Bento's data blocks.+pub fn executable_scripts<'a, 'b>(blocks: &'b [Block<'a>]) -> Vec<&'b Block<'a>> {+ blocks.iter().filter(|b| b.tag == "script" && !is_data_script(b)).collect()+}++/// `/^\s*(refresh|content-security-policy)\s*$/i`, with JavaScript's `\s`.+fn meta_kind(v: &str) -> bool {+ let t = v.trim_matches(js_space).to_ascii_lowercase();+ t == "refresh" || t == "content-security-policy"+}++/// Markup a genuine Bento file never carries, outside a script or style element's own text.+/// Returns the problems; empty = none.+pub fn markup_problems(html: &str) -> Vec<String> {+ let (blocks, mut problems) = walk(html);+ for bl in blocks.iter().filter(|b| is_data_script(b) && b.text.contains('<')) {+ problems.push(format!("the {} block contains \"<\"", bl.type_.as_deref().unwrap_or("")));+ }+ problems+}++// --- pins and the release history -------------------------------------------------++#[derive(Debug, Clone)]+pub struct Pins {+ pub rt: Option<String>,+ pub rt_css: Option<String>,+ pub loader: Option<String>,+ pub remover: Option<String>,+ pub script_src: Vec<String>,+}++#[derive(Debug, Clone)]+pub struct Entry {+ pub version: String,+ pub pins: Pins,+ /// the entry exactly as signed, for anti-rollback's "never changes an entry"+ pub raw: Value,+}++#[derive(Debug, Clone)]+pub struct History {+ pub raw: Value,+}++fn pin_str(blocks: &Value, k: &str) -> Option<String> {+ blocks.get(k).and_then(|v| v.as_str()).map(str::to_string)+}++impl Entry {+ fn from(v: &Value) -> Entry {+ let pins = &v["pins"];+ let blocks = &pins["blocks"];+ Entry {+ version: v["version"].as_str().unwrap_or("").to_string(),+ pins: Pins {+ rt: pin_str(blocks, "bento-rt"),+ rt_css: pin_str(blocks, "bento-rt-css"),+ loader: pin_str(blocks, "loader"),+ remover: pin_str(blocks, "remover"),+ script_src: pins["scriptSrc"].as_array().map(|a| a.iter().filter_map(|x| x.as_str().map(str::to_string)).collect()).unwrap_or_default(),+ },+ raw: v.clone(),+ }+ }+}++impl History {+ pub fn from_value(v: Value) -> History {+ History { raw: v }+ }+ pub fn app(&self) -> Option<&str> {+ self.raw.get("app").and_then(|a| a.as_str())+ }+ pub fn entries(&self) -> Vec<Entry> {+ self.raw.get("releases").and_then(|r| r.as_array()).map(|a| a.iter().map(Entry::from).collect()).unwrap_or_default()+ }++ /// The signed envelope `{ payload, sig }`: ECDSA P-256 SHA-256, P1363 r‖s,+ /// standard base64, over the payload string's UTF-8 bytes. `jwk_x`/`jwk_y`+ /// are the public key's base64url coordinates.+ pub fn from_signed(envelope: &str, jwk_x: &str, jwk_y: &str) -> Result<History, String> {+ let env: Value = serde_json::from_str(envelope).map_err(|e| e.to_string())?;+ let payload = env["payload"].as_str().ok_or("history: no payload")?;+ let sig = B64.decode(env["sig"].as_str().ok_or("history: no sig")?).map_err(|e| e.to_string())?;+ let mut sec1 = vec![4u8];+ sec1.extend(B64URL.decode(jwk_x).map_err(|e| e.to_string())?);+ sec1.extend(B64URL.decode(jwk_y).map_err(|e| e.to_string())?);+ let key = VerifyingKey::from_sec1_bytes(&sec1).map_err(|e| e.to_string())?;+ let sig = Signature::from_slice(&sig).map_err(|e| e.to_string())?;+ key.verify(payload.as_bytes(), &sig).map_err(|_| "history: signature INVALID".to_string())?;+ Ok(History::from_value(serde_json::from_str(payload).map_err(|e| e.to_string())?))+ }+}++/// `^(\d+)\.(\d+)\.(\d+)$`, ASCII digits, compared as JavaScript Numbers.+fn semver(s: &str) -> Option<[f64; 3]> {+ let parts: Vec<&str> = s.split('.').collect();+ if parts.len() != 3 || parts.iter().any(|p| p.is_empty() || !p.bytes().all(|b| b.is_ascii_digit())) { return None }+ Some([parts[0].parse().ok()?, parts[1].parse().ok()?, parts[2].parse().ok()?])+}++pub fn cmp_version(a: &str, b: &str) -> Result<std::cmp::Ordering, String> {+ let (x, y) = (semver(a).ok_or(format!("gate1: not a version: {a}"))?, semver(b).ok_or(format!("gate1: not a version: {b}"))?);+ for k in 0..3 {+ if x[k] != y[k] { return Ok(x[k].partial_cmp(&y[k]).unwrap()) }+ }+ Ok(std::cmp::Ordering::Equal)+}++fn entry_ok(e: &Value) -> bool {+ let is_hex64 = |s: &str| s.len() == 64 && s.bytes().all(|b| b.is_ascii_digit() || (b'a'..=b'f').contains(&b));+ e.is_object()+ && e["version"].as_str().is_some_and(|v| semver(v).is_some())+ && e["sha256"].as_str().is_some_and(is_hex64)+ && e["at"].is_string()+ && e["pins"]["v"].as_f64() == Some(1.0)+ // typeof … === 'object': an object, an array or null+ && e["pins"].get("blocks").is_some_and(|b| b.is_object() || b.is_array() || b.is_null())+}++/// A history payload's shape problems; empty = well-formed (versions unique, newest first).+pub fn history_problems(h: &Value) -> Vec<String> {+ let mut p = vec![];+ if h.get("v").and_then(|v| v.as_f64()) != Some(1.0) { p.push(format!("version {} (expected 1)", h.get("v").map(|v| v.to_string()).unwrap_or("undefined".into()))) }+ if !h.get("app").and_then(|a| a.as_str()).is_some_and(|a| !a.is_empty()) { p.push("no app".into()) }+ let Some(rel) = h.get("releases").and_then(|r| r.as_array()) else {+ p.push("no releases".into());+ return p;+ };+ let mut seen = std::collections::HashSet::new();+ for (i, e) in rel.iter().enumerate() {+ if !entry_ok(e) {+ p.push(format!("entry {i} is malformed"));+ continue;+ }+ let v = e["version"].as_str().unwrap();+ if !seen.insert(v.to_string()) { p.push(format!("version {v} appears twice")) }+ if i > 0 && entry_ok(&rel[i - 1]) && cmp_version(rel[i - 1]["version"].as_str().unwrap(), v).unwrap() != std::cmp::Ordering::Greater {+ p.push(format!("entries are not newest-first at {v}"));+ }+ }+ p+}++/// JSON.stringify equality, with keys in their signed order.+fn same(a: &Value, b: &Value) -> bool {+ serde_json::to_string(a).ok() == serde_json::to_string(b).ok()+}++/// A HOST's acceptance of an incoming, already signature-verified history, given the newest it holds: ANTI-ROLLBACK.+pub fn accept_history(held: Option<&Value>, incoming: &Value, app: &str) -> Result<(), String> {+ let problems = history_problems(incoming);+ if let Some(p) = problems.first() { return Err(format!("malformed: {p}")) }+ let inc_app = incoming["app"].as_str().unwrap_or("");+ if inc_app != app { return Err(format!("for {inc_app}, not {app}")) }+ let Some(held) = held else { return Ok(()) };+ let inc = incoming["releases"].as_array().unwrap();+ let hel = held.get("releases").and_then(|r| r.as_array()).cloned().unwrap_or_default();+ let newest = |a: &[Value]| a.first().and_then(|e| e["version"].as_str()).unwrap_or("").to_string();+ if inc.is_empty() || (!hel.is_empty() && cmp_version(&newest(inc), &newest(&hel))? == std::cmp::Ordering::Less) {+ return Err("rollback: its newest release is older than the newest already held".into());+ }+ for e in &hel {+ let v = e["version"].as_str().unwrap_or("");+ let Some(there) = inc.iter().find(|x| x["version"].as_str() == Some(v)) else {+ return Err(format!("rollback: it lacks {v}, which is already held"));+ };+ if !same(there, e) { return Err(format!("{v} changed: a history never changes an entry")) }+ }+ Ok(())+}++// --- matching -----------------------------------------------------------------------++/// Check a file against ONE release's pins. Returns the problems; empty = this release's file.+pub fn check_against_pins(html: &str, pins: &Pins) -> Vec<String> {+ let mut problems = markup_problems(html);+ let blocks = scan_blocks(html);+ for (id, pin) in [("bento-rt", &pins.rt), ("bento-rt-css", &pins.rt_css)] {+ let found: Vec<_> = blocks.iter().filter(|b| b.id.as_deref() == Some(id)).collect();+ if found.len() != 1 {+ problems.push(format!("{} #{id} blocks (exactly one expected)", found.len()));+ } else if Some(sha256hex(found[0].text)) != *pin {+ problems.push(format!("#{id} does not match"));+ }+ }+ let exec = executable_scripts(&blocks);+ let hashes: Vec<String> = exec.iter().map(|s| sha256hex(s.text)).collect();+ let allowed: Vec<&String> = [&pins.loader, &pins.remover].into_iter().flatten().filter(|s| !s.is_empty()).collect();+ for (s, h) in exec.iter().zip(&hashes) {+ if s.src.is_some() || !allowed.contains(&h) {+ problems.push(format!("an executable script that is neither the pinned loader nor the remover ({})", match &s.src { Some(src) => format!("src={src}"), None => format!("{}B", s.text.len()) }));+ }+ }+ let n = |p: &Option<String>| hashes.iter().filter(|x| Some(*x) == p.as_ref()).count();+ if n(&pins.loader) == 0 { problems.push("no pinned loader".into()) }+ if n(&pins.loader) > 1 { problems.push("more than one loader".into()) }+ if pins.remover.as_deref().is_some_and(|r| !r.is_empty()) && n(&pins.remover) > 1 { problems.push("more than one remover".into()) }+ problems+}++/// The ONE entry matching every block of the file, or None (none, or more than one: UNKNOWN).+pub fn match_release(history: &History, html: &str) -> Option<Entry> {+ let blocks = scan_blocks(html);+ let rt: Vec<_> = blocks.iter().filter(|b| b.id.as_deref() == Some("bento-rt")).collect();+ if rt.len() != 1 { return None }+ let rt_hash = sha256hex(rt[0].text);+ let full: Vec<Entry> = history.entries().into_iter().filter(|e| e.pins.rt.as_deref() == Some(rt_hash.as_str())).filter(|e| check_against_pins(html, &e.pins).is_empty()).collect();+ if full.len() == 1 { full.into_iter().next() } else { None }+}++/// The CSP a host serves a verified document under (security §17/§18, §36a).+pub fn host_policy(pins: &Pins, frame_ancestors: &str) -> String {+ [+ "default-src 'none'".to_string(),+ format!("script-src {} blob:", pins.script_src.iter().map(|h| format!("'{h}'")).collect::<Vec<_>>().join(" ")),+ "style-src 'unsafe-inline'".into(),+ "img-src data: blob: https:".into(),+ "media-src data: blob: https:".into(),+ "font-src data: blob:".into(),+ "connect-src https://bento.page https://sync.bento.page wss://sync.bento.page".into(),+ "frame-src https:".into(),+ "object-src 'none'".into(),+ "base-uri 'none'".into(),+ "form-action 'none'".into(),+ "worker-src 'none'".into(),+ format!("frame-ancestors {frame_ancestors}"),+ ]+ .join("; ")+}++#[derive(Debug, Clone)]+pub enum ServedVerdict {+ Genuine { release: Entry, csp: String },+ Unknown { reason: String },+}++/// THE served-path gate. The history must already have passed the release-key+/// signature check and accept_history(). `doc` is the file's bytes as read once+/// by the host: what is verified is what is served.+pub fn verify_served(doc: &[u8], history: &History, frame_ancestors: &str) -> ServedVerdict {+ let unknown = |reason: String| ServedVerdict::Unknown { reason };+ if let Some(p) = history_problems(&history.raw).first() { return unknown(format!("the history is malformed: {p}")) }+ let Ok(html) = std::str::from_utf8(doc) else { return unknown("not UTF-8".into()) };+ match match_release(history, html) {+ Some(release) => {+ let csp = host_policy(&release.pins, frame_ancestors);+ ServedVerdict::Genuine { release, csp }+ }+ None => {+ let markup = markup_problems(html);+ unknown(markup.into_iter().next().unwrap_or_else(|| "no single release matches every block".into()))+ }+ }+}++// --- the strict file:// fallback (security §15) ------------------------------------+//+// The desktop host always SERVES the bytes it verified, so it never needs this+// path for identity (§16). It is ported so the host can say what a file:// copy+// of a document would get, and to hold the two scanners to the same rows.++const CLOSE: &str = "</script>";+const DOC_ANCHOR: &str = " id=\"bento-doc\"";+const DOC_OPEN: &str = "<script type=\"application/bento+json\" id=\"bento-doc\">";++pub struct StrictExpected {+ pub skeleton: String,+ pub remover: Option<String>,+}++fn has_on_handler(body: &str) -> bool {+ // /\son[a-z]+\s*=/i+ for (p, c) in body.char_indices() {+ if !js_space(c) { continue }+ let k = p + c.len_utf8();+ if !starts_ci(body, k, "on") { continue }+ let mut e = k + 2;+ let s = e;+ while body.as_bytes().get(e).is_some_and(|b| b.is_ascii_alphabetic()) { e += 1 }+ if e == s { continue }+ let e = skip_space(body, e);+ if body.as_bytes().get(e) == Some(&b'=') { return true }+ }+ false+}++fn collapse(h: &str, remover: Option<&str>) -> Result<String, String> {+ let count = |s: &str, n: &str| s.matches(n).count();+ if count(h, DOC_ANCHOR) != 1 { return Err(format!("doc anchor count {}", count(h, DOC_ANCHOR))) }+ let di = h.find(DOC_ANCHOR).unwrap();+ let d_open = h[..di].rfind('<').ok_or("doc block opening tag altered")?;+ let d_tag_end = find_from(h, ">", di).map(|x| x + 1).ok_or("doc block opening tag altered")?;+ if &h[d_open..d_tag_end] != DOC_OPEN { return Err("doc block opening tag altered".into()) }+ let d_end = find_from(h, CLOSE, di).map(|x| x + CLOSE.len()).ok_or("\"<\" inside the doc block")?;+ if h.get(d_tag_end..d_end - CLOSE.len()).map_or(true, |b| b.contains('<')) { return Err("\"<\" inside the doc block".into()) }+ let mut h = format!("{}<!--DOC-->{}", &h[..d_open], &h[d_end..]);+ if count(&h, "data-bento-preview") > 0 {+ let Some(remover) = remover else { return Err("remover missing, altered or repeated".into()) };+ if count(&h, "<script data-bento-preview") != 1 || count(&h, remover) != 1 { return Err("remover missing, altered or repeated".into()) }+ let p_attr = h.find("data-bento-preview").unwrap();+ let p_open = h[..p_attr].rfind('<').ok_or("remover missing, altered or repeated")?;+ let rem = h.find(remover).unwrap();+ let body = h.get(p_open..rem).unwrap_or("");+ if body.to_ascii_lowercase().contains("<script") { return Err("script inside the preview markup".into()) }+ if has_on_handler(body) || body.to_ascii_lowercase().contains("javascript:") { return Err("handler or javascript: in the preview markup".into()) }+ if rem < p_open { return Err("remover missing, altered or repeated".into()) }+ h = format!("{}<!--PREVIEW-->{}", &h[..p_open], &h[rem + remover.len()..]);+ }+ // h.replace(/<title>[^<]*<\/title>/, '<title><!--TITLE--></title>')+ let mut from = 0;+ while let Some(p) = find_from(&h, "<title>", from) {+ let q = find_from(&h, "<", p + 7).unwrap_or(h.len());+ if h[q..].starts_with("</title>") {+ return Ok(format!("{}<title><!--TITLE--></title>{}", &h[..p], &h[q + 8..]));+ }+ from = p + 1;+ }+ Ok(h)+}++/// The strict check: the variable spans type-checked and collapsed, then the+/// WHOLE string equal to the release's saved skeleton, bound at both ends.+pub fn verify_strict(doc: &[u8], expected: &StrictExpected) -> Result<(), String> {+ let html = std::str::from_utf8(doc).map_err(|_| "not UTF-8".to_string())?;+ let c = collapse(html, expected.remover.as_deref())?;+ if c == expected.skeleton { Ok(()) } else { Err("skeleton differs from the release's saved form".into()) }+}diff --git a/home/desktop/gate1/tests/corpus.rs b/home/desktop/gate1/tests/corpus.rsnew file mode 100644index 00000000..d728afe7--- /dev/null+++ b/home/desktop/gate1/tests/corpus.rs@@ -0,0 +1,125 @@+// SPDX-License-Identifier: MIT+// Copyright (c) 2026 The Bento authors+//+// The gate-1 conformance corpus (home/fixtures/gate1), every row, against this+// port. A row this port reads differently from its declared verdict is a+// FINDING for kernel and security: never "fixed" on one side alone.++use bento_gate1::*;+use serde_json::Value;+use std::path::PathBuf;++fn dir() -> PathBuf {+ PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("../../fixtures/gate1")+}+fn read(p: &str) -> Vec<u8> {+ std::fs::read(dir().join(p)).unwrap_or_else(|e| panic!("{p}: {e}"))+}+fn json(p: &str) -> Value {+ serde_json::from_slice(&read(p)).unwrap()+}+fn history() -> History {+ let key = json("test-public-key.json");+ History::from_signed(std::str::from_utf8(&read("history.json")).unwrap(), key["x"].as_str().unwrap(), key["y"].as_str().unwrap()).expect("the corpus history verifies")+}++#[test]+fn history_signature_verifies_and_a_flipped_byte_does_not() {+ let h = history();+ assert_eq!(h.app(), Some("bento-test"));+ // positive control: the same envelope with one payload byte changed must fail+ let key = json("test-public-key.json");+ let mut env = json("history.json");+ let p = env["payload"].as_str().unwrap().replacen("1.2.0", "1.2.1", 1);+ env["payload"] = Value::String(p);+ assert!(History::from_signed(&env.to_string(), key["x"].as_str().unwrap(), key["y"].as_str().unwrap()).is_err());+}++#[test]+fn served_rows() {+ let h = history();+ let exp = json("expected.json");+ let rows = exp["served"].as_array().unwrap();+ assert!(rows.len() >= 60, "the served rows shrank to {}: re-read the corpus", rows.len());+ let mut wrong = vec![];+ for r in rows {+ let case = r["case"].as_str().unwrap();+ let v = verify_served(&read(case), &h, "'none'");+ let got = match &v {+ ServedVerdict::Genuine { release, .. } => format!("genuine {}", release.version),+ ServedVerdict::Unknown { .. } => "unknown".into(),+ };+ let want = match r["verdict"].as_str().unwrap() {+ "genuine" => format!("genuine {}", r["release"].as_str().unwrap()),+ other => other.to_string(),+ };+ if got != want {+ let why = match &v { ServedVerdict::Unknown { reason } => reason.clone(), _ => String::new() };+ wrong.push(format!("{case}: want {want}, got {got} {why}"))+ }+ // a genuine verdict's CSP carries exactly the release's CSP-form pins+ if let ServedVerdict::Genuine { release, csp } = &v {+ for s in &release.pins.script_src { assert!(csp.contains(&format!("'{s}'")), "{case}: CSP lacks {s}") }+ assert!(csp.starts_with("default-src 'none'; script-src 'sha256-"), "{case}: {csp}");+ }+ }+ assert!(wrong.is_empty(), "served rows the port reads differently:\n{}", wrong.join("\n"));+}++#[test]+fn ambiguous_row() {+ let exp = json("expected.json");+ for r in exp["ambiguous"].as_array().unwrap() {+ let h = History::from_value(r["history"].clone());+ let v = verify_served(&read(r["case"].as_str().unwrap()), &h, "'none'");+ assert!(matches!(v, ServedVerdict::Unknown { .. }), "{}: two matching entries must be UNKNOWN, got {v:?}", r["case"]);+ assert_eq!(r["verdict"], "unknown");+ }+}++#[test]+fn strict_rows() {+ let s = json("strict-expected.json");+ let expected = StrictExpected { skeleton: s["skeleton"].as_str().unwrap().into(), remover: s["remover"].as_str().map(str::to_string) };+ let exp = json("expected.json");+ let rows = exp["strict"].as_array().unwrap();+ assert!(rows.len() >= 19, "strict rows shrank to {}", rows.len());+ let mut wrong = vec![];+ for r in rows {+ let case = r["case"].as_str().unwrap();+ let got = verify_strict(&read(case), &expected);+ if got.is_ok() != r["ok"].as_bool().unwrap() { wrong.push(format!("{case}: want ok={}, got {got:?}", r["ok"])) }+ }+ assert!(wrong.is_empty(), "strict rows the port reads differently:\n{}", wrong.join("\n"));+}++#[test]+fn history_rows() {+ let exp = json("expected.json");+ let app = exp["app"].as_str().unwrap();+ let rows = exp["history"].as_array().unwrap();+ assert!(rows.len() >= 8, "history rows shrank to {}", rows.len());+ let mut wrong = vec![];+ for r in rows {+ let held = if r["held"].is_null() { None } else { Some(&r["held"]) };+ let got = accept_history(held, &r["incoming"], app);+ if got.is_ok() != r["ok"].as_bool().unwrap() { wrong.push(format!("{}: want ok={}, got {got:?}", r["name"], r["ok"])) }+ }+ assert!(wrong.is_empty(), "history rows the port reads differently:\n{}", wrong.join("\n"));+}++#[test]+fn every_corpus_file_is_covered_by_a_row() {+ // a file added to the corpus without a row here would be silently untested+ let exp = json("expected.json");+ let mut named: Vec<String> = vec![];+ for sec in ["served", "strict", "ambiguous"] {+ for r in exp[sec].as_array().unwrap() { named.push(r["case"].as_str().unwrap().into()) }+ }+ for sub in ["served", "strict"] {+ for f in std::fs::read_dir(dir().join(sub)).unwrap() {+ let n = format!("{sub}/{}", f.unwrap().file_name().to_string_lossy());+ assert!(named.contains(&n), "{n} has no row in expected.json");+ }+ }+}diff --git a/home/fixtures/gate1/README.md b/home/fixtures/gate1/README.mdindex 2d30d8ce..617c2f2a 100644--- a/home/fixtures/gate1/README.md+++ b/home/fixtures/gate1/README.md@@ -17,7 +17,7 @@ disagrees with any declared verdict.| reference (JS, kernel/src/gate1.ts) | `node scripts/test-gate1.ts` || `home/ios` (Swift) | to build || `home/android` (Kotlin) | to build |-| `home/desktop` (Rust) | to build |+| `home/desktop` (Rust) | `cargo test` in `home/desktop/gate1` |## The files