Bento, the office suite that fits in a file
TypeScript mit-licenseofficeoffice-365office-suiteoffice-toolsoffice365open-sourcepowerpointself-hostedsingle-page-appslidesslideshareslideshowslideshow-galleryslideshow-makerslideshows
home/ios: the bento/id agent core — keys, statements, sign() and host-stamped consent (#774)
nyblnet08fa829b2aaf
diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.ymlindex 5114db79..a1913436 100644--- a/.github/workflows/ci.yml+++ b/.github/workflows/ci.yml@@ -852,6 +852,25 @@ jobs:# the document's origin. Compiles the real HostDocStore; skips off Apple.run: node scripts/test-home-docstore-ios.mjs+ - name: home/ios bento/id keys rig+ # The agent's keys: the account key, the Secure Enclave routine and consent+ # keys, raw low-S signatures (verified in WebCrypto), never minting over a+ # store it could not read, and the §29 biometric-enrolment notice outbox.+ # Apple toolchains only; skips elsewhere.+ run: node scripts/test-home-id-keys.mjs++ - name: home/ios bento/id statements rig+ # The Swift statements against kernel/fixtures/identity-v1.json: verdict+ # and reason on every row, round trips, tampering, transcripts, low-S,+ # purposes, addresses, spendCalled and the frozen display table.+ run: node scripts/test-home-id-statements.mjs++ - name: home/ios bento/id agent rig+ # sign() routing and the host-stamped consent statement (§2e (A)): what+ # the page can name, what only the host stamps, and the verifier refusing+ # a relay, replay, payload swap or docId swap.+ run: node scripts/test-home-id-agent.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 unexpecteddiff --git a/home/ios/IdentityAgent.swift b/home/ios/IdentityAgent.swiftnew file mode 100644index 00000000..7fc13d81--- /dev/null+++ b/home/ios/IdentityAgent.swift@@ -0,0 +1,116 @@+// SPDX-License-Identifier: MIT+// Copyright (c) 2026 The Bento authors++import CryptoKit+import Foundation+import LocalAuthentication++/// What answers a document's `sign(purpose, payload)` (kernel/src/identity.ts),+/// and the host-stamped consent statement (identity-design §2e (A)).+///+/// The page names only WHAT it wants signed and for which purpose. It never names:+/// - which document it is (the host knows from the file it opened)+/// - who will verify the result, or with what challenge+/// - when the consent expires+/// The host stamps all of those itself, so a consent signature can't be pointed+/// at a context the page chose.+///+/// - **Routine purposes** (frame, prove, delegate, show) sign with the routine+/// device key, no prompt, and only a payload of exactly that purpose's shape.+/// - **High-authority purposes** (invite, revoke) need consent. The enrolment+/// gate runs first, so any notice is queued before anything else. Then the+/// host builds `cns.` and the consent key signs it, with the person present.+///+/// The bridge exposure of all this is I2's gate (a verified shell only); this+/// file decides and signs.+enum IdentityAgent {+ /// kernel/src/identity.ts SignRefusal+ enum Refusal: String, Error { case declined, reauth, purpose, noIdentity = "no-identity", unavailable }++ enum Signed: Equatable {+ /// a routine signature over the page's payload+ case routine(sig: String, pub: String)+ /// a consent: the host-stamped `cns.` text and the consent key's signature over it+ case consent(cns: String, sig: String, pub: String)+ }++ static let routine: Set<String> = ["frame", "prove", "delegate", "show"]+ /// the page's high-authority purposes, and the consent purpose each one is+ static let consentFor: [String: String] = ["invite": "invite", "revoke": "revoke"]++ /// The verifier this consent is FOR, as the host knows it: who it's talking+ /// to, and the single-use challenge that verifier issued. Never from the page.+ struct Verifier: Equatable {+ let audience: String // "dir", or "room:<roomName>"+ let challenge: String+ }++ /// Build the host-stamped consent statement, or nil if any part breaks the+ /// rules. `docId` is the one the HOST read from the file it opened.+ static func stampConsent(purpose: String, payload: String, docId: String?, verifier: Verifier,+ rp: String = "bento", now: Int,+ ttlMs: Int = IdentityStatements.consentMaxTtlMs) -> String? {+ guard let family = IdentityStatements.consentFamily[purpose], payload.hasPrefix(family),+ ttlMs > 0, ttlMs <= IdentityStatements.consentMaxTtlMs else { return nil }+ let docScoped = purpose == "invite" || purpose == "revoke"+ if docScoped { guard let d = docId, IdentityStatements.isDocId(d) else { return nil } }+ guard let transcript = IdentityStatements.consentTranscript(audience: verifier.audience,+ challenge: verifier.challenge, payloadText: payload)+ else { return nil }+ return IdentityStatements.buildConsent(.init(rp: rp, purpose: purpose, docId: docScoped ? docId : nil,+ transcript: transcript, exp: now + ttlMs))+ }++ /// What `consent` needs from the host's own state: never from the page.+ struct HostContext {+ let docId: String?+ let verifier: Verifier?+ let deviceName: String+ let devices: Set<String>+ let now: Int+ let domainState: () -> Data?+ let presence: LAContext?+ }++ /// `sign(purpose, payload)` as a document asks it.+ static func sign(purpose: String, payload: String, host: HostContext,+ store: IdentityKeys.Store, enclave: Bool = SecureEnclave.isAvailable) -> Result<Signed, Refusal> {+ // the payload must be exactly the shape its purpose names, before any key is touched+ guard IdentityStatements.payloadMatchesPurpose(purpose, payload) else { return .failure(.purpose) }+ do { _ = try IdentityKeys.account(in: store) }+ catch IdentityKeys.Failure.noIdentity { return .failure(.noIdentity) }+ catch { return .failure(.unavailable) }++ if routine.contains(purpose) {+ do {+ let k = try IdentityKeys.device(.routine, in: store, enclave: enclave)+ let sig = try k.sign(Data(payload.utf8))+ return .success(.routine(sig: IdentityKeys.b64url(sig), pub: IdentityKeys.b64url(k.publicRaw)))+ } catch { return .failure(.unavailable) }+ }++ guard let cp = consentFor[purpose] else { return .failure(.purpose) }+ // The consent key FIRST: minting it is what records the enrolment it was+ // born under, so a brand-new key isn't mistaken for a changed enrolment.+ let k: IdentityKeys.DeviceKey+ do { k = try IdentityKeys.device(.consent, in: store, enclave: enclave, domainState: host.domainState) }+ catch { return .failure(.unavailable) }+ // then the notice (§29): queued before the consent can proceed+ switch IdentityKeys.enrolmentGate(host.domainState(), device: host.deviceName, devices: host.devices, now: host.now, in: store) {+ case .refuse: return .failure(.unavailable)+ case .reconfirm, .proceed: break // a change is re-confirmed by the presence check below+ }+ guard let v = host.verifier,+ let cns = stampConsent(purpose: cp, payload: payload, docId: host.docId, verifier: v, now: host.now)+ else { return .failure(.unavailable) }+ do {+ let sig = try k.sign(Data(cns.utf8), context: host.presence)+ // only now, with the notice queued and the person present, is a changed enrolment accepted+ if IdentityKeys.checkEnrolment(host.domainState(), in: store) == .changed {+ IdentityKeys.acceptEnrolment(host.domainState(), in: store)+ }+ return .success(.consent(cns: cns, sig: IdentityKeys.b64url(sig), pub: IdentityKeys.b64url(k.publicRaw)))+ } catch IdentityKeys.Failure.declined { return .failure(.declined) }+ catch { return .failure(.unavailable) }+ }+}diff --git a/home/ios/IdentityDisplayTable.swift b/home/ios/IdentityDisplayTable.swiftnew file mode 100644index 00000000..be73f629--- /dev/null+++ b/home/ios/IdentityDisplayTable.swift@@ -0,0 +1,151 @@+// SPDX-License-Identifier: MIT+// Copyright (c) 2026 The Bento authors+//+// GENERATED from kernel/fixtures/identity-v1.json `displayForbidden` (Unicode 17.0).+// Do not edit by hand: scripts/test-home-id-statements.mjs fails if this+// drifts from the fixture. Changing the table is a format decision.++/// The code points refused in display text (names, device labels), frozen as+/// explicit ranges rather than read from the platform's Unicode categories, so+/// every host refuses exactly the same characters. It includes every code+/// point unassigned at Unicode 17.0, the noncharacters among them.+enum IdentityDisplayTable {+ static let unicode = "17.0"+ /// [lo, hi] pairs, sorted, inclusive+ static let flat: [UInt32] = [+ 0x0, 0x1F, 0x7F, 0x9F, 0xAD, 0xAD, 0x378, 0x379, 0x380, 0x383, 0x38B, 0x38B,+ 0x38D, 0x38D, 0x3A2, 0x3A2, 0x530, 0x530, 0x557, 0x558, 0x58B, 0x58C, 0x590, 0x590,+ 0x5C8, 0x5CF, 0x5EB, 0x5EE, 0x5F5, 0x605, 0x61C, 0x61C, 0x6DD, 0x6DD, 0x70E, 0x70F,+ 0x74B, 0x74C, 0x7B2, 0x7BF, 0x7FB, 0x7FC, 0x82E, 0x82F, 0x83F, 0x83F, 0x85C, 0x85D,+ 0x85F, 0x85F, 0x86B, 0x86F, 0x890, 0x896, 0x8E2, 0x8E2, 0x984, 0x984, 0x98D, 0x98E,+ 0x991, 0x992, 0x9A9, 0x9A9, 0x9B1, 0x9B1, 0x9B3, 0x9B5, 0x9BA, 0x9BB, 0x9C5, 0x9C6,+ 0x9C9, 0x9CA, 0x9CF, 0x9D6, 0x9D8, 0x9DB, 0x9DE, 0x9DE, 0x9E4, 0x9E5, 0x9FF, 0xA00,+ 0xA04, 0xA04, 0xA0B, 0xA0E, 0xA11, 0xA12, 0xA29, 0xA29, 0xA31, 0xA31, 0xA34, 0xA34,+ 0xA37, 0xA37, 0xA3A, 0xA3B, 0xA3D, 0xA3D, 0xA43, 0xA46, 0xA49, 0xA4A, 0xA4E, 0xA50,+ 0xA52, 0xA58, 0xA5D, 0xA5D, 0xA5F, 0xA65, 0xA77, 0xA80, 0xA84, 0xA84, 0xA8E, 0xA8E,+ 0xA92, 0xA92, 0xAA9, 0xAA9, 0xAB1, 0xAB1, 0xAB4, 0xAB4, 0xABA, 0xABB, 0xAC6, 0xAC6,+ 0xACA, 0xACA, 0xACE, 0xACF, 0xAD1, 0xADF, 0xAE4, 0xAE5, 0xAF2, 0xAF8, 0xB00, 0xB00,+ 0xB04, 0xB04, 0xB0D, 0xB0E, 0xB11, 0xB12, 0xB29, 0xB29, 0xB31, 0xB31, 0xB34, 0xB34,+ 0xB3A, 0xB3B, 0xB45, 0xB46, 0xB49, 0xB4A, 0xB4E, 0xB54, 0xB58, 0xB5B, 0xB5E, 0xB5E,+ 0xB64, 0xB65, 0xB78, 0xB81, 0xB84, 0xB84, 0xB8B, 0xB8D, 0xB91, 0xB91, 0xB96, 0xB98,+ 0xB9B, 0xB9B, 0xB9D, 0xB9D, 0xBA0, 0xBA2, 0xBA5, 0xBA7, 0xBAB, 0xBAD, 0xBBA, 0xBBD,+ 0xBC3, 0xBC5, 0xBC9, 0xBC9, 0xBCE, 0xBCF, 0xBD1, 0xBD6, 0xBD8, 0xBE5, 0xBFB, 0xBFF,+ 0xC0D, 0xC0D, 0xC11, 0xC11, 0xC29, 0xC29, 0xC3A, 0xC3B, 0xC45, 0xC45, 0xC49, 0xC49,+ 0xC4E, 0xC54, 0xC57, 0xC57, 0xC5B, 0xC5B, 0xC5E, 0xC5F, 0xC64, 0xC65, 0xC70, 0xC76,+ 0xC8D, 0xC8D, 0xC91, 0xC91, 0xCA9, 0xCA9, 0xCB4, 0xCB4, 0xCBA, 0xCBB, 0xCC5, 0xCC5,+ 0xCC9, 0xCC9, 0xCCE, 0xCD4, 0xCD7, 0xCDB, 0xCDF, 0xCDF, 0xCE4, 0xCE5, 0xCF0, 0xCF0,+ 0xCF4, 0xCFF, 0xD0D, 0xD0D, 0xD11, 0xD11, 0xD45, 0xD45, 0xD49, 0xD49, 0xD50, 0xD53,+ 0xD64, 0xD65, 0xD80, 0xD80, 0xD84, 0xD84, 0xD97, 0xD99, 0xDB2, 0xDB2, 0xDBC, 0xDBC,+ 0xDBE, 0xDBF, 0xDC7, 0xDC9, 0xDCB, 0xDCE, 0xDD5, 0xDD5, 0xDD7, 0xDD7, 0xDE0, 0xDE5,+ 0xDF0, 0xDF1, 0xDF5, 0xE00, 0xE3B, 0xE3E, 0xE5C, 0xE80, 0xE83, 0xE83, 0xE85, 0xE85,+ 0xE8B, 0xE8B, 0xEA4, 0xEA4, 0xEA6, 0xEA6, 0xEBE, 0xEBF, 0xEC5, 0xEC5, 0xEC7, 0xEC7,+ 0xECF, 0xECF, 0xEDA, 0xEDB, 0xEE0, 0xEFF, 0xF48, 0xF48, 0xF6D, 0xF70, 0xF98, 0xF98,+ 0xFBD, 0xFBD, 0xFCD, 0xFCD, 0xFDB, 0xFFF, 0x10C6, 0x10C6, 0x10C8, 0x10CC, 0x10CE, 0x10CF,+ 0x115F, 0x1160, 0x1249, 0x1249, 0x124E, 0x124F, 0x1257, 0x1257, 0x1259, 0x1259, 0x125E, 0x125F,+ 0x1289, 0x1289, 0x128E, 0x128F, 0x12B1, 0x12B1, 0x12B6, 0x12B7, 0x12BF, 0x12BF, 0x12C1, 0x12C1,+ 0x12C6, 0x12C7, 0x12D7, 0x12D7, 0x1311, 0x1311, 0x1316, 0x1317, 0x135B, 0x135C, 0x137D, 0x137F,+ 0x139A, 0x139F, 0x13F6, 0x13F7, 0x13FE, 0x13FF, 0x169D, 0x169F, 0x16F9, 0x16FF, 0x1716, 0x171E,+ 0x1737, 0x173F, 0x1754, 0x175F, 0x176D, 0x176D, 0x1771, 0x1771, 0x1774, 0x177F, 0x17DE, 0x17DF,+ 0x17EA, 0x17EF, 0x17FA, 0x17FF, 0x180E, 0x180E, 0x181A, 0x181F, 0x1879, 0x187F, 0x18AB, 0x18AF,+ 0x18F6, 0x18FF, 0x191F, 0x191F, 0x192C, 0x192F, 0x193C, 0x193F, 0x1941, 0x1943, 0x196E, 0x196F,+ 0x1975, 0x197F, 0x19AC, 0x19AF, 0x19CA, 0x19CF, 0x19DB, 0x19DD, 0x1A1C, 0x1A1D, 0x1A5F, 0x1A5F,+ 0x1A7D, 0x1A7E, 0x1A8A, 0x1A8F, 0x1A9A, 0x1A9F, 0x1AAE, 0x1AAF, 0x1ADE, 0x1ADF, 0x1AEC, 0x1AFF,+ 0x1B4D, 0x1B4D, 0x1BF4, 0x1BFB, 0x1C38, 0x1C3A, 0x1C4A, 0x1C4C, 0x1C8B, 0x1C8F, 0x1CBB, 0x1CBC,+ 0x1CC8, 0x1CCF, 0x1CFB, 0x1CFF, 0x1F16, 0x1F17, 0x1F1E, 0x1F1F, 0x1F46, 0x1F47, 0x1F4E, 0x1F4F,+ 0x1F58, 0x1F58, 0x1F5A, 0x1F5A, 0x1F5C, 0x1F5C, 0x1F5E, 0x1F5E, 0x1F7E, 0x1F7F, 0x1FB5, 0x1FB5,+ 0x1FC5, 0x1FC5, 0x1FD4, 0x1FD5, 0x1FDC, 0x1FDC, 0x1FF0, 0x1FF1, 0x1FF5, 0x1FF5, 0x1FFF, 0x1FFF,+ 0x200B, 0x200B, 0x200E, 0x200F, 0x2028, 0x202E, 0x2060, 0x206F, 0x2072, 0x2073, 0x208F, 0x208F,+ 0x209D, 0x209F, 0x20C2, 0x20CF, 0x20F1, 0x20FF, 0x218C, 0x218F, 0x242A, 0x243F, 0x244B, 0x245F,+ 0x2B74, 0x2B75, 0x2CF4, 0x2CF8, 0x2D26, 0x2D26, 0x2D28, 0x2D2C, 0x2D2E, 0x2D2F, 0x2D68, 0x2D6E,+ 0x2D71, 0x2D7E, 0x2D97, 0x2D9F, 0x2DA7, 0x2DA7, 0x2DAF, 0x2DAF, 0x2DB7, 0x2DB7, 0x2DBF, 0x2DBF,+ 0x2DC7, 0x2DC7, 0x2DCF, 0x2DCF, 0x2DD7, 0x2DD7, 0x2DDF, 0x2DDF, 0x2E5E, 0x2E7F, 0x2E9A, 0x2E9A,+ 0x2EF4, 0x2EFF, 0x2FD6, 0x2FEF, 0x3040, 0x3040, 0x3097, 0x3098, 0x3100, 0x3104, 0x3130, 0x3130,+ 0x3164, 0x3164, 0x318F, 0x318F, 0x31E6, 0x31EE, 0x321F, 0x321F, 0xA48D, 0xA48F, 0xA4C7, 0xA4CF,+ 0xA62C, 0xA63F, 0xA6F8, 0xA6FF, 0xA7DD, 0xA7F0, 0xA82D, 0xA82F, 0xA83A, 0xA83F, 0xA878, 0xA87F,+ 0xA8C6, 0xA8CD, 0xA8DA, 0xA8DF, 0xA954, 0xA95E, 0xA97D, 0xA97F, 0xA9CE, 0xA9CE, 0xA9DA, 0xA9DD,+ 0xA9FF, 0xA9FF, 0xAA37, 0xAA3F, 0xAA4E, 0xAA4F, 0xAA5A, 0xAA5B, 0xAAC3, 0xAADA, 0xAAF7, 0xAB00,+ 0xAB07, 0xAB08, 0xAB0F, 0xAB10, 0xAB17, 0xAB1F, 0xAB27, 0xAB27, 0xAB2F, 0xAB2F, 0xAB6C, 0xAB6F,+ 0xABEE, 0xABEF, 0xABFA, 0xABFF, 0xD7A4, 0xD7AF, 0xD7C7, 0xD7CA, 0xD7FC, 0xD7FF, 0xE000, 0xF8FF,+ 0xFA6E, 0xFA6F, 0xFADA, 0xFAFF, 0xFB07, 0xFB12, 0xFB18, 0xFB1C, 0xFB37, 0xFB37, 0xFB3D, 0xFB3D,+ 0xFB3F, 0xFB3F, 0xFB42, 0xFB42, 0xFB45, 0xFB45, 0xFDD0, 0xFDEF, 0xFE1A, 0xFE1F, 0xFE53, 0xFE53,+ 0xFE67, 0xFE67, 0xFE6C, 0xFE6F, 0xFE75, 0xFE75, 0xFEFD, 0xFF00, 0xFFA0, 0xFFA0, 0xFFBF, 0xFFC1,+ 0xFFC8, 0xFFC9, 0xFFD0, 0xFFD1, 0xFFD8, 0xFFD9, 0xFFDD, 0xFFDF, 0xFFE7, 0xFFE7, 0xFFEF, 0xFFFB,+ 0xFFFE, 0xFFFF, 0x1000C, 0x1000C, 0x10027, 0x10027, 0x1003B, 0x1003B, 0x1003E, 0x1003E, 0x1004E, 0x1004F,+ 0x1005E, 0x1007F, 0x100FB, 0x100FF, 0x10103, 0x10106, 0x10134, 0x10136, 0x1018F, 0x1018F, 0x1019D, 0x1019F,+ 0x101A1, 0x101CF, 0x101FE, 0x1027F, 0x1029D, 0x1029F, 0x102D1, 0x102DF, 0x102FC, 0x102FF, 0x10324, 0x1032C,+ 0x1034B, 0x1034F, 0x1037B, 0x1037F, 0x1039E, 0x1039E, 0x103C4, 0x103C7, 0x103D6, 0x103FF, 0x1049E, 0x1049F,+ 0x104AA, 0x104AF, 0x104D4, 0x104D7, 0x104FC, 0x104FF, 0x10528, 0x1052F, 0x10564, 0x1056E, 0x1057B, 0x1057B,+ 0x1058B, 0x1058B, 0x10593, 0x10593, 0x10596, 0x10596, 0x105A2, 0x105A2, 0x105B2, 0x105B2, 0x105BA, 0x105BA,+ 0x105BD, 0x105BF, 0x105F4, 0x105FF, 0x10737, 0x1073F, 0x10756, 0x1075F, 0x10768, 0x1077F, 0x10786, 0x10786,+ 0x107B1, 0x107B1, 0x107BB, 0x107FF, 0x10806, 0x10807, 0x10809, 0x10809, 0x10836, 0x10836, 0x10839, 0x1083B,+ 0x1083D, 0x1083E, 0x10856, 0x10856, 0x1089F, 0x108A6, 0x108B0, 0x108DF, 0x108F3, 0x108F3, 0x108F6, 0x108FA,+ 0x1091C, 0x1091E, 0x1093A, 0x1093E, 0x1095A, 0x1097F, 0x109B8, 0x109BB, 0x109D0, 0x109D1, 0x10A04, 0x10A04,+ 0x10A07, 0x10A0B, 0x10A14, 0x10A14, 0x10A18, 0x10A18, 0x10A36, 0x10A37, 0x10A3B, 0x10A3E, 0x10A49, 0x10A4F,+ 0x10A59, 0x10A5F, 0x10AA0, 0x10ABF, 0x10AE7, 0x10AEA, 0x10AF7, 0x10AFF, 0x10B36, 0x10B38, 0x10B56, 0x10B57,+ 0x10B73, 0x10B77, 0x10B92, 0x10B98, 0x10B9D, 0x10BA8, 0x10BB0, 0x10BFF, 0x10C49, 0x10C7F, 0x10CB3, 0x10CBF,+ 0x10CF3, 0x10CF9, 0x10D28, 0x10D2F, 0x10D3A, 0x10D3F, 0x10D66, 0x10D68, 0x10D86, 0x10D8D, 0x10D90, 0x10E5F,+ 0x10E7F, 0x10E7F, 0x10EAA, 0x10EAA, 0x10EAE, 0x10EAF, 0x10EB2, 0x10EC1, 0x10EC8, 0x10ECF, 0x10ED9, 0x10EF9,+ 0x10F28, 0x10F2F, 0x10F5A, 0x10F6F, 0x10F8A, 0x10FAF, 0x10FCC, 0x10FDF, 0x10FF7, 0x10FFF, 0x1104E, 0x11051,+ 0x11076, 0x1107E, 0x110BD, 0x110BD, 0x110C3, 0x110CF, 0x110E9, 0x110EF, 0x110FA, 0x110FF, 0x11135, 0x11135,+ 0x11148, 0x1114F, 0x11177, 0x1117F, 0x111E0, 0x111E0, 0x111F5, 0x111FF, 0x11212, 0x11212, 0x11242, 0x1127F,+ 0x11287, 0x11287, 0x11289, 0x11289, 0x1128E, 0x1128E, 0x1129E, 0x1129E, 0x112AA, 0x112AF, 0x112EB, 0x112EF,+ 0x112FA, 0x112FF, 0x11304, 0x11304, 0x1130D, 0x1130E, 0x11311, 0x11312, 0x11329, 0x11329, 0x11331, 0x11331,+ 0x11334, 0x11334, 0x1133A, 0x1133A, 0x11345, 0x11346, 0x11349, 0x1134A, 0x1134E, 0x1134F, 0x11351, 0x11356,+ 0x11358, 0x1135C, 0x11364, 0x11365, 0x1136D, 0x1136F, 0x11375, 0x1137F, 0x1138A, 0x1138A, 0x1138C, 0x1138D,+ 0x1138F, 0x1138F, 0x113B6, 0x113B6, 0x113C1, 0x113C1, 0x113C3, 0x113C4, 0x113C6, 0x113C6, 0x113CB, 0x113CB,+ 0x113D6, 0x113D6, 0x113D9, 0x113E0, 0x113E3, 0x113FF, 0x1145C, 0x1145C, 0x11462, 0x1147F, 0x114C8, 0x114CF,+ 0x114DA, 0x1157F, 0x115B6, 0x115B7, 0x115DE, 0x115FF, 0x11645, 0x1164F, 0x1165A, 0x1165F, 0x1166D, 0x1167F,+ 0x116BA, 0x116BF, 0x116CA, 0x116CF, 0x116E4, 0x116FF, 0x1171B, 0x1171C, 0x1172C, 0x1172F, 0x11747, 0x117FF,+ 0x1183C, 0x1189F, 0x118F3, 0x118FE, 0x11907, 0x11908, 0x1190A, 0x1190B, 0x11914, 0x11914, 0x11917, 0x11917,+ 0x11936, 0x11936, 0x11939, 0x1193A, 0x11947, 0x1194F, 0x1195A, 0x1199F, 0x119A8, 0x119A9, 0x119D8, 0x119D9,+ 0x119E5, 0x119FF, 0x11A48, 0x11A4F, 0x11AA3, 0x11AAF, 0x11AF9, 0x11AFF, 0x11B0A, 0x11B5F, 0x11B68, 0x11BBF,+ 0x11BE2, 0x11BEF, 0x11BFA, 0x11BFF, 0x11C09, 0x11C09, 0x11C37, 0x11C37, 0x11C46, 0x11C4F, 0x11C6D, 0x11C6F,+ 0x11C90, 0x11C91, 0x11CA8, 0x11CA8, 0x11CB7, 0x11CFF, 0x11D07, 0x11D07, 0x11D0A, 0x11D0A, 0x11D37, 0x11D39,+ 0x11D3B, 0x11D3B, 0x11D3E, 0x11D3E, 0x11D48, 0x11D4F, 0x11D5A, 0x11D5F, 0x11D66, 0x11D66, 0x11D69, 0x11D69,+ 0x11D8F, 0x11D8F, 0x11D92, 0x11D92, 0x11D99, 0x11D9F, 0x11DAA, 0x11DAF, 0x11DDC, 0x11DDF, 0x11DEA, 0x11EDF,+ 0x11EF9, 0x11EFF, 0x11F11, 0x11F11, 0x11F3B, 0x11F3D, 0x11F5B, 0x11FAF, 0x11FB1, 0x11FBF, 0x11FF2, 0x11FFE,+ 0x1239A, 0x123FF, 0x1246F, 0x1246F, 0x12475, 0x1247F, 0x12544, 0x12F8F, 0x12FF3, 0x12FFF, 0x13430, 0x1343F,+ 0x13456, 0x1345F, 0x143FB, 0x143FF, 0x14647, 0x160FF, 0x1613A, 0x167FF, 0x16A39, 0x16A3F, 0x16A5F, 0x16A5F,+ 0x16A6A, 0x16A6D, 0x16ABF, 0x16ABF, 0x16ACA, 0x16ACF, 0x16AEE, 0x16AEF, 0x16AF6, 0x16AFF, 0x16B46, 0x16B4F,+ 0x16B5A, 0x16B5A, 0x16B62, 0x16B62, 0x16B78, 0x16B7C, 0x16B90, 0x16D3F, 0x16D7A, 0x16E3F, 0x16E9B, 0x16E9F,+ 0x16EB9, 0x16EBA, 0x16ED4, 0x16EFF, 0x16F4B, 0x16F4E, 0x16F88, 0x16F8E, 0x16FA0, 0x16FDF, 0x16FE5, 0x16FEF,+ 0x16FF7, 0x16FFF, 0x18CD6, 0x18CFE, 0x18D1F, 0x18D7F, 0x18DF3, 0x1AFEF, 0x1AFF4, 0x1AFF4, 0x1AFFC, 0x1AFFC,+ 0x1AFFF, 0x1AFFF, 0x1B123, 0x1B131, 0x1B133, 0x1B14F, 0x1B153, 0x1B154, 0x1B156, 0x1B163, 0x1B168, 0x1B16F,+ 0x1B2FC, 0x1BBFF, 0x1BC6B, 0x1BC6F, 0x1BC7D, 0x1BC7F, 0x1BC89, 0x1BC8F, 0x1BC9A, 0x1BC9B, 0x1BCA0, 0x1CBFF,+ 0x1CCFD, 0x1CCFF, 0x1CEB4, 0x1CEB9, 0x1CED1, 0x1CEDF, 0x1CEF1, 0x1CEFF, 0x1CF2E, 0x1CF2F, 0x1CF47, 0x1CF4F,+ 0x1CFC4, 0x1CFFF, 0x1D0F6, 0x1D0FF, 0x1D127, 0x1D128, 0x1D173, 0x1D17A, 0x1D1EB, 0x1D1FF, 0x1D246, 0x1D2BF,+ 0x1D2D4, 0x1D2DF, 0x1D2F4, 0x1D2FF, 0x1D357, 0x1D35F, 0x1D379, 0x1D3FF, 0x1D455, 0x1D455, 0x1D49D, 0x1D49D,+ 0x1D4A0, 0x1D4A1, 0x1D4A3, 0x1D4A4, 0x1D4A7, 0x1D4A8, 0x1D4AD, 0x1D4AD, 0x1D4BA, 0x1D4BA, 0x1D4BC, 0x1D4BC,+ 0x1D4C4, 0x1D4C4, 0x1D506, 0x1D506, 0x1D50B, 0x1D50C, 0x1D515, 0x1D515, 0x1D51D, 0x1D51D, 0x1D53A, 0x1D53A,+ 0x1D53F, 0x1D53F, 0x1D545, 0x1D545, 0x1D547, 0x1D549, 0x1D551, 0x1D551, 0x1D6A6, 0x1D6A7, 0x1D7CC, 0x1D7CD,+ 0x1DA8C, 0x1DA9A, 0x1DAA0, 0x1DAA0, 0x1DAB0, 0x1DEFF, 0x1DF1F, 0x1DF24, 0x1DF2B, 0x1DFFF, 0x1E007, 0x1E007,+ 0x1E019, 0x1E01A, 0x1E022, 0x1E022, 0x1E025, 0x1E025, 0x1E02B, 0x1E02F, 0x1E06E, 0x1E08E, 0x1E090, 0x1E0FF,+ 0x1E12D, 0x1E12F, 0x1E13E, 0x1E13F, 0x1E14A, 0x1E14D, 0x1E150, 0x1E28F, 0x1E2AF, 0x1E2BF, 0x1E2FA, 0x1E2FE,+ 0x1E300, 0x1E4CF, 0x1E4FA, 0x1E5CF, 0x1E5FB, 0x1E5FE, 0x1E600, 0x1E6BF, 0x1E6DF, 0x1E6DF, 0x1E6F6, 0x1E6FD,+ 0x1E700, 0x1E7DF, 0x1E7E7, 0x1E7E7, 0x1E7EC, 0x1E7EC, 0x1E7EF, 0x1E7EF, 0x1E7FF, 0x1E7FF, 0x1E8C5, 0x1E8C6,+ 0x1E8D7, 0x1E8FF, 0x1E94C, 0x1E94F, 0x1E95A, 0x1E95D, 0x1E960, 0x1EC70, 0x1ECB5, 0x1ED00, 0x1ED3E, 0x1EDFF,+ 0x1EE04, 0x1EE04, 0x1EE20, 0x1EE20, 0x1EE23, 0x1EE23, 0x1EE25, 0x1EE26, 0x1EE28, 0x1EE28, 0x1EE33, 0x1EE33,+ 0x1EE38, 0x1EE38, 0x1EE3A, 0x1EE3A, 0x1EE3C, 0x1EE41, 0x1EE43, 0x1EE46, 0x1EE48, 0x1EE48, 0x1EE4A, 0x1EE4A,+ 0x1EE4C, 0x1EE4C, 0x1EE50, 0x1EE50, 0x1EE53, 0x1EE53, 0x1EE55, 0x1EE56, 0x1EE58, 0x1EE58, 0x1EE5A, 0x1EE5A,+ 0x1EE5C, 0x1EE5C, 0x1EE5E, 0x1EE5E, 0x1EE60, 0x1EE60, 0x1EE63, 0x1EE63, 0x1EE65, 0x1EE66, 0x1EE6B, 0x1EE6B,+ 0x1EE73, 0x1EE73, 0x1EE78, 0x1EE78, 0x1EE7D, 0x1EE7D, 0x1EE7F, 0x1EE7F, 0x1EE8A, 0x1EE8A, 0x1EE9C, 0x1EEA0,+ 0x1EEA4, 0x1EEA4, 0x1EEAA, 0x1EEAA, 0x1EEBC, 0x1EEEF, 0x1EEF2, 0x1EFFF, 0x1F02C, 0x1F02F, 0x1F094, 0x1F09F,+ 0x1F0AF, 0x1F0B0, 0x1F0C0, 0x1F0C0, 0x1F0D0, 0x1F0D0, 0x1F0F6, 0x1F0FF, 0x1F1AE, 0x1F1E5, 0x1F203, 0x1F20F,+ 0x1F23C, 0x1F23F, 0x1F249, 0x1F24F, 0x1F252, 0x1F25F, 0x1F266, 0x1F2FF, 0x1F6D9, 0x1F6DB, 0x1F6ED, 0x1F6EF,+ 0x1F6FD, 0x1F6FF, 0x1F7DA, 0x1F7DF, 0x1F7EC, 0x1F7EF, 0x1F7F1, 0x1F7FF, 0x1F80C, 0x1F80F, 0x1F848, 0x1F84F,+ 0x1F85A, 0x1F85F, 0x1F888, 0x1F88F, 0x1F8AE, 0x1F8AF, 0x1F8BC, 0x1F8BF, 0x1F8C2, 0x1F8CF, 0x1F8D9, 0x1F8FF,+ 0x1FA58, 0x1FA5F, 0x1FA6E, 0x1FA6F, 0x1FA7D, 0x1FA7F, 0x1FA8B, 0x1FA8D, 0x1FAC7, 0x1FAC7, 0x1FAC9, 0x1FACC,+ 0x1FADD, 0x1FADE, 0x1FAEB, 0x1FAEE, 0x1FAF9, 0x1FAFF, 0x1FB93, 0x1FB93, 0x1FBFB, 0x1FFFF, 0x2A6E0, 0x2A6FF,+ 0x2B81E, 0x2B81F, 0x2CEAE, 0x2CEAF, 0x2EBE1, 0x2EBEF, 0x2EE5E, 0x2F7FF, 0x2FA1E, 0x2FFFF, 0x3134B, 0x3134F,+ 0x3347A, 0xE00FF, 0xE01F0, 0x10FFFF,+ ]++ static func forbidden(_ cp: UInt32) -> Bool {+ var lo = 0, hi = flat.count / 2 - 1+ while lo <= hi {+ let mid = (lo + hi) / 2, a = flat[2 * mid], b = flat[2 * mid + 1]+ if cp < a { hi = mid - 1 } else if cp > b { lo = mid + 1 } else { return true }+ }+ return false+ }+}diff --git a/home/ios/IdentityKeys.swift b/home/ios/IdentityKeys.swiftnew file mode 100644index 00000000..ad9e0850--- /dev/null+++ b/home/ios/IdentityKeys.swift@@ -0,0 +1,521 @@+// SPDX-License-Identifier: MIT+// Copyright (c) 2026 The Bento authors++import CryptoKit+import Foundation+import LocalAuthentication+import Security++/// bento/id's keys on this device (I1). The document side of the contract is+/// kernel/src/identity.ts; this is what answers it.+///+/// - **The account key** is the person. It's a software P-256 key in the Keychain,+/// this device only, because it's re-signed and replaced as devices come and+/// go (identity-design §2g). It's minted only by an explicit setup, never+/// because a read came back empty.+/// - **Two device keys, both in the Secure Enclave**, measured on this hardware:+/// - ROUTINE signs with no prompt: op batches, possession proofs, presence.+/// - CONSENT (`.userPresence`) needs Face ID, Touch ID or the passcode on+/// every use: invites, revocations, linking a device. The chip enforces that+/// split, so no code here can be talked out of it.+/// A Secure Enclave key never leaves the chip. Its opaque blob, useless+/// anywhere else, is kept in the Keychain so the key survives a relaunch.+/// - **Formats, as the kernel speaks them:** a public key is the 65-byte+/// uncompressed point (WebCrypto `exportKey('raw')`); a signature is raw r‖s,+/// 64 bytes, LOW-S normalised, never DER. Both are base64url without padding.+///+/// **Never act while blind.** A key read that failed is `unavailable`, never+/// "absent". Minting over a key that is still there would lose this device's+/// identity for good (the lesson of HostDocStore.Read).+///+/// The simulator has no Secure Enclave. It gets software keys behind the same+/// interface, and its consent key checks presence with an explicit device-owner+/// authentication. That stand-in exists ONLY in the simulator.+enum IdentityKeys {+ enum Role: String { case routine, consent }++ enum Failure: Error, Equatable {+ /// nothing set up on this device (no account key)+ case noIdentity+ /// a store or the chip couldn't answer; retry later, never mint over it+ case unavailable+ /// the person declined the presence check+ case declined+ }++ /// One device key: its public half, and a way to sign with it.+ struct DeviceKey {+ let role: Role+ let publicRaw: Data // 65 bytes, 0x04‖X‖Y+ fileprivate let signRaw: (Data, LAContext?) throws -> Data+ /// raw r‖s, low-S+ func sign(_ message: Data, context: LAContext? = nil) throws -> Data {+ IdentityKeys.lowS(try signRaw(message, context))+ }+ }++ /// Where key material lives: the Keychain in the app, a stand-in in the rig.+ typealias Store = HostDocStore.Secrets++ static let accountItem = "identity/account"+ static let enrolmentItem = "identity/consent-enrolment"+ static func deviceItem(_ r: Role) -> String { "identity/device-\(r.rawValue)" }++ // MARK: account key++ /// The account key, or `.noIdentity` when none is set up.+ static func account(in store: Store) throws -> P256.Signing.PrivateKey {+ switch store.get(accountItem) {+ case .found(let raw):+ guard let k = try? P256.Signing.PrivateKey(rawRepresentation: raw) else { throw Failure.unavailable }+ return k+ case .absent: throw Failure.noIdentity+ case .unavailable: throw Failure.unavailable+ }+ }++ /// Set up an identity on this device: mint the account key. Refuses if one is+ /// there, or if it can't tell whether one is there.+ static func createAccount(in store: Store) throws -> P256.Signing.PrivateKey {+ switch store.get(accountItem) {+ case .found: throw Failure.unavailable // never silently replace a person+ case .unavailable: throw Failure.unavailable+ case .absent:+ let k = P256.Signing.PrivateKey()+ guard store.set(accountItem, k.rawRepresentation) else { throw Failure.unavailable }+ return k+ }+ }++ // MARK: device keys++ /// This device's key for `role`, minting it on first use. A device key is+ /// minted only when the store says it's truly absent.+ static func device(_ role: Role, in store: Store, enclave: Bool = SecureEnclave.isAvailable,+ domainState: () -> Data? = IdentityKeys.currentDomainState) throws -> DeviceKey {+ switch store.get(deviceItem(role)) {+ case .found(let blob): return try load(role, blob, enclave: enclave)+ case .unavailable: throw Failure.unavailable+ case .absent:+ let (key, blob) = try mint(role, enclave: enclave)+ guard store.set(deviceItem(role), blob) else { throw Failure.unavailable }+ // the enrolment the consent key was born under: see Enrolment+ if role == .consent {+ // never mint a consent key under an enrolment we can't read: its+ // baseline would be missing, and the first consent a false alarm+ let reading = domainState()+ guard reading != cantTell else { store.delete(deviceItem(role)); throw Failure.unavailable }+ _ = recordEnrolment(reading, in: store)+ }+ return key+ }+ }++ // MARK: biometric enrolment tripwire (threat model §29)++ /// The consent key is `.userPresence`, so it accepts the passcode and+ /// survives a change of enrolled faces or fingers. That's deliberate: it+ /// doesn't lock out people without biometrics, or people whose biometrics+ /// fail. Android's consent key, which also accepts the device credential,+ /// survives new enrolments the same way (measured by home-android; only a+ /// biometric-only key is invalidated). So every host needs this tripwire.+ /// Android detects the change with a biometric-only canary key; iOS reads+ /// the enrolment directly. The enrolment is recorded when the consent key is+ /// created and checked at every consent:+ /// - UNCHANGED: go ahead.+ /// - CHANGED: the agent tells every device and the address "biometrics+ /// changed on <device>", and asks for the consent to be re-confirmed;+ /// `acceptEnrolment` then records the new state.+ /// - UNKNOWN: the record couldn't be read. Refuse the consent; never skip+ /// the check.+ /// A missing record (a key from before this check) is CHANGED, so it gets+ /// re-confirmed once. Measured on the simulator: gaining biometrics+ /// (nil → state) and losing them (state → nil) both show; re-enrolling the+ /// SAME simulated face reads identically. A different face or finger, a real+ /// device's case, is a different state.+ enum Enrolment: Equatable { case unchanged, changed, unknown }++ /// Stands in for "no biometrics enrolled", so losing them is a change too.+ private static let noBiometrics = Data("none".utf8)++ /// The reading when biometrics exist but can't be read right now: locked out+ /// after failed attempts, hardware unavailable, or any other error. It is NOT+ /// "no biometrics": reading a lockout as "removed" would alarm every device+ /// for nothing. The gate refuses on it instead (matching Android, where+ /// BiometricManager's HW_UNAVAILABLE and the like refuse).+ static let cantTell = Data("unknown".utf8)++ static func currentDomainState() -> Data? {+ let c = LAContext()+ var err: NSError?+ let can = c.canEvaluatePolicy(.deviceOwnerAuthenticationWithBiometrics, error: &err)+ return reading(canEvaluate: can, errorCode: err?.code, state: c.evaluatedPolicyDomainState)+ }++ /// What a canEvaluatePolicy answer means for the tripwire:+ /// - a readable state → that state+ /// - biometryNotEnrolled (measured: -7 on the simulator) → nil, "no biometrics"+ /// - anything else (lockout -8, not available -6, …) → `cantTell`+ static func reading(canEvaluate: Bool, errorCode: Int?, state: Data?) -> Data? {+ if canEvaluate { return state ?? cantTell }+ if errorCode == LAError.biometryNotEnrolled.rawValue { return nil }+ return cantTell+ }++ @discardableResult+ static func recordEnrolment(_ state: Data?, in store: Store) -> Bool {+ guard state != cantTell else { return false } // never a baseline+ return store.set(enrolmentItem, state ?? noBiometrics)+ }++ static func checkEnrolment(_ current: Data?, in store: Store) -> Enrolment {+ if current == cantTell { return .unknown }+ switch store.get(enrolmentItem) {+ case .found(let recorded): return recorded == (current ?? noBiometrics) ? .unchanged : .changed+ case .absent: return .changed+ case .unavailable: return .unknown+ }+ }++ /// After the person has re-confirmed a consent under a changed enrolment.+ /// Refused unless the notice for this change is durably queued: the+ /// protection is the NOTICE (someone who added their own face re-confirms+ /// trivially), so the new state may never be accepted without it.+ @discardableResult+ static func acceptEnrolment(_ current: Data?, in store: Store) -> Bool {+ guard case .found(let q) = store.get(outboxItem), let queued = try? JSONDecoder().decode([Notice].self, from: q),+ queued.contains(where: { $0.state == stateTag(current) }) else { return false }+ return recordEnrolment(current, in: store)+ }++ // MARK: the notice, before anything else (threat model §29)++ /// "Biometrics changed on <device>", for every device and the address.+ struct Notice: Codable, Equatable {+ var kind = "biometrics-changed"+ let device: String+ /// which new state it's about (a hash, never the state itself)+ let state: String+ let at: Int+ /// WHO it goes to, snapshotted when it was queued: the devices listed+ /// then, plus "address". A later change to the device list never+ /// shrinks it, because the device whose biometrics changed holds the+ /// account key and could otherwise drop the victim's other devices+ /// before delivery, suppressing the very notice that warns about it.+ let recipients: Set<String>+ /// who has confirmed receiving it+ var deliveredTo: Set<String> = []+ }++ /// The anchor recipient: nothing on the device side can remove it.+ static let addressRecipient = "address"+ /// A snapshotted device that can never confirm (wiped, destroyed) stops+ /// holding the notice back after this long — but only once the address has.+ static let silentDeviceTimeoutMs = 7 * 86_400_000++ /// Whether `n` may leave the outbox at `now`: everyone confirmed; or the+ /// address confirmed and every device still silent has timed out. Never+ /// without the address.+ static func isDone(_ n: Notice, now: Int) -> Bool {+ guard n.deliveredTo.contains(addressRecipient) else { return false }+ if n.recipients.isSubset(of: n.deliveredTo) { return true }+ return now - n.at >= silentDeviceTimeoutMs+ }++ static let outboxItem = "identity/notice-outbox"++ private static func stateTag(_ d: Data?) -> String {+ b64url(Data(SHA256.hash(data: d ?? noBiometrics)))+ }++ enum Gate: Equatable {+ /// the enrolment is the one the consent key was made under+ case proceed+ /// changed: the notice IS queued; ask for re-confirmation, then acceptEnrolment+ case reconfirm+ /// the record or the outbox can't be read or written: refuse the consent+ case refuse+ }++ /// Run before every consent. On a change, the notice is written to the+ /// durable outbox FIRST, before the consent can go on, whether it then+ /// completes or is cancelled. Queuing is idempotent per new state, so a+ /// restart neither drops nor repeats it. Nothing here takes input from the+ /// page, so a page can't suppress or delay it.+ /// `devices` is the account's device list as it stands NOW; it's+ /// snapshotted into the notice along with the address.+ static func enrolmentGate(_ current: Data?, device: String, devices: Set<String>, now: Int, in store: Store) -> Gate {+ switch checkEnrolment(current, in: store) {+ case .unchanged: return .proceed+ case .unknown: return .refuse+ case .changed:+ var queued: [Notice] = []+ switch store.get(outboxItem) {+ case .found(let q): guard let l = try? JSONDecoder().decode([Notice].self, from: q) else { return .refuse }; queued = l+ case .absent: break+ case .unavailable: return .refuse+ }+ let tag = stateTag(current)+ if !queued.contains(where: { $0.state == tag }) {+ queued.append(Notice(device: device, state: tag, at: now,+ recipients: devices.union([addressRecipient])))+ guard let d = try? JSONEncoder().encode(queued), store.set(outboxItem, d) else { return .refuse }+ }+ return .reconfirm+ }+ }++ /// The notices still to deliver. A notice leaves only when EVERY recipient+ /// has confirmed it (see markDelivered).+ static func pendingNotices(in store: Store) -> [Notice]? {+ switch store.get(outboxItem) {+ case .found(let q): return try? JSONDecoder().decode([Notice].self, from: q)+ case .absent: return []+ case .unavailable: return nil+ }+ }++ // MARK: the device-list change's own notice (threat model §29 point 4, §2g)++ /// The snapshot above defeats "add a face, then drop the victim's devices".+ /// The reverse order (drop them first, then add a face) leaves a snapshot+ /// that already excludes them, and the only thing that warns those devices+ /// is THIS notice: "the device list changed", sent to the list as it was+ /// BEFORE the change, plus the address, under the same snapshot and anchor+ /// rules. It must be queued before the change is published:+ /// `mayPublishDeviceList` is the check the publisher passes.+ private static func changeTag(_ before: Set<String>, _ after: Set<String>) -> String {+ b64url(Data(SHA256.hash(data: Data("devices.\(before.sorted().joined(separator: ","))>\(after.sorted().joined(separator: ","))".utf8))))+ }++ /// Queue the notice for a device-list change. Idempotent per change.+ static func queueDeviceListChange(before: Set<String>, after: Set<String>, by device: String, now: Int, in store: Store) -> Bool {+ guard before != after else { return true }+ var queued: [Notice] = []+ switch store.get(outboxItem) {+ case .found(let q): guard let l = try? JSONDecoder().decode([Notice].self, from: q) else { return false }; queued = l+ case .absent: break+ case .unavailable: return false+ }+ let tag = changeTag(before, after)+ if !queued.contains(where: { $0.state == tag }) {+ queued.append(Notice(kind: "devices-changed", device: device, state: tag, at: now,+ recipients: before.union([addressRecipient])))+ return save(queued, in: store)+ }+ return true+ }++ /// True only once the notice for exactly this change is durably queued.+ static func mayPublishDeviceList(before: Set<String>, after: Set<String>, in store: Store) -> Bool {+ if before == after { return true }+ let tag = changeTag(before, after)+ return pendingNotices(in: store)?.contains(where: { $0.state == tag && $0.kind == "devices-changed" }) ?? false+ }++ // MARK: the receiver's own check (threat model §29, defence in depth)++ /// `mayPublishDeviceList` binds only an honest publisher. Where any+ /// same-user process can use the account key (desktop, §26), a hostile one+ /// can skip it. So every device also checks the synced list for itself, and+ /// raises its OWN local alert when it finds:+ /// - itself removed: "this device was removed from your account by <device>"+ /// - any device removed that it didn't remove itself+ /// That happens whether or not any notice arrives. A thief can choose not to+ /// send one, but can't stop a removed device noticing on its next read.+ /// The alert is recorded durably BEFORE the new list becomes the baseline,+ /// so a crash between the two can't swallow it.+ struct Alert: Codable, Equatable {+ enum Kind: String, Codable { case thisDeviceRemoved, deviceRemoved, unknown }+ let kind: Kind+ /// the device removed (thisDeviceRemoved: this device)+ let device: String+ /// the device that signed the new list+ let by: String+ let at: Int+ }++ static let lastListItem = "identity/last-device-list"+ static let alertsItem = "identity/local-alerts"++ /// Run on every fetch of the synced device list. `current` is the list as+ /// fetched, `signedBy` the device that published it, `me` this device's key,+ /// and `removedHere` the devices this device itself removed (they raise+ /// nothing). Returns the alerts raised, or nil if the check couldn't be made;+ /// the caller must then not treat the list as checked.+ static func observeDeviceList(_ current: Set<String>, signedBy: String, me: String,+ removedHere: Set<String> = [], now: Int, in store: Store) -> [Alert]? {+ var last: Set<String>?+ switch store.get(lastListItem) {+ case .found(let d):+ guard let l = try? JSONDecoder().decode(Set<String>.self, from: d) else {+ // a baseline that can't be decoded: say so, and never adopt the new list blind+ _ = raise([Alert(kind: .unknown, device: me, by: signedBy, at: now)], in: store)+ return nil+ }+ last = l+ case .absent: last = nil // the first fetch sets the baseline+ case .unavailable: return nil // never adopt a list blind+ }+ var alerts: [Alert] = []+ if let last {+ if last.contains(me) && !current.contains(me) {+ alerts.append(Alert(kind: .thisDeviceRemoved, device: me, by: signedBy, at: now))+ }+ for gone in last.subtracting(current).subtracting([me]).subtracting(removedHere).sorted() {+ alerts.append(Alert(kind: .deviceRemoved, device: gone, by: signedBy, at: now))+ }+ }+ // the alert first, then the new baseline+ guard alerts.isEmpty || raise(alerts, in: store) else { return nil }+ guard let d = try? JSONEncoder().encode(current), store.set(lastListItem, d) else { return nil }+ return alerts+ }++ private static func raise(_ new: [Alert], in store: Store) -> Bool {+ var all: [Alert] = []+ switch store.get(alertsItem) {+ case .found(let d): guard let l = try? JSONDecoder().decode([Alert].self, from: d) else { return false }; all = l+ case .absent: break+ case .unavailable: return false+ }+ all.append(contentsOf: new)+ guard let d = try? JSONEncoder().encode(all) else { return false }+ return store.set(alertsItem, d)+ }++ /// The alerts this device has raised and not yet shown and dismissed.+ static func localAlerts(in store: Store) -> [Alert]? {+ switch store.get(alertsItem) {+ case .found(let d): return try? JSONDecoder().decode([Alert].self, from: d)+ case .absent: return []+ case .unavailable: return nil+ }+ }++ /// Record that `recipient` confirmed receiving `n`. It counts only if it's+ /// in the notice's own snapshotted recipients (removed devices included);+ /// nothing the caller passes can add to or shrink that set.+ @discardableResult+ static func markDelivered(_ n: Notice, to recipient: String, now: Int, in store: Store) -> Bool {+ guard var l = pendingNotices(in: store),+ let i = l.firstIndex(where: { $0.state == n.state && $0.device == n.device }),+ l[i].recipients.contains(recipient) else { return false }+ l[i].deliveredTo.insert(recipient)+ return save(l.filter { !isDone($0, now: now) }, in: store)+ }++ /// Clear notices whose silent devices have timed out (only once the address+ /// has confirmed). Run when the agent checks its outbox.+ @discardableResult+ static func sweepNotices(now: Int, in store: Store) -> Bool {+ guard let l = pendingNotices(in: store) else { return false }+ return save(l.filter { !isDone($0, now: now) }, in: store)+ }++ private static func save(_ l: [Notice], in store: Store) -> Bool {+ guard let d = try? JSONEncoder().encode(l) else { return false }+ return store.set(outboxItem, d)+ }++ private static func access(_ role: Role) throws -> SecAccessControl {+ let flags: SecAccessControlCreateFlags = role == .consent ? [.privateKeyUsage, .userPresence] : [.privateKeyUsage]+ guard let ac = SecAccessControlCreateWithFlags(nil, kSecAttrAccessibleWhenUnlockedThisDeviceOnly, flags, nil)+ else { throw Failure.unavailable }+ return ac+ }++ private static func mint(_ role: Role, enclave: Bool) throws -> (DeviceKey, Data) {+ if enclave {+ let k = try SecureEnclave.P256.Signing.PrivateKey(accessControl: access(role))+ return (wrap(role, k), k.dataRepresentation)+ }+ #if targetEnvironment(simulator) || BENTO_SOFTWARE_DEVICE_KEYS+ let k = P256.Signing.PrivateKey()+ return (wrapSoftware(role, k), k.rawRepresentation)+ #else+ // A real device with no Secure Enclave isn't a supported identity+ // device: device keys are hardware or nothing.+ throw Failure.unavailable+ #endif+ }++ private static func load(_ role: Role, _ blob: Data, enclave: Bool) throws -> DeviceKey {+ if enclave {+ guard let k = try? SecureEnclave.P256.Signing.PrivateKey(dataRepresentation: blob) else { throw Failure.unavailable }+ return wrap(role, k)+ }+ #if targetEnvironment(simulator) || BENTO_SOFTWARE_DEVICE_KEYS+ guard let k = try? P256.Signing.PrivateKey(rawRepresentation: blob) else { throw Failure.unavailable }+ return wrapSoftware(role, k)+ #else+ throw Failure.unavailable+ #endif+ }++ private static func wrap(_ role: Role, _ k: SecureEnclave.P256.Signing.PrivateKey) -> DeviceKey {+ DeviceKey(role: role, publicRaw: k.publicKey.x963Representation) { msg, ctx in+ do {+ // The consent key's presence check is the chip's, run with this+ // context's prompt text. Without a context it prompts by itself.+ let key = ctx.flatMap { try? SecureEnclave.P256.Signing.PrivateKey(dataRepresentation: k.dataRepresentation, authenticationContext: $0) } ?? k+ return try key.signature(for: msg).rawRepresentation+ } catch let e as NSError where e.code == Int(errSecUserCanceled) || e.code == LAError.userCancel.rawValue || e.code == LAError.appCancel.rawValue {+ throw Failure.declined+ } catch {+ throw role == .consent ? Failure.declined : Failure.unavailable+ }+ }+ }++ #if targetEnvironment(simulator) || BENTO_SOFTWARE_DEVICE_KEYS+ private static func wrapSoftware(_ role: Role, _ k: P256.Signing.PrivateKey) -> DeviceKey {+ DeviceKey(role: role, publicRaw: k.publicKey.x963Representation) { msg, ctx in+ if role == .consent {+ // the stand-in for the chip's .userPresence: an explicit check+ let c = ctx ?? LAContext()+ var err: NSError?+ guard c.canEvaluatePolicy(.deviceOwnerAuthentication, error: &err) else { throw Failure.declined }+ let sem = DispatchSemaphore(value: 0)+ var passed = false+ c.evaluatePolicy(.deviceOwnerAuthentication, localizedReason: "Confirm with bento/home") { ok, _ in passed = ok; sem.signal() }+ sem.wait()+ guard passed else { throw Failure.declined }+ }+ return try k.signature(for: msg).rawRepresentation+ }+ }+ #endif++ // MARK: encodings++ /// The P-256 group order n.+ private static let n: [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]+ /// n / 2+ private static let halfN: [UInt8] = [+ 0x7F, 0xFF, 0xFF, 0xFF, 0x80, 0x00, 0x00, 0x00, 0x7F, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF,+ 0xDE, 0x73, 0x7D, 0x56, 0xD3, 0x8B, 0xCF, 0x42, 0x79, 0xDC, 0xE5, 0x61, 0x7E, 0x31, 0x92, 0xA8]++ /// Normalise s to the lower half: (r, s) and (r, n − s) are both valid, and+ /// the contract promises the low one, so a signature has ONE form.+ static func lowS(_ sig: Data) -> Data {+ guard sig.count == 64 else { return sig }+ let r = Array(sig.prefix(32)), s = Array(sig.suffix(32))+ guard s.lexicographicallyPrecedes(halfN) == false, s != halfN else { return sig }+ var out = [UInt8](repeating: 0, count: 32), borrow = 0+ for i in stride(from: 31, through: 0, by: -1) {+ var d = Int(n[i]) - Int(s[i]) - borrow+ borrow = d < 0 ? 1 : 0+ if d < 0 { d += 256 }+ out[i] = UInt8(d)+ }+ return Data(r + out)+ }++ static func b64url(_ d: Data) -> String {+ d.base64EncodedString().replacingOccurrences(of: "+", with: "-")+ .replacingOccurrences(of: "/", with: "_").replacingOccurrences(of: "=", with: "")+ }+}diff --git a/home/ios/IdentityStatements.swift b/home/ios/IdentityStatements.swiftnew file mode 100644index 00000000..49db2ec8--- /dev/null+++ b/home/ios/IdentityStatements.swift@@ -0,0 +1,459 @@+// SPDX-License-Identifier: MIT+// Copyright (c) 2026 The Bento authors++import CryptoKit+import Foundation++/// bento/id's signed statements, in Swift: the same bytes as+/// kernel/src/statements.ts and kernel/src/address.ts, the reference every host+/// must match. The conformance contract is kernel/fixtures/identity-v1.json;+/// scripts/test-home-id-statements.mjs runs this file against every row of it.+///+/// The family rules, briefly:+/// - A statement is dot-joined printable ASCII, signed over its exact bytes.+/// - A field is a closed token or base64url free text.+/// - Parsing keeps empty fields and requires the exact field count.+/// - Keys are raw 65-byte P-256 points.+/// - Signatures are raw r‖s, low-S.+/// - Times are epoch milliseconds.+///+/// The check ORDER follows the reference too, so a refusal gives the same+/// reason everywhere, not just the same verdict.+enum IdentityStatements {+ struct Verdict<T> {+ let value: T?+ let reason: String?+ var ok: Bool { value != nil }+ static func yes(_ v: T) -> Verdict { Verdict(value: v, reason: nil) }+ static func no(_ r: String) -> Verdict { Verdict(value: nil, reason: r) }+ }++ // MARK: strict base64url++ static func b64uEnc(_ d: Data) -> String {+ d.base64EncodedString().replacingOccurrences(of: "+", with: "-")+ .replacingOccurrences(of: "/", with: "_").replacingOccurrences(of: "=", with: "")+ }++ /// Canonical base64url only: the alphabet, no padding, and it must re-encode+ /// to exactly the same string.+ static func b64uDec(_ s: String) -> Data? {+ guard s.utf8.allSatisfy({ isB64u($0) }), s.utf8.count % 4 != 1 else { return nil }+ let pad = String(repeating: "=", count: (4 - s.utf8.count % 4) % 4)+ guard let d = Data(base64Encoded: s.replacingOccurrences(of: "-", with: "+").replacingOccurrences(of: "_", with: "/") + pad),+ b64uEnc(d) == s else { return nil }+ return d+ }++ private static func isB64u(_ c: UInt8) -> Bool {+ (c >= 0x41 && c <= 0x5A) || (c >= 0x61 && c <= 0x7A) || (c >= 0x30 && c <= 0x39) || c == 0x2D || c == 0x5F+ }++ private static func freeText(_ f: String) -> String? {+ guard let b = b64uDec(f), let t = String(data: b, encoding: .utf8), b64uEnc(Data(t.utf8)) == f else { return nil }+ return t+ }++ /// Display text a person sees (a name, a device label), as the kernel+ /// defines it:+ /// - at most 64 code points, and in NFC+ /// - nothing in the frozen `IdentityDisplayTable` (Unicode 17.0, not the+ /// platform's categories, so every host refuses the same characters)+ /// - ZWNJ/ZWJ only mid-text+ static func displayText(_ f: String) -> String? {+ guard let t = freeText(f), !t.isEmpty else { return nil }+ let cps = Array(t.unicodeScalars)+ guard cps.count <= 64 else { return nil }+ // NFC needs Unicode 17.0 data (fixtures/README). Where the platform's is+ // older, refuse rather than normalise with the wrong tables.+ guard platformUnicodeIs17 else { return nil }+ // compare SCALARS: String == is canonical equivalence, which would call+ // a decomposed é equal to the composed one+ guard Array(t.precomposedStringWithCanonicalMapping.unicodeScalars) == cps else { return nil }+ guard !cps.contains(where: { IdentityDisplayTable.forbidden($0.value) }) else { return nil }+ let zw: Set<UInt32> = [0x200C, 0x200D]+ guard !zw.contains(cps[0].value), !zw.contains(cps[cps.count - 1].value) else { return nil }+ return t+ }++ /// Whether the platform's normaliser (ICU) has Unicode 17.0 or later data.+ static let platformUnicodeIs17: Bool = {+ typealias GetVersion = @convention(c) (UnsafeMutablePointer<UInt8>) -> Void+ guard let h = dlopen("/usr/lib/libicucore.dylib", RTLD_NOW), let sym = dlsym(h, "u_getUnicodeVersion") else { return false }+ var v = [UInt8](repeating: 0, count: 4)+ unsafeBitCast(sym, to: GetVersion.self)(&v)+ return v[0] >= 17+ }()++ static func sha256b64u(_ text: String) -> String { b64uEnc(Data(SHA256.hash(data: Data(text.utf8)))) }++ // MARK: keys and signatures++ private static let n: [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]+ private static let halfN: [UInt8] = [+ 0x7F, 0xFF, 0xFF, 0xFF, 0x80, 0x00, 0x00, 0x00, 0x7F, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF,+ 0xDE, 0x73, 0x7D, 0x56, 0xD3, 0x8B, 0xCF, 0x42, 0x79, 0xDC, 0xE5, 0x61, 0x7E, 0x31, 0x92, 0xA8]++ /// big-endian compare of equal-length byte strings+ private static func cmp(_ a: [UInt8], _ b: [UInt8]) -> Int {+ for i in 0..<a.count where a[i] != b[i] { return a[i] < b[i] ? -1 : 1 }+ return 0+ }++ /// A raw r‖s signature in range, with s in the lower half.+ private static func sigInRange(_ sig: Data) -> Bool {+ guard sig.count == 64 else { return false }+ let r = Array(sig.prefix(32)), s = Array(sig.suffix(32)), zero = [UInt8](repeating: 0, count: 32)+ return cmp(r, zero) > 0 && cmp(r, n) < 0 && cmp(s, zero) > 0 && cmp(s, halfN) <= 0+ }++ /// The low-S form (what every signer must emit). Same as IdentityKeys.lowS.+ static func lowS(_ sig: Data) -> Data { IdentityKeys.lowS(sig) }++ static func signingKey(_ b64: String) -> P256.Signing.PublicKey? {+ guard let raw = b64uDec(b64), raw.count == 65, raw.first == 0x04 else { return nil }+ return try? P256.Signing.PublicKey(x963Representation: raw)+ }+ static func isSigningKey(_ b64: String) -> Bool { signingKey(b64) != nil }+ static func isKxKey(_ b64: String) -> Bool {+ guard let raw = b64uDec(b64), raw.count == 65, raw.first == 0x04 else { return false }+ return (try? P256.KeyAgreement.PublicKey(x963Representation: raw)) != nil+ }++ static func verifyStatementSig(_ pubB64: String, _ sigB64: String, _ text: String) -> Bool {+ guard let sig = b64uDec(sigB64), sigInRange(sig), let key = signingKey(pubB64),+ let s = try? P256.Signing.ECDSASignature(rawRepresentation: sig) else { return false }+ return key.isValidSignature(s, for: Data(text.utf8))+ }++ // MARK: strict parsing++ private static let maxStatement = 4096++ /// Printable ASCII only, exact prefix and field count, empty fields kept.+ private static func fields(_ text: String, _ prefix: String, _ count: Int) -> [String]? {+ let bytes = Array(text.utf8)+ guard !bytes.isEmpty, bytes.count <= maxStatement, bytes.allSatisfy({ $0 >= 0x21 && $0 <= 0x7E }) else { return nil }+ let parts = text.components(separatedBy: ".")+ return parts.count == count && parts[0] == prefix ? parts : nil+ }++ private static func int(_ f: String) -> Int? {+ let b = Array(f.utf8)+ guard !b.isEmpty, b.count <= 16, b.allSatisfy({ $0 >= 0x30 && $0 <= 0x39 }), !(b.count > 1 && b[0] == 0x30),+ let v = Int(f), v <= 9_007_199_254_740_991 else { return nil }+ return v+ }+ private static func ms(_ f: String) -> Int? { int(f).flatMap { $0 > 0 ? $0 : nil } }+ private static func isHash(_ f: String) -> Bool { b64uDec(f)?.count == 32 }++ private static func matches(_ s: String, _ pattern: String) -> Bool {+ s.range(of: pattern, options: .regularExpression) != nil+ }+ private static func isKid(_ s: String) -> Bool { matches(s, "^[a-z0-9][a-z0-9-]{0,62}$") }+ private static func isRp(_ s: String) -> Bool { matches(s, "^(bento|vault-[a-z0-9][a-z0-9-]{0,62})$") }+ static func isDocId(_ s: String) -> Bool { matches(s, "^[A-Za-z0-9_-]{1,128}$") }+ private static func isCode(_ s: String) -> Bool { matches(s, "^[23456789ABCDEFGHJKMNPQRSTUVWXYZ]{8}$") }+ private static func isAudience(_ s: String) -> Bool { matches(s, "^(dir|room:w[A-Za-z0-9_-]{43})$") }++ static let skewMs = 5 * 60_000+ private static let day = 86_400_000+ static let certMaxMs = Int((13 * 30.5 + 1) * Double(day))++ private static func lifetime(_ created: Int, _ expires: Int, _ now: Int) -> String? {+ if expires <= created { return "lifetime" }+ if expires - created > certMaxMs { return "lifetime" }+ if created > now + skewMs { return "not-yet-valid" }+ if now >= expires { return "expired" }+ return nil+ }++ // MARK: kx placement (unruled, identity-design §6b)++ enum KxMode: String { case unruled, A, B, C }+ /// Until the maintainer rules, BOTH slots must be empty.+ static let kxMode: KxMode = .unruled+ private static func kxRule(_ m: KxMode) -> (bind: Bool, dev: Bool) { // true = required+ switch m { case .unruled: return (false, false); case .A: return (true, false); case .B: return (false, true); case .C: return (true, true) }+ }+ /// nil = empty and allowed; .some(key) = present and valid; throws-as-false via `ok`+ private static func kxSlot(_ f: String, required: Bool, others: [String]) -> (ok: Bool, kx: String?) {+ if !required { return (f.isEmpty, nil) }+ if f.isEmpty || !isKxKey(f) || others.contains(f) { return (false, nil) }+ return (true, f)+ }++ // MARK: dev. — the device certificate++ struct DeviceCert: Equatable {+ let devicePub: String+ let consentPub: String?+ let accountPub: String+ let kx: String?+ let label: String?+ let created: Int+ let expires: Int+ }++ static func buildDev(_ c: DeviceCert) -> String {+ ["dev", c.devicePub, c.consentPub ?? "", c.accountPub, c.kx ?? "",+ c.label.map { b64uEnc(Data($0.utf8)) } ?? "", String(c.created), String(c.expires)].joined(separator: ".")+ }++ static func verifyDev(_ text: String, _ sig: String, now: Int, kxMode m: KxMode = kxMode) -> Verdict<DeviceCert> {+ guard let p = fields(text, "dev", 8) else { return .no("grammar") }+ let devicePub = p[1], consentF = p[2], accountPub = p[3], kxF = p[4], labelF = p[5]+ guard isSigningKey(devicePub), isSigningKey(accountPub) else { return .no("key") }+ if devicePub == accountPub { return .no("key") }+ var consentPub: String?+ if !consentF.isEmpty {+ guard isSigningKey(consentF), consentF != devicePub, consentF != accountPub else { return .no("consent-key") }+ consentPub = consentF+ }+ let kx = kxSlot(kxF, required: kxRule(m).dev, others: [devicePub, accountPub, consentF])+ guard kx.ok else { return .no("kx") }+ var label: String?+ if !labelF.isEmpty { guard let l = displayText(labelF) else { return .no("label") }; label = l }+ guard let created = ms(p[6]), let expires = ms(p[7]) else { return .no("grammar") }+ if let life = lifetime(created, expires, now) { return .no(life) }+ guard verifyStatementSig(accountPub, sig, text) else { return .no("signature") }+ return .yes(DeviceCert(devicePub: devicePub, consentPub: consentPub, accountPub: accountPub, kx: kx.kx, label: label, created: created, expires: expires))+ }++ // MARK: bind. — the person certificate++ struct BindCert: Equatable {+ let address: String+ let accountPub: String+ let kx: String?+ let name: String?+ let seq: Int+ let prev: String?+ let created: Int+ let expires: Int+ }++ static func buildBind(_ c: BindCert) -> String {+ ["bind", b64uEnc(Data(c.address.utf8)), c.accountPub, c.kx ?? "", c.name.map { b64uEnc(Data($0.utf8)) } ?? "",+ String(c.seq), c.prev ?? "", String(c.created), String(c.expires)].joined(separator: ".")+ }++ static func verifyBind(_ text: String, _ sig: String, now: Int, kxMode m: KxMode = kxMode) -> Verdict<BindCert> {+ guard let p = fields(text, "bind", 9) else { return .no("grammar") }+ guard let address = freeText(p[1]), isNormalAddress(address) else { return .no("address") }+ let accountPub = p[2]+ guard isSigningKey(accountPub) else { return .no("key") }+ let kx = kxSlot(p[3], required: kxRule(m).bind, others: [accountPub])+ guard kx.ok else { return .no("kx") }+ var name: String?+ if !p[4].isEmpty { guard let nm = displayText(p[4]) else { return .no("name") }; name = nm }+ guard let seq = int(p[5]), seq >= 1 else { return .no("seq") }+ let prevF = p[6]+ if (seq == 1) != prevF.isEmpty { return .no("prev") }+ if !prevF.isEmpty && !isHash(prevF) { return .no("prev") }+ guard let created = ms(p[7]), let expires = ms(p[8]) else { return .no("grammar") }+ if let life = lifetime(created, expires, now) { return .no(life) }+ guard verifyStatementSig(accountPub, sig, text) else { return .no("signature") }+ return .yes(BindCert(address: address, accountPub: accountPub, kx: kx.kx, name: name, seq: seq,+ prev: prevF.isEmpty ? nil : prevF, created: created, expires: expires))+ }++ // MARK: att. — the directory's attestation++ struct Attestation: Equatable {+ let bindHash: String+ let verifiedAt: Int+ let issuedAt: Int+ let kid: String+ let state: String+ }++ static func buildAtt(_ a: Attestation) -> String {+ ["att", a.bindHash, String(a.verifiedAt), String(a.issuedAt), a.kid, a.state].joined(separator: ".")+ }++ static func verifyAtt(_ text: String, _ sig: String, directoryKeys: [String: String], bindText: String,+ now: Int, maxAgeMs: Int) -> Verdict<Attestation> {+ guard let p = fields(text, "att", 6) else { return .no("grammar") }+ let bindHash = p[1], kid = p[4], state = p[5]+ guard isHash(bindHash), isKid(kid) else { return .no("grammar") }+ guard ["active", "pending", "frozen"].contains(state) else { return .no("grammar") }+ guard let verifiedAt = ms(p[2]), let issuedAt = ms(p[3]), verifiedAt <= issuedAt else { return .no("grammar") }+ if issuedAt > now + skewMs { return .no("not-yet-valid") }+ if now - issuedAt > maxAgeMs { return .no("stale") }+ if bindHash != sha256b64u(bindText) { return .no("bind-mismatch") }+ guard let dk = directoryKeys[kid] else { return .no("unknown-kid") }+ guard verifyStatementSig(dk, sig, text) else { return .no("signature") }+ return .yes(Attestation(bindHash: bindHash, verifiedAt: verifiedAt, issuedAt: issuedAt, kid: kid, state: state))+ }++ // MARK: tomb. — the directory's deletion record++ struct Tombstone: Equatable {+ let lastBindHash: String?+ let seq: Int+ let deletedAt: Int+ let by: String+ let kid: String+ }++ static func buildTomb(_ t: Tombstone) -> String {+ ["tomb", t.lastBindHash ?? "", String(t.seq), String(t.deletedAt), t.by, t.kid].joined(separator: ".")+ }++ static func verifyTomb(_ text: String, _ sig: String, directoryKeys: [String: String], now: Int) -> Verdict<Tombstone> {+ guard let p = fields(text, "tomb", 6) else { return .no("grammar") }+ let hashF = p[1], by = p[4], kid = p[5]+ if !hashF.isEmpty && !isHash(hashF) { return .no("grammar") }+ guard let seq = int(p[2]), seq >= 1, let deletedAt = ms(p[3]) else { return .no("grammar") }+ guard ["holder", "mailbox", "operator"].contains(by) else { return .no("grammar") }+ guard isKid(kid) else { return .no("grammar") }+ if deletedAt > now + skewMs { return .no("not-yet-valid") }+ guard let dk = directoryKeys[kid] else { return .no("unknown-kid") }+ guard verifyStatementSig(dk, sig, text) else { return .no("signature") }+ return .yes(Tombstone(lastBindHash: hashF.isEmpty ? nil : hashF, seq: seq, deletedAt: deletedAt, by: by, kid: kid))+ }++ // MARK: del. — a holder's delete request++ static let deleteWindowMs = 5 * 60_000++ static func buildDel(address: String, ts: Int) -> String { ["del", b64uEnc(Data(address.utf8)), String(ts)].joined(separator: ".") }++ static func verifyDel(_ text: String, _ sig: String, accountPub: String, now: Int) -> Verdict<(address: String, ts: Int)> {+ guard let p = fields(text, "del", 3) else { return .no("grammar") }+ guard let address = freeText(p[1]), isNormalAddress(address) else { return .no("address") }+ guard let ts = ms(p[2]) else { return .no("grammar") }+ if abs(now - ts) > deleteWindowMs { return .no("expired") }+ guard verifyStatementSig(accountPub, sig, text) else { return .no("signature") }+ return .yes((address, ts))+ }++ // MARK: cmp. — the email-code completion++ static func buildCmp(bindHash: String, code: String) -> String { ["cmp", bindHash, code].joined(separator: ".") }++ static func verifyCmp(_ text: String, _ sig: String, accountPub: String, bindText: String) -> Verdict<(bindHash: String, code: String)> {+ guard let p = fields(text, "cmp", 3) else { return .no("grammar") }+ let bindHash = p[1], code = p[2]+ guard isHash(bindHash), isCode(code) else { return .no("grammar") }+ if bindHash != sha256b64u(bindText) { return .no("bind-mismatch") }+ guard verifyStatementSig(accountPub, sig, text) else { return .no("signature") }+ return .yes((bindHash, code))+ }++ // MARK: cns. — host-stamped consent++ /// The closed set of consent purposes, and the statement family each authorises.+ static let consentFamily: [String: String] = ["invite": "inv.", "revoke": "rev.", "link": "dev.", "rotate": "bind.", "unbind": "del."]+ private static let reservedPurposes: Set<String> = ["grant", "role"]+ private static let docScoped: Set<String> = ["invite", "revoke"]+ static let consentMaxTtlMs = 5 * 60_000++ /// The channel binding (security §24): who verifies, the single-use challenge+ /// they issued, and the exact statement being authorised.+ static func consentTranscript(audience: String, challenge: String, payloadText: String) -> String? {+ guard isAudience(audience), let c = b64uDec(challenge), c.count >= 16, c.count <= 64 else { return nil }+ return sha256b64u("cnst.v1.\(audience).\(challenge).\(sha256b64u(payloadText))")+ }++ struct Consent: Equatable {+ let rp: String+ let purpose: String+ let docId: String?+ let transcript: String+ let exp: Int+ }++ /// `cns.<rp>.<purpose>.<docId|empty>.<transcript>.<exp>`, every field host-stamped.+ static func buildConsent(_ c: Consent) -> String {+ ["cns", c.rp, c.purpose, c.docId ?? "", c.transcript, String(c.exp)].joined(separator: ".")+ }++ static func verifyConsent(_ text: String, _ sig: String, consentPub: String, rp: String, audience: String,+ challenge: String, payloadText: String, docId: String?, now: Int,+ spend: (String) -> Bool) -> Verdict<Consent> {+ guard let p = fields(text, "cns", 6) else { return .no("grammar") }+ if !spend(challenge) { return .no("replay") }+ let rpF = p[1], purposeF = p[2], docIdF = p[3], transcript = p[4]+ guard isRp(rpF), isHash(transcript) else { return .no("grammar") }+ if reservedPurposes.contains(purposeF) { return .no("reserved-purpose") }+ guard let family = consentFamily[purposeF] else { return .no("grammar") }+ guard let exp = ms(p[5]) else { return .no("grammar") }+ if rpF != rp { return .no("rp") }+ if !payloadText.hasPrefix(family) { return .no("payload-family") }+ if docScoped.contains(purposeF) {+ if !isDocId(docIdF) || docIdF != docId { return .no("docid") }+ } else if !docIdF.isEmpty || docId != nil { return .no("docid") }+ guard let expected = consentTranscript(audience: audience, challenge: challenge, payloadText: payloadText),+ transcript == expected else { return .no("transcript") }+ if now >= exp { return .no("expired") }+ if exp - now > consentMaxTtlMs { return .no("lifetime") }+ guard verifyStatementSig(consentPub, sig, text) else { return .no("signature") }+ return .yes(Consent(rp: rpF, purpose: purposeF, docId: docIdF.isEmpty ? nil : docIdF, transcript: transcript, exp: exp))+ }++ /// The light tier's WebAuthn challenge for a consent: b64u(SHA-256(exact cns. bytes)).+ static func webauthnChallenge(for cnsText: String) -> String { sha256b64u(cnsText) }++ // MARK: routine signing — what each SignPurpose may sign++ private static func b64Len(_ f: String, min: Int, exact: Int? = nil) -> Bool {+ guard let b = b64uDec(f) else { return false }+ return exact.map { b.count == $0 } ?? (b.count >= min)+ }+ private static func isPubField(_ f: String) -> Bool { guard let b = b64uDec(f) else { return false }; return b.count == 65 && b.first == 0x04 }+ private static func iv(_ f: String) -> Bool { b64Len(f, min: 0, exact: 12) }+ private static func ct(_ f: String) -> Bool { b64Len(f, min: 16) }++ /// Does `payload` have the exact shape of the statement `purpose` names? The+ /// agent signs only a matching payload, so a prompt for one kind of action can+ /// never yield a signature on another.+ static func payloadMatchesPurpose(_ purpose: String, _ payload: String) -> Bool {+ guard payload.utf16.count <= maxStatement else { return false }+ let p = payload.components(separatedBy: ".")+ switch purpose {+ case "frame": return p.count == 2 && iv(p[0]) && ct(p[1])+ case "prove": return p.count == 3 && p[0] == "prove" && b64Len(p[1], min: 16) && matches(p[2], "^[rw][A-Za-z0-9_-]{1,64}$")+ case "delegate": return p.count == 2 && p[0] == "dlg" && isPubField(p[1])+ case "show":+ return (p.count == 1 && (p[0] == "live" || p[0] == "end")) ||+ (p.count == 4 && (p[0] == "nav" || p[0] == "black") && p[1] == "aud" && iv(p[2]) && ct(p[3]))+ case "invite": return p.count == 4 && p[0] == "inv" && isPubField(p[1]) &&+ ["writer", "commenter", "audience"].contains(p[2]) && matches(p[3], "^(0|[1-9][0-9]{0,15})$")+ case "revoke": return p.count == 2 && p[0] == "rev" && isPubField(p[1])+ default: return false+ }+ }++ // MARK: addresses (kernel/src/address.ts)++ enum Address: Equatable { case ok(String), refused(String) }++ static func normalizeAddress(_ input: String) -> Address {+ let s = input.trimmingCharacters(in: .whitespacesAndNewlines)+ if s.utf16.count > 254 { return .refused("too-long") }+ for c in s.utf16 where c < 0x21 || c > 0x7E { return .refused("not-ascii") }+ let chars = Array(s)+ guard let at = chars.firstIndex(of: "@"), at > 0, at == chars.lastIndex(of: "@"), at != chars.count - 1+ else { return .refused("at-sign") }+ let local = String(chars[..<at]).lowercased(), domain = String(chars[(at + 1)...]).lowercased()+ if local.utf16.count > 64 { return .refused("too-long") }+ for atom in local.components(separatedBy: ".") where !matches(atom, "^[a-z0-9!#$%&'*+/=?^_`{|}~-]+$") {+ return .refused("local-part")+ }+ let labels = domain.components(separatedBy: ".")+ if labels.count < 2 { return .refused("domain") }+ for l in labels {+ if l.isEmpty || l.utf16.count > 63 { return .refused("domain") }+ if !matches(l, "^[a-z0-9-]+$") { return .refused("domain") }+ if l.hasPrefix("-") || l.hasSuffix("-") { return .refused("domain") }+ }+ if matches(labels[labels.count - 1], "^[0-9]+$") { return .refused("numeric-tld") }+ return .ok("\(local)@\(domain)")+ }++ static func isNormalAddress(_ s: String) -> Bool { normalizeAddress(s) == .ok(s) }+}diff --git a/scripts/test-home-id-agent.mjs b/scripts/test-home-id-agent.mjsnew file mode 100644index 00000000..571c219b--- /dev/null+++ b/scripts/test-home-id-agent.mjs@@ -0,0 +1,156 @@+#!/usr/bin/env node+// SPDX-License-Identifier: MIT+// Copyright (c) 2026 The Bento authors+/**+ * bento/id on iOS and the Mac — the agent's sign() and host-stamped consent+ * (home/ios/IdentityAgent.swift).+ *+ * node scripts/test-home-id-agent.mjs+ *+ * WHY. A consent signature is only as good as the context it binds, and the+ * HOST stamps that context: the RP, the docId it read from the file, the+ * verifier's audience and challenge, and the expiry. The page names only what+ * to sign and for which purpose. This checks that a stamped cns. verifies under+ * the kernel-conformant verifier exactly when it should, and is refused when:+ * - relayed to another audience+ * - replayed+ * - applied to a swapped payload+ * - applied to another document+ * It also checks sign()'s routing:+ * - a mismatched purpose is refused before any key is touched+ * - routine purposes sign with the routine key+ * - consent is refused without an identity, a verifier or presence+ * Consent signing itself needs a person present, so the rig signs the stamped+ * text with a test key to check the verifier side.+ *+ * Apple platforms only; 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 = ['HostDocStore.swift', 'IdentityKeys.swift', 'IdentityDisplayTable.swift', 'IdentityStatements.swift', process.env.ID_AGENT_SRC || 'IdentityAgent.swift']+ .map((f) => f.includes('/') ? f : join(ROOT, 'home/ios', f))+// Apple platforms only: the Linux CI runner has swiftc but no CryptoKit, Security+// or LocalAuthentication, so probe for xcrun, which only Apple toolchains ship.+try { execFileSync('xcrun', ['--find', 'swiftc'], { stdio: 'pipe' }) } catch { console.log('home id agent: SKIPPED — needs an Apple toolchain (CryptoKit, Security).'); process.exit(0) }++const main = String.raw`+import CryptoKit+import Foundation+import LocalAuthentication+final class Mem: HostDocStore.Secrets {+ var d: [String: Data] = [:]+ func get(_ a: String) -> HostDocStore.Read { 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 }+}+func e(_ k: String, _ v: Any) { print("\(k)=\(v)") }+typealias A = IdentityAgent+typealias S = IdentityStatements+let now = 1_800_000_000_000+let challenge = S.b64uEnc(Data(repeating: 7, count: 24))+let dir = A.Verifier(audience: "dir", challenge: challenge)+let realPub = S.b64uEnc(P256.Signing.PrivateKey().publicKey.x963Representation)+let invite = "inv.\(realPub).writer.1800000000000"+let docId = "7025b63c-733c-404b-ba00-7fb4becf38df"++// stamping: every field the host's own+let cns = A.stampConsent(purpose: "invite", payload: invite, docId: docId, verifier: dir, now: now)!+let f = cns.components(separatedBy: ".")+e("stamp.fields", f.count == 6 && f[0] == "cns" && f[1] == "bento" && f[2] == "invite" && f[3] == docId && Int(f[5])! == now + S.consentMaxTtlMs)+e("stamp.transcript", f[4] == S.consentTranscript(audience: "dir", challenge: challenge, payloadText: invite)!)+let k = P256.Signing.PrivateKey(), kp = S.b64uEnc(k.publicKey.x963Representation)+let sig = S.b64uEnc(S.lowS(try! k.signature(for: Data(cns.utf8)).rawRepresentation))+func verify(audience: String = "dir", payload: String = invite, doc: String? = docId, spent: Bool = false, at: Int = now) -> String {+ let v = S.verifyConsent(cns, sig, consentPub: kp, rp: "bento", audience: audience, challenge: challenge,+ payloadText: payload, docId: doc, now: at, spend: { _ in !spent })+ return v.ok ? "accept" : "reject:\(v.reason!)"+}+e("verify.ok", verify())+e("verify.relay", verify(audience: "room:w" + String(repeating: "A", count: 43)))+e("verify.replay", verify(spent: true))+e("verify.payloadswap", verify(payload: "inv.\(realPub).audience.1800000000000"))+e("verify.docswap", verify(doc: "another-document"))+e("verify.expired", verify(at: now + S.consentMaxTtlMs))+e("stamp.nodoc", A.stampConsent(purpose: "invite", payload: invite, docId: nil, verifier: dir, now: now) == nil)+e("stamp.baddoc", A.stampConsent(purpose: "invite", payload: invite, docId: "a/b", verifier: dir, now: now) == nil)+e("stamp.family", A.stampConsent(purpose: "revoke", payload: invite, docId: docId, verifier: dir, now: now) == nil)+e("stamp.badaudience", A.stampConsent(purpose: "invite", payload: invite, docId: docId, verifier: .init(audience: "evil.example", challenge: challenge), now: now) == nil)+e("stamp.shortchallenge", A.stampConsent(purpose: "invite", payload: invite, docId: docId, verifier: .init(audience: "dir", challenge: S.b64uEnc(Data(count: 8))), now: now) == nil)+e("stamp.ttl", A.stampConsent(purpose: "invite", payload: invite, docId: docId, verifier: dir, now: now, ttlMs: S.consentMaxTtlMs + 1) == nil)+let link = A.stampConsent(purpose: "link", payload: "dev.x", docId: docId, verifier: dir, now: now) ?? ""+let lf = link.components(separatedBy: ".")+e("stamp.linkNoDoc", lf.count == 6 && lf[3] == "")++// sign(): routing+let m = Mem()+let noCtx = LAContext(); noCtx.interactionNotAllowed = true+let host = A.HostContext(docId: docId, verifier: dir, deviceName: "iPhone", devices: ["devA"], now: now, domainState: { nil }, presence: noCtx)+func r(_ x: Result<A.Signed, A.Refusal>) -> String {+ switch x {+ case .success(let s): if case .routine = s { return "routine" }; return "consent"+ case .failure(let f): return "refuse:\(f.rawValue)"+ }+}+let prove = "prove.\(challenge).wROOM"+e("sign.noIdentity", r(A.sign(purpose: "prove", payload: prove, host: host, store: m, enclave: false)))+_ = try! IdentityKeys.createAccount(in: m)+e("sign.badshape", r(A.sign(purpose: "prove", payload: "rev.\(realPub)", host: host, store: m, enclave: false)))+e("sign.unknownPurpose", r(A.sign(purpose: "link", payload: "dev.x", host: host, store: m, enclave: false)))+let rs = A.sign(purpose: "prove", payload: prove, host: host, store: m, enclave: false)+e("sign.routine", r(rs))+if case .success(.routine(let s1, let p1)) = rs, let pk = try? P256.Signing.PublicKey(x963Representation: S.b64uDec(p1)!),+ let es = try? P256.Signing.ECDSASignature(rawRepresentation: S.b64uDec(s1)!) {+ e("sign.routineVerifies", pk.isValidSignature(es, for: Data(prove.utf8)))+} else { e("sign.routineVerifies", false) }+let noVerifier = A.HostContext(docId: docId, verifier: nil, deviceName: "iPhone", devices: ["devA"], now: now, domainState: { nil }, presence: noCtx)+e("sign.consentNoVerifier", r(A.sign(purpose: "invite", payload: invite, host: noVerifier, store: m, enclave: false)))+e("sign.consentNoPresence", r(A.sign(purpose: "invite", payload: invite, host: host, store: m, enclave: false)))+e("sign.freshNoNotice", (IdentityKeys.pendingNotices(in: m) ?? []).count)+// a consent key from before the check (no recorded enrolment): CHANGED, notice queued before the refusal+let legacy = Mem(); _ = try! IdentityKeys.createAccount(in: legacy)+_ = try! IdentityKeys.device(.consent, in: legacy, enclave: false, domainState: { nil })+legacy.delete(IdentityKeys.enrolmentItem)+_ = A.sign(purpose: "invite", payload: invite, host: host, store: legacy, enclave: false)+e("sign.legacyNotice", (IdentityKeys.pendingNotices(in: legacy) ?? []).count)+`+const dir = mkdtempSync(join(tmpdir(), 'bento-idagent-'))+let out+try {+ writeFileSync(join(dir, 'main.swift'), main)+ execFileSync('swiftc', ['-O', '-D', 'BENTO_SOFTWARE_DEVICE_KEYS', '-o', join(dir, 'a'), ...SRC, join(dir, 'main.swift')], { stdio: 'pipe' })+ out = Object.fromEntries(execFileSync(join(dir, 'a')).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 {} }++let checks = 0, failures = 0+const ok = (c, m) => { checks++; if (!c) failures++; console.log(` ${c ? 'ok ' : 'FAIL'} ${m}`) }+console.log('host-stamped consent (§2e (A)):')+ok(out['stamp.fields'] === 'true', 'cns. carries the host-stamped rp, purpose, the docId the HOST read, and an expiry within the cap')+ok(out['stamp.transcript'] === 'true', 'and the channel binding to the verifier the host is talking to')+ok(out['verify.ok'] === 'accept', 'the directory accepts it')+ok(out['verify.relay'] === 'reject:transcript', 'RELAYED to another audience: refused')+ok(out['verify.replay'] === 'reject:replay', 'REPLAYED with a spent challenge: refused')+ok(out['verify.payloadswap'] === 'reject:transcript', 'applied to a SWAPPED payload: refused')+ok(out['verify.docswap'] === 'reject:docid', 'applied to ANOTHER DOCUMENT: refused')+ok(out['verify.expired'] === 'reject:expired', 'past its expiry: refused')+ok(out['stamp.nodoc'] === 'true' && out['stamp.baddoc'] === 'true', 'a document-scoped consent needs a valid docId from the host, or nothing is stamped')+ok(out['stamp.family'] === 'true', "a purpose stamped over another family's payload: nothing is stamped")+ok(out['stamp.badaudience'] === 'true' && out['stamp.shortchallenge'] === 'true', 'a bad audience or a short challenge: nothing is stamped')+ok(out['stamp.ttl'] === 'true', 'an expiry past the 5-minute cap: nothing is stamped')+ok(out['stamp.linkNoDoc'] === 'true', 'an account-scoped consent (link) carries no docId, even when the host has one')+console.log('sign() routing:')+ok(out['sign.noIdentity'] === 'refuse:no-identity', 'no identity on the device: no-identity')+ok(out['sign.badshape'] === 'refuse:purpose', "a payload not of its purpose's shape is refused before any key is touched")+ok(out['sign.unknownPurpose'] === 'refuse:purpose', 'a purpose the page may not ask for is refused')+ok(out['sign.routine'] === 'routine' && out['sign.routineVerifies'] === 'true', 'a routine purpose signs with the routine key, verifiably')+ok(out['sign.consentNoVerifier'] === 'refuse:unavailable', 'a consent with no verifier context from the host is refused')+ok(out['sign.consentNoPresence'] === 'refuse:declined', 'a consent without the person present is DECLINED')+ok(out['sign.freshNoNotice'] === '0', "a BRAND-NEW consent key raises no 'biometrics changed' notice: minting records its baseline first")+ok(out['sign.legacyNotice'] === '1', 'a consent key from before the check (no record) is CHANGED: its notice is queued, before the refusal')+console.log(`\n${checks - failures}/${checks} checks passed`)+process.exit(failures ? 1 : 0)diff --git a/scripts/test-home-id-keys.mjs b/scripts/test-home-id-keys.mjsnew file mode 100644index 00000000..637c4378--- /dev/null+++ b/scripts/test-home-id-keys.mjs@@ -0,0 +1,283 @@+#!/usr/bin/env node+// SPDX-License-Identifier: MIT+// Copyright (c) 2026 The Bento authors+/**+ * bento/id on iOS and the Mac — the agent's keys (home/ios/IdentityKeys.swift).+ *+ * node scripts/test-home-id-keys.mjs+ *+ * WHY. The agent's signatures are checked by the relay and the kernel in+ * WebCrypto, so the only proof that the formats are right is WebCrypto+ * accepting them. This compiles the real Swift, signs with the Secure Enclave+ * on this Mac (and with the software stand-in the simulator uses), and verifies+ * every signature in Node's WebCrypto against the public key the agent+ * publishes. It also checks low-S, and that a key is never minted over a+ * store it could not read.+ *+ * Apple platforms only (CryptoKit + Secure Enclave); 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'+import { webcrypto } from 'node:crypto'++const ROOT = resolve(dirname(fileURLToPath(import.meta.url)), '..')+const SRC = [join(ROOT, 'home/ios/HostDocStore.swift'), join(ROOT, process.env.ID_KEYS_SRC || 'home/ios/IdentityKeys.swift')]+// Apple platforms only: the Linux CI runner has swiftc but no CryptoKit, Security+// or LocalAuthentication, so probe for xcrun, which only Apple toolchains ship.+try { execFileSync('xcrun', ['--find', 'swiftc'], { stdio: 'pipe' }) } catch { console.log('home id keys: SKIPPED — needs an Apple toolchain (CryptoKit, Security).'); process.exit(0) }++const main = String.raw`+import CryptoKit+import Foundation+import LocalAuthentication+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 }+}+func e(_ k: String, _ v: Any) { print("\(k)=\(v)") }+let b = IdentityKeys.b64url+let msgs = ["prove.n0nce.wROOM", "inv.BPUB.editor.1760000000", String(repeating: "x", count: 5000)]+for enclave in (SecureEnclave.isAvailable ? [true, false] : [false]) {+ let tag = enclave ? "se" : "sw"+ let m = Mem()+ // account: absent → no-identity; create → present; a second create is refused+ do { _ = try IdentityKeys.account(in: m); e("\(tag).acct.absent", "minted?!") } catch { e("\(tag).acct.absent", error as! IdentityKeys.Failure == .noIdentity) }+ let acct = try! IdentityKeys.createAccount(in: m)+ e("\(tag).acct.again", (try? IdentityKeys.createAccount(in: m)) == nil)+ e("\(tag).acct.same", (try! IdentityKeys.account(in: m)).publicKey.rawRepresentation == acct.publicKey.rawRepresentation)+ e("\(tag).acctpub", b(acct.publicKey.x963Representation))+ for (i, msg) in msgs.enumerated() { e("\(tag).acctsig\(i)", b(IdentityKeys.lowS(try! acct.signature(for: Data(msg.utf8)).rawRepresentation))) }+ // routine device key: mint once, the same key after reload+ let r = try! IdentityKeys.device(.routine, in: m, enclave: enclave)+ let r2 = try! IdentityKeys.device(.routine, in: m, enclave: enclave)+ e("\(tag).routine.stable", r.publicRaw == r2.publicRaw)+ e("\(tag).routinepub", b(r.publicRaw))+ for (i, msg) in msgs.enumerated() { e("\(tag).routinesig\(i)", b(try! r2.sign(Data(msg.utf8)))) }+ // 200 more signatures: every one low-S (the raw chip output is high-S about half the time)+ var all: [String] = []+ for i in 0..<200 { all.append(b(try! r.sign(Data("m\(i)".utf8)))) }+ e("\(tag).many", all.joined(separator: ","))+ // consent: refused without presence+ let c = try! IdentityKeys.device(.consent, in: m, enclave: enclave)+ e("\(tag).consent.distinct", c.publicRaw != r.publicRaw)+ let ctx = LAContext(); ctx.interactionNotAllowed = true+ do { _ = try c.sign(Data("rev.X".utf8), context: ctx); e("\(tag).consent.nopresence", "SIGNED") } catch { e("\(tag).consent.nopresence", (error as? IdentityKeys.Failure) == .declined) }+ // never mint while blind+ m.failReads = true+ do { _ = try IdentityKeys.device(.routine, in: m, enclave: enclave); e("\(tag).blind.device", "minted") } catch { e("\(tag).blind.device", (error as? IdentityKeys.Failure) == .unavailable) }+ do { _ = try IdentityKeys.createAccount(in: m); e("\(tag).blind.account", "minted") } catch { e("\(tag).blind.account", (error as? IdentityKeys.Failure) == .unavailable) }+ m.failReads = false+ e("\(tag).blind.kept", (try! IdentityKeys.device(.routine, in: m, enclave: enclave)).publicRaw == r.publicRaw)+}+// The biometric enrolment tripwire, with the domain state injected (a real+// device's "different face" can't be simulated; gaining or losing them can).+do {+ let m = Mem(), X = Data("faceX".utf8), Y = Data("faceY".utf8)+ _ = try! IdentityKeys.device(.consent, in: m, enclave: false, domainState: { X })+ e("trip.same", IdentityKeys.checkEnrolment(X, in: m) == .unchanged)+ e("trip.other", IdentityKeys.checkEnrolment(Y, in: m) == .changed)+ e("trip.lost", IdentityKeys.checkEnrolment(nil, in: m) == .changed)+ // through the gate, as the agent does: queue the notice, then accept+ _ = IdentityKeys.enrolmentGate(Y, device: "iPhone", devices: ["devA"], now: 1, in: m)+ IdentityKeys.acceptEnrolment(Y, in: m)+ e("trip.accepted", IdentityKeys.checkEnrolment(Y, in: m) == .unchanged && IdentityKeys.checkEnrolment(X, in: m) == .changed)+ let n0 = Mem()+ _ = try! IdentityKeys.device(.consent, in: n0, enclave: false, domainState: { nil })+ e("trip.gained", IdentityKeys.checkEnrolment(X, in: n0) == .changed && IdentityKeys.checkEnrolment(nil, in: n0) == .unchanged)+ let legacy = Mem()+ e("trip.norecord", IdentityKeys.checkEnrolment(X, in: legacy) == .changed)+ legacy.failReads = true+ e("trip.unreadable", IdentityKeys.checkEnrolment(X, in: legacy) == .unknown)+}+// The notice comes first, and survives a kill before acceptance (§29).+do {+ let m = Mem(), X = Data("faceX".utf8), Y = Data("faceY".utf8)+ _ = try! IdentityKeys.device(.consent, in: m, enclave: false, domainState: { X })+ e("gate.same", IdentityKeys.enrolmentGate(X, device: "iPhone", devices: ["devA", "devB"], now: 1, in: m) == .proceed)+ e("gate.noaccept.before", !IdentityKeys.acceptEnrolment(Y, in: m) && IdentityKeys.checkEnrolment(Y, in: m) == .changed)+ e("gate.changed", IdentityKeys.enrolmentGate(Y, device: "iPhone", devices: ["devA", "devB", "devC"], now: 2, in: m) == .reconfirm)+ e("gate.queued", (IdentityKeys.pendingNotices(in: m) ?? []).count == 1)+ // the agent is killed here, before acceptEnrolment. A fresh process, the same store:+ let restarted = m+ e("gate.survives", (IdentityKeys.pendingNotices(in: restarted) ?? []).count == 1 && IdentityKeys.checkEnrolment(Y, in: restarted) == .changed)+ e("gate.idempotent", IdentityKeys.enrolmentGate(Y, device: "iPhone", devices: ["devA", "devB", "devC"], now: 3, in: restarted) == .reconfirm && (IdentityKeys.pendingNotices(in: restarted) ?? []).count == 1)+ e("gate.accept", IdentityKeys.acceptEnrolment(Y, in: restarted) && IdentityKeys.enrolmentGate(Y, device: "iPhone", devices: ["devA", "devB", "devC"], now: 4, in: restarted) == .proceed)+ e("gate.stillqueued", (IdentityKeys.pendingNotices(in: restarted) ?? []).count == 1)+ let D = 86_400_000+ if let n = IdentityKeys.pendingNotices(in: restarted)?.first {+ e("snap.recipients", n.recipients == ["devA", "devB", "devC", "address"])+ // the thief removes devB and devC from the device list: nothing here changes+ _ = IdentityKeys.markDelivered(n, to: "devA", now: 10, in: restarted)+ _ = IdentityKeys.markDelivered(n, to: "address", now: 10, in: restarted)+ e("snap.partial", (IdentityKeys.pendingNotices(in: restarted) ?? []).count == 1)+ e("snap.stranger", !IdentityKeys.markDelivered(n, to: "mallory", now: 10, in: restarted))+ e("snap.removedStillCounts", IdentityKeys.markDelivered(n, to: "devB", now: 11, in: restarted) && (IdentityKeys.pendingNotices(in: restarted) ?? []).count == 1)+ IdentityKeys.sweepNotices(now: 2 + 6 * D, in: restarted)+ e("snap.beforeTimeout", (IdentityKeys.pendingNotices(in: restarted) ?? []).count == 1)+ IdentityKeys.sweepNotices(now: 2 + 7 * D, in: restarted)+ e("snap.afterTimeout", IdentityKeys.pendingNotices(in: restarted)?.isEmpty ?? false)+ } else { for k in ["snap.recipients", "snap.partial", "snap.stranger", "snap.removedStillCounts", "snap.beforeTimeout", "snap.afterTimeout"] { e(k, "no notice queued") } }+ // §29 point 4: the reverse order — drop the victim's devices FIRST, then add a face+ do {+ let L = Mem(); _ = try! IdentityKeys.device(.consent, in: L, enclave: false, domainState: { X })+ let before: Set<String> = ["devA", "devB", "devC"], after: Set<String> = ["devA"]+ e("list.blockedBeforeQueue", !IdentityKeys.mayPublishDeviceList(before: before, after: after, in: L))+ e("list.queued", IdentityKeys.queueDeviceListChange(before: before, after: after, by: "devA", now: 1, in: L)+ && IdentityKeys.mayPublishDeviceList(before: before, after: after, in: L))+ // now the thief adds a face: its snapshot excludes B and C …+ _ = IdentityKeys.enrolmentGate(Y, device: "devA", devices: after, now: 2, in: L)+ let notes = IdentityKeys.pendingNotices(in: L) ?? []+ let listNote = notes.first { $0.kind == "devices-changed" }, faceNote = notes.first { $0.kind == "biometrics-changed" }+ e("list.toBefore", listNote?.recipients == ["devA", "devB", "devC", "address"])+ e("list.faceExcludes", faceNote.map { !$0.recipients.contains("devB") } ?? false)+ // … but B and C still receive the list-change notice, and it waits for them+ if let ln = listNote {+ _ = IdentityKeys.markDelivered(ln, to: "devA", now: 3, in: L); _ = IdentityKeys.markDelivered(ln, to: "address", now: 3, in: L)+ e("list.waitsForRemoved", (IdentityKeys.pendingNotices(in: L) ?? []).contains { $0.kind == "devices-changed" })+ _ = IdentityKeys.markDelivered(ln, to: "devB", now: 3, in: L); _ = IdentityKeys.markDelivered(ln, to: "devC", now: 3, in: L)+ e("list.removedGetIt", !(IdentityKeys.pendingNotices(in: L) ?? []).contains { $0.kind == "devices-changed" })+ } else { e("list.waitsForRemoved", "none"); e("list.removedGetIt", "none") }+ e("list.idempotent", IdentityKeys.queueDeviceListChange(before: ["devA", "devB"], after: ["devA"], by: "devA", now: 5, in: L)+ && IdentityKeys.queueDeviceListChange(before: ["devA", "devB"], after: ["devA"], by: "devA", now: 6, in: L)+ && (IdentityKeys.pendingNotices(in: L) ?? []).filter { $0.kind == "devices-changed" }.count == 1)+ }+ // the receiver's own check: a HOSTILE publisher skips the gate entirely+ do {+ let B = Mem() // device B's own store+ e("recv.baseline", IdentityKeys.observeDeviceList(["devA", "devB", "devC"], signedBy: "devA", me: "devB", now: 1, in: B) == [])+ // devA publishes A,B,C → A without ever calling queueDeviceListChange / mayPublishDeviceList+ let got = IdentityKeys.observeDeviceList(["devA"], signedBy: "devA", me: "devB", now: 2, in: B) ?? []+ e("recv.self", got.contains { $0.kind == .thisDeviceRemoved && $0.device == "devB" && $0.by == "devA" })+ e("recv.other", got.contains { $0.kind == .deviceRemoved && $0.device == "devC" && $0.by == "devA" })+ e("recv.durable", (IdentityKeys.localAlerts(in: B) ?? []).count == got.count && got.count == 2)+ let C = Mem() // device C removed devD itself: no alert for that one+ _ = IdentityKeys.observeDeviceList(["devC", "devD"], signedBy: "devC", me: "devC", now: 1, in: C)+ e("recv.ownRemoval", IdentityKeys.observeDeviceList(["devC"], signedBy: "devC", me: "devC", removedHere: ["devD"], now: 2, in: C) == [])+ let U = Mem(); _ = IdentityKeys.observeDeviceList(["devA", "devB"], signedBy: "devA", me: "devB", now: 1, in: U); U.failReads = true+ e("recv.blind", IdentityKeys.observeDeviceList(["devA"], signedBy: "devA", me: "devB", now: 2, in: U) == nil)+ U.failReads = false+ e("recv.blindKeepsBaseline", (IdentityKeys.observeDeviceList(["devA"], signedBy: "devA", me: "devB", now: 3, in: U) ?? []).contains { $0.kind == .thisDeviceRemoved })+ }+ // "can't tell" (locked out, hardware unavailable) is NOT "no biometrics"+ do {+ let L = Mem(), X = Data("faceX".utf8)+ _ = try! IdentityKeys.device(.consent, in: L, enclave: false, domainState: { X })+ let ct = IdentityKeys.cantTell+ e("ct.check", IdentityKeys.checkEnrolment(ct, in: L) == .unknown)+ e("ct.gate", IdentityKeys.enrolmentGate(ct, device: "iPhone", devices: ["devA"], now: 1, in: L) == .refuse && (IdentityKeys.pendingNotices(in: L) ?? []).isEmpty)+ e("ct.noBaseline", !IdentityKeys.recordEnrolment(ct, in: L) && IdentityKeys.checkEnrolment(X, in: L) == .unchanged)+ let F = Mem()+ var threw = false+ do { _ = try IdentityKeys.device(.consent, in: F, enclave: false, domainState: { ct }) } catch { threw = true }+ e("ct.noMint", threw && F.get(IdentityKeys.deviceItem(.consent)) == .absent)+ e("ct.map", IdentityKeys.reading(canEvaluate: true, errorCode: nil, state: X) == X+ && IdentityKeys.reading(canEvaluate: false, errorCode: -7, state: nil) == nil+ && IdentityKeys.reading(canEvaluate: false, errorCode: -8, state: nil) == ct+ && IdentityKeys.reading(canEvaluate: false, errorCode: -6, state: nil) == ct+ && IdentityKeys.reading(canEvaluate: true, errorCode: nil, state: nil) == ct)+ }+ // without the address it NEVER clears, however long and however many devices confirm+ do {+ let a = Mem(); _ = try! IdentityKeys.device(.consent, in: a, enclave: false, domainState: { X })+ _ = IdentityKeys.enrolmentGate(Y, device: "iPhone", devices: ["devA", "devB"], now: 1, in: a)+ if let n = IdentityKeys.pendingNotices(in: a)?.first {+ _ = IdentityKeys.markDelivered(n, to: "devA", now: 2, in: a); _ = IdentityKeys.markDelivered(n, to: "devB", now: 2, in: a)+ IdentityKeys.sweepNotices(now: 1 + 30 * D, in: a)+ e("anchor.never", (IdentityKeys.pendingNotices(in: a) ?? []).count == 1)+ _ = IdentityKeys.markDelivered(n, to: "address", now: 1 + 30 * D, in: a)+ e("anchor.then", IdentityKeys.pendingNotices(in: a)?.isEmpty ?? false)+ } else { e("anchor.never", "none"); e("anchor.then", "none") }+ }+ let f = Mem(); _ = try! IdentityKeys.device(.consent, in: f, enclave: false, domainState: { X }); f.failReads = true+ e("gate.blind", IdentityKeys.enrolmentGate(Y, device: "iPhone", devices: ["devA", "devB", "devC"], now: 5, in: f) == .refuse)+}+`+const dir = mkdtempSync(join(tmpdir(), 'bento-idkeys-'))+let out+try {+ writeFileSync(join(dir, 'main.swift'), main)+ execFileSync('swiftc', ['-O', '-D', 'BENTO_SOFTWARE_DEVICE_KEYS', '-o', join(dir, 'k'), ...SRC, join(dir, 'main.swift')], { stdio: 'pipe' })+ out = Object.fromEntries(execFileSync(join(dir, 'k'), { maxBuffer: 1 << 26 }).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 d64 = (s) => Buffer.from(s.replace(/-/g, '+').replace(/_/g, '/'), 'base64')+const halfN = BigInt('0x7FFFFFFF800000007FFFFFFFFFFFFFFFDE737D56D38BCF4279DCE5617E3192A8')+const lowS = (sig) => BigInt('0x' + d64(sig).subarray(32).toString('hex')) <= halfN+const msgs = ['prove.n0nce.wROOM', 'inv.BPUB.editor.1760000000', 'x'.repeat(5000)]+async function verify(pubB64, sigB64, msg) {+ const key = await webcrypto.subtle.importKey('raw', d64(pubB64), { name: 'ECDSA', namedCurve: 'P-256' }, false, ['verify'])+ return webcrypto.subtle.verify({ name: 'ECDSA', hash: 'SHA-256' }, key, d64(sigB64), Buffer.from(msg))+}+let checks = 0, failures = 0+const ok = (c, m) => { checks++; if (!c) failures++; console.log(` ${c ? 'ok ' : 'FAIL'} ${m}`) }+for (const tag of ['se', 'sw'].filter((t) => out[`${t}.routinepub`])) {+ const name = tag === 'se' ? 'Secure Enclave' : 'software stand-in (simulator)'+ console.log(`${name}:`)+ ok(out[`${tag}.acct.absent`] === 'true', 'no account key yet reads as no-identity, and nothing is minted')+ ok(out[`${tag}.acct.again`] === 'true' && out[`${tag}.acct.same`] === 'true', 'the account key is created once; a second create is refused, never a replacement')+ ok(d64(out[`${tag}.routinepub`]).length === 65 && d64(out[`${tag}.routinepub`])[0] === 4, 'a device public key is the 65-byte uncompressed point (WebCrypto raw)')+ let v = true+ for (let i = 0; i < msgs.length; i++) {+ v &&= await verify(out[`${tag}.acctpub`], out[`${tag}.acctsig${i}`], msgs[i])+ v &&= await verify(out[`${tag}.routinepub`], out[`${tag}.routinesig${i}`], msgs[i])+ v &&= d64(out[`${tag}.routinesig${i}`]).length === 64+ }+ ok(v, 'WebCrypto verifies the account and routine signatures: raw r‖s, 64 bytes')+ const many = out[`${tag}.many`].split(',')+ let mv = true; for (let i = 0; i < many.length; i++) mv &&= await verify(out[`${tag}.routinepub`], many[i], `m${i}`)+ ok(mv && many.every(lowS), `200 more signatures all verify, and every one is LOW-S`)+ ok(out[`${tag}.routine.stable`] === 'true', 'the routine key is the same key after a reload')+ ok(out[`${tag}.consent.distinct`] === 'true', 'the consent key is a separate key')+ ok(out[`${tag}.consent.nopresence`] === 'true', 'the consent key REFUSES to sign without presence')+ ok(out[`${tag}.blind.device`] === 'true' && out[`${tag}.blind.account`] === 'true', 'a store that cannot be read never gets a key minted over it')+ ok(out[`${tag}.blind.kept`] === 'true', 'and the existing device key is still the one in use afterwards')+}+console.log('the notice comes first (§29):')+ok(out['gate.same'] === 'true', 'an unchanged enrolment proceeds')+ok(out['gate.noaccept.before'] === 'true', 'a new enrolment cannot be ACCEPTED before its notice is queued')+ok(out['gate.changed'] === 'true' && out['gate.queued'] === 'true', 'a change queues the notice durably, then asks for re-confirmation')+ok(out['gate.survives'] === 'true', 'killed before acceptance: on restart the notice is still queued and the state still not accepted')+ok(out['gate.idempotent'] === 'true', 'the gate after a restart neither drops nor repeats the notice')+ok(out['gate.accept'] === 'true' && out['gate.stillqueued'] === 'true', 'accepting after re-confirmation leaves the notice queued until it is SENT')+ok(out['snap.recipients'] === 'true', 'the recipients are SNAPSHOTTED when the notice is queued: the devices listed then, plus the address')+ok(out['snap.partial'] === 'true', 'a partial delivery leaves the notice queued')+ok(out['snap.stranger'] === 'true', "a confirmation from someone who isn't a recipient is ignored")+ok(out['snap.removedStillCounts'] === 'true', 'devices REMOVED from the list after queuing are still recipients, and still hold the notice back')+ok(out['snap.beforeTimeout'] === 'true', 'a snapshotted device that never confirms still holds it back at 6 days')+ok(out['snap.afterTimeout'] === 'true', 'and stops holding it back at 7 days, once the address has confirmed')+ok(out['list.blockedBeforeQueue'] === 'true', 'a device-list change may NOT be published before its notice is queued')+ok(out['list.queued'] === 'true', 'once queued, it may')+ok(out['list.toBefore'] === 'true', 'the list-change notice goes to the list as it was BEFORE the change, plus the address')+ok(out['list.faceExcludes'] === 'true', 'the reverse-order attack: the later face notice really does exclude the dropped devices…')+ok(out['list.waitsForRemoved'] === 'true' && out['list.removedGetIt'] === 'true', '…but the dropped devices still receive the list-change notice, which waits for them')+ok(out['list.idempotent'] === 'true', 'queuing the same change twice queues one notice')+ok(out['recv.baseline'] === 'true', "the receiver's first fetch only records the list")+ok(out['recv.self'] === 'true', 'a hostile publisher skips the gate and drops B: B raises its OWN alert on its next fetch, naming who did it')+ok(out['recv.other'] === 'true', 'and alerts for every other device it did not remove itself')+ok(out['recv.durable'] === 'true', 'the alerts are recorded durably')+ok(out['recv.ownRemoval'] === 'true', 'a removal this device made itself raises nothing')+ok(out['recv.blind'] === 'true' && out['recv.blindKeepsBaseline'] === 'true', "an unreadable baseline is never replaced blind: the next good read still sees the removal")+ok(out['ct.check'] === 'true', "a reading that can't be made (lockout, hardware) is UNKNOWN, not 'no biometrics'")+ok(out['ct.gate'] === 'true', 'so the gate refuses the consent, and raises NO false notice')+ok(out['ct.noBaseline'] === 'true', 'it is never recorded as a baseline; the real one stands')+ok(out['ct.noMint'] === 'true', 'and no consent key is minted under it (its first consent would be a false alarm)')+ok(out['ct.map'] === 'true', 'the mapping: a state is that state; not-enrolled (-7) is none; lockout (-8), unavailable (-6) and an empty success are unknown')+ok(out['anchor.never'] === 'true', 'without the ADDRESS a notice never clears, whatever the devices do and however long')+ok(out['anchor.then'] === 'true', 'and clears once the address confirms')+ok(out['gate.blind'] === 'true', "a record or outbox that can't be read refuses the consent")+console.log('biometric enrolment tripwire (§29):')+ok(out['trip.same'] === 'true', 'the enrolment the consent key was created under reads unchanged')+ok(out['trip.other'] === 'true', 'a different enrolment is CHANGED (notify every device, re-confirm)')+ok(out['trip.lost'] === 'true', 'biometrics removed is CHANGED')+ok(out['trip.gained'] === 'true', 'biometrics added where there were none is CHANGED')+ok(out['trip.accepted'] === 'true', 'after a re-confirmed consent the new enrolment is the baseline, and the old one would now be a change')+ok(out['trip.norecord'] === 'true', 'a consent key with no recorded enrolment (made before the check) is CHANGED, re-confirmed once')+ok(out['trip.unreadable'] === 'true', 'a record that cannot be read is UNKNOWN — the consent is refused, the check never skipped')+console.log(`\n${checks - failures}/${checks} checks passed`)+process.exit(failures ? 1 : 0)diff --git a/scripts/test-home-id-statements.mjs b/scripts/test-home-id-statements.mjsnew file mode 100644index 00000000..ee69c914--- /dev/null+++ b/scripts/test-home-id-statements.mjs@@ -0,0 +1,132 @@+#!/usr/bin/env node+// SPDX-License-Identifier: MIT+// Copyright (c) 2026 The Bento authors+/**+ * bento/id on iOS and the Mac — the Swift statements against the conformance+ * contract, kernel/fixtures/identity-v1.json.+ *+ * node scripts/test-home-id-statements.mjs (ID_FIXTURE=<path> to point elsewhere)+ *+ * WHY. Every host's statement code must reach the stated verdict on every row+ * (kernel/fixtures/README.md); two hosts reading the same bytes differently+ * would make one signature mean two things. This compiles the real+ * home/ios/IdentityStatements.swift and runs the same checks as the kernel's+ * own runner (scripts/test-statements.ts):+ * - verdict AND reason on every statement row+ * - accepted rows rebuild to the exact text and refuse a flipped signature+ * bit, an extra field and a changed byte+ * - the consent transcripts and the WebAuthn challenge+ * - low-S pairs, routine purposes, and address normal forms+ * It re-reads the fixture every run and pins nothing: a regeneration changes+ * signatures, not verdicts.+ *+ * Apple platforms only (CryptoKit); skips elsewhere.+ */+import { execFileSync } from 'node:child_process'+import { existsSync, 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 FIXTURE = process.env.ID_FIXTURE || join(ROOT, 'kernel/fixtures/identity-v1.json')+const SRC = ['HostDocStore.swift', 'IdentityKeys.swift', 'IdentityDisplayTable.swift', process.env.ID_STATEMENTS_SRC || 'IdentityStatements.swift'].map((f) => f.includes('/') ? f : join(ROOT, 'home/ios', f))+if (!existsSync(FIXTURE)) { console.log(`home id statements: the fixture is missing (${FIXTURE}) — it lands with K2.`); process.exit(1) }+// Apple platforms only: the Linux CI runner has swiftc but no CryptoKit, Security+// or LocalAuthentication, so probe for xcrun, which only Apple toolchains ship.+try { execFileSync('xcrun', ['--find', 'swiftc'], { stdio: 'pipe' }) } catch { console.log('home id statements: SKIPPED — needs an Apple toolchain (CryptoKit, Security).'); process.exit(0) }++const main = String.raw`+import Foundation+typealias S = IdentityStatements+let F = try! JSONSerialization.jsonObject(with: Data(contentsOf: URL(fileURLWithPath: CommandLine.arguments[1]))) as! [String: Any]+let keys = F["keys"] as! [String: String], dirKeys = F["directoryKeys"] as! [String: String]+let fNow = (F["now"] as! NSNumber).intValue+var checks = 0, fails = 0+var spendCalled = false+func ok(_ c: Bool, _ m: String) { checks += 1; if !c { fails += 1 }; print("\(c ? " ok " : " FAIL") \(m)") }+func check(_ r: [String: Any], _ text: String, _ sig: String) -> (Bool, String?, String?) {+ let now = (r["now"] as? NSNumber)?.intValue ?? fNow+ let kx = S.KxMode(rawValue: (r["kxMode"] as? String) ?? (F["kxModeDefault"] as! String)) ?? .unruled+ switch r["type"] as! String {+ case "dev": let v = S.verifyDev(text, sig, now: now, kxMode: kx); return (v.ok, v.reason, v.value.map(S.buildDev))+ case "bind": let v = S.verifyBind(text, sig, now: now, kxMode: kx); return (v.ok, v.reason, v.value.map(S.buildBind))+ case "att": let v = S.verifyAtt(text, sig, directoryKeys: dirKeys, bindText: r["bindText"] as! String, now: now, maxAgeMs: (r["maxAgeMs"] as! NSNumber).intValue); return (v.ok, v.reason, v.value.map(S.buildAtt))+ case "tomb": let v = S.verifyTomb(text, sig, directoryKeys: dirKeys, now: now); return (v.ok, v.reason, v.value.map(S.buildTomb))+ case "del": let v = S.verifyDel(text, sig, accountPub: keys["account"]!, now: now); return (v.ok, v.reason, v.value.map { S.buildDel(address: $0.address, ts: $0.ts) })+ case "cmp": let v = S.verifyCmp(text, sig, accountPub: keys["account"]!, bindText: r["bindText"] as! String); return (v.ok, v.reason, v.value.map { S.buildCmp(bindHash: $0.bindHash, code: $0.code) })+ case "cns":+ let spent = (r["challengeSpent"] as? Bool) ?? false+ spendCalled = false+ let v = S.verifyConsent(text, sig, consentPub: keys["consent"]!, rp: r["rp"] as! String, audience: r["audience"] as! String,+ challenge: r["challenge"] as! String, payloadText: r["payloadText"] as! String, docId: r["docId"] as? String, now: now,+ spend: { _ in spendCalled = true; return !spent })+ return (v.ok, v.reason, v.value.map(S.buildConsent))+ default: return (false, "unknown-type", nil)+ }+}+let rows = F["statements"] as! [[String: Any]]+print("every statement row: verdict and reason (\(rows.count))")+for r in rows {+ let (accepted, reason, _) = check(r, r["text"] as! String, r["sig"] as! String)+ let want = (r["expect"] as! String) == "accept" ? "accept" : "reject:\(r["reason"] as? String ?? "?")"+ let got = accepted ? "accept" : "reject:\(reason ?? "?")"+ ok(got == want, "\(r["name"] as! String) → \(want)\(got == want ? "" : " (got \(got))")")+ if let wantSpend = r["spendCalled"] as? Bool {+ ok(spendCalled == wantSpend, "\(r["name"] as! String): the challenge is \(wantSpend ? "" : "NOT ")spent")+ }+}+print("the embedded display table is the fixture's, exactly")+let tbl = F["displayForbidden"] as! [String: Any]+let fixtureFlat = (tbl["ranges"] as! [[Int]]).flatMap { $0 }.map(UInt32.init)+ok(IdentityDisplayTable.flat == fixtureFlat && IdentityDisplayTable.unicode == (tbl["unicode"] as! String), "IdentityDisplayTable matches displayForbidden (\(fixtureFlat.count / 2) ranges, Unicode \(IdentityDisplayTable.unicode))")+ok(S.platformUnicodeIs17, "this platform's normaliser has Unicode 17.0 data (where it doesn't, display text is refused)")+print("accepted rows round-trip and refuse tampering")+for r in rows where (r["expect"] as! String) == "accept" {+ let text = r["text"] as! String, sig = r["sig"] as! String, t = r["type"] as! String+ let (a, _, rebuilt) = check(r, text, sig)+ guard a else { continue }+ ok(rebuilt == text, "\(t): the builder reproduces the exact text")+ var s = S.b64uDec(sig)!; s[10] ^= 0x01+ ok(!check(r, text, S.b64uEnc(s)).0, "\(t): a flipped signature bit is refused")+ ok(!check(r, text + ".x", sig).0, "\(t): an extra field is refused")+ var cs = Array(text); let i = cs.count - 2; cs[i] = cs[i] == "1" ? "2" : "1"+ ok(!check(r, String(cs), sig).0, "\(t): one changed byte of text is refused")+}+print("derivations")+for t in F["transcripts"] as! [[String: Any]] {+ let got = S.consentTranscript(audience: t["audience"] as! String, challenge: t["challenge"] as! String, payloadText: t["payload"] as! String)+ ok(got == (t["transcript"] as? String), "transcript(\(t["audience"] as! String)) \(t["transcript"] is NSNull ? "→ refused (\(t["note"] as? String ?? ""))" : "→ the fixture value")")+}+for w in F["webauthn"] as! [[String: String]] { ok(S.webauthnChallenge(for: w["cns"]!) == w["challenge"]!, "WebAuthn challenge = b64u(SHA-256(exact cns. bytes))") }+print("low-S")+for (i, p) in (F["lowS"] as! [[String: String]]).enumerated() {+ let text = "dev.lows.\(i)"+ ok(S.verifyStatementSig(keys["account"]!, p["low"]!, text), "pair \(i): the low-S signature verifies")+ ok(!S.verifyStatementSig(keys["account"]!, p["high"]!, text), "pair \(i): its high-S twin is refused")+ ok(S.b64uEnc(S.lowS(S.b64uDec(p["high"]!)!)) == p["low"]! && S.b64uEnc(S.lowS(S.b64uDec(p["low"]!)!)) == p["low"]!, "pair \(i): lowS folds high to low and leaves low alone")+}+print("routine purposes")+for p in F["purposes"] as! [[String: Any]] {+ let pl = p["payload"] as! String, m = p["match"] as! Bool+ ok(S.payloadMatchesPurpose(p["purpose"] as! String, pl) == m, "\(p["purpose"] as! String) \(m ? "accepts" : "refuses") \(pl.prefix(24))")+}+print("addresses")+for a in F["addresses"] as! [[String: Any]] {+ let want: S.Address = (a["address"] as? String).map { .ok($0) } ?? .refused(a["reason"] as! String)+ let got = S.normalizeAddress(a["input"] as! String)+ ok(got == want, "\(String(describing: a["input"]!).prefix(40)) → \(want)\(got == want ? "" : " (got \(got))")")+}+print("\n\(checks - fails)/\(checks) checks passed")+exit(fails == 0 ? 0 : 1)+`+const dir = mkdtempSync(join(tmpdir(), 'bento-idstmt-'))+try {+ writeFileSync(join(dir, 'main.swift'), main)+ execFileSync('swiftc', ['-O', '-o', join(dir, 's'), ...SRC, join(dir, 'main.swift')], { stdio: 'pipe' })+} catch (e) { console.error('swiftc failed:\n' + (e.stderr?.toString() ?? e.message)); rmSync(dir, { recursive: true, force: true }); process.exit(2) }+let code = 0+try { process.stdout.write(execFileSync(join(dir, 's'), [FIXTURE], { maxBuffer: 1 << 26 })) }+catch (e) { process.stdout.write(e.stdout?.toString() ?? ''); code = 1 }+finally { rmSync(dir, { recursive: true, force: true }) }+process.exit(code)