Skip to content

armgit / bento

Public Imported from GitHub
0

Bento, the office suite that fits in a file

home/ios: the bento/connect recovery code and key blobs, with a native Argon2id (#776)

nyblnet8d3b9f379b01
diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml
index d630bbfe..3537a4ac 100644
--- a/.github/workflows/ci.yml
+++ b/.github/workflows/ci.yml
@@ -888,6 +888,12 @@ jobs:
# a relay, replay, payload swap or docId swap.
run: node scripts/test-home-id-agent.mjs
+ - name: home/ios bento/connect recovery rig
+ # Argon2id (ours: RFC 9106, Node's native one on random inputs) and every
+ # byte of kernel/fixtures/recovery-v1.json: the recovery code, derivations,
+ # both key blobs, and recovered scalars checked through CryptoKit. Apple only.
+ run: node scripts/test-home-id-recovery.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
@@ -2750,6 +2756,7 @@ jobs:
test-home-id-keys.mjs
test-home-id-statements.mjs
test-home-id-agent.mjs
+ test-home-id-recovery.mjs
)
for rig in "${rigs[@]}"; do
echo "::group::$rig"
diff --git a/home/ios/Argon2id.swift b/home/ios/Argon2id.swift
new file mode 100644
index 00000000..c374d67a
--- /dev/null
+++ b/home/ios/Argon2id.swift
@@ -0,0 +1,279 @@
+// SPDX-License-Identifier: MIT
+// Copyright (c) 2026 The Bento authors
+
+import Foundation
+
+/// Argon2id (RFC 9106, version 0x13), which neither CryptoKit nor CommonCrypto
+/// has. It stretches a recovery code into its keys (kernel/src/recovery.ts).
+///
+/// Self-contained, no third-party code. scripts/test-home-id-recovery.mjs holds
+/// it to RFC 9106 §5.3, to every byte of kernel/fixtures/recovery-v1.json, and
+/// to Node's native Argon2id on random inputs.
+///
+/// Lanes are filled one after another (no threads), which is what the format
+/// allows and is the same result as filling them in parallel.
+///
+/// Everything derived from the password (the 64 MiB of blocks, the scratch
+/// blocks, H0 and the H' intermediates) is wiped with memset_s before it's
+/// released, which the compiler may not elide. That's best effort in Swift: an
+/// Array the runtime copied behind our back can't be reached.
+enum Argon2id {
+ struct Params: Equatable {
+ let memoryKiB: Int
+ let passes: Int
+ let parallelism: Int
+ let tagLength: Int
+ }
+
+ /// security §28: p = 1, 64 MiB, t = 3, a 32-byte tag
+ static let bento = Params(memoryKiB: 65536, passes: 3, parallelism: 1, tagLength: 32)
+
+ static func hash(password: [UInt8], salt: [UInt8], secret: [UInt8] = [], ad: [UInt8] = [],
+ params: Params = bento) -> [UInt8] {
+ let p = params.parallelism, t = params.passes
+ precondition(p >= 1 && t >= 1 && params.tagLength >= 4 && params.memoryKiB >= 8 * p)
+ let mPrime = 4 * p * (params.memoryKiB / (4 * p))
+ let laneLen = mPrime / p, segLen = laneLen / 4
+
+ var h0in: [UInt8] = []
+ for v in [p, params.tagLength, params.memoryKiB, t, 0x13, 2] { h0in += le32(v) }
+ for field in [password, salt, secret, ad] { h0in += le32(field.count) + field }
+ var h0 = Blake2b.hash(h0in, outLength: 64)
+ wipe(&h0in)
+ defer { wipe(&h0) }
+
+ let mem = UnsafeMutablePointer<UInt64>.allocate(capacity: mPrime * 128)
+ mem.initialize(repeating: 0, count: mPrime * 128)
+ defer { release(mem, mPrime * 128) }
+ func block(_ lane: Int, _ col: Int) -> UnsafeMutablePointer<UInt64> { mem + (lane * laneLen + col) * 128 }
+
+ for lane in 0..<p {
+ for col in 0..<2 {
+ var seed = h0 + le32(col) + le32(lane), first = hPrime(seed, 1024)
+ load(first, into: block(lane, col))
+ wipe(&seed); wipe(&first)
+ }
+ }
+
+ let g = Compressor()
+ defer { g.free() }
+ let zero = UnsafeMutablePointer<UInt64>.allocate(capacity: 128); zero.initialize(repeating: 0, count: 128)
+ let input = UnsafeMutablePointer<UInt64>.allocate(capacity: 128); input.initialize(repeating: 0, count: 128)
+ let address = UnsafeMutablePointer<UInt64>.allocate(capacity: 128); address.initialize(repeating: 0, count: 128)
+ defer { release(zero, 128); release(input, 128); release(address, 128) }
+
+ for pass in 0..<t {
+ for slice in 0..<4 {
+ for lane in 0..<p {
+ // Argon2id: data-independent addressing for the first half of the first pass
+ let independent = pass == 0 && slice < 2
+ if independent {
+ input.initialize(repeating: 0, count: 128)
+ input[0] = UInt64(pass); input[1] = UInt64(lane); input[2] = UInt64(slice)
+ input[3] = UInt64(mPrime); input[4] = UInt64(t); input[5] = 2
+ }
+ func nextAddresses() {
+ input[6] &+= 1
+ g.fill(prev: zero, ref: input, next: address, xor: false)
+ g.fill(prev: zero, ref: address, next: address, xor: false)
+ }
+ var start = 0
+ if pass == 0 && slice == 0 {
+ start = 2
+ if independent { nextAddresses() }
+ }
+ for i in start..<segLen {
+ let col = slice * segLen + i
+ let prev = block(lane, col == 0 ? laneLen - 1 : col - 1)
+ let rand: UInt64
+ if independent {
+ if i % 128 == 0 { nextAddresses() }
+ rand = address[i % 128]
+ } else {
+ rand = prev[0]
+ }
+ let refLane = (pass == 0 && slice == 0) ? lane : Int((rand >> 32) % UInt64(p))
+ let same = refLane == lane
+ var area: Int
+ if pass == 0 {
+ if slice == 0 { area = i - 1 }
+ else if same { area = slice * segLen + i - 1 }
+ else { area = slice * segLen + (i == 0 ? -1 : 0) }
+ } else {
+ area = laneLen - segLen + (same ? i - 1 : (i == 0 ? -1 : 0))
+ }
+ var x = rand & 0xFFFF_FFFF
+ x = (x &* x) >> 32
+ let rel = UInt64(area) - 1 - ((UInt64(area) &* x) >> 32)
+ let startPos = pass != 0 ? (slice == 3 ? 0 : (slice + 1) * segLen) : 0
+ let refCol = (startPos + Int(rel)) % laneLen
+ g.fill(prev: prev, ref: block(refLane, refCol), next: block(lane, col), xor: pass != 0)
+ }
+ }
+ }
+ }
+
+ var c = [UInt64](repeating: 0, count: 128)
+ for lane in 0..<p { let b = block(lane, laneLen - 1); for k in 0..<128 { c[k] ^= b[k] } }
+ var cBytes: [UInt8] = []; cBytes.reserveCapacity(1024)
+ for w in c { for s in 0..<8 { cBytes.append(UInt8(truncatingIfNeeded: w >> (8 * s))) } }
+ wipe(&c)
+ defer { wipe(&cBytes) }
+ return hPrime(cBytes, params.tagLength)
+ }
+
+ // MARK: - pieces
+
+ /// Overwrite with zeros in a way the optimiser must keep (C11 memset_s).
+ static func wipe<T>(_ a: inout [T]) {
+ a.withUnsafeMutableBytes { b in if let base = b.baseAddress { _ = memset_s(base, b.count, 0, b.count) } }
+ }
+
+ #if BENTO_WIPE_PROBE
+ /// test builds only: sees each buffer after the wipe, before it's freed
+ nonisolated(unsafe) static var probe: ((UnsafeMutablePointer<UInt64>, Int) -> Void)?
+ #endif
+
+ static func release(_ p: UnsafeMutablePointer<UInt64>, _ count: Int) {
+ _ = memset_s(p, count * 8, 0, count * 8)
+ #if BENTO_WIPE_PROBE
+ probe?(p, count)
+ #endif
+ p.deinitialize(count: count)
+ p.deallocate()
+ }
+
+ private static func le32(_ v: Int) -> [UInt8] { (0..<4).map { UInt8(truncatingIfNeeded: v >> (8 * $0)) } }
+
+ private static func load(_ bytes: [UInt8], into b: UnsafeMutablePointer<UInt64>) {
+ for k in 0..<128 {
+ var w: UInt64 = 0
+ for s in 0..<8 { w |= UInt64(bytes[8 * k + s]) << (8 * s) }
+ b[k] = w
+ }
+ }
+
+ /// RFC 9106 §3.3 H': a variable-length hash built from BLAKE2b
+ static func hPrime(_ x: [UInt8], _ tau: Int) -> [UInt8] {
+ var input = le32(tau) + x
+ defer { wipe(&input) }
+ if tau <= 64 { return Blake2b.hash(input, outLength: tau) }
+ let r = (tau + 31) / 32 - 2
+ var v = Blake2b.hash(input, outLength: 64)
+ var out = Array(v[0..<32])
+ for _ in 1..<r { var next = Blake2b.hash(v, outLength: 64); swap(&v, &next); wipe(&next); out += v[0..<32] }
+ out += Blake2b.hash(v, outLength: tau - 32 * r)
+ wipe(&v)
+ return out
+ }
+
+ /// The compression function G over 1 KiB blocks, with its scratch space allocated once.
+ private final class Compressor {
+ let r = UnsafeMutablePointer<UInt64>.allocate(capacity: 128)
+ let tmp = UnsafeMutablePointer<UInt64>.allocate(capacity: 128)
+ init() { r.initialize(repeating: 0, count: 128); tmp.initialize(repeating: 0, count: 128) }
+ func free() { Argon2id.release(r, 128); Argon2id.release(tmp, 128) }
+
+ /// next = G(prev, ref), XORed into next's old value when `xor` (passes after the first)
+ func fill(prev: UnsafeMutablePointer<UInt64>, ref: UnsafeMutablePointer<UInt64>,
+ next: UnsafeMutablePointer<UInt64>, xor: Bool) {
+ for k in 0..<128 { r[k] = ref[k] ^ prev[k] }
+ for k in 0..<128 { tmp[k] = xor ? r[k] ^ next[k] : r[k] }
+ for i in 0..<8 { // rows: 16 consecutive words
+ let b = 16 * i
+ round(b, b + 1, b + 2, b + 3, b + 4, b + 5, b + 6, b + 7,
+ b + 8, b + 9, b + 10, b + 11, b + 12, b + 13, b + 14, b + 15)
+ }
+ for i in 0..<8 { // columns: word pairs 2i, 2i+1 of each row
+ let b = 2 * i
+ round(b, b + 1, b + 16, b + 17, b + 32, b + 33, b + 48, b + 49,
+ b + 64, b + 65, b + 80, b + 81, b + 96, b + 97, b + 112, b + 113)
+ }
+ for k in 0..<128 { next[k] = tmp[k] ^ r[k] }
+ }
+
+ @inline(__always)
+ private func round(_ v0: Int, _ v1: Int, _ v2: Int, _ v3: Int, _ v4: Int, _ v5: Int, _ v6: Int, _ v7: Int,
+ _ v8: Int, _ v9: Int, _ v10: Int, _ v11: Int, _ v12: Int, _ v13: Int, _ v14: Int, _ v15: Int) {
+ gb(v0, v4, v8, v12); gb(v1, v5, v9, v13); gb(v2, v6, v10, v14); gb(v3, v7, v11, v15)
+ gb(v0, v5, v10, v15); gb(v1, v6, v11, v12); gb(v2, v7, v8, v13); gb(v3, v4, v9, v14)
+ }
+
+ @inline(__always)
+ private func gb(_ a: Int, _ b: Int, _ c: Int, _ d: Int) {
+ @inline(__always) func mix(_ x: UInt64, _ y: UInt64) -> UInt64 {
+ x &+ y &+ 2 &* ((x & 0xFFFF_FFFF) &* (y & 0xFFFF_FFFF))
+ }
+ @inline(__always) func rotr(_ x: UInt64, _ n: UInt64) -> UInt64 { (x >> n) | (x << (64 - n)) }
+ r[a] = mix(r[a], r[b]); r[d] = rotr(r[d] ^ r[a], 32)
+ r[c] = mix(r[c], r[d]); r[b] = rotr(r[b] ^ r[c], 24)
+ r[a] = mix(r[a], r[b]); r[d] = rotr(r[d] ^ r[a], 16)
+ r[c] = mix(r[c], r[d]); r[b] = rotr(r[b] ^ r[c], 63)
+ }
+ }
+}
+
+/// BLAKE2b (RFC 7693), unkeyed, one-shot: all Argon2 needs.
+enum Blake2b {
+ private static let iv: [UInt64] = [
+ 0x6a09e667f3bcc908, 0xbb67ae8584caa73b, 0x3c6ef372fe94f82b, 0xa54ff53a5f1d36f1,
+ 0x510e527fade682d1, 0x9b05688c2b3e6c1f, 0x1f83d9abfb41bd6b, 0x5be0cd19137e2179,
+ ]
+ private static let sigma: [[Int]] = [
+ [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15],
+ [14, 10, 4, 8, 9, 15, 13, 6, 1, 12, 0, 2, 11, 7, 5, 3],
+ [11, 8, 12, 0, 5, 2, 15, 13, 10, 14, 3, 6, 7, 1, 9, 4],
+ [7, 9, 3, 1, 13, 12, 11, 14, 2, 6, 5, 10, 4, 0, 15, 8],
+ [9, 0, 5, 7, 2, 4, 10, 15, 14, 1, 11, 12, 6, 8, 3, 13],
+ [2, 12, 6, 10, 0, 11, 8, 3, 4, 13, 7, 5, 15, 14, 1, 9],
+ [12, 5, 1, 15, 14, 13, 4, 10, 0, 7, 6, 3, 9, 2, 8, 11],
+ [13, 11, 7, 14, 12, 1, 3, 9, 5, 0, 15, 4, 8, 6, 2, 10],
+ [6, 15, 14, 9, 11, 3, 0, 8, 12, 2, 13, 7, 1, 4, 10, 5],
+ [10, 2, 8, 4, 7, 6, 1, 5, 15, 11, 9, 14, 3, 12, 13, 0],
+ ]
+
+ static func hash(_ data: [UInt8], outLength: Int) -> [UInt8] {
+ precondition(outLength >= 1 && outLength <= 64)
+ var h = iv
+ h[0] ^= 0x0101_0000 ^ UInt64(outLength)
+ let blocks = max(1, (data.count + 127) / 128)
+ var m = [UInt64](repeating: 0, count: 16)
+ for bi in 0..<blocks {
+ let last = bi == blocks - 1
+ for k in 0..<16 {
+ var w: UInt64 = 0
+ for s in 0..<8 {
+ let idx = bi * 128 + 8 * k + s
+ if idx < data.count { w |= UInt64(data[idx]) << (8 * s) }
+ }
+ m[k] = w
+ }
+ let counted = last ? data.count : (bi + 1) * 128
+ compress(&h, m, UInt64(counted), last)
+ }
+ var out: [UInt8] = []
+ for w in h { for s in 0..<8 { out.append(UInt8(truncatingIfNeeded: w >> (8 * s))) } }
+ return Array(out[0..<outLength])
+ }
+
+ private static func compress(_ h: inout [UInt64], _ m: [UInt64], _ t: UInt64, _ last: Bool) {
+ var v = h + iv
+ v[12] ^= t
+ if last { v[14] = ~v[14] }
+ @inline(__always) func rotr(_ x: UInt64, _ n: UInt64) -> UInt64 { (x >> n) | (x << (64 - n)) }
+ func g(_ a: Int, _ b: Int, _ c: Int, _ d: Int, _ x: UInt64, _ y: UInt64) {
+ v[a] = v[a] &+ v[b] &+ x; v[d] = rotr(v[d] ^ v[a], 32)
+ v[c] = v[c] &+ v[d]; v[b] = rotr(v[b] ^ v[c], 24)
+ v[a] = v[a] &+ v[b] &+ y; v[d] = rotr(v[d] ^ v[a], 16)
+ v[c] = v[c] &+ v[d]; v[b] = rotr(v[b] ^ v[c], 63)
+ }
+ for round in 0..<12 {
+ let s = sigma[round % 10]
+ g(0, 4, 8, 12, m[s[0]], m[s[1]]); g(1, 5, 9, 13, m[s[2]], m[s[3]])
+ g(2, 6, 10, 14, m[s[4]], m[s[5]]); g(3, 7, 11, 15, m[s[6]], m[s[7]])
+ g(0, 5, 10, 15, m[s[8]], m[s[9]]); g(1, 6, 11, 12, m[s[10]], m[s[11]])
+ g(2, 7, 8, 13, m[s[12]], m[s[13]]); g(3, 4, 9, 14, m[s[14]], m[s[15]])
+ }
+ for i in 0..<8 { h[i] ^= v[i] ^ v[i + 8] }
+ }
+}
diff --git a/home/ios/IdentityRecovery.swift b/home/ios/IdentityRecovery.swift
new file mode 100644
index 00000000..53260cdc
--- /dev/null
+++ b/home/ios/IdentityRecovery.swift
@@ -0,0 +1,252 @@
+// SPDX-License-Identifier: MIT
+// Copyright (c) 2026 The Bento authors
+
+import CryptoKit
+import Foundation
+
+/// bento/connect's recovery code and key blobs (identity-design §2f, security §28), a
+/// Swift port of kernel/src/recovery.ts held to every byte of
+/// kernel/fixtures/recovery-v1.json by scripts/test-home-id-recovery.mjs.
+///
+/// Two ways back into an account on a new device:
+/// - a passkey's PRF output unwraps the account key from a per-passkey blob
+/// - the printed recovery code, stretched by Argon2id, unwraps a second blob
+///
+/// The directory's pepper layer over the recovery blob is server-side and isn't
+/// here.
+enum IdentityRecovery {
+ enum Verdict<T> {
+ case ok(T)
+ case no(String)
+ }
+
+ // MARK: - the recovery code: 80 bits, Crockford base32, a mod-37 check symbol
+
+ static let codeBytes = 10
+ static let saltLength = 16
+ private static let alphabet = Array("0123456789ABCDEFGHJKMNPQRSTVWXYZ".utf16)
+ /// the 32 above, plus * ~ $ = U for check values 32–36
+ private static let checkAlphabet = alphabet + Array("*~$=U".utf16)
+
+ private static func check37(_ code: [UInt8]) -> Int { code.reduce(0) { ($0 * 256 + Int($1)) % 37 } }
+
+ /// The printed form: XXXX-XXXX-XXXX-XXXX-C.
+ static func formatCode(_ code: [UInt8]) -> String? {
+ guard code.count == codeBytes else { return nil }
+ var s: [UInt16] = []
+ for i in 0..<16 { // symbol i is bits 5i..5i+4 from the top
+ let bit = i * 5, byte = bit >> 3, sh = bit & 7
+ let two = (Int(code[byte]) << 8) | (byte + 1 < codeBytes ? Int(code[byte + 1]) : 0)
+ s.append(alphabet[(two >> (11 - sh)) & 31])
+ }
+ let g = { (r: Range<Int>) in String(utf16CodeUnits: Array(s[r]), count: r.count) }
+ return "\(g(0..<4))-\(g(4..<8))-\(g(8..<12))-\(g(12..<16))-" +
+ String(utf16CodeUnits: [checkAlphabet[check37(code)]], count: 1)
+ }
+
+ /// JavaScript's \s, which the reference strips: a host must forgive exactly the same.
+ private static let jsSpace: Set<UInt16> = [0x09, 0x0A, 0x0B, 0x0C, 0x0D, 0x20, 0xA0, 0x1680,
+ 0x2000, 0x2001, 0x2002, 0x2003, 0x2004, 0x2005, 0x2006, 0x2007, 0x2008, 0x2009, 0x200A,
+ 0x2028, 0x2029, 0x202F, 0x205F, 0x3000, 0xFEFF]
+
+ /// Read what a person typed: case, spaces and hyphens don't matter; O reads
+ /// as 0 and I/L as 1; the check symbol must match, so a typo is caught here.
+ /// Returns the 10 bytes Argon2id takes, never the string. Counted in UTF-16,
+ /// as the reference counts, so the two agree on every input.
+ static func parseCode(_ input: String) -> Verdict<[UInt8]> {
+ let up = input.uppercased().utf16.filter { !jsSpace.contains($0) && $0 != 0x2D }.map { (u: UInt16) -> UInt16 in
+ switch u { case 0x4F: return 0x30; case 0x49, 0x4C: return 0x31; default: return u }
+ }
+ guard up.count == 17 else { return .no("length") }
+ var code = [UInt8](repeating: 0, count: codeBytes)
+ for i in 0..<16 {
+ guard let v = alphabet.firstIndex(of: up[i]) else { return .no("character") } // U is only a check
+ let bit = i * 5, byte = bit >> 3, sh = bit & 7
+ let two = v << (11 - sh)
+ code[byte] |= UInt8(two >> 8)
+ if byte + 1 < codeBytes { code[byte + 1] |= UInt8(two & 0xFF) }
+ }
+ guard let check = checkAlphabet.firstIndex(of: up[16]) else { return .no("character") }
+ guard check == check37(code) else { return .no("check") }
+ return .ok(code)
+ }
+
+ // MARK: - derivations
+
+ /// HKDF-SHA-256 to 32 bytes; an empty salt is zero-length (the same as 32 zero bytes).
+ static func hkdf(_ ikm: [UInt8], salt: [UInt8] = [], info: String) -> [UInt8] {
+ let k = HKDF<SHA256>.deriveKey(inputKeyMaterial: SymmetricKey(data: ikm), salt: salt,
+ info: Data(info.utf8), outputByteCount: 32)
+ return k.withUnsafeBytes { Array($0) }
+ }
+
+ /// the recovery blob's wrap key: HKDF(Argon2id(code, salt), empty, "bento/id/rc-wrap/v1")
+ static func recoveryWrapKey(code: [UInt8], salt: [UInt8]) -> [UInt8]? {
+ guard code.count == codeBytes, salt.count == saltLength else { return nil }
+ var stretched = Argon2id.hash(password: code, salt: salt)
+ defer { Argon2id.wipe(&stretched) }
+ return hkdf(stretched, info: "bento/id/rc-wrap/v1")
+ }
+
+ /// what proves knowledge of the code to the directory: Argon2id(code, salt_v)
+ static func recoveryVerifier(code: [UInt8], saltV: [UInt8]) -> [UInt8]? {
+ guard code.count == codeBytes, saltV.count == saltLength else { return nil }
+ return Argon2id.hash(password: code, salt: saltV)
+ }
+
+ /// the PRF blob's key: HKDF(PRF output, 32-byte salt, "bento/id/acct-wrap/v1")
+ static func prfKek(prfOutput: [UInt8], salt: [UInt8]) -> [UInt8]? {
+ guard prfOutput.count == 32, salt.count == 32 else { return nil }
+ return hkdf(prfOutput, salt: salt, info: "bento/id/acct-wrap/v1")
+ }
+
+ // MARK: - AES-256-GCM: ciphertext ‖ 16-byte tag, 12-byte IV
+
+ static func gcmSeal(key: [UInt8], iv: [UInt8], aad: String, _ pt: [UInt8]) -> [UInt8]? {
+ guard key.count == 32, iv.count == 12, let nonce = try? AES.GCM.Nonce(data: iv),
+ let box = try? AES.GCM.seal(pt, using: SymmetricKey(data: key), nonce: nonce, authenticating: Data(aad.utf8))
+ else { return nil }
+ return Array(box.ciphertext) + Array(box.tag)
+ }
+
+ static func gcmOpen(key: [UInt8], iv: [UInt8], aad: String, _ ct: [UInt8]) -> [UInt8]? {
+ guard key.count == 32, iv.count == 12, ct.count >= 16, let nonce = try? AES.GCM.Nonce(data: iv),
+ let box = try? AES.GCM.SealedBox(nonce: nonce, ciphertext: ct.dropLast(16), tag: ct.suffix(16)),
+ let pt = try? AES.GCM.open(box, using: SymmetricKey(data: key), authenticating: Data(aad.utf8))
+ else { return nil }
+ return Array(pt)
+ }
+
+ // MARK: - the blob plaintext: raw private scalars, checked before use
+
+ /// identity-design §6b: which kx placement is ruled (unruled while it isn't)
+ enum KxMode: String { case unruled, A, B, C
+ var blobCarriesKx: Bool { self == .A || self == .C }
+ }
+ static let kxMode: KxMode = .unruled
+
+ struct BlobKeys: Equatable {
+ let account: [UInt8]
+ let kx: [UInt8]?
+ }
+
+ static func packScalars(_ keys: BlobKeys, mode: KxMode = kxMode) -> [UInt8]? {
+ guard keys.account.count == 32 else { return nil }
+ if !mode.blobCarriesKx { return keys.kx == nil ? keys.account : nil }
+ guard let kx = keys.kx, kx.count == 32 else { return nil }
+ return keys.account + kx
+ }
+
+ /// Read a blob's plaintext and CHECK it before anything uses it: the right
+ /// length for the mode, every scalar in 1..n−1, and each one's public half
+ /// equal to the key in the directory-signed binding, so a swapped blob fails
+ /// closed. These are recovered PRIVATE scalars: the range check doesn't branch
+ /// on their bytes, and the match goes through CryptoKit, never arithmetic here.
+ static func unpackScalars(_ pt: [UInt8], accountPub: String, kxPub: String? = nil,
+ mode: KxMode = kxMode) -> Verdict<BlobKeys> {
+ let withKx = mode.blobCarriesKx
+ guard pt.count == (withKx ? 64 : 32) else { return .no("length") }
+ let scalars = withKx ? [Array(pt[0..<32]), Array(pt[32...])] : [pt]
+ let pubs = withKx ? [accountPub, kxPub] : [accountPub]
+ for (d, pub) in zip(scalars, pubs) {
+ guard scalarInRange(d) else { return .no("scalar-range") }
+ guard let pub, scalarMatches(d, pub) else { return .no("key-mismatch") }
+ }
+ return .ok(BlobKeys(account: scalars[0], kx: withKx ? scalars[1] : nil))
+ }
+
+ private static let nBytes: [UInt8] = [
+ 0xff, 0xff, 0xff, 0xff, 0x00, 0x00, 0x00, 0x00, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
+ 0xbc, 0xe6, 0xfa, 0xad, 0xa7, 0x17, 0x9e, 0x84, 0xf3, 0xb9, 0xca, 0xc2, 0xfc, 0x63, 0x25, 0x51,
+ ]
+
+ /// 1 ≤ d < n for a 32-byte big-endian scalar, without branching on its bytes.
+ static func scalarInRange(_ d: [UInt8]) -> Bool {
+ guard d.count == 32 else { return false }
+ var nonzero: UInt32 = 0, lt: UInt32 = 0, gt: UInt32 = 0
+ for i in 0..<32 {
+ let a = UInt32(d[i]), b = UInt32(nBytes[i]), open = 1 ^ (lt | gt)
+ lt |= open & ((a &- b) >> 31)
+ gt |= open & ((b &- a) >> 31)
+ nonzero |= a
+ }
+ return (lt & ((nonzero | (0 &- nonzero)) >> 31)) == 1
+ }
+
+ /// Does d belong to the raw public key `pub`? CryptoKit computes d·G (and
+ /// itself refuses 0 and ≥ n); comparing public points reveals nothing secret.
+ private static func scalarMatches(_ d: [UInt8], _ pub: String) -> Bool {
+ guard let raw = b64uDec(pub), raw.count == 65, raw[0] == 4,
+ let k = try? P256.Signing.PrivateKey(rawRepresentation: d) else { return false }
+ return Array(k.publicKey.x963Representation) == raw
+ }
+
+ // MARK: - the PRF blob, one per passkey
+
+ struct PrfBlob: Equatable {
+ let v: Int
+ let cred: String
+ let salt: String
+ let iv: String
+ let ct: String
+ }
+
+ private static func credTag(_ credentialId: [UInt8]) -> String { b64uEnc(Array(SHA256.hash(data: credentialId))) }
+
+ /// aad = "bento/id/acct-wrap/v1." ‖ b64u(sha256(credentialId))
+ static func sealPrfBlob(prfOutput: [UInt8], credentialId: [UInt8], salt: [UInt8], iv: [UInt8],
+ keys: BlobKeys, mode: KxMode = kxMode) -> PrfBlob? {
+ let cred = credTag(credentialId)
+ guard let kek = prfKek(prfOutput: prfOutput, salt: salt), let pt = packScalars(keys, mode: mode),
+ let ct = gcmSeal(key: kek, iv: iv, aad: "bento/id/acct-wrap/v1.\(cred)", pt) else { return nil }
+ return PrfBlob(v: 1, cred: cred, salt: b64uEnc(salt), iv: b64uEnc(iv), ct: b64uEnc(ct))
+ }
+
+ static func openPrfBlob(_ blob: PrfBlob, prfOutput: [UInt8], credentialId: [UInt8],
+ accountPub: String, kxPub: String? = nil, mode: KxMode = kxMode) -> Verdict<BlobKeys> {
+ guard blob.v == 1 else { return .no("version") }
+ let cred = credTag(credentialId)
+ guard blob.cred == cred else { return .no("credential") }
+ guard let salt = b64uDec(blob.salt), salt.count == 32, let iv = b64uDec(blob.iv), iv.count == 12,
+ let ct = b64uDec(blob.ct) else { return .no("grammar") }
+ guard prfOutput.count == 32, let kek = prfKek(prfOutput: prfOutput, salt: salt),
+ let pt = gcmOpen(key: kek, iv: iv, aad: "bento/id/acct-wrap/v1.\(cred)", ct) else { return .no("decrypt") }
+ return unpackScalars(pt, accountPub: accountPub, kxPub: kxPub, mode: mode)
+ }
+
+ // MARK: - the recovery-code blob (inner layer; the directory adds its pepper)
+
+ static func accountTag(_ accountPub: String) -> String { b64uEnc(Array(SHA256.hash(data: Data(accountPub.utf8)))) }
+
+ /// aad = "bento/id/rc-wrap/v1." ‖ b64u(sha256(accountPub))
+ static func sealRecoveryInner(wrapKey: [UInt8], iv: [UInt8], accountPub: String, keys: BlobKeys,
+ mode: KxMode = kxMode) -> [UInt8]? {
+ guard let pt = packScalars(keys, mode: mode) else { return nil }
+ return gcmSeal(key: wrapKey, iv: iv, aad: "bento/id/rc-wrap/v1.\(accountTag(accountPub))", pt)
+ }
+
+ static func openRecoveryInner(_ ct: [UInt8], wrapKey: [UInt8], iv: [UInt8], accountPub: String,
+ kxPub: String? = nil, mode: KxMode = kxMode) -> Verdict<BlobKeys> {
+ guard let pt = gcmOpen(key: wrapKey, iv: iv, aad: "bento/id/rc-wrap/v1.\(accountTag(accountPub))", ct)
+ else { return .no("decrypt") }
+ return unpackScalars(pt, accountPub: accountPub, kxPub: kxPub, mode: mode)
+ }
+
+ // MARK: - canonical base64url (kernel statements.ts)
+
+ static func b64uEnc(_ b: [UInt8]) -> String {
+ Data(b).base64EncodedString().replacingOccurrences(of: "+", with: "-")
+ .replacingOccurrences(of: "/", with: "_").replacingOccurrences(of: "=", with: "")
+ }
+
+ /// strict: the alphabet only, no padding, and it must re-encode identically
+ static func b64uDec(_ s: String) -> [UInt8]? {
+ guard s.count % 4 != 1, s.allSatisfy({ $0.isASCII && ($0.isLetter || $0.isNumber || $0 == "-" || $0 == "_") })
+ else { return nil }
+ var t = s.replacingOccurrences(of: "-", with: "+").replacingOccurrences(of: "_", with: "/")
+ while t.count % 4 != 0 { t += "=" }
+ guard let d = Data(base64Encoded: t) else { return nil }
+ let b = Array(d)
+ return b64uEnc(b) == s ? b : nil
+ }
+}
diff --git a/scripts/test-home-id-recovery.mjs b/scripts/test-home-id-recovery.mjs
new file mode 100644
index 00000000..911833a1
--- /dev/null
+++ b/scripts/test-home-id-recovery.mjs
@@ -0,0 +1,213 @@
+#!/usr/bin/env node
+// SPDX-License-Identifier: MIT
+// Copyright (c) 2026 The Bento authors
+/**
+ * bento/connect on iOS and the Mac: the recovery code and the key blobs
+ * (home/ios/Argon2id.swift, home/ios/IdentityRecovery.swift) against every byte
+ * of kernel/fixtures/recovery-v1.json.
+ *
+ * node scripts/test-home-id-recovery.mjs
+ *
+ * Argon2id has no Apple implementation, so the Swift one is held to:
+ * - RFC 9106 §5.3 (p = 4, a secret and associated data)
+ * - the fixture's derivations, at our parameters
+ * - Node's native Argon2id on random inputs and parameters
+ * Then every fixture row is reproduced (codes, parsing, derivations, both blobs,
+ * the directory's pepper rows) and the blob checks are exercised: a swapped
+ * key, a wrong passkey, a scalar out of range.
+ *
+ * The fixture is read fresh each run (REC_FIXTURE overrides the path) and
+ * nothing is pinned here. Apple platforms only; skips elsewhere.
+ */
+import { execFileSync } from 'node:child_process'
+import { mkdtempSync, writeFileSync, rmSync, readFileSync, existsSync } from 'node:fs'
+import { tmpdir } from 'node:os'
+import { join, resolve, dirname } from 'node:path'
+import { fileURLToPath } from 'node:url'
+import { argon2Sync, randomBytes, randomInt } from 'node:crypto'
+
+const ROOT = resolve(dirname(fileURLToPath(import.meta.url)), '..')
+const SRC = [process.env.ARGON2_SRC || 'Argon2id.swift', process.env.ID_RECOVERY_SRC || 'IdentityRecovery.swift']
+ .map((f) => f.includes('/') ? f : join(ROOT, 'home/ios', f))
+const FIXTURE = process.env.REC_FIXTURE || join(ROOT, 'kernel/fixtures/recovery-v1.json')
+try { execFileSync('xcrun', ['--find', 'swiftc'], { stdio: 'pipe' }) } catch { console.log('home id recovery: SKIPPED — needs an Apple toolchain (CryptoKit).'); process.exit(0) }
+if (!existsSync(FIXTURE)) { console.error(`no fixture at ${FIXTURE}`); process.exit(2) }
+
+// random Argon2id cases for the cross-check, answered by Node's native implementation
+const cases = Array.from({ length: Number(process.env.ARGON2_CASES || 24) }, () => {
+ const p = randomInt(1, 5)
+ const c = {
+ password: randomBytes(randomInt(0, 80)).toString('hex'), salt: randomBytes(randomInt(8, 40)).toString('hex'),
+ secret: randomInt(0, 2) ? randomBytes(randomInt(1, 33)).toString('hex') : '',
+ ad: randomInt(0, 2) ? randomBytes(randomInt(1, 33)).toString('hex') : '',
+ parallelism: p, memoryKiB: 8 * p + randomInt(0, 600), passes: randomInt(1, 5), tagLength: [4, 16, 32, 64, 65, 100, 128][randomInt(0, 7)],
+ }
+ c.tag = argon2Sync('argon2id', {
+ message: Buffer.from(c.password, 'hex'), nonce: Buffer.from(c.salt, 'hex'),
+ secret: Buffer.from(c.secret, 'hex'), associatedData: Buffer.from(c.ad, 'hex'),
+ parallelism: c.parallelism, memory: c.memoryKiB, passes: c.passes, tagLength: c.tagLength,
+ }).toString('hex')
+ return c
+})
+
+const main = String.raw`
+import CryptoKit
+import Foundation
+typealias R = IdentityRecovery
+func hx(_ s: String) -> [UInt8] { var o: [UInt8] = []; var i = s.startIndex; while i < s.endIndex { let j = s.index(i, offsetBy: 2); o.append(UInt8(s[i..<j], radix: 16)!); i = j }; return o }
+func hs(_ b: [UInt8]?) -> String { b.map { $0.map { String(format: "%02x", $0) }.joined() } ?? "nil" }
+func emit(_ k: String, _ v: Any) { print("\(k)=\(v)") }
+func j(_ path: String) -> Any { try! JSONSerialization.jsonObject(with: Data(contentsOf: URL(fileURLWithPath: path))) }
+func verdict<T>(_ v: R.Verdict<T>, _ show: (T) -> String) -> String { switch v { case .ok(let x): return "ok:" + show(x); case .no(let r): return "no:" + r } }
+let F = j(CommandLine.arguments[1]) as! [String: Any]
+let cases = j(CommandLine.arguments[2]) as! [[String: Any]]
+
+// Argon2id: RFC 9106, then the random cross-check
+let rfc = F["rfc9106"] as! [String: Any]
+emit("rfc", hs(Argon2id.hash(password: hx(rfc["password"] as! String), salt: hx(rfc["salt"] as! String), secret: hx(rfc["secret"] as! String), ad: hx(rfc["ad"] as! String),
+ params: .init(memoryKiB: rfc["memoryKiB"] as! Int, passes: rfc["passes"] as! Int, parallelism: rfc["parallelism"] as! Int, tagLength: rfc["tagLength"] as! Int))))
+for (i, c) in cases.enumerated() {
+ emit("case\(i)", hs(Argon2id.hash(password: hx(c["password"] as! String), salt: hx(c["salt"] as! String), secret: hx(c["secret"] as! String), ad: hx(c["ad"] as! String),
+ params: .init(memoryKiB: c["memoryKiB"] as! Int, passes: c["passes"] as! Int, parallelism: c["parallelism"] as! Int, tagLength: c["tagLength"] as! Int))))
+}
+let pa = (F["params"] as! [String: Any])["argon2"] as! [String: Any]
+emit("params", Argon2id.bento == .init(memoryKiB: pa["memoryKiB"] as! Int, passes: pa["passes"] as! Int, parallelism: pa["parallelism"] as! Int, tagLength: pa["tagLength"] as! Int) && pa["version"] as! Int == 0x13)
+
+// the wipe: every buffer Argon2id frees is all zeros by then, the 64 MiB of blocks included
+var released = 0, largest = 0, dirty = 0
+Argon2id.probe = { p, n in released += 1; largest = max(largest, n); for i in 0..<n where p[i] != 0 { dirty += 1; break } }
+_ = Argon2id.hash(password: hx("009e01a578034a5304ef"), salt: hx("101112131415161718191a1b1c1d1e1f"))
+Argon2id.probe = nil
+emit("wipe", "\(released)|\(largest)|\(dirty)")
+
+// codes and parsing
+for (i, c) in (F["codes"] as! [[String: Any]]).enumerated() { emit("fmt\(i)", R.formatCode(hx(c["bytes"] as! String)) ?? "nil") }
+for (i, c) in (F["parse"] as! [[String: Any]]).enumerated() { emit("parse\(i)", verdict(R.parseCode(c["input"] as! String)) { hs($0) }) }
+
+// derivations
+let d = F["derivations"] as! [String: Any]
+let code = hx(d["code"] as! String)
+let s0 = Date()
+emit("argon2_A", hs(Argon2id.hash(password: code, salt: hx(d["salt"] as! String))))
+emit("argon2_ms", Int(Date().timeIntervalSince(s0) * 1000))
+emit("wrapKey", hs(R.recoveryWrapKey(code: code, salt: hx(d["salt"] as! String))))
+emit("verifier", hs(R.recoveryVerifier(code: code, saltV: hx(d["saltV"] as! String))))
+let prf = d["prf"] as! [String: String]
+emit("prfKek", hs(R.prfKek(prfOutput: hx(prf["output"]!), salt: hx(prf["salt"]!))))
+emit("short.code", R.recoveryWrapKey(code: Array(code.dropLast()), salt: hx(d["salt"] as! String)) == nil)
+
+// blobs: reproduce, open, and refuse
+let b = F["blobs"] as! [String: Any]
+let k = b["keys"] as! [String: String]
+let acct = hx(k["accountD"]!), kx = hx(k["kxD"]!), other = hx(k["otherD"]!)
+let pb = b["prf"] as! [String: Any], pin = pb["inputs"] as! [String: String]
+func blobStr(_ x: R.PrfBlob?) -> String { x.map { "\($0.v)|\($0.cred)|\($0.salt)|\($0.iv)|\($0.ct)" } ?? "nil" }
+func fixBlob(_ m: [String: Any]) -> R.PrfBlob { R.PrfBlob(v: m["v"] as! Int, cred: m["cred"] as! String, salt: m["salt"] as! String, iv: m["iv"] as! String, ct: m["ct"] as! String) }
+for (name, mode, keys) in [("unruled", R.KxMode.unruled, R.BlobKeys(account: acct, kx: nil)), ("modeA", R.KxMode.A, R.BlobKeys(account: acct, kx: kx))] {
+ emit("prf.\(name).seal", blobStr(R.sealPrfBlob(prfOutput: hx(pin["prfOutput"]!), credentialId: hx(pin["credentialId"]!), salt: hx(pin["salt"]!), iv: hx(pin["iv"]!), keys: keys, mode: mode)))
+ emit("prf.\(name).want", blobStr(fixBlob(pb[name] as! [String: Any])))
+ emit("prf.\(name).open", verdict(R.openPrfBlob(fixBlob(pb[name] as! [String: Any]), prfOutput: hx(pin["prfOutput"]!), credentialId: hx(pin["credentialId"]!), accountPub: k["accountPub"]!, kxPub: k["kxPub"]!, mode: mode)) { hs($0.account) + "+" + hs($0.kx) })
+}
+let ub = fixBlob(pb["unruled"] as! [String: Any])
+emit("prf.otherCred", verdict(R.openPrfBlob(ub, prfOutput: hx(pin["prfOutput"]!), credentialId: hx("00"), accountPub: k["accountPub"]!)) { _ in "" })
+emit("prf.otherPrf", verdict(R.openPrfBlob(ub, prfOutput: [UInt8](repeating: 9, count: 32), credentialId: hx(pin["credentialId"]!), accountPub: k["accountPub"]!)) { _ in "" })
+emit("prf.swappedKey", verdict(R.openPrfBlob(ub, prfOutput: hx(pin["prfOutput"]!), credentialId: hx(pin["credentialId"]!), accountPub: k["kxPub"]!)) { _ in "" })
+emit("prf.modeMismatch", verdict(R.openPrfBlob(ub, prfOutput: hx(pin["prfOutput"]!), credentialId: hx(pin["credentialId"]!), accountPub: k["accountPub"]!, kxPub: k["kxPub"]!, mode: .A)) { _ in "" })
+emit("prf.v2", verdict(R.openPrfBlob(R.PrfBlob(v: 2, cred: ub.cred, salt: ub.salt, iv: ub.iv, ct: ub.ct), prfOutput: hx(pin["prfOutput"]!), credentialId: hx(pin["credentialId"]!), accountPub: k["accountPub"]!)) { _ in "" })
+emit("prf.badSalt", verdict(R.openPrfBlob(R.PrfBlob(v: 1, cred: ub.cred, salt: "AAAA", iv: ub.iv, ct: ub.ct), prfOutput: hx(pin["prfOutput"]!), credentialId: hx(pin["credentialId"]!), accountPub: k["accountPub"]!)) { _ in "" })
+// a blob sealed around ANOTHER key: it decrypts, and the check refuses it
+let swapped = R.sealPrfBlob(prfOutput: hx(pin["prfOutput"]!), credentialId: hx(pin["credentialId"]!), salt: hx(pin["salt"]!), iv: hx(pin["iv"]!), keys: R.BlobKeys(account: other, kx: nil))!
+emit("prf.swappedBlob", verdict(R.openPrfBlob(swapped, prfOutput: hx(pin["prfOutput"]!), credentialId: hx(pin["credentialId"]!), accountPub: k["accountPub"]!)) { _ in "" })
+
+let rb = b["recovery"] as! [String: Any], rin = rb["inputs"] as! [String: String]
+let wk = R.recoveryWrapKey(code: hx(rin["code"]!), salt: hx(rin["salt"]!))!
+emit("rc.inner", hs(R.sealRecoveryInner(wrapKey: wk, iv: hx(rin["iv"]!), accountPub: k["accountPub"]!, keys: R.BlobKeys(account: acct, kx: nil))))
+emit("rc.open", verdict(R.openRecoveryInner(hx(rb["inner"] as! String), wrapKey: wk, iv: hx(rin["iv"]!), accountPub: k["accountPub"]!)) { hs($0.account) })
+emit("rc.otherAccount", verdict(R.openRecoveryInner(hx(rb["inner"] as! String), wrapKey: wk, iv: hx(rin["iv"]!), accountPub: k["kxPub"]!)) { _ in "" })
+var flipped = hx(rb["inner"] as! String); flipped[3] ^= 1
+emit("rc.tampered", verdict(R.openRecoveryInner(flipped, wrapKey: wk, iv: hx(rin["iv"]!), accountPub: k["accountPub"]!)) { _ in "" })
+
+// the directory's pepper rows, from the same primitives (the host doesn't run these)
+let pp = b["pepper"] as! [String: String]
+let P = R.hkdf(hx(pp["secret"]!), info: "bento/id/pepper/v1.\(R.accountTag(k["accountPub"]!))")
+let vk = R.hkdf(P, info: "bento/id/pepper/v1/verify"), pwk = R.hkdf(P, info: "bento/id/pepper/v1/wrap")
+emit("pep.verifyKey", hs(vk)); emit("pep.wrapKey", hs(pwk))
+emit("pep.tag", hs(Array(HMAC<SHA256>.authenticationCode(for: hx(d["verifier"] as! String), using: SymmetricKey(data: vk)))))
+emit("pep.outer", hs(R.gcmSeal(key: pwk, iv: hx(pp["iv"]!), aad: "bento/id/rc-pepper/v1.\(R.accountTag(k["accountPub"]!))", hx(rb["inner"] as! String))))
+
+// scalars
+for (i, s) in (F["scalars"] as! [[String: String]]).enumerated() {
+ emit("scalar\(i)", verdict(R.unpackScalars(hx(s["d"]!), accountPub: s["pub"]!)) { _ in "" })
+}
+emit("scalar.length", verdict(R.unpackScalars(Array(acct.dropLast()), accountPub: k["accountPub"]!)) { _ in "" })
+`
+const dir = mkdtempSync(join(tmpdir(), 'bento-idrec-'))
+let out
+try {
+ writeFileSync(join(dir, 'main.swift'), main)
+ writeFileSync(join(dir, 'cases.json'), JSON.stringify(cases))
+ execFileSync('swiftc', ['-O', '-D', 'BENTO_WIPE_PROBE', '-o', join(dir, 'a'), ...SRC, join(dir, 'main.swift')], { stdio: 'pipe' })
+ out = Object.fromEntries(execFileSync(join(dir, 'a'), [FIXTURE, join(dir, 'cases.json')], { maxBuffer: 1 << 24 }).toString().trim().split('\n').map((l) => l.split(/=(.*)/s).slice(0, 2)))
+} catch (err) { console.error('swiftc or run failed:\n' + (err.stderr?.toString() ?? err.message)); process.exit(2) }
+finally { try { rmSync(dir, { recursive: true, force: true }) } catch {} }
+
+const F = JSON.parse(readFileSync(FIXTURE, 'utf8'))
+let checks = 0, failures = 0
+const ok = (c, m) => { checks++; if (!c) failures++; console.log(` ${c ? 'ok ' : 'FAIL'} ${m}`) }
+
+console.log('Argon2id (no Apple implementation; this is ours):')
+ok(out.rfc === F.rfc9106.tag, 'RFC 9106 §5.3: p = 4, with a secret and associated data')
+const bad = cases.filter((c, i) => out[`case${i}`] !== c.tag)
+ok(bad.length === 0, `${cases.length} random inputs and parameters agree with Node's native Argon2id` + (bad.length ? ` (${bad.length} differ, first: ${JSON.stringify(bad[0])})` : ''))
+ok(out.params === 'true', "the fixture's parameters are ours: version 0x13, p = 1, 64 MiB, t = 3, 32 bytes")
+console.log(` (64 MiB, t = 3 took ${out.argon2_ms} ms here)`)
+
+{
+ const [released, largest, dirty] = (out.wipe ?? '').split('|').map(Number)
+ ok(released >= 6 && largest === 65536 * 128 && dirty === 0, `every buffer is zeroed before it's freed, the 64 MiB of blocks included (${released} buffers, ${dirty} not zeroed)`)
+}
+console.log('the recovery code:')
+F.codes.forEach((c, i) => ok(out[`fmt${i}`] === c.printed, `${c.bytes} prints as ${c.printed}`))
+F.parse.forEach((p, i) => {
+ const want = p.bytes ? `ok:${p.bytes}` : `no:${p.reason}`
+ ok(out[`parse${i}`] === want, `"${p.input}" (${p.note}) → ${want}${out[`parse${i}`] === want ? '' : ` (got ${out[`parse${i}`]})`}`)
+})
+
+console.log('derivations:')
+const dv = F.derivations
+ok(out.argon2_A === dv.argon2_A, 'Argon2id(code, salt)')
+ok(out.wrapKey === dv.wrapKey, 'the recovery blob\'s wrap key')
+ok(out.verifier === dv.verifier, 'the verifier, under its own salt')
+ok(out.prfKek === dv.prfKek, "the PRF blob's key")
+ok(out['short.code'] === 'true', 'a code of the wrong length derives nothing')
+
+console.log('the PRF blob:')
+const k = F.blobs.keys
+for (const [name, kxPart] of [['unruled', 'nil'], ['modeA', k.kxD]]) {
+ ok(out[`prf.${name}.seal`] === out[`prf.${name}.want`], `${name}: sealed byte for byte`)
+ ok(out[`prf.${name}.open`] === `ok:${k.accountD}+${kxPart}`, `${name}: opens to the account scalar${name === 'modeA' ? ' and the kx scalar' : ''}`)
+}
+ok(out['prf.otherCred'] === 'no:credential', 'another passkey\'s credential: refused before decrypting')
+ok(out['prf.otherPrf'] === 'no:decrypt', 'a wrong PRF output: does not decrypt')
+ok(out['prf.swappedKey'] === 'no:key-mismatch', 'checked against another public key: key-mismatch')
+ok(out['prf.swappedBlob'] === 'no:key-mismatch', 'a blob around ANOTHER key (a malicious directory\'s swap) decrypts, and is refused')
+ok(out['prf.modeMismatch'] === 'no:length', 'read under a kx mode it was not sealed for: length')
+ok(out['prf.v2'] === 'no:version' && out['prf.badSalt'] === 'no:grammar', 'an unknown version or a malformed salt: refused')
+
+console.log('the recovery-code blob:')
+ok(out['rc.inner'] === F.blobs.recovery.inner, 'the inner layer, sealed byte for byte')
+ok(out['rc.open'] === `ok:${k.accountD}`, 'and opened back to the account scalar')
+ok(out['rc.otherAccount'] === 'no:decrypt', "bound to the account: another account's tag does not decrypt")
+ok(out['rc.tampered'] === 'no:decrypt', 'one flipped bit: does not decrypt')
+const pp = F.blobs.pepper
+ok(out['pep.verifyKey'] === pp.verifyKey && out['pep.wrapKey'] === pp.wrapKey, "the directory's pepper subkeys (its rows, from the same primitives)")
+ok(out['pep.tag'] === pp.verifierTag && out['pep.outer'] === pp.outer, 'its verifier tag and outer layer')
+
+console.log('recovered scalars, checked through CryptoKit:')
+F.scalars.forEach((s, i) => {
+ const want = s.expect === 'accept' ? 'ok:' : `no:${s.reason}`
+ ok(out[`scalar${i}`] === want, `${s.name} → ${want}${out[`scalar${i}`] === want ? '' : ` (got ${out[`scalar${i}`]})`}`)
+})
+ok(out['scalar.length'] === 'no:length', 'a plaintext of the wrong length: refused')
+console.log(`\n${checks - failures}/${checks} checks passed`)
+process.exit(failures ? 1 : 0)