Bento, the office suite that fits in a file
TypeScript mit-licenseofficeoffice-365office-suiteoffice-toolsoffice365open-sourcepowerpointself-hostedsingle-page-appslidesslideshareslideshowslideshow-galleryslideshow-makerslideshows
home/android: a document's web origin belongs to the document, not its path (#754)
nyblnetfb1ec0da4c9f
diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.ymlindex 60c41820..ea933c54 100644--- a/.github/workflows/ci.yml+++ b/.github/workflows/ci.yml@@ -2357,6 +2357,27 @@ jobs:# The last section is two real sessions over a real BroadcastChannel.run: node --no-warnings scripts/test-sync-spaces-session.ts+ home-android-unit:+ runs-on: ubuntu-latest+ timeout-minutes: 20+ steps:+ - uses: actions/checkout@v4+ - uses: actions/setup-java@v4+ with:+ distribution: temurin+ java-version: 17+ - name: Android host unit tests+ # The JVM rigs for home/android: which web origin a document may run+ # under (a different file at a path a document used before must never+ # read its storage), the signed new-document verifier, and the Kotlin+ # port of the document index against home/fixtures. They need no+ # emulator, and until this job nothing ran them — the corpus note above+ # said "the Kotlin port under Gradle" of a step that did not exist.+ # The runner image ships the Android SDK (ANDROID_HOME); the wrapper is+ # pinned at 8.14.3 because AGP 8 cannot run on Gradle 9.6+.+ working-directory: home/android+ run: ./gradlew --no-daemon testDebugUnitTest+type-find-browser:runs-on: ubuntu-latesttimeout-minutes: 15diff --git a/docs/DECISIONS.md b/docs/DECISIONS.mdindex 4acbf236..f87f280c 100644--- a/docs/DECISIONS.md+++ b/docs/DECISIONS.md@@ -14,6 +14,67 @@ Decision. Why. Pointers.---+## 2026-10-18 — Android: a document's web origin belongs to the document, not to its path++**Supersedes one line of 2026-09-19** ("The native hosts were never exposed …+cross-deck reads are impossible there"). That holds across different paths. It+was false across ONE path reused by a different file.++**What was measured** (emulator, Android 16, before this change). The Android+host served each document from `https://<sha24(URI)>.bento-tray.invalid/`, and+common document URIs are paths: the folder index's+`primary:Documents/x.bento.html`, and the Files app's Downloads view, which+hands over `raw:/storage/…` (a path) or `msf:<row>`, a MediaStore id that+survives an overwrite. So a DIFFERENT file at the same place opened under the+previous document's origin and read its localStorage, its autosave recovery+copy and version history, and, because Android supplies no docstore, this+device's member private key for that document. A different file elsewhere read+nothing.++**Decided.** The origin is a CLAIM in a device-local index, bound to the+document (`DocumentOrigin.kt`, `OriginIndex.kt`):++- **The docId refuses, never claims.** On every open, a URI's claim is reused+ only for the same docId (a strict UUID read from the plaintext `#bento-doc`).+ A different docId gets a fresh origin. A docId never selects an origin: an+ unknown URI does not inherit another URI's claim because the docIds match.+- **No docId** (an encrypted envelope, or a never-saved shell): reuse only for+ exactly the bytes the host last read or wrote (SHA-256). Any other change gets+ a fresh origin. A first save, which writes the docId the kernel just minted,+ moves the claim to that docId, because the host itself wrote those bytes.+- **New origins** are HMAC-SHA256(Keystore key, URI ‖ docId), or ‖ the content+ hash when there is no docId. The key never leaves the device, and nothing in a+ file selects or reproduces it.+- **Legacy origins are adopted on update**, so existing recovery copies and+ member keys survive. But only after an inspector page, served IN the legacy+ origin before any document code runs there, finds no autosave record and no+ member key belonging to another docId. Anything it can't attribute, or no+ answer, gets a fresh origin.+- **Nothing is cleared.** An abandoned origin's data stays, unreachable. Its+ owner may have moved, and wiping it would destroy their recovery copy.+- **A move or rename done outside the app gets a fresh origin.** The only+ device-local evidence of a move would be the app performing it, and it has no+ such feature. Letting a matching docId follow the file would let a docId claim+ an origin, which is the hole this closes.++**Verified on the emulator**, old build upgraded to new, app data kept:+- the same document reopens on its legacy origin, with its own data;+- a different document at a URI whose legacy storage holds another docId gets a+ fresh origin and reads nothing;+- an `msf:` overwrite by a different docId gets a fresh origin;+- a successor at the same folder-index path after a delete gets a fresh origin;+- a document reopened unchanged keeps its origin and data;+- a never-saved shell keeps its storage across its first save and reopen.++JVM rig: `DocumentOriginTest`, 18 cases. Removing the docId refusal fails 4;+always adopting legacy storage fails 3. CI now runs the Android unit tests+(`home-android-unit`); nothing ran them before.++**Still open:** the member private key leaves localStorage only with a host+docstore (`kernel/src/docstore.ts`). Android's, Keystore-backed and partitioned+by this same claim, is next. iOS has the same path-derived origin and is fixing+it in its own change.+## 2026-10-18 — The Mac app is the iOS app, built for Mac Catalyst; a Mac double-click edits in place**Decision (maintainer, 2026-10-18).** Native desktop apps are the primary desktopdiff --git a/home/android/app/src/main/java/page/bento/home/DocumentOrigin.kt b/home/android/app/src/main/java/page/bento/home/DocumentOrigin.ktnew file mode 100644index 00000000..7e3cac21--- /dev/null+++ b/home/android/app/src/main/java/page/bento/home/DocumentOrigin.kt@@ -0,0 +1,209 @@+// SPDX-License-Identifier: MIT+// Copyright (c) 2026 The Bento authors++package page.bento.home++import java.security.MessageDigest++/**+ * Which web origin a document runs under — and so whose localStorage, IndexedDB+ * autosave and member key it can read.+ *+ * It used to be a hash of the document's URI. But many URIs are PATHS — the+ * folder index (`primary:Documents/x.bento.html`) and the Files app's Downloads+ * view (`raw:/storage/…`) — and a Downloads `msf:` id survives an overwrite. So a+ * DIFFERENT file at the same place inherited the previous one's storage: its+ * unsaved recovery copy, its version history and this device's member key.+ * Measured on the emulator before this change.+ *+ * The origin is now a CLAIM held in a device-local index, bound to the document+ * it was issued for, and the file can never name one:+ *+ * - **docId refuses, never claims.** A document carries a docId (a UUID in its+ * `#bento-doc` block). On EVERY open, a claim is reused only if it was issued+ * for that same docId. A different docId at the same URI gets a fresh origin.+ * A docId alone never selects an origin: an unknown URI never inherits+ * another URI's claim because the docIds match.+ * - **No docId** (an encrypted envelope, or a never-saved shell): the claim is+ * reused only if the bytes are exactly those the host last read or wrote+ * (SHA-256 of the content). An unexplained change gets a fresh origin.+ * - **Legacy origins** (sha24 of the URI, the old scheme) are adopted for a URI+ * with no claim yet, so existing recovery copies and member keys survive the+ * update — but only after an inspector page running IN that origin reports+ * no autosave record and no member key belonging to another docId.+ * - **Nothing is cleared.** An old origin's data is simply left unreachable; its+ * owner may have moved, and wiping it would destroy their recovery copy.+ *+ * The decision is pure and runs on the JVM rig ([decide]); the Keystore, the+ * index and the inspector are the Android-side callers.+ */+object DocumentOrigin {++ /** What the host knows about the file it is about to serve. */+ data class Facts(val uri: String, val docId: String?, val contentSha256: String)++ /** One URI's claim in the device-local index. */+ data class Claim(val origin: String, val docId: String?, val contentSha256: String)++ /** What an inspector page found in a LEGACY origin's storage. */+ data class Findings(val docIdsWithData: Set<String>, val unattributedData: Boolean) {+ companion object { val EMPTY = Findings(emptySet(), false) }+ }++ sealed class Decision {+ /** Serve under this claim's origin (re-recorded with current facts). */+ data class Reuse(val origin: String) : Decision()+ /** No claim for this URI: look inside the legacy origin first. */+ data class InspectLegacy(val legacyOrigin: String) : Decision()+ /** Mint a new origin: the old one belongs to some other document. */+ object Fresh : Decision()+ }++ /** The first step, before any inspection. */+ fun decide(facts: Facts, claim: Claim?): Decision {+ if (claim == null) return Decision.InspectLegacy(legacyOrigin(facts.uri))+ return if (sameDocument(facts, claim)) Decision.Reuse(claim.origin) else Decision.Fresh+ }++ /**+ * With a docId, ONLY the docId decides: content changes are expected (another+ * device's edit, a sync) and must not lose state. Without one, only identical+ * bytes do.+ */+ fun sameDocument(facts: Facts, claim: Claim): Boolean =+ if (facts.docId != null) facts.docId == claim.docId+ else claim.docId == null && facts.contentSha256 == claim.contentSha256++ /**+ * May an unclaimed URI keep its legacy origin? Only if nothing in that+ * origin belongs to a different document. For a file with no docId, any data+ * at all is someone else's — there is nothing to attribute it to.+ */+ fun mayAdoptLegacy(facts: Facts, found: Findings): Boolean {+ if (found.unattributedData) return false+ val mine = facts.docId ?: return found.docIdsWithData.isEmpty()+ return found.docIdsWithData.all { it == mine }+ }++ /** The scheme every installed build used until now: sha24 of the URI. */+ fun legacyOrigin(uri: String): String = hex(sha256(uri.toByteArray())).take(24)++ /**+ * A new origin: HMAC(host secret, URI ‖ docId) — or ‖ the content hash when+ * the document has no docId, so two different docless files at one URI still+ * get two origins. The secret is device-local (a Keystore key), so nobody+ * else can compute it, and nothing in the file selects it.+ */+ fun freshOrigin(facts: Facts, hmac: (ByteArray) -> ByteArray): String {+ val subject = facts.uri + "\u001f" + (facts.docId ?: ("sha256:" + facts.contentSha256))+ return hex(hmac(subject.toByteArray())).take(24)+ }++ private val UUID = Regex("^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}$")++ /**+ * The docId from the document's `#bento-doc` block, or null when there is+ * none to trust: no block, an empty block (a never-saved shell), an+ * encrypted envelope (no top-level docId), or a value that is not a strict+ * UUID.+ *+ * Only the TOP-LEVEL `docId` key counts. Document content can carry the+ * string `"docId"` anywhere — a pasted clip, a comment — so this tracks+ * nesting depth and string state rather than searching for the text.+ */+ fun extractDocId(html: String): String? {+ val anchor = html.indexOf(" id=\"bento-doc\"")+ if (anchor < 0) return null+ val start = html.indexOf('>', anchor)+ if (start < 0) return null+ val end = html.indexOf("</script", start)+ if (end < 0) return null+ val json = html.substring(start + 1, end)+ var depth = 0+ var i = 0+ while (i < json.length) {+ val c = json[i]+ when {+ c == '"' -> {+ val close = stringEnd(json, i) ?: return null+ if (depth == 1) {+ // a key at the top level: is it "docId", followed by ':' and a string?+ val key = json.substring(i + 1, close)+ var j = close + 1+ while (j < json.length && json[j].isWhitespace()) j+++ if (key == "docId" && j < json.length && json[j] == ':') {+ j+++ while (j < json.length && json[j].isWhitespace()) j+++ if (j < json.length && json[j] == '"') {+ val vEnd = stringEnd(json, j) ?: return null+ val v = json.substring(j + 1, vEnd)+ return if (UUID.matches(v)) v.lowercase() else null+ }+ return null+ }+ }+ i = close+ }+ c == '{' || c == '[' -> depth+++ c == '}' || c == ']' -> depth--+ }+ i+++ }+ return null+ }++ /** Index of the closing quote of the string opening at [open], honouring escapes. */+ private fun stringEnd(s: String, open: Int): Int? {+ var k = open + 1+ while (k < s.length) {+ when (s[k]) {+ '\\' -> k += 2+ '"' -> return k+ else -> k+++ }+ }+ return null+ }++ fun sha256(b: ByteArray): ByteArray = MessageDigest.getInstance("SHA-256").digest(b)+ fun hex(b: ByteArray): String = b.joinToString("") { "%02x".format(it) }++ /**+ * The inspector, served AT the legacy origin before anything else runs there.+ * It reports which docIds own data — autosave recovery and version records,+ * and `bento-member-<docId>` keys — and whether anything else is present that+ * cannot be attributed. It only reads: it opens only databases that already+ * exist, so looking does not create one.+ */+ const val INSPECTOR_PATH = "/.bento-host-inspect"+ val INSPECTOR_HTML = """<!doctype html><meta charset="utf-8"><script>+(async () => {+ const ids = new Set(); let unattributed = false+ try {+ for (let i = 0; i < localStorage.length; i++) {+ const k = localStorage.key(i)+ const m = /^bento-member-(.+)$/.exec(k)+ if (m) ids.add(m[1].toLowerCase())+ }+ } catch (e) { unattributed = true }+ try {+ // No way to list databases means no way to know what is here: that is+ // unattributable, never "empty". Only names that already exist are+ // opened, at their own version, so looking never creates a database.+ if (!indexedDB.databases) throw new Error('cannot list databases')+ const dbs = await indexedDB.databases()+ for (const { name } of dbs) {+ if (!name || !/autosave$/.test(name)) { if (name) unattributed = true; continue }+ const db = await new Promise((res, rej) => { const r = indexedDB.open(name); r.onsuccess = () => res(r.result); r.onerror = () => rej(r.error) })+ for (const st of db.objectStoreNames) {+ const all = await new Promise(res => { const r = db.transaction(st).objectStore(st).getAll(); r.onsuccess = () => res(r.result || []); r.onerror = () => res(null) })+ if (!all) { unattributed = true; continue }+ for (const rec of all) { if (rec && typeof rec.docId === 'string') ids.add(rec.docId.toLowerCase()); else unattributed = true }+ }+ db.close()+ }+ } catch (e) { unattributed = true }+ __bentoInspect.postMessage(JSON.stringify({ docIds: [...ids], unattributed }))+})()+</script>"""+}diff --git a/home/android/app/src/main/java/page/bento/home/EditorActivity.kt b/home/android/app/src/main/java/page/bento/home/EditorActivity.ktindex 16f31d3b..f6969603 100644--- a/home/android/app/src/main/java/page/bento/home/EditorActivity.kt+++ b/home/android/app/src/main/java/page/bento/home/EditorActivity.kt@@ -34,7 +34,6 @@ import androidx.webkit.WebViewCompatimport androidx.webkit.WebViewFeatureimport org.json.JSONObjectimport java.io.ByteArrayInputStream-import java.security.MessageDigestimport java.util.concurrent.Executors/**@@ -161,13 +160,12 @@ class EditorActivity : Activity() {*/private val io = Executors.newSingleThreadExecutor()- /** Stable per-document host: a truncated SHA-256 of the document's URI.- * Hex only, so it is always a valid host component. */- private val originHost: String by lazy {- val digest = MessageDigest.getInstance("SHA-256")- .digest((docUri?.toString() ?: "unsaved").toByteArray())- digest.joinToString("") { "%02x".format(it) }.take(24) + ".bento-tray.invalid"- }+ /**+ * The document's web origin, chosen by [DocumentOrigin] before the page+ * loads: whose localStorage, autosave and member key this page can read.+ * Hex only, so it is always a valid host component.+ */+ private var originHost = ""override fun onCreate(savedInstanceState: Bundle?) {super.onCreate(savedInstanceState)@@ -198,6 +196,9 @@ class EditorActivity : Activity() {} catch (e: Exception) {Log.w(TAG, "open failed", e); null}+ // Decoding and hashing a multi-megabyte deck belongs here, off the+ // main thread, not in the origin decision that follows.+ val facts = data?.let { factsOf(uri, it) }runOnUiThread {if (isFinishing || isDestroyed) return@runOnUiThreadif (data == null) {@@ -205,12 +206,95 @@ class EditorActivity : Activity() {} else {bytes = dataRecents.touch(this, uri, docName)- startWebView()+ chooseOrigin(facts!!) { origin ->+ if (isFinishing || isDestroyed) return@chooseOrigin+ originHost = "$origin.bento-tray.invalid"+ startWebView()+ }}}}.start()}+ /** What the host knows about the file it is about to serve. */+ private fun factsOf(uri: Uri, data: ByteArray) = DocumentOrigin.Facts(+ uri = uri.toString(),+ docId = DocumentOrigin.extractDocId(data.toString(Charsets.UTF_8)),+ contentSha256 = DocumentOrigin.hex(DocumentOrigin.sha256(data)),+ )++ /**+ * Pick the origin for this open — see [DocumentOrigin] for the rules. The+ * claim is re-recorded with the current facts every time, so the index+ * always describes the instance this host last saw.+ */+ private fun chooseOrigin(facts: DocumentOrigin.Facts, then: (String) -> Unit) {+ val fresh = { DocumentOrigin.freshOrigin(facts) { OriginIndex.hmac(this, it) } }+ fun settle(origin: String) {+ OriginIndex.record(this, facts.uri, DocumentOrigin.Claim(origin, facts.docId, facts.contentSha256))+ then(origin)+ }+ when (val d = DocumentOrigin.decide(facts, OriginIndex.claim(this, facts.uri))) {+ is DocumentOrigin.Decision.Reuse -> settle(d.origin)+ is DocumentOrigin.Decision.Fresh -> settle(fresh())+ is DocumentOrigin.Decision.InspectLegacy -> inspectLegacy(d.legacyOrigin) { found ->+ settle(if (DocumentOrigin.mayAdoptLegacy(facts, found)) d.legacyOrigin else fresh())+ }+ }+ }++ /**+ * Look inside a legacy origin before adopting it. The inspector page runs IN+ * that origin — the only place its storage can be read from — in a separate,+ * throwaway WebView, before any document code has run there. No answer in+ * time counts as unattributable data, so the safe outcome (a fresh origin)+ * is also the default.+ */+ private fun inspectLegacy(origin: String, done: (DocumentOrigin.Findings) -> Unit) {+ val host = "$origin.bento-tray.invalid"+ val probe = WebView(this)+ var settled = false+ fun finish(f: DocumentOrigin.Findings) {+ if (settled) return+ settled = true+ probe.post { probe.destroy() }+ done(f)+ }+ probe.settings.javaScriptEnabled = true+ probe.settings.domStorageEnabled = true+ probe.settings.allowFileAccess = false+ probe.settings.allowContentAccess = false+ probe.webViewClient = object : WebViewClient() {+ override fun shouldInterceptRequest(view: WebView, request: WebResourceRequest): WebResourceResponse? {+ // Serve the inspector and nothing else; everything else on this+ // origin answers 404, so the probe can never load the document.+ if (request.url.host != host) return null+ val body = if (request.url.path == DocumentOrigin.INSPECTOR_PATH)+ DocumentOrigin.INSPECTOR_HTML.toByteArray() else ByteArray(0)+ val code = if (body.isEmpty()) 404 else 200+ return WebResourceResponse("text/html", "utf-8", code, if (code == 200) "OK" else "Not Found",+ emptyMap(), ByteArrayInputStream(body))+ }+ override fun shouldOverrideUrlLoading(view: WebView, request: WebResourceRequest) = true+ }+ if (!WebViewFeature.isFeatureSupported(WebViewFeature.WEB_MESSAGE_LISTENER)) {+ finish(DocumentOrigin.Findings(emptySet(), true)); return+ }+ WebViewCompat.addWebMessageListener(probe, "__bentoInspect", setOf("https://$host")) { _, message, _, isMainFrame, _ ->+ if (!isMainFrame) return@addWebMessageListener+ val f = try {+ val o = JSONObject(message.data ?: "")+ val ids = o.getJSONArray("docIds")+ DocumentOrigin.Findings((0 until ids.length()).map { ids.getString(it) }.toSet(), o.optBoolean("unattributed", true))+ } catch (e: Exception) {+ Log.w(TAG, "unreadable inspector report", e); DocumentOrigin.Findings(emptySet(), true)+ }+ finish(f)+ }+ probe.postDelayed({ finish(DocumentOrigin.Findings(emptySet(), true)) }, 8_000)+ probe.loadUrl("https://$host${DocumentOrigin.INSPECTOR_PATH}")+ }+private fun startWebView() {// Debug builds only: makes the document inspectable from// chrome://inspect, which is the only way to see what a hosted page is@@ -643,8 +727,17 @@ class EditorActivity : Activity() {val data = text.toByteArray()io.execute {val err = writeBytes(uri, data)+ // This host wrote these bytes, so the claim follows them: a+ // never-saved document's first save gives it its docId here, and a+ // docless document's claim tracks its new content. Computed on this+ // thread — an autosave writes megabytes every few seconds.+ val f = if (err == null) factsOf(uri, data) else nullrunOnUiThread {- if (err == null) bytes = data+ if (err == null) {+ bytes = data+ OriginIndex.record(this, f!!.uri,+ DocumentOrigin.Claim(originHost.substringBefore('.'), f.docId, f.contentSha256))+ }reply(id, err == null, err)}}diff --git a/home/android/app/src/main/java/page/bento/home/OriginIndex.kt b/home/android/app/src/main/java/page/bento/home/OriginIndex.ktnew file mode 100644index 00000000..6f4cb8a9--- /dev/null+++ b/home/android/app/src/main/java/page/bento/home/OriginIndex.kt@@ -0,0 +1,84 @@+// SPDX-License-Identifier: MIT+// Copyright (c) 2026 The Bento authors++package page.bento.home++import android.content.Context+import android.security.keystore.KeyGenParameterSpec+import android.security.keystore.KeyProperties+import android.util.Log+import org.json.JSONObject+import java.io.File+import java.security.KeyStore+import java.security.SecureRandom+import javax.crypto.KeyGenerator+import javax.crypto.Mac+import javax.crypto.SecretKey+import javax.crypto.spec.SecretKeySpec++/**+ * The device-local half of [DocumentOrigin]: which origin each URI was issued,+ * and the secret new origins are derived from.+ *+ * Both live only on this device and travel with no file, which is the point:+ * nothing a document carries can select or reproduce an origin. The index is a+ * cache of claims, like [Recents] is a cache of grants — losing it (clear+ * storage) also loses every origin's data, so nothing is stranded.+ */+object OriginIndex {+ private const val TAG = "BentoTray"+ private const val PREFS = "doc-origins"+ private const val KEY_ALIAS = "bento-origin-hmac"++ fun claim(c: Context, uri: String): DocumentOrigin.Claim? {+ val raw = prefs(c).getString(uri, null) ?: return null+ return try {+ val o = JSONObject(raw)+ DocumentOrigin.Claim(+ origin = o.getString("o"),+ docId = if (o.isNull("d")) null else o.getString("d"),+ contentSha256 = o.getString("h"),+ )+ } catch (e: Exception) {+ // An unreadable claim is no claim: the open falls back to inspection,+ // which refuses anything that is not this document's.+ Log.w(TAG, "unreadable origin claim", e); null+ }+ }++ fun record(c: Context, uri: String, claim: DocumentOrigin.Claim) {+ val o = JSONObject().put("o", claim.origin).put("h", claim.contentSha256)+ .put("d", claim.docId ?: JSONObject.NULL)+ prefs(c).edit().putString(uri, o.toString()).apply()+ }++ /**+ * HMAC-SHA256 under a key that never leaves the Keystore. If the Keystore+ * cannot be used on this device, a random secret in no-backup app storage+ * stands in: still device-local, still never in a file a document carries.+ */+ fun hmac(c: Context, message: ByteArray): ByteArray {+ val mac = Mac.getInstance("HmacSHA256")+ mac.init(keystoreKey() ?: fallbackKey(c))+ return mac.doFinal(message)+ }++ private fun keystoreKey(): SecretKey? = try {+ val ks = KeyStore.getInstance("AndroidKeyStore").apply { load(null) }+ (ks.getKey(KEY_ALIAS, null) as? SecretKey) ?: KeyGenerator+ .getInstance(KeyProperties.KEY_ALGORITHM_HMAC_SHA256, "AndroidKeyStore")+ .apply { init(KeyGenParameterSpec.Builder(KEY_ALIAS, KeyProperties.PURPOSE_SIGN).build()) }+ .generateKey()+ } catch (e: Exception) {+ Log.w(TAG, "Keystore HMAC key unavailable; using the app-private secret", e); null+ }++ private fun fallbackKey(c: Context): SecretKey {+ val f = File(c.noBackupFilesDir, "origin-secret")+ val bytes = if (f.length() == 32L) f.readBytes()+ else ByteArray(32).also { SecureRandom().nextBytes(it); f.writeBytes(it) }+ return SecretKeySpec(bytes, "HmacSHA256")+ }++ private fun prefs(c: Context) = c.getSharedPreferences(PREFS, Context.MODE_PRIVATE)+}diff --git a/home/android/app/src/test/java/page/bento/home/DocumentOriginTest.kt b/home/android/app/src/test/java/page/bento/home/DocumentOriginTest.ktnew file mode 100644index 00000000..e7226c32--- /dev/null+++ b/home/android/app/src/test/java/page/bento/home/DocumentOriginTest.kt@@ -0,0 +1,145 @@+// SPDX-License-Identifier: MIT+// Copyright (c) 2026 The Bento authors++package page.bento.home++import org.junit.Assert.assertEquals+import org.junit.Assert.assertFalse+import org.junit.Assert.assertNotEquals+import org.junit.Assert.assertNull+import org.junit.Assert.assertTrue+import org.junit.Test+import page.bento.home.DocumentOrigin.Claim+import page.bento.home.DocumentOrigin.Decision+import page.bento.home.DocumentOrigin.Facts+import page.bento.home.DocumentOrigin.Findings+import javax.crypto.Mac+import javax.crypto.spec.SecretKeySpec++/**+ * Which storage a document is allowed to read. Each case is one way a different+ * file can arrive at a URI a document used before — the decision must never hand+ * it the previous document's storage — or one way the SAME document comes back,+ * which must keep its recovery copy and member key.+ */+class DocumentOriginTest {++ private val uri = "content://com.android.externalstorage.documents/tree/primary%3ADocuments/document/primary%3ADocuments%2Fdeck.bento.html"+ private val a = "0176ab3a-fd86-4cd6-9d1a-5339e0a3bab4"+ private val b = "7a26ddd3-da56-4f82-b303-b32d086c7000"+ private fun facts(docId: String?, sha: String = "s1") = Facts(uri, docId, sha)+ private fun claim(docId: String?, sha: String = "s1") = Claim("origin-a", docId, sha)+ private val hmac: (ByteArray) -> ByteArray = { m ->+ Mac.getInstance("HmacSHA256").apply { init(SecretKeySpec(ByteArray(32) { 7 }, "HmacSHA256")) }.doFinal(m)+ }++ // ------------------------------------------------- a different file arrives++ @Test fun `a different docId at a claimed URI gets a fresh origin`() {+ // folder index (primary:path), Downloads raw:path, and an msf: overwrite all+ // reach the decision the same way: same URI, someone else's document+ assertEquals(Decision.Fresh, DocumentOrigin.decide(facts(b), claim(a)))+ }++ @Test fun `a docless file at a URI claimed by a document gets a fresh origin`() {+ assertEquals(Decision.Fresh, DocumentOrigin.decide(facts(null), claim(a)))+ }++ @Test fun `a docless file with different bytes gets a fresh origin`() {+ assertEquals(Decision.Fresh, DocumentOrigin.decide(facts(null, "s2"), claim(null, "s1")))+ }++ @Test fun `a docId never claims a docless URI's origin, even with matching bytes`() {+ // the claim was issued for a docless instance; a docId'd file is a different case+ assertEquals(Decision.Fresh, DocumentOrigin.decide(facts(a, "s1"), claim(null, "s1")))+ }++ // ------------------------------------------------- the same document returns++ @Test fun `the same docId is reused even when the content changed`() {+ // an edit from another device, a sync, or simply the host's own save+ assertEquals(Decision.Reuse("origin-a"), DocumentOrigin.decide(facts(a, "s9"), claim(a, "s1")))+ }++ @Test fun `a docless file with exactly the recorded bytes is reused`() {+ assertEquals(Decision.Reuse("origin-a"), DocumentOrigin.decide(facts(null, "s1"), claim(null, "s1")))+ }++ // ------------------------------------------------- legacy adoption++ @Test fun `an unclaimed URI is inspected at its legacy origin first`() {+ val d = DocumentOrigin.decide(facts(a), null)+ assertEquals(Decision.InspectLegacy(DocumentOrigin.legacyOrigin(uri)), d)+ }++ @Test fun `the legacy origin is the old scheme, so existing data is found`() {+ // sha24 of the URI string — what every build before this one served+ assertEquals("08d6866eedf14858a1d1583d".length, DocumentOrigin.legacyOrigin(uri).length)+ assertEquals(DocumentOrigin.hex(DocumentOrigin.sha256(uri.toByteArray())).take(24), DocumentOrigin.legacyOrigin(uri))+ }++ @Test fun `legacy data belonging only to this docId is adopted`() {+ assertTrue(DocumentOrigin.mayAdoptLegacy(facts(a), Findings(setOf(a), false)))+ assertTrue(DocumentOrigin.mayAdoptLegacy(facts(a), Findings.EMPTY))+ }++ @Test fun `legacy data belonging to a foreign docId refuses adoption`() {+ assertFalse(DocumentOrigin.mayAdoptLegacy(facts(b), Findings(setOf(a), false)))+ assertFalse(DocumentOrigin.mayAdoptLegacy(facts(a), Findings(setOf(a, b), false)))+ }++ @Test fun `unattributable legacy data refuses adoption`() {+ assertFalse(DocumentOrigin.mayAdoptLegacy(facts(a), Findings(emptySet(), true)))+ }++ @Test fun `a docless file adopts only an empty legacy origin`() {+ assertTrue(DocumentOrigin.mayAdoptLegacy(facts(null), Findings.EMPTY))+ assertFalse(DocumentOrigin.mayAdoptLegacy(facts(null), Findings(setOf(a), false)))+ }++ // ------------------------------------------------- fresh origins++ @Test fun `fresh origins differ per docId and per docless content`() {+ val oa = DocumentOrigin.freshOrigin(facts(a), hmac)+ val ob = DocumentOrigin.freshOrigin(facts(b), hmac)+ val n1 = DocumentOrigin.freshOrigin(facts(null, "s1"), hmac)+ val n2 = DocumentOrigin.freshOrigin(facts(null, "s2"), hmac)+ assertEquals(24, oa.length)+ assertNotEquals(oa, ob); assertNotEquals(n1, n2); assertNotEquals(oa, n1)+ assertNotEquals("a fresh origin is never the legacy one", DocumentOrigin.legacyOrigin(uri), oa)+ }++ @Test fun `a fresh origin depends on the host secret, not only on the file`() {+ val other: (ByteArray) -> ByteArray = { m ->+ Mac.getInstance("HmacSHA256").apply { init(SecretKeySpec(ByteArray(32) { 9 }, "HmacSHA256")) }.doFinal(m)+ }+ assertNotEquals(DocumentOrigin.freshOrigin(facts(a), hmac), DocumentOrigin.freshOrigin(facts(a), other))+ }++ // ------------------------------------------------- reading the docId++ private fun doc(json: String) = "<html><head><script type=\"application/bento+json\" id=\"bento-doc\">$json</script></head></html>"++ @Test fun `the top-level docId is read`() {+ assertEquals(a, DocumentOrigin.extractDocId(doc("""{"format":"bento/slides","docId":"$a","title":"x"}""")))+ }++ @Test fun `a docId nested in content is ignored`() {+ val json = """{"format":"bento/slides","slides":[{"html":"{\"docId\":\"$b\"}","clip":{"docId":"$b"}}],"docId":"$a"}"""+ assertEquals(a, DocumentOrigin.extractDocId(doc(json)))+ assertNull(DocumentOrigin.extractDocId(doc("""{"slides":[{"docId":"$b"}]}""")))+ }++ @Test fun `no block, an empty block, an envelope and a non-UUID all give null`() {+ assertNull(DocumentOrigin.extractDocId("<html></html>"))+ assertNull(DocumentOrigin.extractDocId(doc("\n")))+ assertNull(DocumentOrigin.extractDocId(doc("""{"format":"bento/enc","v":1,"it":300000,"salt":"x","iv":"y","data":"z"}""")))+ assertNull(DocumentOrigin.extractDocId(doc("""{"docId":"not-a-uuid"}""")))+ assertNull(DocumentOrigin.extractDocId(doc("""{"docId":"$a-and-more"}""")))+ }++ @Test fun `escaped quotes and the save's u003c escaping do not derail the scan`() {+ val json = """{"title":"a \"quoted\" <b>","docId":"$a"}"""+ assertEquals(a, DocumentOrigin.extractDocId(doc(json)))+ }+}