Skip to content

armgit / bento

Public Imported from GitHub
0

Bento, the office suite that fits in a file

home/ios: a document's storage origin follows the file, not its path (#753)

nyblnet4a48cb365d8a
diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml
index ea933c54..15a77242 100644
--- a/.github/workflows/ci.yml
+++ b/.github/workflows/ci.yml
@@ -775,6 +775,14 @@ jobs:
# changes.
run: node scripts/test-tray-releases.mjs
+ - name: home/ios origin identity rig
+ # Which storage origin a document runs in. It used to be a hash of the
+ # file's path, so a different file that later took the same path read
+ # the previous one's recovery copy and member key. The origin follows the
+ # file's document identifier now; this compiles the real OriginIdentity
+ # and checks every rule. CryptoKit only, so it skips off Apple platforms.
+ run: node scripts/test-home-origin.mjs
+
- name: WebExtension package rig
# Validates the store package without writing it: every file the
# manifest names exists, every icon is the size it claims, no unexpected
@@ -2596,6 +2604,30 @@ jobs:
# replaces it with the real workbook.
run: node scripts/test-dash-gate-browser.mjs
+ home-origin-probe-browser:
+ # The probe that decides whether a file opened for the first time may keep
+ # the storage origin it had before origins followed the file. It runs in
+ # WebKit on iOS, so it's tested in WebKit, against storage laid out the way
+ # the kernel lays it out AND against a real slides deck's own autosave.
+ runs-on: ubuntu-latest
+ timeout-minutes: 15
+ steps:
+ - uses: actions/checkout@v4
+ - uses: actions/setup-node@v4
+ with:
+ node-version: 24
+ - name: Install browser test runtime
+ run: |
+ npm install --prefix "$RUNNER_TEMP/bento-browser" --no-package-lock --ignore-scripts [email protected]
+ "$RUNNER_TEMP/bento-browser/node_modules/.bin/playwright" install --with-deps webkit
+ echo "PLAYWRIGHT_MODULE=$RUNNER_TEMP/bento-browser/node_modules/playwright/index.mjs" >> "$GITHUB_ENV"
+ - name: Build the slides shell the real-deck case opens
+ run: |
+ npm ci --prefix slides
+ npm run build:single --prefix slides
+ - name: Origin probe in WebKit
+ run: node scripts/test-home-origin-probe.mjs
+
spaces-save-browser:
runs-on: ubuntu-latest
timeout-minutes: 15
diff --git a/docs/DECISIONS.md b/docs/DECISIONS.md
index f87f280c..a5507e2a 100644
--- a/docs/DECISIONS.md
+++ b/docs/DECISIONS.md
@@ -14,6 +14,62 @@ Decision. Why. Pointers.
---
+## 2026-10-18 — A document's storage origin follows the file, not its path (iOS)
+
+**Corrects 2026-09-19**, which said the native hosts "were never exposed"
+because each document gets its own origin. That held **across paths**, and was
+false **across reuse of one path**. iOS derived the origin from a hash of the
+file's path, so a different file that later took the same path (the original
+deleted, a new download taking the name) inherited the previous file's web
+storage.
+
+Measured on a build of the host, with a real invite copy joined as a member:
+the successor read the old file's recovery copy, its version history, and this
+device's collab member private key for it. Encrypted decks skip the snapshots,
+but not the member key. Android derives its origin the same way, from the
+document's URI, and is fixing it separately.
+
+**Decision.** The origin follows the FILE (`home/ios/OriginIdentity.swift`):
+
+- **The anchor is the file's document identifier** (`NSURLDocumentIdentifierKey`),
+ with `UF_TRACKED` set on first open so a local file has one. Measured: it
+ survives the app's atomic saves, moves, and iCloud eviction and re-download;
+ a copy doesn't carry it; a new file at the same path gets a new one. It's
+ filesystem metadata, so nothing in a file can claim another's.
+- **A fresh origin is an HMAC under a device-local secret** (Keychain, this
+ device only), so knowing a path or an identifier doesn't reveal it.
+- **The host's index is the authority.** It maps a document to its origin
+ string. A moved file keeps its storage, recovery and member key included.
+- **A path that has had a document is never handed to another.** A newcomer
+ gets fresh storage. Old storage is never cleared, because its owner may simply
+ have moved.
+- **Files opened before this change keep their storage.** A legacy origin is
+ adopted only if everything stored there belongs to the file's own docId, so
+ nobody has to re-join a shared document. docId can refuse an origin, never
+ claim one: it's in the file's contents.
+- **The probe that looks (`home/ios/OriginProbe.js`) enumerates every database**
+ with `indexedDB.databases()`: each app's `${appId}-autosave`, the old shared
+ `bento-autosave`, and `bento-handles`, all attributed by docId. Anything it
+ can't attribute (a blob cache, an unknown database holding records, no
+ `databases()` at all, an error) refuses. "Couldn't look" never reads as
+ "empty". The first version looked only in `bento-autosave` and missed every
+ app's real data; `scripts/test-home-origin-probe.mjs` now runs the probe
+ itself in WebKit, including against a real deck's own autosave.
+- **Without a document identifier,** a random extended-attribute id is a hint,
+ honoured only where the index recorded it for this same file or a move of it.
+ Attributes travel with copies; only device-local state can tell "my file" from
+ someone else's copy of it.
+
+**Also:** the scheme handler serves a document only under its own host. It used
+to answer every `bento-tray://` host with the open document, so a page could
+frame another document's host and run itself there. Measured: WebKit partitions
+that frame's storage by the top-level page, so it read nothing, and the bridge
+already refuses frames. Defence in depth.
+
+**Guarded by** `scripts/test-home-origin.mjs`: the real `OriginIdentity.swift`,
+20 cases. It fails against a path-only origin.
+
+---
## 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 …
diff --git a/home/README.md b/home/README.md
index 722c0e6e..175e1e2c 100644
--- a/home/README.md
+++ b/home/README.md
@@ -469,7 +469,8 @@ here rather than discovered later.
| behaviour | `home/ios` | `home/android` | |
|---|---|---|---|
| FSA polyfill | `home/bridge.js` | `home/bridge.js` | **one shared file** |
-| per-document origin | `bento-tray://<sha24>` custom scheme | `https://<sha24>.bento-tray.invalid`, intercepted | same |
+| per-document origin | `bento-tray://<host>`: follows the FILE (its document identifier), not the path — `OriginIdentity` | `https://<sha24>.bento-tray.invalid`, intercepted — from the URI | **differs** (Android fixing) |
+| a document is served only under its own host | ✓ | — | — |
| document served from memory, never parsed | ✓ | ✓ | same |
| bridge injected at document start | `WKUserScript(.atDocumentStart)` | `addDocumentStartJavaScript` | same |
| bridge reachable only from the document | every message checked: main frame + own origin (`BridgeSender`) | `allowedOriginRules` + `isMainFrame` | same |
diff --git a/home/ios/EditorViewController.swift b/home/ios/EditorViewController.swift
index 92ab3b76..6f28aee5 100644
--- a/home/ios/EditorViewController.swift
+++ b/home/ios/EditorViewController.swift
@@ -57,13 +57,17 @@ final class EditorViewController: UIViewController, WKScriptMessageHandler, WKUR
private var isPresentingFullscreen = false
private var fullscreenObs: NSKeyValueObservation?
- /// Stable per-document host: a truncated SHA-256 of the file's path. Hex
- /// only, so it is always a valid host component.
- private lazy var originHost: String = {
- let path = document.fileURL.standardizedFileURL.path
- let digest = SHA256.hash(data: Data(path.utf8))
- return digest.compactMap { String(format: "%02x", $0) }.joined().prefix(24).description
- }()
+ /// This document's `bento-tray://` host, and so whose web storage it can
+ /// read. It follows the FILE, not the path: see OriginIdentity. Empty until
+ /// decided, and nothing is served or accepted for an empty host.
+ private var originHost = ""
+ /// While a possibly-legacy origin's storage is being checked, before the
+ /// document itself loads.
+ private var probing: (candidate: String, facts: OriginIdentity.Facts, timer: DispatchWorkItem)?
+ /// The attribute hint this document runs under, when it has no document
+ /// identifier. Our own saves replace the file, so its recorded resource id
+ /// is refreshed after each one, or a later move couldn't be followed.
+ private var originHint: String?
/// Called when the user leaves the document. The browser owns teardown —
/// closing the UIDocument and releasing the security scope — because it
@@ -258,6 +262,7 @@ final class EditorViewController: UIViewController, WKScriptMessageHandler, WKUR
cfg.preferences.isElementFullscreenEnabled = false
cfg.setURLSchemeHandler(self, forURLScheme: "bento-tray")
cfg.userContentController.add(self, name: "bentoFile")
+ cfg.userContentController.add(self, name: "bentoOriginProbe")
// .atDocumentStart is required, not stylistic: Bento decides whether it
// can save during boot, so a bridge injected later arrives after the
@@ -284,7 +289,7 @@ final class EditorViewController: UIViewController, WKScriptMessageHandler, WKUR
webView.scrollView.contentInsetAdjustmentBehavior = .never
view.addSubview(webView)
observeFullscreen()
- webView.load(URLRequest(url: URL(string: "bento-tray://\(originHost)/index.html")!))
+ decideOrigin()
view.addGestureRecognizer(TouchWatcher { [weak self] in self?.armIdleFade() })
@@ -311,6 +316,25 @@ final class EditorViewController: UIViewController, WKScriptMessageHandler, WKUR
// MARK: - serving the deck
func webView(_ webView: WKWebView, start task: WKURLSchemeTask) {
+ // Serve THIS document's host only. Navigations away are refused
+ // elsewhere (LinkPolicy), but a frame inside the document is not a
+ // navigation, and this handler used to answer every host with the open
+ // document. So a page could frame another document's host and run
+ // itself there. Measured: it did run in that origin, but WebKit
+ // partitions a framed origin's storage by the top-level page, so it saw
+ // none of that document's storage, and the bridge already refuses
+ // frames (BridgeSender). Defence in depth, then: there is no reason to
+ // serve a document under any host but its own.
+ guard let url = task.request.url, !originHost.isEmpty, url.host == originHost else {
+ task.didFailWithError(URLError(.resourceUnavailable)); return
+ }
+ if probing != nil {
+ guard url.path == Self.probePath else { task.didFailWithError(URLError(.resourceUnavailable)); return }
+ let body = Data((Self.probeHTML ?? "").utf8)
+ task.didReceive(HTTPURLResponse(url: url, statusCode: 200, httpVersion: "HTTP/1.1",
+ headerFields: ["Content-Type": "text/html; charset=utf-8"])!)
+ task.didReceive(body); task.didFinish(); return
+ }
let resp = HTTPURLResponse(url: task.request.url!, statusCode: 200, httpVersion: "HTTP/1.1",
headerFields: ["Content-Type": "text/html; charset=utf-8",
"Content-Length": String(document.html.count)])!
@@ -320,6 +344,61 @@ final class EditorViewController: UIViewController, WKScriptMessageHandler, WKUR
}
func webView(_ webView: WKWebView, stop task: WKURLSchemeTask) {}
+ // MARK: - Which origin
+
+ private func decideOrigin() {
+ let facts = OriginStore.facts(for: document.fileURL, html: document.html)
+ let d = OriginIdentity.decide(facts, index: OriginStore.shared.index,
+ secret: OriginStore.shared.secret, newHint: OriginStore.newHint)
+ guard case .probeLegacy(let candidate) = d else { settleOrigin(d, facts: facts); return }
+ guard Self.probeHTML != nil else {
+ // no probe to ask with: never adopt blind
+ settleOrigin(OriginIdentity.settleLegacy(candidate, storedDocIds: [OriginIdentity.unattributable], f: facts,
+ secret: OriginStore.shared.secret, newHint: OriginStore.newHint), facts: facts)
+ return
+ }
+ // A file never seen here, at a path never claimed: possibly one opened
+ // before origins followed the file. Its storage stays its own only if
+ // everything stored there is this document's — ask that origin, then load.
+ let timer = DispatchWorkItem { [weak self] in
+ guard let self, let p = self.probing else { return }
+ // no answer: never adopt blind
+ self.settleOrigin(OriginIdentity.settleLegacy(p.candidate, storedDocIds: [OriginIdentity.unattributable], f: p.facts,
+ secret: OriginStore.shared.secret, newHint: OriginStore.newHint),
+ facts: p.facts)
+ }
+ probing = (candidate, facts, timer)
+ originHost = candidate
+ DispatchQueue.main.asyncAfter(deadline: .now() + 5, execute: timer)
+ webView.load(URLRequest(url: URL(string: "bento-tray://\(candidate)\(Self.probePath)")!))
+ }
+
+ private func settleOrigin(_ d: OriginIdentity.Decision, facts: OriginIdentity.Facts) {
+ let origin: String, hint: String?
+ switch d {
+ case .known(let o): origin = o; hint = nil
+ case .fresh(let o, let h): origin = o; hint = h
+ case .probeLegacy(let o): origin = o; hint = nil // not reached: settleLegacy never returns it
+ }
+ if let hint { OriginStore.writeHint(hint, to: document.fileURL) }
+ OriginStore.shared.record(origin, hint: hint, facts: facts)
+ originHint = facts.documentKey == nil ? (hint ?? facts.hint) : nil
+ probing = nil
+ originHost = origin
+ webView.load(URLRequest(url: URL(string: "bento-tray://\(origin)/index.html")!))
+ }
+
+ private static let probePath = "/__bento-origin-probe"
+ /// OriginProbe.js, wrapped as a page. It says whose data a possibly-legacy
+ /// origin holds; the same file is run against real IndexedDB by
+ /// scripts/test-home-origin-probe.mjs. nil if it's missing from the bundle,
+ /// and then nothing is ever adopted.
+ private static let probeHTML: String? = {
+ guard let u = Bundle.main.url(forResource: "OriginProbe", withExtension: "js"),
+ let js = try? String(contentsOf: u, encoding: .utf8) else { return nil }
+ return "<!doctype html><meta charset=\"utf-8\"><script>\n" + js + "\n</script>"
+ }()
+
// MARK: - downloads
//
// Not every self-contained HTML app saves through the File System Access
@@ -486,6 +565,21 @@ final class EditorViewController: UIViewController, WKScriptMessageHandler, WKUR
// MARK: - the save bridge
func userContentController(_ c: WKUserContentController, didReceive message: WKScriptMessage) {
+ if message.name == "bentoOriginProbe" {
+ let sender = message.frameInfo.securityOrigin
+ guard let p = probing, message.frameInfo.isMainFrame, sender.protocol == "bento-tray",
+ sender.host == p.candidate, let body = message.body as? [String: Any],
+ let ids = body["ids"] as? [String] else { return }
+ p.timer.cancel()
+ // Anything the probe couldn't attribute to a docId refuses the origin.
+ var stored = Set(ids)
+ if body["unattributable"] as? Bool != false { stored.insert(OriginIdentity.unattributable) }
+ let d = OriginIdentity.settleLegacy(p.candidate, storedDocIds: stored, f: p.facts,
+ secret: OriginStore.shared.secret, newHint: OriginStore.newHint)
+ settleOrigin(d, facts: p.facts)
+ return
+ }
+ guard message.name == "bentoFile" else { return }
// Only the open document may use the bridge. Checked before anything in
// the message is read; see BridgeSender.
let sender = message.frameInfo.securityOrigin
@@ -546,6 +640,7 @@ final class EditorViewController: UIViewController, WKScriptMessageHandler, WKUR
// writing behind UIDocument's back.
document.updateChangeCount(.done)
document.save(to: document.fileURL, for: .forOverwriting) { [weak self] ok in
+ if ok, let self, let h = self.originHint { OriginStore.shared.refreshHint(h, for: self.document.fileURL) }
self?.reply(id, ok: ok, value: ok ? nil : "write failed")
}
} else {
diff --git a/home/ios/OriginIdentity.swift b/home/ios/OriginIdentity.swift
new file mode 100644
index 00000000..78b2542b
--- /dev/null
+++ b/home/ios/OriginIdentity.swift
@@ -0,0 +1,169 @@
+// SPDX-License-Identifier: MIT
+// Copyright (c) 2026 The Bento authors
+
+import CryptoKit
+import Foundation
+
+/// Which `bento-tray://<host>` origin a document runs in — and so whose
+/// localStorage and IndexedDB it can read.
+///
+/// The origin used to be a hash of the file's PATH. A different file that later
+/// landed at the same path (the original deleted, a new download taking the same
+/// name — "Untitled.bento.html" is common) therefore inherited the previous
+/// file's storage: its recovery snapshot, its version history, and this device's
+/// collab member private key for it. Measured: a second file at a reused path
+/// read all three.
+///
+/// The origin now follows the FILE, not the path:
+///
+/// - **Anchor: the file's document identifier** (`NSURLDocumentIdentifierKey`),
+/// with `UF_TRACKED` set on first open so a local file has one. Measured on the
+/// app's own atomic save, a move, and iCloud eviction and re-download: it
+/// stays. A copy does not carry it, and a new file at the same path gets a new
+/// one. It is filesystem metadata, so nothing in a file can claim another's.
+/// Origin = HMAC(this device's host secret, volume ‖ document identifier).
+/// - **The index is the authority**, mapping a document to its origin string.
+/// That is what lets a moved file keep its storage, and lets a file opened
+/// before this change keep the origin its storage already lives in.
+/// - **Where there is no document identifier** (a provider that won't track
+/// files), a random id in an extended attribute is a HINT, honoured only when
+/// the index recorded it for this same file or a move of it. An attribute
+/// travels with copies; device-local state is the only thing that can tell
+/// "my file" from someone else's copy of it.
+/// - **A path once claimed is never adopted again.** A newcomer there gets fresh
+/// storage. The old storage is never cleared: its owner may simply have moved.
+///
+/// Foundation-only, so every rule is checked standalone with `swiftc`
+/// (scripts/test-home-origin.mjs). EditorViewController gathers the facts, runs
+/// the probe, and loads the page.
+enum OriginIdentity {
+ /// What the host knows about the file being opened.
+ struct Facts: Equatable {
+ var path: String
+ /// volume ‖ document identifier, when the filesystem provides one
+ var documentKey: String?
+ /// the extended-attribute hint, when there is no document key
+ var hint: String?
+ /// the file's current resource identifier (inode-like), for hint checks
+ var resourceID: String?
+ /// the document's own docId from #bento-doc, when it can be read
+ var docId: String?
+ }
+
+ struct HintRecord: Codable, Equatable {
+ var origin: String
+ var path: String
+ var resourceID: String?
+ }
+
+ struct Index: Codable, Equatable {
+ /// document key → origin string
+ var byDocument: [String: String] = [:]
+ /// extended-attribute hint → where and what it was recorded for
+ var hints: [String: HintRecord] = [:]
+ /// paths a document has run from. Never adopted again for another.
+ var claimedPaths: Set<String> = []
+ }
+
+ enum Decision: Equatable {
+ /// The index knows this file: use its origin.
+ case known(String)
+ /// A file never seen at a path never claimed — it may be one opened
+ /// before this change. Probe this origin's storage, then `settleLegacy`.
+ case probeLegacy(String)
+ /// Fresh storage. When `hint` is set, write it to the file's attribute.
+ case fresh(String, hint: String?)
+ }
+
+ /// Stands in, among stored docIds, for data the probe couldn't attribute (or
+ /// a probe that never answered). It matches no document, so it refuses.
+ static let unattributable = "\u{0}unattributable"
+
+ /// The origin every file had before this change: a hash of its path.
+ static func legacyOrigin(path: String) -> String {
+ hex(SHA256.hash(data: Data(path.utf8)))
+ }
+
+ static func freshOrigin(secret: Data, key: String) -> String {
+ hex(HMAC<SHA256>.authenticationCode(for: Data(key.utf8), using: SymmetricKey(data: secret)))
+ }
+
+ static func decide(_ f: Facts, index: Index, secret: Data, newHint: () -> String) -> Decision {
+ if let key = f.documentKey {
+ if let origin = index.byDocument[key] { return .known(origin) }
+ if index.claimedPaths.contains(f.path) {
+ return .fresh(freshOrigin(secret: secret, key: "d:" + key), hint: nil)
+ }
+ return .probeLegacy(legacyOrigin(path: f.path))
+ }
+ // No document identifier: the attribute is a hint, never an authority.
+ if let hint = f.hint, let rec = index.hints[hint] {
+ let sameFile = rec.path == f.path // in place, or edited elsewhere and synced
+ let moved = rec.resourceID != nil && rec.resourceID == f.resourceID
+ if sameFile || moved { return .known(rec.origin) }
+ }
+ if index.claimedPaths.contains(f.path) {
+ let token = newHint()
+ return .fresh(freshOrigin(secret: secret, key: "x:" + token), hint: token)
+ }
+ return .probeLegacy(legacyOrigin(path: f.path))
+ }
+
+ /// After probing a legacy origin: adopt it only if everything stored there
+ /// belongs to this document. docId never CLAIMS an origin; it only refuses
+ /// one. A file whose docId can't be read (an encrypted envelope) is refused
+ /// whenever the origin holds anything at all.
+ static func settleLegacy(_ candidate: String, storedDocIds: Set<String>, f: Facts,
+ secret: Data, newHint: () -> String) -> Decision {
+ let own = f.docId.map { storedDocIds.subtracting([$0]).isEmpty } ?? storedDocIds.isEmpty
+ if own { return .known(candidate) }
+ if let key = f.documentKey { return .fresh(freshOrigin(secret: secret, key: "d:" + key), hint: nil) }
+ let token = newHint()
+ return .fresh(freshOrigin(secret: secret, key: "x:" + token), hint: token)
+ }
+
+ /// Record what was decided, so the next open — or the next open after a
+ /// move — finds it.
+ static func record(_ origin: String, hint: String?, f: Facts, into index: inout Index) {
+ index.claimedPaths.insert(f.path)
+ if let key = f.documentKey {
+ index.byDocument[key] = origin
+ } else if let h = hint ?? f.hint {
+ index.hints[h] = HintRecord(origin: origin, path: f.path, resourceID: f.resourceID)
+ }
+ }
+
+ /// The document's own docId, read from the `#bento-doc` block without
+ /// running anything. nil for an encrypted envelope or a file that isn't Bento.
+ static func docId(inHTML html: Data) -> String? {
+ let s = String(decoding: html, as: UTF8.self)
+ // Anchored to the data block's own <script> tag, not the first place the
+ // string appears: a docId only ever REFUSES an origin, but read it right.
+ var from = s.startIndex
+ while let tag = s.range(of: "<script", range: from..<s.endIndex) {
+ guard let end = s.range(of: ">", range: tag.upperBound..<s.endIndex) else { return nil }
+ let attrs = s[tag.upperBound..<end.lowerBound]
+ from = end.upperBound
+ guard attrs.contains("id=\"bento-doc\""), attrs.contains("application/bento+json"),
+ let close = s.range(of: "</script>", range: end.upperBound..<s.endIndex) else { continue }
+ guard let obj = try? JSONSerialization.jsonObject(with: Data(s[end.upperBound..<close.lowerBound].utf8)) as? [String: Any],
+ let id = obj["docId"] as? String, isDocIdShaped(id) else { return nil }
+ // as stored: the probe reports ids exactly as the kernel keyed them
+ return id
+ }
+ return nil
+ }
+
+ /// Not "a UUID": the editor mints `crypto.randomUUID()` where it can and
+ /// `doc-<random>` where it can't (a context that isn't secure), and saved
+ /// files carry both. Short, and plain characters only.
+ static func isDocIdShaped(_ s: String) -> Bool {
+ !s.isEmpty && s.count <= 128 && s.unicodeScalars.allSatisfy {
+ ("a"..."z").contains($0) || ("A"..."Z").contains($0) || ("0"..."9").contains($0) || $0 == "-" || $0 == "_"
+ }
+ }
+
+ private static func hex<D: Sequence>(_ d: D) -> String where D.Element == UInt8 {
+ String(d.map { String(format: "%02x", $0) }.joined().prefix(24))
+ }
+}
diff --git a/home/ios/OriginProbe.js b/home/ios/OriginProbe.js
new file mode 100644
index 00000000..24f10427
--- /dev/null
+++ b/home/ios/OriginProbe.js
@@ -0,0 +1,79 @@
+// SPDX-License-Identifier: MIT
+// Copyright (c) 2026 The Bento authors
+//
+// Run at a POSSIBLY-LEGACY document origin, before the document loads, to say
+// whose data that origin holds. The host adopts the origin only if every record
+// belongs to the file being opened (home/ios/OriginIdentity.swift).
+//
+// Reports { ids: [docId…], unattributable: bool }. Anything it can't attribute
+// to a docId makes `unattributable` true, and the host then refuses the origin:
+// "couldn't look" must never read as "empty", or a predecessor's plaintext is
+// handed to whoever takes its path.
+//
+// It enumerates with indexedDB.databases() and opens each database at the
+// version it already has, so nothing is ever created or upgraded. An empty
+// database planted at version 1 would make the editor's own upgrade skip
+// creating its stores. The upgrade is aborted besides, as a belt.
+//
+// Shared by the host and scripts/test-home-origin-probe.mjs, which runs this
+// file itself against real IndexedDB, so the two can't drift.
+(async () => {
+ const ids = new Set()
+ let unattributable = false
+ const why = [] // reported for diagnosis; the host reads only ids and unattributable
+ const give = (reason) => { unattributable = true; why.push(String(reason)) }
+ const report = () => window.webkit.messageHandlers.bentoOriginProbe.postMessage({ ids: [...ids], unattributable, why })
+
+ try {
+ for (let i = 0; i < localStorage.length; i++) {
+ const k = localStorage.key(i)
+ // member keys are named by docId; the rest are viewer preferences
+ if (k && k.startsWith('bento-member-')) ids.add(k.slice('bento-member-'.length))
+ }
+ } catch (e) { give('localStorage: ' + e) }
+
+ const open = (name, version) => new Promise((res, rej) => {
+ const q = indexedDB.open(name, version)
+ q.onupgradeneeded = () => { q.transaction.abort() }
+ q.onsuccess = () => res(q.result)
+ q.onerror = () => rej(q.error)
+ })
+ const keys = (store, viaIndex) => new Promise((res, rej) => {
+ const out = []
+ const c = viaIndex ? store.index(viaIndex).openKeyCursor(null, 'nextunique') : store.openKeyCursor()
+ c.onsuccess = () => { const cur = c.result; if (!cur) return res(out); out.push(cur.key); cur.continue() }
+ c.onerror = () => rej(c.error)
+ })
+ const count = (store) => new Promise((res, rej) => { const r = store.count(); r.onsuccess = () => res(r.result); r.onerror = () => rej(r.error) })
+
+ try {
+ if (typeof indexedDB.databases !== 'function') { give('no indexedDB.databases()'); return report() }
+ for (const info of await indexedDB.databases()) {
+ if (!info.name) { give('a database with no name'); continue }
+ let db
+ try { db = await open(info.name, info.version) } catch (e) { give(info.name + ': open: ' + e); continue }
+ try {
+ const autosave = info.name === 'bento-autosave' || /-autosave$/.test(info.name)
+ for (const sname of db.objectStoreNames) {
+ // An empty store holds nobody's data. Skip it before opening a cursor:
+ // WebKit can refuse a cursor on one just after its last user closed.
+ if (await count(db.transaction(sname).objectStore(sname)) === 0) continue
+ const store = db.transaction(sname).objectStore(sname)
+ if (autosave && sname === 'recovery') {
+ for (const k of await keys(store)) ids.add(String(k))
+ } else if (autosave && sname === 'versions' && store.indexNames.contains('docId')) {
+ for (const k of await keys(store, 'docId')) ids.add(String(k))
+ } else if (info.name === 'bento-handles') {
+ for (const k of await keys(store)) {
+ const s = String(k), cut = s.indexOf('\u001f')
+ if (cut > 0) ids.add(s.slice(0, cut)); else give(info.name + ': a key with no docId')
+ }
+ } else {
+ give(info.name + '/' + sname + ': records with no docId') // a blob cache, or anything we don't know
+ }
+ }
+ } catch (e) { give(info.name + ': ' + e) } finally { db.close() }
+ }
+ } catch (e) { give('databases(): ' + e) }
+ report()
+})()
diff --git a/home/ios/OriginStore.swift b/home/ios/OriginStore.swift
new file mode 100644
index 00000000..85d4e04d
--- /dev/null
+++ b/home/ios/OriginStore.swift
@@ -0,0 +1,143 @@
+// SPDX-License-Identifier: MIT
+// Copyright (c) 2026 The Bento authors
+
+import Darwin
+import Foundation
+import Security
+
+/// The device-local half of OriginIdentity: the host secret, the index, and
+/// reading the facts a decision needs off a real file.
+///
+/// The SECRET never leaves this device. It's a Keychain item, this device only
+/// and never synchronised. A fresh origin is an HMAC under it, so nobody who
+/// knows a file's path or identifier can work out the origin it runs in here.
+/// The INDEX is a small JSON file in Application Support: document → origin
+/// string, the paths documents have run from, and the extended-attribute hints
+/// recorded for files without a document identifier.
+final class OriginStore {
+ static let shared = OriginStore()
+
+ private(set) var index: OriginIdentity.Index
+ let secret: Data
+ private let indexURL: URL?
+
+ /// The extended attribute holding the hint, only where there is no document
+ /// identifier. Never an authority: see OriginIdentity.
+ static let hintAttribute = "page.bento.home.origin"
+
+ private init() {
+ secret = Self.loadOrMintSecret()
+ // In a folder of our own: on an unsandboxed Mac, Application Support is
+ // the person's shared ~/Library/Application Support, not a container.
+ let dir = FileManager.default.urls(for: .applicationSupportDirectory, in: .userDomainMask).first?
+ .appendingPathComponent(Bundle.main.bundleIdentifier ?? "page.bento.home", isDirectory: true)
+ indexURL = dir?.appendingPathComponent("origin-index.json")
+ if let u = indexURL, let data = try? Data(contentsOf: u),
+ let ix = try? JSONDecoder().decode(OriginIdentity.Index.self, from: data) {
+ index = ix
+ } else {
+ index = OriginIdentity.Index()
+ }
+ }
+
+ func record(_ origin: String, hint: String?, facts: OriginIdentity.Facts) {
+ OriginIdentity.record(origin, hint: hint, f: facts, into: &index)
+ persist()
+ }
+
+ private func persist() {
+ guard let u = indexURL, let data = try? JSONEncoder().encode(index) else { return }
+ try? FileManager.default.createDirectory(at: u.deletingLastPathComponent(), withIntermediateDirectories: true)
+ try? data.write(to: u, options: [.atomic, .completeFileProtectionUntilFirstUserAuthentication])
+ }
+
+ static func newHint() -> String { UUID().uuidString }
+
+ /// After our own save replaced the file, point the hint at its new resource id.
+ func refreshHint(_ hint: String, for url: URL) {
+ guard var rec = index.hints[hint] else { return }
+ var st = stat()
+ guard stat(url.standardizedFileURL.path, &st) == 0 else { return }
+ rec.resourceID = "\(st.st_dev):\(st.st_ino)"
+ index.hints[hint] = rec
+ persist()
+ }
+
+ /// What the file itself can tell us. Called with the document's security
+ /// scope open.
+ static func facts(for url: URL, html: Data) -> OriginIdentity.Facts {
+ let path = url.standardizedFileURL.path
+ var st = stat()
+ let haveStat = stat(path, &st) == 0
+ return OriginIdentity.Facts(
+ path: path,
+ documentKey: documentKey(url, path: path, st: haveStat ? st : nil),
+ hint: readHint(path),
+ resourceID: haveStat ? "\(st.st_dev):\(st.st_ino)" : nil,
+ docId: OriginIdentity.docId(inHTML: html))
+ }
+
+ /// volume ‖ document identifier. A plain local file has no document
+ /// identifier until it is TRACKED, so set UF_TRACKED first — measured: the
+ /// identifier then survives the app's atomic saves, moves, and iCloud
+ /// eviction, and a copy doesn't carry it. nil where the filesystem or
+ /// provider won't track it; the hint path takes over.
+ private static func documentKey(_ url: URL, path: String, st: stat?) -> String? {
+ func read() -> (Int?, String?) {
+ var u = url
+ u.removeAllCachedResourceValues()
+ let v = try? u.resourceValues(forKeys: [.documentIdentifierKey, .volumeUUIDStringKey])
+ return (v?.documentIdentifier, v?.volumeUUIDString)
+ }
+ var (id, volume) = read()
+ if id == nil, let st, st.st_flags & UInt32(UF_TRACKED) == 0, chflags(path, st.st_flags | UInt32(UF_TRACKED)) == 0 {
+ (id, volume) = read()
+ }
+ guard let id, let volume else { return nil }
+ return "\(volume):\(id)"
+ }
+
+ private static func readHint(_ path: String) -> String? {
+ let n = getxattr(path, hintAttribute, nil, 0, 0, 0)
+ guard n > 0, n < 256 else { return nil }
+ var buf = [UInt8](repeating: 0, count: n)
+ guard getxattr(path, hintAttribute, &buf, n, 0, 0) == n else { return nil }
+ return String(decoding: buf, as: UTF8.self)
+ }
+
+ static func writeHint(_ hint: String, to url: URL) {
+ let bytes = Array(hint.utf8)
+ _ = setxattr(url.standardizedFileURL.path, hintAttribute, bytes, bytes.count, 0, 0)
+ }
+
+ private static func loadOrMintSecret() -> Data {
+ let q: [String: Any] = [
+ kSecClass as String: kSecClassGenericPassword,
+ kSecAttrService as String: "page.bento.home.origin",
+ kSecAttrAccount as String: "host-secret",
+ ]
+ var out: CFTypeRef?
+ var read = q
+ read[kSecReturnData as String] = true
+ if SecItemCopyMatching(read as CFDictionary, &out) == errSecSuccess, let d = out as? Data, d.count == 32 {
+ return d
+ }
+ var bytes = [UInt8](repeating: 0, count: 32)
+ if SecRandomCopyBytes(kSecRandomDefault, bytes.count, &bytes) != errSecSuccess {
+ var g = SystemRandomNumberGenerator()
+ bytes = (0..<32).map { _ in UInt8.random(in: 0...255, using: &g) }
+ }
+ let secret = Data(bytes)
+ var add = q
+ add[kSecValueData as String] = secret
+ add[kSecAttrAccessible as String] = kSecAttrAccessibleAfterFirstUnlockThisDeviceOnly
+ add[kSecAttrSynchronizable as String] = false
+ SecItemDelete(q as CFDictionary)
+ let added = SecItemAdd(add as CFDictionary, nil)
+ // A failed add costs less than it looks: the index stores ORIGIN STRINGS,
+ // so every document already seen keeps its origin. Only origins minted
+ // later would come from a different secret. Say so, rather than nothing.
+ if added != errSecSuccess { NSLog("bento/home: origin secret not kept in the Keychain (%d)", added) }
+ return secret
+ }
+}
diff --git a/scripts/test-home-origin-probe.mjs b/scripts/test-home-origin-probe.mjs
new file mode 100644
index 00000000..d9730b64
--- /dev/null
+++ b/scripts/test-home-origin-probe.mjs
@@ -0,0 +1,151 @@
+#!/usr/bin/env node
+// SPDX-License-Identifier: MIT
+// Copyright (c) 2026 The Bento authors
+/**
+ * bento/home origin probe — runs home/ios/OriginProbe.js ITSELF against real
+ * IndexedDB and localStorage, in WebKit (the engine it runs in on iOS).
+ *
+ * PLAYWRIGHT_MODULE=…/playwright/index.mjs node scripts/test-home-origin-probe.mjs
+ * BENTO_BROWSER=chromium … to run it in Chromium instead
+ *
+ * WHY. Before a file opened for the first time adopts the storage origin it had
+ * before origins followed the file, the host asks this probe whose data that
+ * origin holds, and adopts only if every record is the file's own. The first
+ * version looked only in the old shared 'bento-autosave' database, while every
+ * app writes to `${appId}-autosave` since the per-app split. Against a real
+ * edited deck it reported nothing, and "nothing" means adopt. The Swift rule
+ * (scripts/test-home-origin.mjs) was right and tested on supplied sets; this
+ * tests the half that actually looks, with storage laid out the way the kernel
+ * lays it out (kernel/src/autosave.ts, save.ts, sync/blobs.ts).
+ */
+import { readFileSync } from 'node:fs'
+import { join, resolve, dirname } from 'node:path'
+import { fileURLToPath } from 'node:url'
+
+const ROOT = resolve(dirname(fileURLToPath(import.meta.url)), '..')
+const PROBE = readFileSync(process.env.ORIGIN_PROBE || join(ROOT, 'home/ios/OriginProbe.js'), 'utf8')
+const pw = await import(process.env.PLAYWRIGHT_MODULE || 'playwright')
+const engine = pw[process.env.BENTO_BROWSER || 'webkit']
+const browser = await engine.launch()
+
+let checks = 0, failures = 0
+const ok = (c, m) => { checks++; if (!c) failures++; console.log(` ${c ? 'ok ' : 'FAIL'} ${m}`) }
+
+const A = '7025b63c-1111-4222-8333-944455556666', B = '11111111-2222-4333-8444-555566667777'
+// Storage exactly as the kernel lays it out.
+const SEED = {
+ autosave: (name, docId) => `await new Promise((res, rej) => { const q = indexedDB.open(${JSON.stringify(name)}, 1)
+ q.onupgradeneeded = () => { const db = q.result; db.createObjectStore('recovery', { keyPath: 'docId' })
+ const v = db.createObjectStore('versions', { keyPath: 'id', autoIncrement: true }); v.createIndex('docId', 'docId', { unique: false }) }
+ q.onsuccess = () => { const db = q.result, t = db.transaction(['recovery', 'versions'], 'readwrite')
+ t.objectStore('recovery').put({ docId: ${JSON.stringify(docId)}, at: 1, title: 'plaintext', json: '{}' })
+ t.objectStore('versions').put({ docId: ${JSON.stringify(docId)}, at: 1, json: '{}' })
+ t.oncomplete = () => { db.close(); res() }; t.onerror = () => rej(t.error) }; q.onerror = () => rej(q.error) })`,
+ versionsOnly: (name, docId) => `await new Promise((res) => { const q = indexedDB.open(${JSON.stringify(name)}, 1)
+ q.onupgradeneeded = () => { const db = q.result; db.createObjectStore('recovery', { keyPath: 'docId' })
+ const v = db.createObjectStore('versions', { keyPath: 'id', autoIncrement: true }); v.createIndex('docId', 'docId', { unique: false }) }
+ q.onsuccess = () => { const db = q.result, t = db.transaction('versions', 'readwrite'); t.objectStore('versions').put({ docId: ${JSON.stringify(docId)}, at: 1, json: '{}' }); t.oncomplete = () => { db.close(); res() } } })`,
+ keyed: (name, store, key, empty = false) => `await new Promise((res) => { const q = indexedDB.open(${JSON.stringify(name)}, 1)
+ q.onupgradeneeded = () => { q.result.createObjectStore(${JSON.stringify(store)}) }
+ q.onsuccess = () => { const db = q.result; if (${empty}) { db.close(); return res() }
+ const t = db.transaction(${JSON.stringify(store)}, 'readwrite'); t.objectStore(${JSON.stringify(store)}).put({ x: 1 }, ${JSON.stringify(key)}); t.oncomplete = () => { db.close(); res() } } })`,
+ member: (docId) => `localStorage.setItem('bento-member-${docId}', JSON.stringify({ pub: 'P', priv: 'S' }))`,
+ pref: () => `localStorage.setItem('bento-lang', 'fr'); localStorage.setItem('bento-author', 'me')`,
+}
+
+let n = 0
+async function probe(seeds, { noDatabases = false } = {}) {
+ const host = `case${++n}.test`
+ const ctx = await browser.newContext()
+ await ctx.route('**/*', (r) => r.fulfill({ contentType: 'text/html', body: r.request().url().endsWith('/probe')
+ ? `<!doctype html><script>${noDatabases ? 'try { delete IDBFactory.prototype.databases } catch (e) {}; indexedDB.databases = undefined;' : ''}
+ window.webkit = { messageHandlers: { bentoOriginProbe: { postMessage: (v) => { window.__result = v } } } }</script><script>${PROBE}</script>`
+ : '<!doctype html><title>seed</title>' }))
+ const page = await ctx.newPage()
+ await page.goto(`http://${host}/seed`)
+ for (const s of seeds) await page.evaluate(`(async () => { ${s} })()`)
+ await page.goto(`http://${host}/probe`)
+ await page.waitForFunction(() => window.__result, null, { timeout: 10000 })
+ const r = await page.evaluate(() => window.__result)
+ const after = await page.evaluate(() => indexedDB.databases ? indexedDB.databases().then((d) => d.map((x) => x.name)) : null)
+ await ctx.close()
+ return { ids: new Set(r.ids), un: r.unattributable, after }
+}
+
+console.log(`origin probe, in ${process.env.BENTO_BROWSER || 'webkit'}:`)
+{ const r = await probe([]); ok(r.ids.size === 0 && r.un === false, 'an empty origin: nothing stored, attributable — the host adopts')
+ ok(Array.isArray(r.after) && r.after.length === 0, 'probing an empty origin CREATES nothing (no database planted for the editor to trip on)') }
+for (const app of ['bento-slides', 'bento-spaces', 'bento-dash', 'bento-type']) {
+ const r = await probe([SEED.autosave(`${app}-autosave`, A)])
+ ok(r.ids.has(A) && r.ids.size === 1 && r.un === false, `${app}-autosave: the recovery copy is attributed to its docId`)
+}
+{ const r = await probe([SEED.autosave('bento-autosave', A)]); ok(r.ids.has(A) && !r.un, 'the old shared bento-autosave is read too') }
+{ const r = await probe([SEED.versionsOnly('bento-slides-autosave', B)]); ok(r.ids.has(B) && !r.un, 'version history alone (no recovery) is attributed through its docId index') }
+{ const r = await probe([SEED.autosave('bento-slides-autosave', A), SEED.autosave('bento-type-autosave', B)]); ok(r.ids.has(A) && r.ids.has(B), "two apps' data at one origin: both docIds reported") }
+{ const r = await probe([SEED.member(A)]); ok(r.ids.has(A) && !r.un, 'a member key in localStorage is attributed to its docId') }
+{ const r = await probe([SEED.pref()]); ok(r.ids.size === 0 && !r.un, "viewer preferences in localStorage don't count as anyone's data") }
+{ const r = await probe([SEED.keyed('bento-handles', 'handles', `${A}\u001fDeck.bento.html`)]); ok(r.ids.has(A) && !r.un, 'a saved file handle is attributed by its docId prefix') }
+{ const r = await probe([SEED.keyed('bento-handles', 'handles', 'no-separator')]); ok(r.un === true, 'a handle key without a docId is unattributable') }
+{ const r = await probe([SEED.keyed('bento-blobcache', 'blobs', 'sha256-abc')]); ok(r.un === true, 'a blob cache (content-addressed, no docId) is unattributable — the host refuses') }
+{ const r = await probe([SEED.keyed('something-else', 's', 'k')]); ok(r.un === true, 'an unknown database holding records is unattributable — the host refuses') }
+{ const r = await probe([SEED.keyed('something-empty', 's', 'k', true)]); ok(r.un === false, 'an unknown database holding nothing does not refuse') }
+{ const r = await probe([SEED.autosave('bento-slides-autosave', A)], { noDatabases: true }); ok(r.un === true, "no indexedDB.databases(): 'couldn't look' reports unattributable, never empty") }
+
+// The real thing: the slides shell boots, is edited, and ITS kernel autosaves.
+// Then the probe runs at that origin. Needs a built shell (slides/dist-single,
+// or ORIGIN_PROBE_SHELL); without one this case is reported as skipped.
+{
+ const { existsSync } = await import('node:fs')
+ const shell = process.env.ORIGIN_PROBE_SHELL || join(ROOT, 'slides/dist-single/Bento_Slides.bento.html')
+ if (!existsSync(shell)) {
+ console.log(' skip no built slides shell — the real-deck case did not run (npm run build:single --prefix slides)')
+ } else {
+ const html = readFileSync(shell, 'utf8')
+ const ctx = await browser.newContext()
+ await ctx.route('**/*', (r) => r.fulfill({ contentType: 'text/html', body: r.request().url().endsWith('/probe')
+ ? `<!doctype html><script>window.webkit = { messageHandlers: { bentoOriginProbe: { postMessage: (v) => { window.__result = v } } } }</script><script>${PROBE}</script>`
+ : html }))
+ const page = await ctx.newPage()
+ await page.goto('http://realdeck.test/deck.bento.html')
+ await page.waitForFunction(() => window.bento && window.bento.doc && window.bento.loadDoc, null, { timeout: 30000 })
+ const docId = await page.evaluate(async () => {
+ const d = structuredClone(window.bento.doc); d.title = 'An edit the autosave must keep'
+ // loadDoc takes the document as a JSON STRING; an object is refused (false)
+ if (!window.bento.loadDoc(JSON.stringify(d))) throw new Error('loadDoc refused the edit')
+ return window.bento.doc.docId
+ })
+ // The database exists from boot; the copy lands after the 2.5s debounce.
+ // Wait for the RECORD, not the database, or the probe runs on empty stores.
+ // An explicit loop that awaits a real boolean: a predicate that RETURNS a
+ // promise is just truthy to waitForFunction, which then passes at once.
+ const hasRecord = (id) => page.evaluate((id) => new Promise((res) => {
+ const q = indexedDB.open('bento-slides-autosave')
+ q.onupgradeneeded = () => { q.transaction.abort(); res(false) }
+ q.onerror = () => res(false)
+ q.onsuccess = () => { const db = q.result
+ if (!db.objectStoreNames.contains('recovery')) { db.close(); return res(false) }
+ const g = db.transaction('recovery').objectStore('recovery').getKey(id)
+ g.onsuccess = () => { db.close(); res(g.result === id) }; g.onerror = () => { db.close(); res(false) } }
+ }), id)
+ let saved = false
+ for (let i = 0; i < 40 && !(saved = await hasRecord(docId)); i++) await page.waitForTimeout(500)
+ ok(saved, "the real deck's own autosave wrote its recovery copy (the case below tests something)")
+ // The host probes BEFORE the document loads, in a web view nothing else is
+ // using. Close the deck first: a page kept alive in the back-forward cache
+ // still holds its database connections, and WebKit then refuses the probe's
+ // cursors ("Unable to open cursor"). That refusal is safe (it reads as
+ // unattributable), but it isn't the host's situation.
+ await page.close()
+ const probePage = await ctx.newPage()
+ await probePage.goto('http://realdeck.test/probe')
+ await probePage.waitForFunction(() => window.__result, null, { timeout: 10000 })
+ const r = await probePage.evaluate(() => window.__result)
+ if (!r.ids.includes(docId)) console.log(' probe said:', JSON.stringify(r), 'wanted', docId, 'databases:', JSON.stringify(await probePage.evaluate(() => indexedDB.databases())))
+ ok(r.ids.includes(docId), `a REAL edited deck's autosave (docId ${String(docId).slice(0, 8)}…) is found by the probe — the host would refuse a successor`)
+ await ctx.close()
+ }
+}
+
+await browser.close()
+console.log(`\n${checks - failures}/${checks} checks passed`)
+process.exit(failures ? 1 : 0)
diff --git a/scripts/test-home-origin.mjs b/scripts/test-home-origin.mjs
new file mode 100644
index 00000000..4f01998e
--- /dev/null
+++ b/scripts/test-home-origin.mjs
@@ -0,0 +1,157 @@
+#!/usr/bin/env node
+// SPDX-License-Identifier: MIT
+// Copyright (c) 2026 The Bento authors
+/**
+ * bento/home origin identity — which storage origin a document runs in.
+ *
+ * node scripts/test-home-origin.mjs
+ *
+ * WHY. The iOS host derived each document's `bento-tray://` origin from its file
+ * PATH, so a different file that later took the same path inherited the
+ * previous file's localStorage and IndexedDB: its recovery copy, its version
+ * history, and this device's collab member private key for it (measured). The
+ * origin now follows the file (home/ios/OriginIdentity.swift). This compiles the
+ * real file and checks every rule, including the ones that keep existing
+ * storage: a moved file keeps its origin, a legacy file keeps the one its
+ * storage already lives in.
+ *
+ * Apple platforms only (CryptoKit); it skips cleanly elsewhere, like the
+ * releases rig. Run it on a Mac before touching OriginIdentity.swift.
+ */
+import { execFileSync } from 'node:child_process'
+import { createHash } from 'node:crypto'
+import { mkdtempSync, writeFileSync, rmSync } from 'node:fs'
+import { tmpdir } from 'node:os'
+import { join, resolve, dirname } from 'node:path'
+import { fileURLToPath } from 'node:url'
+
+const ROOT = resolve(dirname(fileURLToPath(import.meta.url)), '..')
+const SRC = process.env.ORIGIN_SRC || join(ROOT, 'home/ios/OriginIdentity.swift')
+
+function haveCryptoKit() {
+ let probe
+ try {
+ probe = mkdtempSync(join(tmpdir(), 'bento-cryptokit-'))
+ writeFileSync(join(probe, 'main.swift'), 'import CryptoKit\nimport Foundation\nprint(SHA256.hash(data: Data()).description)\n')
+ execFileSync('swiftc', ['-o', join(probe, 'p'), join(probe, 'main.swift')], { stdio: 'pipe' })
+ return true
+ } catch { return false } finally { if (probe) try { rmSync(probe, { recursive: true, force: true }) } catch {} }
+}
+if (!haveCryptoKit()) {
+ console.log('home origin: SKIPPED — no CryptoKit on this machine (Apple platforms only).')
+ console.log(' Run it on a Mac before touching home/ios/OriginIdentity.swift.')
+ process.exit(0)
+}
+
+// The legacy origin must be EXACTLY what shipped builds derived, or every
+// existing document would lose its storage: sha256(path), hex, first 24.
+const legacyFor = (p) => createHash('sha256').update(p).digest('hex').slice(0, 24)
+
+const main = String.raw`
+import Foundation
+typealias O = OriginIdentity
+let secret = Data(repeating: 7, count: 32)
+var n = 0
+func hint() -> String { n += 1; return "hint-\(n)" }
+func emit(_ k: String, _ v: Any) { print("\(k)=\(v)") }
+func origin(_ d: O.Decision) -> String { switch d { case .known(let o): return o; case .probeLegacy(let o): return o; case .fresh(let o, _): return o } }
+func kind(_ d: O.Decision) -> String { switch d { case .known: return "known"; case .probeLegacy: return "probe"; case .fresh: return "fresh" } }
+
+// --- with a document identifier
+var ix = O.Index()
+let a = O.Facts(path: "/d/Untitled.bento.html", documentKey: "vol1:191", docId: "doc-A")
+let d1 = O.decide(a, index: ix, secret: secret, newHint: hint)
+emit("first.kind", kind(d1)); emit("first.origin", origin(d1))
+let a1 = O.settleLegacy(origin(d1), storedDocIds: [], f: a, secret: secret, newHint: hint)
+O.record(origin(a1), hint: nil, f: a, into: &ix)
+emit("first.settled", origin(a1))
+emit("reopen.kind", kind(O.decide(a, index: ix, secret: secret, newHint: hint)))
+emit("reopen.same", origin(O.decide(a, index: ix, secret: secret, newHint: hint)) == origin(a1))
+// a move: same document identifier, another path
+let moved = O.Facts(path: "/d/sub/Renamed.bento.html", documentKey: "vol1:191", docId: "doc-A")
+let dm = O.decide(moved, index: ix, secret: secret, newHint: hint)
+emit("move.kind", kind(dm)); emit("move.same", origin(dm) == origin(a1))
+// a successor: another file at the SAME, claimed path
+let succ = O.Facts(path: "/d/Untitled.bento.html", documentKey: "vol1:192", docId: "doc-B")
+let ds = O.decide(succ, index: ix, secret: secret, newHint: hint)
+emit("successor.kind", kind(ds)); emit("successor.differs", origin(ds) != origin(a1))
+// a cp copy: no document identifier carried, so a new one at a new path
+let cp = O.Facts(path: "/d/copy.bento.html", documentKey: "vol1:193", docId: "doc-A")
+let dc = O.decide(cp, index: ix, secret: secret, newHint: hint)
+let dcs = O.settleLegacy(origin(dc), storedDocIds: [], f: cp, secret: secret, newHint: hint)
+emit("copy.differs", origin(dcs) != origin(a1))
+// the fresh origin is device-local: another secret, another origin
+emit("secret.local", O.freshOrigin(secret: secret, key: "d:k") != O.freshOrigin(secret: Data(repeating: 8, count: 32), key: "d:k"))
+
+// --- legacy adoption, refused on any other document's data
+emit("legacy.own", kind(O.settleLegacy("L", storedDocIds: ["doc-A"], f: a, secret: secret, newHint: hint)))
+emit("legacy.foreign", kind(O.settleLegacy("L", storedDocIds: ["doc-A", "doc-Z"], f: a, secret: secret, newHint: hint)))
+emit("legacy.otheronly", kind(O.settleLegacy("L", storedDocIds: ["doc-Z"], f: a, secret: secret, newHint: hint)))
+let enc = O.Facts(path: "/d/e.bento.html", documentKey: "vol1:300", docId: nil)
+emit("legacy.unreadable.withdata", kind(O.settleLegacy("L", storedDocIds: ["doc-Z"], f: enc, secret: secret, newHint: hint)))
+emit("legacy.unreadable.empty", kind(O.settleLegacy("L", storedDocIds: [], f: enc, secret: secret, newHint: hint)))
+
+// --- no document identifier: the attribute is a hint, validated by the index
+var hx = O.Index()
+let h1 = O.Facts(path: "/p/Doc.bento.html", documentKey: nil, hint: nil, resourceID: "r1", docId: "doc-H")
+let hd = O.decide(h1, index: hx, secret: secret, newHint: hint)
+let hs = O.settleLegacy(origin(hd), storedDocIds: [], f: h1, secret: secret, newHint: hint)
+// first open of an unclaimed path adopts; give it a hint so a later move can be followed
+let token = hint(); O.record(origin(hs), hint: token, f: h1, into: &hx)
+let hBack = O.Facts(path: "/p/Doc.bento.html", documentKey: nil, hint: token, resourceID: "r2", docId: "doc-H") // after our save: new inode
+emit("hint.inplace", kind(O.decide(hBack, index: hx, secret: secret, newHint: hint)))
+let hMove = O.Facts(path: "/p/elsewhere.bento.html", documentKey: nil, hint: token, resourceID: "r1", docId: "doc-H")
+emit("hint.move", kind(O.decide(hMove, index: hx, secret: secret, newHint: hint)))
+let foreign = O.Facts(path: "/attacker/Planted.bento.html", documentKey: nil, hint: token, resourceID: "r9", docId: "doc-H")
+let df = O.decide(foreign, index: hx, secret: secret, newHint: hint)
+emit("hint.foreign.kind", kind(df)); emit("hint.foreign.differs", origin(df) != origin(hs))
+let hSucc = O.Facts(path: "/p/Doc.bento.html", documentKey: nil, hint: nil, resourceID: "r7", docId: "doc-Q")
+let dhs = O.decide(hSucc, index: hx, secret: secret, newHint: hint)
+emit("hint.successor.kind", kind(dhs)); emit("hint.successor.differs", origin(dhs) != origin(hs))
+if case .fresh(_, let h) = dhs { emit("hint.successor.newhint", h != nil && h != token) }
+
+// --- reading docId without running anything
+emit("docid.plain", O.docId(inHTML: Data("<script type=\"application/bento+json\" id=\"bento-doc\">{\"docId\":\"7025B63C-1111-4222-8333-944455556666\",\"title\":\"x\"}</script>".utf8)) ?? "nil")
+emit("docid.minted", O.docId(inHTML: Data("<script type=\"application/bento+json\" id=\"bento-doc\">{\"docId\":\"doc-mvdqlzln-0f16k\"}</script>".utf8)) ?? "nil")
+emit("docid.junk", O.docId(inHTML: Data("<script type=\"application/bento+json\" id=\"bento-doc\">{\"docId\":\"a b/../c\"}</script>".utf8)) ?? "nil")
+emit("docid.decoy", O.docId(inHTML: Data("<!-- id=\"bento-doc\">{\"docId\":\"00000000-0000-4000-8000-000000000000\"} --><div id=\"bento-doc\">{}</div><script type=\"application/bento+json\" id=\"bento-doc\">{\"docId\":\"7025b63c-1111-4222-8333-944455556666\"}</script>".utf8)) ?? "nil")
+emit("docid.enc", O.docId(inHTML: Data("<script type=\"application/bento+json\" id=\"bento-doc\">{\"format\":\"bento/enc\",\"v\":1}</script>".utf8)) ?? "nil")
+emit("docid.notbento", O.docId(inHTML: Data("<html><body>hi</body></html>".utf8)) ?? "nil")
+`
+const dir = mkdtempSync(join(tmpdir(), 'bento-origin-'))
+let out
+try {
+ writeFileSync(join(dir, 'main.swift'), main)
+ execFileSync('swiftc', ['-O', '-o', join(dir, 'o'), SRC, join(dir, 'main.swift')], { stdio: 'pipe' })
+ out = Object.fromEntries(execFileSync(join(dir, 'o')).toString().trim().split('\n').map((l) => l.split(/=(.*)/s).slice(0, 2)))
+} catch (e) {
+ console.error('swiftc or run failed:\n' + (e.stderr?.toString() ?? e.message)); process.exit(2)
+} finally { try { rmSync(dir, { recursive: true, force: true }) } catch {} }
+
+let failures = 0, checks = 0
+const ok = (c, m) => { checks++; if (!c) failures++; console.log(` ${c ? 'ok ' : 'FAIL'} ${m}`) }
+ok(out['first.kind'] === 'probe', 'a file never seen, at a path never claimed, is probed as possibly legacy')
+ok(out['first.origin'] === legacyFor('/d/Untitled.bento.html'), 'the legacy origin is exactly what shipped builds derived from the path')
+ok(out['first.settled'] === out['first.origin'], 'legacy storage holding only its own docId is adopted (no member re-join)')
+ok(out['reopen.kind'] === 'known' && out['reopen.same'] === 'true', 'reopening finds the same origin in the index')
+ok(out['move.kind'] === 'known' && out['move.same'] === 'true', 'a MOVED file keeps its origin, so recovery and the member key follow it')
+ok(out['successor.kind'] === 'fresh' && out['successor.differs'] === 'true', 'a different file at the same, claimed path gets FRESH storage, never the old one')
+ok(out['copy.differs'] === 'true', 'a cp copy gets storage of its own (the document identifier is not carried)')
+ok(out['secret.local'] === 'true', 'a fresh origin depends on the device-local secret')
+ok(out['legacy.own'] === 'known', 'legacy adoption: storage with only this docId is adopted')
+ok(out['legacy.foreign'] === 'fresh', "legacy refusal: storage holding ANOTHER document's data is refused")
+ok(out['legacy.otheronly'] === 'fresh', 'legacy refusal: storage holding only another docId is refused')
+ok(out['legacy.unreadable.withdata'] === 'fresh', 'an unreadable docId (encrypted) never adopts storage that holds anything')
+ok(out['legacy.unreadable.empty'] === 'known', 'an unreadable docId may adopt EMPTY legacy storage')
+ok(out['hint.inplace'] === 'known', 'no document identifier: the attribute hint is honoured for the same file after our own save')
+ok(out['hint.move'] === 'known', 'no document identifier: the hint follows a move of the recorded file')
+ok(out['hint.foreign.kind'] !== 'known' && out['hint.foreign.differs'] === 'true', "a file planted elsewhere carrying another document's attribute does NOT inherit its origin")
+ok(out['hint.successor.kind'] === 'fresh' && out['hint.successor.differs'] === 'true', 'no document identifier: a successor at a claimed path gets fresh storage')
+ok(out['hint.successor.newhint'] === 'true', 'and a new hint of its own, never the old one')
+ok(out['docid.plain'] === '7025B63C-1111-4222-8333-944455556666', "the document's docId is read from #bento-doc without running anything, exactly as stored")
+ok(out['docid.minted'] === 'doc-mvdqlzln-0f16k', 'the editor\'s non-UUID form (doc-<random>, minted where randomUUID is unavailable) is read too')
+ok(out['docid.junk'] === 'nil', 'a docId with anything but plain characters is not read at all')
+ok(out['docid.decoy'] === '7025b63c-1111-4222-8333-944455556666', "the docId comes from the data block's own <script> tag, not the first match in the file")
+ok(out['docid.enc'] === 'nil' && out['docid.notbento'] === 'nil', 'an encrypted envelope or a non-Bento page yields no docId')
+console.log(`\n${checks - failures}/${checks} checks passed`)
+process.exit(failures ? 1 : 0)