Skip to content

armgit / bento

Public Imported from GitHub
0

Bento, the office suite that fits in a file

home/ios: hold the kernel's per-document store natively (member key in the Keychain) (#757)

nyblneta83a734993ac
diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml
index 05c23723..cbce102c 100644
--- a/.github/workflows/ci.yml
+++ b/.github/workflows/ci.yml
@@ -802,6 +802,12 @@ jobs:
# and checks every rule. CryptoKit only, so it skips off Apple platforms.
run: node scripts/test-home-origin.mjs
+ - name: home/ios docstore rig
+ # The host's per-document store: this device's collab member private key
+ # in the Keychain, the recovery copy in an app-private file, partitioned by
+ # the document's origin. Compiles the real HostDocStore; skips off Apple.
+ run: node scripts/test-home-docstore-ios.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
diff --git a/docs/DECISIONS.md b/docs/DECISIONS.md
index dbc5b74f..5639f7a9 100644
--- a/docs/DECISIONS.md
+++ b/docs/DECISIONS.md
@@ -74,8 +74,20 @@ records. That includes `bento-blobcache`, which caches live-session media in
plaintext. `scripts/test-home-inspector.mjs` runs the script as it ships; it
also matched real Chromium IndexedDB case for case.
-**iOS** implements the same native contract in its own change, keeping the
-member key in the Keychain (this device only).
+**iOS** implements the same native contract (`home/ios/HostDocStore.swift`).
+The member key goes to the Keychain, this device only and never synchronised;
+the recovery copy goes to an app-private file. Both are partitioned by the
+origin string the iOS origin fix mints, so on iOS a moved document keeps its
+store. Measured on the iOS simulator with this bridge and a real invite copy
+joined as a member:
+- the private key lands in the Keychain, and localStorage keeps only `{pub}`
+- the key survives a fresh launch and a move
+- a different file at that path gets an empty partition and mints its own key
+
+An ad-hoc (unsigned) Mac Catalyst build can't reach the Keychain
+(`errSecMissingEntitlement`, -34018). Its store answers 'unavailable', and the
+kernel keeps the key for the session only, never in web storage. A signed build
+needs the Apple team. The iOS simulator works ad-hoc.
## 2026-10-18 — Android: every docId form the apps mint counts as a docId
diff --git a/home/README.md b/home/README.md
index 037d691d..ed42766d 100644
--- a/home/README.md
+++ b/home/README.md
@@ -478,7 +478,7 @@ here rather than discovered later.
| per-document origin | `bento-tray://<host>`: follows the FILE (its document identifier), not the path — `OriginIdentity` | `https://<claim>.bento-tray.invalid`: a claim bound to the document's docId in a device-local index, not the URI — `DocumentOrigin` | same |
| a document is served only under its own host | ✓ | ✓ (by code: the interceptor answers only the document's own host) | same |
| a moved document keeps its storage | ✓ (the document identifier follows the file) | ✗ by design: a move outside the app gets a fresh claim; the old storage is left, never cleared — SAF has no device-local anchor | **differs** |
-| per-document store for the recovery copy and member key (`__bentoHost`) | — | ✓ Keystore-encrypted, no-backup app storage, partitioned by the claim — `DocStore` | **differs** (iOS in progress) |
+| per-document store for the recovery copy and member key (`__bentoHost`) | ✓ member key in the Keychain (this device only), recovery in an app-private file, partitioned by the origin — `HostDocStore`. Unsigned Mac builds can't reach the Keychain | ✓ Keystore-encrypted, no-backup app storage, partitioned by the claim — `DocStore` | same |
| 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 6f28aee5..00f87048 100644
--- a/home/ios/EditorViewController.swift
+++ b/home/ios/EditorViewController.swift
@@ -68,6 +68,11 @@ final class EditorViewController: UIViewController, WKScriptMessageHandler, WKUR
/// 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?
+ /// The kernel's per-document store, held natively: see HostDocStore.
+ private let docStore = HostDocStore()
+ /// Store requests run here, one at a time and in order, off the main thread:
+ /// a recovery copy can be tens of megabytes.
+ private let storeQueue = DispatchQueue(label: "page.bento.home.docstore-requests")
/// Called when the user leaves the document. The browser owns teardown —
/// closing the UIDocument and releasing the security scope — because it
@@ -269,8 +274,13 @@ final class EditorViewController: UIViewController, WKScriptMessageHandler, WKUR
// editor has already concluded it cannot.
if let js = Bundle.main.url(forResource: "bridge", withExtension: "js"),
let src = try? String(contentsOf: js, encoding: .utf8) {
+ // What THIS host implements, declared before the bridge reads it. The
+ // bridge offers the page a per-document store only when told so: a
+ // bridge that advertised one a host didn't implement would have the
+ // kernel keep member keys for the page only, and lose them on reload.
+ let caps = "window.__bentoHostCaps = ['store'];\n"
cfg.userContentController.addUserScript(
- WKUserScript(source: src, injectionTime: .atDocumentStart, forMainFrameOnly: true))
+ WKUserScript(source: caps + src, injectionTime: .atDocumentStart, forMainFrameOnly: true))
}
webView = WKWebView(frame: view.bounds, configuration: cfg)
@@ -344,6 +354,51 @@ final class EditorViewController: UIViewController, WKScriptMessageHandler, WKUR
}
func webView(_ webView: WKWebView, stop task: WKURLSchemeTask) {}
+ // MARK: - The per-document store
+
+ /// The wire is pinned in home/bridge.js, shared with Android:
+ /// get → b64 or null · set → null · list → a JSON array string · delete →
+ /// null; failures are !ok with 'refused' (an unknown name), 'too-large' or
+ /// 'unavailable'. The partition is THIS document's origin — the identity
+ /// OriginIdentity minted — and never anything the page sent.
+ private func handleStore(_ op: String, _ m: [String: Any], _ id: Int) {
+ let partition = originHost
+ let name = (m["name"] as? String).flatMap(HostDocStore.Name.init(rawValue:))
+ let b64 = m["b64"] as? String
+ storeQueue.async { [weak self] in
+ guard let self else { return }
+ let answer: (Bool, String?)
+ switch op {
+ case "store.list":
+ guard let names = self.docStore.list(in: partition)?.map(\.rawValue),
+ let json = (try? JSONSerialization.data(withJSONObject: names)).flatMap({ String(data: $0, encoding: .utf8) })
+ else { answer = (false, "unavailable"); break }
+ answer = (true, json)
+ case "store.get":
+ guard let name else { answer = (false, "refused"); break }
+ // a read that failed is NOT "absent": see HostDocStore.Read
+ switch self.docStore.get(name, in: partition) {
+ case .found(let d): answer = (true, d.base64EncodedString())
+ case .absent: answer = (true, nil)
+ case .unavailable: answer = (false, "unavailable")
+ }
+ case "store.set":
+ guard let name else { answer = (false, "refused"); break }
+ guard let b64, let data = Data(base64Encoded: b64) else { answer = (false, "refused"); break }
+ switch self.docStore.set(name, data, in: partition) {
+ case .stored: answer = (true, nil)
+ case .tooLarge: answer = (false, "too-large")
+ case .unavailable: answer = (false, "unavailable")
+ }
+ default: // store.delete
+ guard let name else { answer = (false, "refused"); break }
+ self.docStore.delete(name, in: partition)
+ answer = (true, nil)
+ }
+ DispatchQueue.main.async { self.reply(id, ok: answer.0, value: answer.1) }
+ }
+ }
+
// MARK: - Which origin
private func decideOrigin() {
@@ -662,6 +717,9 @@ final class EditorViewController: UIViewController, WKScriptMessageHandler, WKUR
}
}
+ case "store.get", "store.set", "store.list", "store.delete":
+ handleStore(op, m, id)
+
default:
reply(id, ok: false, value: "unknown op")
}
diff --git a/home/ios/HostDocStore.swift b/home/ios/HostDocStore.swift
new file mode 100644
index 00000000..ae553c87
--- /dev/null
+++ b/home/ios/HostDocStore.swift
@@ -0,0 +1,176 @@
+// SPDX-License-Identifier: MIT
+// Copyright (c) 2026 The Bento authors
+
+import Foundation
+import Security
+
+/// The kernel's per-document store (kernel/src/docstore.ts), held natively.
+///
+/// Without it, a document keeps its crash-recovery copy and this device's collab
+/// member PRIVATE key in its web origin's localStorage and IndexedDB. With it,
+/// those two leave web storage:
+///
+/// - **memberkey** goes to the Keychain: this device only, never synchronised, readable
+/// after first unlock (an autosave can run while the screen is locked).
+/// - **recovery**, which can be megabytes, goes to a file in the app's own Application
+/// Support folder, under complete-until-first-authentication protection.
+///
+/// **The partition is the document's origin string**, the identity #753 mints
+/// (OriginIdentity), never a path or anything the page names. So a moved file
+/// keeps its entries, and a newcomer at a reused path starts empty, exactly as
+/// its web storage does. The kernel also checks that a stored member key's docId
+/// is its own before using it.
+///
+/// Only the two names the kernel uses exist. Anything else is refused.
+final class HostDocStore {
+ enum Name: String, CaseIterable { case recovery, memberkey }
+ /// The bridge reports these as ok, 'too-large' and 'unavailable' (an I/O or
+ /// Keychain failure). An unknown NAME is refused before it gets here.
+ enum SetResult: Equatable { case stored, tooLarge, unavailable }
+
+ /// What a read found. ABSENT means the entry really isn't there, and nothing
+ /// else does: a read that failed is UNAVAILABLE. The difference is the
+ /// member key's life. Told "no key" after a transient Keychain failure, the
+ /// kernel would mint a new one and the write would replace the valid key,
+ /// losing this device's identity in the room for good. Told "unavailable",
+ /// it neither mints nor writes while blind (online.ts deviceIdentity).
+ enum Read: Equatable { case found(Data), absent, unavailable }
+
+ /// One message per value; the recovery copy is the whole document JSON, and
+ /// decks with media are large.
+ static let maxBytes = 64 * 1024 * 1024
+
+ /// Where small secrets live. The Keychain in the app; a stand-in in the rig.
+ protocol Secrets {
+ func get(_ account: String) -> Read
+ func set(_ account: String, _ data: Data) -> Bool
+ func delete(_ account: String)
+ }
+
+ private let secrets: Secrets
+ private let root: URL?
+ /// Writes and reads per name run in order. Two overlapping writes therefore
+ /// never race, and "superseded" never happens on this host.
+ private let queue = DispatchQueue(label: "page.bento.home.docstore")
+
+ init(secrets: Secrets = KeychainSecrets(), root: URL? = HostDocStore.defaultRoot()) {
+ self.secrets = secrets
+ self.root = root
+ }
+
+ static func defaultRoot() -> URL? {
+ // a folder of our own: on an unsandboxed Mac, Application Support is the
+ // person's shared folder, not a container
+ FileManager.default.urls(for: .applicationSupportDirectory, in: .userDomainMask).first?
+ .appendingPathComponent(Bundle.main.bundleIdentifier ?? "page.bento.home", isDirectory: true)
+ .appendingPathComponent("docstore", isDirectory: true)
+ }
+
+ /// The origin string becomes a path component and a Keychain account, so
+ /// only the shape the host mints is accepted: lowercase hex.
+ static func validPartition(_ p: String) -> Bool {
+ !p.isEmpty && p.count <= 64 && p.unicodeScalars.allSatisfy { ("0"..."9").contains($0) || ("a"..."f").contains($0) }
+ }
+
+ func get(_ name: Name, in partition: String) -> Read {
+ // the partition is host-minted, so a bad one is the host's fault: never "absent"
+ guard Self.validPartition(partition) else { return .unavailable }
+ return queue.sync {
+ switch name {
+ case .memberkey: return secrets.get(account(partition, name))
+ case .recovery:
+ guard let u = file(partition, name) else { return .unavailable }
+ // only a file that isn't there is absent; one that is there and
+ // can't be read is unavailable, or the next autosave would
+ // replace a recovery copy that still exists
+ guard FileManager.default.fileExists(atPath: u.path) else { return .absent }
+ guard let d = try? Data(contentsOf: u) else { return .unavailable }
+ return .found(d)
+ }
+ }
+ }
+
+ func set(_ name: Name, _ data: Data, in partition: String) -> SetResult {
+ guard Self.validPartition(partition) else { return .unavailable }
+ guard data.count <= Self.maxBytes else { return .tooLarge }
+ return queue.sync {
+ switch name {
+ case .memberkey:
+ return secrets.set(account(partition, name), data) ? .stored : .unavailable
+ case .recovery:
+ guard let u = file(partition, name) else { return .unavailable }
+ do {
+ try FileManager.default.createDirectory(at: u.deletingLastPathComponent(), withIntermediateDirectories: true)
+ try data.write(to: u, options: [.atomic, .completeFileProtectionUntilFirstUserAuthentication])
+ return .stored
+ } catch { return .unavailable }
+ }
+ }
+ }
+
+ /// The names held, or nil when any of them couldn't be checked.
+ func list(in partition: String) -> [Name]? {
+ guard Self.validPartition(partition) else { return nil }
+ var held: [Name] = []
+ for n in Name.allCases {
+ switch get(n, in: partition) {
+ case .found: held.append(n)
+ case .absent: break
+ case .unavailable: return nil
+ }
+ }
+ return held
+ }
+
+ func delete(_ name: Name, in partition: String) {
+ guard Self.validPartition(partition) else { return }
+ queue.sync {
+ switch name {
+ case .memberkey: secrets.delete(account(partition, name))
+ case .recovery: if let u = file(partition, name) { try? FileManager.default.removeItem(at: u) }
+ }
+ }
+ }
+
+ private func account(_ p: String, _ n: Name) -> String { "\(p)/\(n.rawValue)" }
+ private func file(_ p: String, _ n: Name) -> URL? { root?.appendingPathComponent(p, isDirectory: true).appendingPathComponent(n.rawValue) }
+}
+
+/// The Keychain, this device only. Never synchronised: a member key is this
+/// device's identity in a room, and must not travel.
+struct KeychainSecrets: HostDocStore.Secrets {
+ private let service = "page.bento.home.docstore"
+ private func query(_ account: String) -> [String: Any] {
+ [kSecClass as String: kSecClassGenericPassword,
+ kSecAttrService as String: service,
+ kSecAttrAccount as String: account]
+ }
+ func get(_ account: String) -> HostDocStore.Read {
+ var q = query(account); q[kSecReturnData as String] = true
+ var out: CFTypeRef?
+ let status = SecItemCopyMatching(q as CFDictionary, &out)
+ return Self.classify(status, out as? Data)
+ }
+
+ /// Only errSecItemNotFound is absence. Every other failure (locked,
+ /// interaction not allowed, missing entitlement, …) is unavailable.
+ static func classify(_ status: OSStatus, _ data: Data?) -> HostDocStore.Read {
+ switch status {
+ case errSecSuccess: return data.map { .found($0) } ?? .unavailable
+ case errSecItemNotFound: return .absent
+ default: return .unavailable
+ }
+ }
+ func set(_ account: String, _ data: Data) -> Bool {
+ let q = query(account)
+ let update = SecItemUpdate(q as CFDictionary, [kSecValueData as String: data] as CFDictionary)
+ if update == errSecSuccess { return true }
+ guard update == errSecItemNotFound else { return false }
+ var add = q
+ add[kSecValueData as String] = data
+ add[kSecAttrAccessible as String] = kSecAttrAccessibleAfterFirstUnlockThisDeviceOnly
+ add[kSecAttrSynchronizable as String] = false
+ return SecItemAdd(add as CFDictionary, nil) == errSecSuccess
+ }
+ func delete(_ account: String) { SecItemDelete(query(account) as CFDictionary) }
+}
diff --git a/scripts/test-home-bridge.ts b/scripts/test-home-bridge.ts
index 59be4180..f6603488 100644
--- a/scripts/test-home-bridge.ts
+++ b/scripts/test-home-bridge.ts
@@ -174,6 +174,28 @@ ok(exportCopy.includes('hasPrefix(') && exportCopy.includes('safeFileName(name)'
'the app builds for Mac Catalyst, as page.bento.home on every Apple platform')
}
+// The per-document store (HostDocStore). The bridge offers it only when the host
+// DECLARES it, so the capability must be declared ahead of the bridge source. And
+// the partition is the document's own origin, never a value the page sent: a
+// page that could name a partition could read another document's member key.
+{
+ ok(/__bentoHostCaps = \['store'\];[^]*?caps \+ src/.test(swift),
+ 'the host declares its store capability ahead of the injected bridge')
+ const store = slice(swift, 'private func handleStore(')
+ ok(/let partition = originHost/.test(store) && !/m\["partition"\]|m\["origin"\]|m\["host"\]/.test(store),
+ "the store partition is this document's origin, never a value from the page")
+ ok(/HostDocStore\.Name\.init\(rawValue:\)/.test(store) && /"refused"/.test(store),
+ 'a name the kernel does not use is refused')
+ // A read that FAILED must reach the kernel as 'unavailable', never as "no
+ // value": told "no key", it would mint a new one over the device's real key.
+ const getCase = store.slice(store.indexOf('case "store.get":'), store.indexOf('case "store.set":'))
+ ok(/case \.unavailable: answer = \(false, "unavailable"\)/.test(getCase) && /case \.absent: answer = \(true, nil\)/.test(getCase),
+ "a failed store read answers 'unavailable'; only real absence answers null")
+ const sw = swift.slice(swift.indexOf('func userContentController('), swift.indexOf('case "store.get", "store.set"'))
+ ok(sw.indexOf('BridgeSender.accepts') > 0,
+ "store requests pass the same sender check as every other op (they're handled after it)")
+}
+
if (spawnSync('swiftc', ['--version']).status !== 0) {
console.log(' skip no Swift toolchain on this machine — behaviour checks not run')
console.log(`\n${checks - failures}/${checks} checks passed`)
diff --git a/scripts/test-home-docstore-ios.mjs b/scripts/test-home-docstore-ios.mjs
new file mode 100644
index 00000000..fc0d4c20
--- /dev/null
+++ b/scripts/test-home-docstore-ios.mjs
@@ -0,0 +1,119 @@
+#!/usr/bin/env node
+// SPDX-License-Identifier: MIT
+// Copyright (c) 2026 The Bento authors
+/**
+ * iOS host docstore — the native store the kernel's per-document store
+ * (kernel/src/docstore.ts) talks to on bento/home for iOS and the Mac.
+ *
+ * node scripts/test-home-docstore-ios.mjs
+ *
+ * WHY. Without a host store, a document keeps this device's collab member
+ * PRIVATE key and its plaintext crash-recovery copy in its web origin's
+ * storage. home/ios/HostDocStore.swift moves them out: the member key into the
+ * Keychain, the recovery copy into an app-private file, partitioned by the
+ * document's origin string so a newcomer at a reused path starts empty. This
+ * compiles the real file and checks the rules, with an in-memory stand-in for
+ * the Keychain; the real Keychain is exercised in the app.
+ *
+ * Apple platforms only (Security framework); skips elsewhere.
+ */
+import { execFileSync } from 'node:child_process'
+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.DOCSTORE_SRC || join(ROOT, 'home/ios/HostDocStore.swift')
+try { execFileSync('xcrun', ['--find', 'swiftc'], { stdio: 'pipe' }); execFileSync('swiftc', ['--version'], { stdio: 'pipe' }) }
+catch { console.log('home docstore (iOS): SKIPPED — no Swift toolchain with the Security framework here.'); process.exit(0) }
+
+const main = String.raw`
+import Foundation
+final class Mem: HostDocStore.Secrets {
+ var d: [String: Data] = [:]
+ var failReads = false
+ func get(_ a: String) -> HostDocStore.Read { failReads ? .unavailable : (d[a].map { .found($0) } ?? .absent) }
+ func set(_ a: String, _ v: Data) -> Bool { d[a] = v; return true }
+ func delete(_ a: String) { d[a] = nil }
+}
+let root = URL(fileURLWithPath: CommandLine.arguments[1])
+let mem = Mem()
+let s = HostDocStore(secrets: mem, root: root)
+func emit(_ k: String, _ v: Any) { print("\(k)=\(v)") }
+let A = "0ff8c8a95086abca29e9a3e4", B = "d796984aa4680044f0b8734d"
+let key = Data("{\"docId\":\"x\",\"pub\":\"P\",\"priv\":\"S\"}".utf8)
+emit("set.member", s.set(.memberkey, key, in: A) == .stored)
+emit("get.member", s.get(.memberkey, in: A) == .found(key))
+emit("member.inKeychain", mem.d["\(A)/memberkey"] == key)
+let rec = Data(repeating: 65, count: 3 * 1024 * 1024)
+emit("set.recovery", s.set(.recovery, rec, in: A) == .stored)
+emit("get.recovery", s.get(.recovery, in: A) == .found(rec))
+emit("recovery.onDisk", FileManager.default.fileExists(atPath: root.appendingPathComponent("\(A)/recovery").path))
+emit("recovery.notInKeychain", mem.d["\(A)/recovery"] == nil)
+emit("list", (s.list(in: A) ?? []).map(\.rawValue).sorted().joined(separator: ","))
+emit("other.empty", s.get(.memberkey, in: B) == .absent && s.get(.recovery, in: B) == .absent && s.list(in: B) == [])
+s.delete(.memberkey, in: A)
+emit("delete", s.get(.memberkey, in: A) == .absent && (s.list(in: A) ?? []).map(\.rawValue) == ["recovery"])
+emit("toolarge", s.set(.recovery, Data(count: HostDocStore.maxBytes + 1), in: A) == .tooLarge)
+emit("max.ok", s.set(.recovery, Data(count: 16), in: A) == .stored)
+for (i, bad) in ["", "../etc", "ABCDEF", "a/b", "0ff8 ", String(repeating: "a", count: 65)].enumerated() {
+ emit("bad[\(i)] \(bad.count > 12 ? "65 chars" : "'" + bad + "'")", s.set(.memberkey, key, in: bad) == .unavailable && s.get(.memberkey, in: bad) == .unavailable)
+}
+// A read that FAILS is unavailable, never absent, and leaves the stored key alone.
+let C = "aaaaaaaaaaaaaaaaaaaaaaaa"
+_ = s.set(.memberkey, key, in: C)
+mem.failReads = true
+emit("failread.member", s.get(.memberkey, in: C) == .unavailable)
+emit("failread.list", s.list(in: C) == nil)
+mem.failReads = false
+emit("failread.keyKept", s.get(.memberkey, in: C) == .found(key))
+// A recovery file that exists but can't be read is unavailable; a missing one is absent.
+let D = "bbbbbbbbbbbbbbbbbbbbbbbb"
+_ = s.set(.recovery, Data("plaintext".utf8), in: D)
+let rf = root.appendingPathComponent("\(D)/recovery").path
+chmod(rf, 0)
+emit("unreadable.recovery", s.get(.recovery, in: D) == .unavailable)
+chmod(rf, 0o600)
+emit("readable.again", s.get(.recovery, in: D) == .found(Data("plaintext".utf8)))
+emit("missing.recovery", s.get(.recovery, in: C) == .absent)
+emit("classify.ok", KeychainSecrets.classify(errSecSuccess, Data([1])) == .found(Data([1])))
+emit("classify.notfound", KeychainSecrets.classify(errSecItemNotFound, nil) == .absent)
+emit("classify.entitlement", KeychainSecrets.classify(-34018, nil) == .unavailable)
+emit("classify.interaction", KeychainSecrets.classify(errSecInteractionNotAllowed, nil) == .unavailable)
+emit("classify.nodata", KeychainSecrets.classify(errSecSuccess, nil) == .unavailable)
+emit("noEscape", !FileManager.default.fileExists(atPath: root.deletingLastPathComponent().appendingPathComponent("etc").path))
+`
+const dir = mkdtempSync(join(tmpdir(), 'bento-docstore-'))
+let out
+try {
+ writeFileSync(join(dir, 'main.swift'), main)
+ execFileSync('swiftc', ['-O', '-o', join(dir, 'd'), SRC, join(dir, 'main.swift')], { stdio: 'pipe' })
+ out = Object.fromEntries(execFileSync(join(dir, 'd'), [join(dir, 'store')]).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 checks = 0, failures = 0
+const ok = (c, m) => { checks++; if (!c) failures++; console.log(` ${c ? 'ok ' : 'FAIL'} ${m}`) }
+ok(out['set.member'] === 'true' && out['get.member'] === 'true', 'the member key round-trips')
+ok(out['member.inKeychain'] === 'true', 'the member key is held by the secrets store (the Keychain in the app), not a file')
+ok(out['set.recovery'] === 'true' && out['get.recovery'] === 'true', 'a 3 MB recovery copy round-trips')
+ok(out['recovery.onDisk'] === 'true' && out['recovery.notInKeychain'] === 'true', 'the recovery copy is a file, never a Keychain item')
+ok(out['list'] === 'memberkey,recovery', 'list names exactly what is stored')
+ok(out['other.empty'] === 'true', "another document's partition sees none of it (a newcomer at a reused path starts empty)")
+ok(out['delete'] === 'true', 'delete removes one entry and leaves the other')
+ok(out['toolarge'] === 'true', 'a value over the cap is refused as too large')
+ok(out['max.ok'] === 'true', 'a value under the cap is stored')
+for (const [k, v] of Object.entries(out).filter(([k]) => k.startsWith('bad['))) ok(v === 'true', `a partition that isn't host-minted hex is refused: ${k}`)
+ok(out['failread.member'] === 'true', "a member-key read that FAILS is unavailable, not absent (so the kernel won't mint over it)")
+ok(out['failread.list'] === 'true', "list can't answer when a read fails — it says unavailable, not a partial list")
+ok(out['failread.keyKept'] === 'true', 'the stored member key is unchanged by the failed read')
+ok(out['unreadable.recovery'] === 'true', "a recovery file that exists but can't be read is unavailable (the next autosave must not replace it)")
+ok(out['readable.again'] === 'true', 'and reads back once it can be read')
+ok(out['missing.recovery'] === 'true', 'a recovery file that is not there is absent')
+ok(out['classify.ok'] === 'true' && out['classify.notfound'] === 'true', 'Keychain: success is found; errSecItemNotFound, and only it, is absent')
+ok(out['classify.entitlement'] === 'true' && out['classify.interaction'] === 'true', 'Keychain: a missing entitlement or a locked device is unavailable')
+ok(out['classify.nodata'] === 'true', 'Keychain: success with no data is unavailable, not absent')
+ok(out['noEscape'] === 'true', 'nothing is written outside the store folder')
+console.log(`\n${checks - failures}/${checks} checks passed`)
+process.exit(failures ? 1 : 0)