From 35fc180a195a733a18d9f537151a59dee1afa9ca Mon Sep 17 00:00:00 2001 From: Daniel Bejarano Date: Thu, 26 Nov 2026 18:53:20 -0600 Subject: [PATCH 1/2] iOS: a Secure Enclave approval key, so payments and logins can be signed on an iPhone (#125) The iOS approval key module no longer fails closed. It makes a P-256 key in the Secure Enclave with access control [.privateKeyUsage, .biometryCurrentSet], WhenPasscodeSetThisDeviceOnly: Face ID or Touch ID for every signature, no passcode fallback, never a software key. It signs the exact UTF-8 message with ecdsaSignatureMessageX962SHA256 (DER, as Android's SHA256withECDSA) and reports the public key as a P-256 SubjectPublicKeyInfo, so the cage verifies it unchanged. state() reports lost without a prompt when the enrolled biometric set changed. The prompt's words come from ApprovalText.swift, a port of ApprovalText.kt. ApprovalKeyLevel gains secure_enclave, with its line on the approval key screen in both locales. Signed-off-by: Daniel Bejarano --- .../modules/hermit-approval-key/index.ts | 13 +- .../ios/ApprovalText.swift | 197 ++++++++++++ .../ios/HermitApprovalKey.podspec | 5 +- .../ios/HermitApprovalKeyModule.swift | 300 +++++++++++++++++- docs/devices.md | 5 +- packages/cage/test/signed-approval.test.ts | 30 ++ packages/copy/locales/en.json | 1 + packages/copy/locales/es-419.json | 1 + packages/copy/test/copy.test.ts | 9 +- packages/core/src/approval-key.ts | 11 +- packages/runtime/src/approval-key.ts | 6 +- packages/runtime/test/approval-key.test.ts | 19 +- 12 files changed, 565 insertions(+), 32 deletions(-) create mode 100644 apps/mobile/modules/hermit-approval-key/ios/ApprovalText.swift diff --git a/apps/mobile/modules/hermit-approval-key/index.ts b/apps/mobile/modules/hermit-approval-key/index.ts index 17722b7..8ad1c64 100644 --- a/apps/mobile/modules/hermit-approval-key/index.ts +++ b/apps/mobile/modules/hermit-approval-key/index.ts @@ -1,4 +1,5 @@ import { NativeModule, requireNativeModule } from "expo"; +import type { ApprovalKeyLevel } from "@hermit/core"; /** * The only thing JavaScript chooses about the system prompt: which of the module's own languages it speaks. The title, @@ -7,18 +8,18 @@ import { NativeModule, requireNativeModule } from "expo"; export type PromptLocale = "en" | "es-419"; declare class HermitApprovalKeyNative extends NativeModule { - /** The key without a prompt: none, lost (retired by a fingerprint change), no_biometric, or ready with its public part. */ - state(): Promise<{ state: "none" | "lost" | "no_biometric" } | { state: "ready"; publicKey: string; level: "strongbox" | "tee" }>; + /** The key without a prompt: none, lost (retired by a biometric change), no_biometric, or ready with its public part. */ + state(): Promise<{ state: "none" | "lost" | "no_biometric" } | { state: "ready"; publicKey: string; level: ApprovalKeyLevel }>; /** A new key, proven by a fresh strong biometric over `message` (an enrollment challenge). Rejects with a code. */ - enroll(message: string, locale: PromptLocale): Promise<{ publicKey: string; level: "strongbox" | "tee"; signature: string }>; + enroll(message: string, locale: PromptLocale): Promise<{ publicKey: string; level: ApprovalKeyLevel; signature: string }>; /** - * One signature over one approval `message`, inside BiometricPrompt. Rejects with `code`: cancelled, lockout, lost, - * expired, no_biometric, bad_message, busy, no_activity or failed. + * One signature over one approval `message`, inside BiometricPrompt (Android) or Face ID or Touch ID (iOS). Rejects + * with `code`: cancelled, lockout, lost, expired, no_biometric, bad_message, busy, no_activity or failed. */ sign(message: string, locale: PromptLocale): Promise; /** Delete everything (SL-26). Idempotent. */ destroy(): Promise; } -/** SL-37: the Keystore key that signs money and password approvals. Android only. */ +/** SL-37: the key that signs money and password approvals: Android Keystore, or the Secure Enclave on an iPhone. */ export const HermitApprovalKey = requireNativeModule("HermitApprovalKey"); diff --git a/apps/mobile/modules/hermit-approval-key/ios/ApprovalText.swift b/apps/mobile/modules/hermit-approval-key/ios/ApprovalText.swift new file mode 100644 index 0000000..f99ac8a --- /dev/null +++ b/apps/mobile/modules/hermit-approval-key/ios/ApprovalText.swift @@ -0,0 +1,197 @@ +import Foundation + +/** + SL-37 on iOS: what the Face ID or Touch ID prompt says, the same rules as Android's ApprovalText.kt. + + - The title, the button and the labels are this module's own strings, picked by a locale code ("en" or "es-419"); + JavaScript passes no display text at all. + - Every fact (amount, recipient, network, site, and for a login the app, its key and the browser) is read from the very + message being signed, never from a separate display string. + - Control characters, bidi overrides and isolates, zero-width and line separators are stripped from the values, and the + recipient and site are shown in full, never truncated. + */ +enum ApprovalText { + static let approvalDomain = "hermit.approval.v1" + static let enrollDomain = "hermit.approval-key.enroll.v1" + + /** USD₮ has 6 decimals (CT-01). The only asset Hermit pays in (PDR-027). */ + private static let usdtDecimals = 6 + + /** SL-40: the networks the prompt names in words, keyed by the CAIP-2 id in the signed payload only. */ + private static let networkNames = ["eip155:2201": "Stable testnet"] + + struct Approval: Equatable { + let risk: String + let amount: String? + let network: String? + let recipient: String? + let origin: String? + let requester: String? + let expiresAt: Int64 + } + + struct Strings { + let payTitle: String + let passwordTitle: String + let enrollTitle: String + let enrollDescription: String + let cancel: String + let amount: String + let to: String + let network: String + let site: String + let app: String + let appKey: String + let browser: String + } + + private static let en = Strings( + payTitle: "Approve this payment", + passwordTitle: "Approve using this password", + enrollTitle: "Set up your approval key", + enrollDescription: "Payments and passwords will need your fingerprint, every time.", + cancel: "Cancel", + amount: "Amount", + to: "To", + network: "Network", + site: "Site", + app: "App", + appKey: "Signing key", + browser: "Browser" + ) + + private static let es419 = Strings( + payTitle: "Aprueba este pago", + passwordTitle: "Aprueba usar esta contraseña", + enrollTitle: "Configura tu clave de aprobación", + enrollDescription: "Los pagos y las contraseñas pedirán tu huella, cada vez.", + cancel: "Cancelar", + amount: "Monto", + to: "Para", + network: "Red", + site: "Sitio", + app: "App", + appKey: "Clave de firma", + browser: "Navegador" + ) + + /** Only the two locales Hermit ships; anything else is English. */ + static func strings(_ locale: String) -> Strings { locale == "es-419" ? es419 : en } + + /** The payload of an approval message, or nil when it isn't one (wrong domain, not JSON, not USD₮). */ + static func parse(_ message: String) -> Approval? { + let prefix = "\(approvalDomain)\n" + guard message.hasPrefix(prefix), + let data = String(message.dropFirst(prefix.count)).data(using: .utf8), + let o = (try? JSONSerialization.jsonObject(with: data)) as? [String: Any] else { return nil } + guard o["domain"] as? String == approvalDomain, (o["v"] as? NSNumber)?.intValue == 1 else { return nil } + guard let risk = o["risk"] as? String, risk == "spend" || risk == "credential" else { return nil } + var value: String? + var network: String? + if let raw = o["amount"] { + guard let amount = raw as? [String: Any], amount["asset"] as? String == "USDT", + let v = amount["value"] as? String, v.range(of: "^[1-9][0-9]*$", options: .regularExpression) != nil else { return nil } + value = v + network = amount["network"] as? String + } + let recipient = o["recipient"] as? String + let origin = o["origin"] as? String + if o["recipient"] != nil && recipient == nil { return nil } + if o["origin"] != nil && origin == nil { return nil } + if risk == "spend" && (value == nil || recipient == nil) { return nil } + if risk == "credential" && origin == nil { return nil } + return Approval( + risk: risk, amount: value, network: network, recipient: recipient, origin: origin, + requester: o["requester"] as? String, expiresAt: (o["expiresAt"] as? NSNumber)?.int64Value ?? 0 + ) + } + + /** + A value as one visible line: drops control characters (newlines included), format characters (bidi overrides, + isolates, zero-width marks), line or paragraph separators, unassigned, private use and surrogate code points. + Nothing is truncated. + */ + static func clean(_ value: String) -> String { + var out = String.UnicodeScalarView() + for scalar in value.unicodeScalars { + switch scalar.properties.generalCategory { + case .control, .format, .lineSeparator, .paragraphSeparator, .unassigned, .privateUse, .surrogate: continue + default: out.append(scalar) + } + } + return String(out).trimmingCharacters(in: .whitespacesAndNewlines) + } + + /** Base units to a decimal string ("5000000" is "5", "1500000" is "1.5"). Plain digits, never grouped or rounded. */ + static func usdt(_ baseUnits: String) -> String { + let digits = String(repeating: "0", count: max(0, usdtDecimals + 1 - baseUnits.count)) + baseUnits + let whole = String(digits.dropLast(usdtDecimals)) + var fraction = String(digits.suffix(usdtDecimals)) + while fraction.hasSuffix("0") { fraction.removeLast() } + return fraction.isEmpty ? whole : "\(whole).\(fraction)" + } + + /** The name for a CAIP-2 id from the signed payload ("eip155:2201" is "Stable testnet"), else the id itself, cleaned. */ + static func networkName(_ id: String) -> String { networkNames[id] ?? clean(id) } + + static func title(_ a: Approval, _ locale: String) -> String { + let s = strings(locale) + return a.risk == "spend" ? s.payTitle : s.passwordTitle + } + + /** The prompt's description, one fact per line, every value from the signed payload. */ + static func describe(_ a: Approval, _ locale: String) -> String { + let s = strings(locale) + guard a.risk == "spend", let amount = a.amount, let recipient = a.recipient else { return credential(a, s) } + var lines = ["\(s.amount): \(usdt(amount)) USD₮", "\(s.to): \(clean(recipient))"] + if let network = a.network { lines.append("\(s.network): \(networkName(network))") } + return lines.joined(separator: "\n") + } + + /** `android://@`: the cert and the package, or nil. */ + private static func app(_ value: String) -> (cert: String, package: String)? { + guard value.hasPrefix("android://") else { return nil } + let rest = value.dropFirst("android://".count) + guard let at = rest.firstIndex(of: "@") else { return nil } + let cert = rest[rest.startIndex.. String { + let origin = clean(a.origin ?? "") + var lines: [String] = [] + if let app = app(origin) { + lines.append("\(s.app): \(app.package)") + lines.append("\(s.appKey): \(app.cert)") + } else { + lines.append("\(s.site): \(origin)") + } + if let requester = a.requester.map(clean), requester != origin, let via = app(requester) { + lines.append("\(s.browser): \(via.package)") + } + return lines.joined(separator: "\n") + } +} + +/** The key's formats, as the cage reads them (packages/cage/src/signed-approval.ts). */ +enum ApprovalKeyFormat { + /** The DER header of an X.509 SubjectPublicKeyInfo for a P-256 key, before the 65-byte uncompressed point. */ + static let p256SpkiPrefix: [UInt8] = [ + 0x30, 0x59, 0x30, 0x13, 0x06, 0x07, 0x2a, 0x86, 0x48, 0xce, 0x3d, 0x02, 0x01, 0x06, 0x08, 0x2a, 0x86, 0x48, 0xce, 0x3d, + 0x03, 0x01, 0x07, 0x03, 0x42, 0x00, + ] + + static func hex(_ data: Data) -> String { data.map { String(format: "%02x", $0) }.joined() } + + /** + The SubjectPublicKeyInfo of a P-256 public key, from what `SecKeyCopyExternalRepresentation` gives (X9.63: 0x04, X, Y), + so the pinned key reads the same as Android's `getEncoded()`. Nil for anything that isn't a 65-byte uncompressed point. + */ + static func spki(x963: Data) -> Data? { + guard x963.count == 65, x963.first == 0x04 else { return nil } + return Data(p256SpkiPrefix) + x963 + } +} diff --git a/apps/mobile/modules/hermit-approval-key/ios/HermitApprovalKey.podspec b/apps/mobile/modules/hermit-approval-key/ios/HermitApprovalKey.podspec index b8c2f87..104de19 100644 --- a/apps/mobile/modules/hermit-approval-key/ios/HermitApprovalKey.podspec +++ b/apps/mobile/modules/hermit-approval-key/ios/HermitApprovalKey.podspec @@ -1,8 +1,8 @@ Pod::Spec.new do |s| s.name = 'HermitApprovalKey' s.version = '0.1.0' - s.summary = 'On iOS, for now: the approval key fails closed (no key, no signature).' - s.description = 'On iOS, for now: the approval key fails closed (no key, no signature).' + s.summary = 'The approval key in the Secure Enclave: P-256, Face ID or Touch ID for every signature.' + s.description = 'The approval key in the Secure Enclave: P-256, Face ID or Touch ID for every signature.' s.license = 'Apache-2.0' s.author = 'Hermit contributors' s.homepage = 'https://github.com/DojoCodingLabs/hermit' @@ -12,6 +12,7 @@ Pod::Spec.new do |s| s.static_framework = true s.dependency 'ExpoModulesCore' + s.frameworks = 'LocalAuthentication', 'Security' s.source_files = "**/*.swift" s.pod_target_xcconfig = { diff --git a/apps/mobile/modules/hermit-approval-key/ios/HermitApprovalKeyModule.swift b/apps/mobile/modules/hermit-approval-key/ios/HermitApprovalKeyModule.swift index 18aee5e..e9ad158 100644 --- a/apps/mobile/modules/hermit-approval-key/ios/HermitApprovalKeyModule.swift +++ b/apps/mobile/modules/hermit-approval-key/ios/HermitApprovalKeyModule.swift @@ -1,31 +1,309 @@ import ExpoModulesCore +import Foundation +import LocalAuthentication +import Security /** - On iOS, for now: the approval key that signs money and login approvals FAILS CLOSED here. + SL-37 on iOS (US-CAGE-03, FR-CAGE-06, ADR-007): the key that signs money and password approvals, with the same contract + as the Android Keystore key (android/.../HermitApprovalKeyModule.kt). - There is no Secure Enclave key yet, so this module never creates, stores or reports a key, and never signs, with a - software key or any other. `state()` says no key can be made ("no_biometric"), `enroll()` and `sign()` always reject, - and `destroy()` has nothing to delete. Payments and logins therefore stay blocked on iOS, as the cage's hard limits - require. + - EC P-256, made inside the Secure Enclave and never exportable: only the public part is read. There is no software + key, ever: if the Secure Enclave can't make the key, enrollment fails and nothing is stored. + - Its access control is `.privateKeyUsage` and `.biometryCurrentSet` only: Face ID or Touch ID for every signature, no + passcode fallback, and no reuse of an earlier match (each call uses a fresh LAContext, reuse duration 0). + - Adding or removing a face or a finger retires it: the Secure Enclave never signs with it again, and `state` reports + "lost" without a prompt, by comparing the biometric set recorded at enrollment with today's. Money and passwords are + then blocked until the user sets the key up again. + - The signature is ECDSA with SHA-256 over the message's exact UTF-8 bytes, in DER (X9.62), the same bytes Android's + SHA256withECDSA gives; the public key is the X.509 SubjectPublicKeyInfo, as Android's `getEncoded()`. + - Every word of the prompt is chosen here (ApprovalText.swift): its own strings by locale code, and the facts read from + the message being signed. JavaScript passes no display text. */ public class HermitApprovalKeyModule: Module { + private static let tag = Data("hermit.approval-key.v1".utf8) + /** Where the enrolled biometric set is recorded (a Keychain item on this device only, deleted with the key). */ + private static let biometryService = "hermit.approval-key.v1" + private static let biometryAccount = "biometry-set" + private static let level = "secure_enclave" + + private let lock = NSLock() + private var prompting = false + + private struct Failure: Error { + let code: String + let message: String + } + + // MARK: The biometric set + + private enum Biometry { + /** Face ID or Touch ID is enrolled; `set` identifies the enrolled faces or fingers (nil while locked out). */ + case available(set: Data?) + case lockedOut + case none + } + + private func biometry() -> Biometry { + let context = LAContext() + defer { context.invalidate() } + var error: NSError? + if context.canEvaluatePolicy(.deviceOwnerAuthenticationWithBiometrics, error: &error) { + return .available(set: context.evaluatedPolicyDomainState) + } + if let error, error.domain == LAError.errorDomain, error.code == LAError.Code.biometryLockout.rawValue { return .lockedOut } + return .none + } + + private func biometryQuery() -> [String: Any] { + [ + kSecClass as String: kSecClassGenericPassword, + kSecAttrService as String: Self.biometryService, + kSecAttrAccount as String: Self.biometryAccount, + ] + } + + private func enrolledBiometry() -> Data? { + var query = biometryQuery() + query[kSecReturnData as String] = true + var out: CFTypeRef? + guard SecItemCopyMatching(query as CFDictionary, &out) == errSecSuccess else { return nil } + return out as? Data + } + + private func recordBiometry(_ set: Data) -> Bool { + SecItemDelete(biometryQuery() as CFDictionary) + var item = biometryQuery() + item[kSecValueData as String] = set + item[kSecAttrAccessible as String] = kSecAttrAccessibleWhenPasscodeSetThisDeviceOnly + return SecItemAdd(item as CFDictionary, nil) == errSecSuccess + } + + /** True when the faces or fingers enrolled today aren't the ones the key was made under. Unknown counts as changed. */ + private func biometryChanged(_ now: Biometry) -> Bool { + guard let enrolled = enrolledBiometry() else { return true } + switch now { + case .available(let set?): return set != enrolled + // Locked out: the set can't be read now, and the Secure Enclave still refuses a changed set when signing. + case .available(nil), .lockedOut: return false + case .none: return true + } + } + + // MARK: The key + + private enum Lookup { + case found(SecKey) + case missing + case unusable + } + + private func findKey(context: LAContext? = nil) -> Lookup { + var query: [String: Any] = [ + kSecClass as String: kSecClassKey, + kSecAttrKeyClass as String: kSecAttrKeyClassPrivate, + kSecAttrKeyType as String: kSecAttrKeyTypeECSECPrimeRandom, + kSecAttrApplicationTag as String: Self.tag, + kSecReturnRef as String: true, + ] + if let context { query[kSecUseAuthenticationContext as String] = context } + var out: CFTypeRef? + let status = SecItemCopyMatching(query as CFDictionary, &out) + if status == errSecItemNotFound { return .missing } + guard status == errSecSuccess, let ref = out, CFGetTypeID(ref) == SecKeyGetTypeID() else { return .unusable } + let key = ref as! SecKey + return inSecureEnclave(key) ? .found(key) : .unusable + } + + /** A key Hermit would trust: P-256, kept by the Secure Enclave. Anything else is never used. */ + private func inSecureEnclave(_ key: SecKey) -> Bool { + guard let attrs = SecKeyCopyAttributes(key) as? [String: Any] else { return false } + return attrs[kSecAttrTokenID as String] as? String == (kSecAttrTokenIDSecureEnclave as String) + && attrs[kSecAttrKeySizeInBits as String] as? Int == 256 + } + + /** The public part as the cage reads it: the X.509 SubjectPublicKeyInfo, in lowercase hex. */ + private func publicKey(_ key: SecKey) -> String? { + guard let pub = SecKeyCopyPublicKey(key), let x963 = SecKeyCopyExternalRepresentation(pub, nil) as Data?, + let spki = ApprovalKeyFormat.spki(x963: x963) else { return nil } + return ApprovalKeyFormat.hex(spki) + } + + private func destroy() { + let key: [String: Any] = [ + kSecClass as String: kSecClassKey, + kSecAttrKeyClass as String: kSecAttrKeyClassPrivate, + kSecAttrApplicationTag as String: Self.tag, + ] + SecItemDelete(key as CFDictionary) + SecItemDelete(biometryQuery() as CFDictionary) + } + + /** A new key in the Secure Enclave, replacing any old one. Never a software key: no Secure Enclave, no key. */ + private func generate() throws -> SecKey { + destroy() + var error: Unmanaged? + guard let access = SecAccessControlCreateWithFlags( + nil, kSecAttrAccessibleWhenPasscodeSetThisDeviceOnly, [.privateKeyUsage, .biometryCurrentSet], &error + ) else { + throw Failure(code: "failed", message: "No access control for the key.") + } + let attributes: [String: Any] = [ + kSecAttrKeyType as String: kSecAttrKeyTypeECSECPrimeRandom, + kSecAttrKeySizeInBits as String: 256, + kSecAttrTokenID as String: kSecAttrTokenIDSecureEnclave, + kSecPrivateKeyAttrs as String: [ + kSecAttrIsPermanent as String: true, + kSecAttrApplicationTag as String: Self.tag, + kSecAttrAccessControl as String: access, + ] as [String: Any], + ] + guard let key = SecKeyCreateRandomKey(attributes as CFDictionary, &error) else { + throw Failure(code: "no_secure_hardware", message: "This phone can't keep the key in the Secure Enclave.") + } + guard inSecureEnclave(key) else { + throw Failure(code: "no_secure_hardware", message: "This phone can't keep the key in the Secure Enclave.") + } + return key + } + + // MARK: Signing + + /** + One Face ID or Touch ID check, one signature over exactly `message`. The fresh context allows no earlier match and + no passcode; the Secure Enclave checks the key's own access control. Blocks until the prompt is answered. + */ + private func signOnce(_ message: String, reason: String, cancel: String) throws -> String { + let context = LAContext() + defer { context.invalidate() } + context.touchIDAuthenticationAllowableReuseDuration = 0 + context.localizedFallbackTitle = "" + context.localizedCancelTitle = cancel + context.localizedReason = reason + guard case .found(let key) = findKey(context: context) else { throw Failure(code: "lost", message: "No approval key.") } + var error: Unmanaged? + guard let signature = SecKeyCreateSignature(key, .ecdsaSignatureMessageX962SHA256, Data(message.utf8) as CFData, &error) as Data? else { + throw Self.failure(error?.takeRetainedValue()) + } + return ApprovalKeyFormat.hex(signature) + } + + /** What went wrong at the prompt, as the codes the app maps to copy. Anything unexpected is "failed". */ + private static func failure(_ error: CFError?) -> Failure { + guard let cf = error else { return Failure(code: "failed", message: "No signature.") } + let error = cf as Error as NSError + let code: String + if error.domain == LAError.errorDomain { + switch LAError.Code(rawValue: error.code) { + case .userCancel, .appCancel, .systemCancel, .userFallback: code = "cancelled" + case .biometryLockout: code = "lockout" + case .biometryNotAvailable, .biometryNotEnrolled, .passcodeNotSet: code = "no_biometric" + default: code = "failed" + } + } else if error.domain == NSOSStatusErrorDomain { + switch OSStatus(error.code) { + case errSecUserCanceled: code = "cancelled" + case errSecItemNotFound: code = "lost" + default: code = "failed" + } + } else { + code = "failed" + } + return Failure(code: code, message: error.localizedDescription) + } + + private func state() -> [String: Any] { + let now = biometry() + if case .none = now { return ["state": "no_biometric"] } + switch findKey() { + case .missing: return ["state": "none"] + case .unusable: return ["state": "lost"] + case .found(let key): + // Fail closed: a key made under other faces or fingers, or one whose public part can't be read, is lost. + if biometryChanged(now) { return ["state": "lost"] } + guard let pub = publicKey(key) else { return ["state": "lost"] } + return ["state": "ready", "publicKey": pub, "level": Self.level] + } + } + + /** At most one prompt at a time, as on Android ("busy"). The prompt itself runs off the module's queue. */ + private func withPrompt(_ promise: Promise, _ work: @escaping () throws -> Any) { + lock.lock() + if prompting { + lock.unlock() + promise.reject("busy", "A Face ID or Touch ID prompt is already open.") + return + } + prompting = true + lock.unlock() + DispatchQueue.global(qos: .userInitiated).async { + defer { + self.lock.lock() + self.prompting = false + self.lock.unlock() + } + do { + promise.resolve(try work()) + } catch let failure as Failure { + promise.reject(failure.code, failure.message) + } catch { + promise.reject("failed", error.localizedDescription) + } + } + } + + private static func nowMs() -> Int64 { Int64(Date().timeIntervalSince1970 * 1000) } + public func definition() -> ModuleDefinition { Name("HermitApprovalKey") AsyncFunction("state") { () -> [String: Any] in - return ["state": "no_biometric"] + self.state() } - AsyncFunction("enroll") { (_: String, _: String) -> [String: Any] in - throw Exception(name: "ApprovalKeyUnavailable", description: "No approval key on iOS yet.", code: "no_biometric") + /** + Makes a new key (replacing any old one) and proves it with a fresh Face ID or Touch ID: the new key signs the + enrollment challenge behind the prompt. Any failure leaves no key behind. + */ + AsyncFunction("enroll") { (message: String, locale: String, promise: Promise) in + self.withPrompt(promise) { + guard message.hasPrefix("\(ApprovalText.enrollDomain)\n") else { throw Failure(code: "bad_message", message: "Not an enrollment challenge.") } + let set: Data + switch self.biometry() { + case .available(let s?): set = s + case .available(nil), .lockedOut: throw Failure(code: "lockout", message: "Face ID or Touch ID is locked.") + case .none: throw Failure(code: "no_biometric", message: "No Face ID or Touch ID is enrolled.") + } + do { + let key = try self.generate() + guard let pub = self.publicKey(key) else { throw Failure(code: "failed", message: "No public key.") } + let s = ApprovalText.strings(locale) + let signature = try self.signOnce(message, reason: "\(s.enrollTitle)\n\(s.enrollDescription)", cancel: s.cancel) + guard self.recordBiometry(set) else { throw Failure(code: "failed", message: "The biometric set wasn't recorded.") } + return ["publicKey": pub, "level": Self.level, "signature": signature] + } catch { + self.destroy() + throw error + } + } } - AsyncFunction("sign") { (_: String, _: String) -> String in - throw Exception(name: "ApprovalKeyUnavailable", description: "No approval key on iOS yet.", code: "no_biometric") + /** Signs one approval message. The prompt shows the amount and recipient (or the site) read from the message. */ + AsyncFunction("sign") { (message: String, locale: String, promise: Promise) in + self.withPrompt(promise) { + guard let approval = ApprovalText.parse(message) else { throw Failure(code: "bad_message", message: "Not an approval Hermit signs.") } + guard approval.expiresAt > Self.nowMs() else { throw Failure(code: "expired", message: "The approval expired.") } + let now = self.biometry() + if case .none = now { throw Failure(code: "no_biometric", message: "No Face ID or Touch ID is enrolled.") } + guard case .found = self.findKey() else { throw Failure(code: "lost", message: "No approval key.") } + if self.biometryChanged(now) { throw Failure(code: "lost", message: "The approval key was retired.") } + let reason = "\(ApprovalText.title(approval, locale))\n\(ApprovalText.describe(approval, locale))" + return try self.signOnce(message, reason: reason, cancel: ApprovalText.strings(locale).cancel) + } } + /** Delete everything (SL-26). Idempotent. */ AsyncFunction("destroy") { () in - // Nothing was ever made, so there is nothing to delete. + self.destroy() } } } diff --git a/docs/devices.md b/docs/devices.md index 7a083e6..8874a27 100644 --- a/docs/devices.md +++ b/docs/devices.md @@ -80,8 +80,9 @@ Device Management. On an iPhone, Hermit is still missing pieces. Today: -- Payments and logins are refused, because there is no Secure Enclave approval key yet. The vault and the wallet are - off. +- The approval key for payments and logins can be set up: it is made in the Secure Enclave, never leaves it, and needs + Face ID or Touch ID for every signature. Payments and logins are still refused, because the vault and the wallet are + off: iOS has no hardware-wrapped vault or wallet key yet. - There is no WhatsApp capture and no night shift. - **Delete everything** before you delete the app: iOS keeps an app's Keychain entries (Hermit's database key and tokens) after the app is gone. diff --git a/packages/cage/test/signed-approval.test.ts b/packages/cage/test/signed-approval.test.ts index 2cb7b9c..7da0e00 100644 --- a/packages/cage/test/signed-approval.test.ts +++ b/packages/cage/test/signed-approval.test.ts @@ -207,6 +207,36 @@ describe("enrollment proof", () => { }); }); +describe("an iPhone's Secure Enclave key (iOS module)", () => { + // A known vector, made once on a Mac with a throwaway software P-256 SecKey and the calls the iOS module makes: + // SecKeyCopyExternalRepresentation (X9.63, 0x04 X Y) behind the SPKI header (ApprovalKeyFormat.spki), and + // SecKeyCreateSignature(.ecdsaSignatureMessageX962SHA256), which is SHA256withECDSA in DER, as on Android. + const IOS_SPKI = "3059301306072a8648ce3d020106082a8648ce3d03010703420004f4c4b0fa0e50f6d9c585110cde10f5c640e702c7362cc7494524ce9e83e95fd5e483629a03cb510982694e34212fb9ed36c47327d6f47782e24896f72dcbb533"; + const IOS_ENROLL_SIG = "3045022100fefc6ce44df7f06f1a7ced461c1859db6c0f835a8b81fbb53ca6659012ef873102201954ff1284f24f52ca3af01663729975e13ceb1e5d8396d0fd16f2c80e42bc06"; + const IOS_SPEND_SIG = "3045022100ff44e09dc9f46e5a388dea7dc0d3cd579dd946662422f521360fa5379faa12fa02206716c1cdd70b32094f97221840caff99c74520adce47bcc781782663ba8c57a4"; + const iosTerms = spendTerms({ amount: money(5_000_000n, "USDT", "eip155:2201") }); + + test("its public key and its enrollment signature verify as they come from the module, with no conversion in JavaScript", () => { + const key = publicKeyFromSpki(IOS_SPKI); + expect(key).toBeDefined(); + expect(spkiFromPublicKey(key!)).toBe(IOS_SPKI); + expect(verifyEnrollment(enrollmentMessage("cd".repeat(32), NOW), IOS_ENROLL_SIG, IOS_SPKI)).toBe(true); + expect(verifyEnrollment(enrollmentMessage("ef".repeat(32), NOW), IOS_ENROLL_SIG, IOS_SPKI)).toBe(false); + }); + + test("its signature approves exactly the payment it was made over, and nothing changed from it", () => { + const { message } = built(iosTerms); + const publicKey = publicKeyFromSpki(IOS_SPKI)!; + expect(verifySignedApproval({ message, signature: IOS_SPEND_SIG, publicKey, expected: expected(iosTerms), now: NOW + 1 })).toMatchObject({ ok: true }); + // Another amount: the cage's expected call no longer matches the payload. + const more = spendTerms({ amount: money(6_000_000n, "USDT", "eip155:2201") }); + expect(verifySignedApproval({ message, signature: IOS_SPEND_SIG, publicKey, expected: expected(more), now: NOW + 1 })).toEqual({ ok: false, reason: "mismatch" }); + // The changed payload itself, offered with the old signature: not the key's signature over it. + const changed = built(more).message; + expect(verifySignedApproval({ message: changed, signature: IOS_SPEND_SIG, publicKey, expected: expected(more), now: NOW + 1 })).toEqual({ ok: false, reason: "bad_signature" }); + }); +}); + describe("createSignedApprovals (what the loop calls)", () => { const setup = (state: ApprovalKeyState, enrolled: string | null = spki) => { let n = 0; diff --git a/packages/copy/locales/en.json b/packages/copy/locales/en.json index 9235ab0..902e3be 100644 --- a/packages/copy/locales/en.json +++ b/packages/copy/locales/en.json @@ -625,6 +625,7 @@ "HM-APPR-01.key.readyBody": "Payments and passwords will ask for your {biometric} every time.", "HM-APPR-01.key.level.strongbox": "Kept in this phone's StrongBox security chip.", "HM-APPR-01.key.level.tee": "Kept in this phone's secure hardware.", + "HM-APPR-01.key.level.secure_enclave": "Kept in this iPhone's Secure Enclave.", "HM-APPR-01.key.setUp": "Set up with {biometric}", "HM-APPR-01.key.setUpAgain": "Set up again with {biometric}", "HM-APPR-01.key.note.done": "Done. The approval key is set up.", diff --git a/packages/copy/locales/es-419.json b/packages/copy/locales/es-419.json index 7cb902d..24a8786 100644 --- a/packages/copy/locales/es-419.json +++ b/packages/copy/locales/es-419.json @@ -625,6 +625,7 @@ "HM-APPR-01.key.readyBody": "Los pagos y las contraseñas pedirán tu {biometric} cada vez.", "HM-APPR-01.key.level.strongbox": "Guardada en el chip de seguridad StrongBox de este teléfono.", "HM-APPR-01.key.level.tee": "Guardada en el hardware seguro de este teléfono.", + "HM-APPR-01.key.level.secure_enclave": "Guardada en el Secure Enclave de este iPhone.", "HM-APPR-01.key.setUp": "Configurar con {biometric}", "HM-APPR-01.key.setUpAgain": "Configurar de nuevo con {biometric}", "HM-APPR-01.key.note.done": "Listo. La clave de aprobación está configurada.", diff --git a/packages/copy/test/copy.test.ts b/packages/copy/test/copy.test.ts index 07dcbdc..7303fdf 100644 --- a/packages/copy/test/copy.test.ts +++ b/packages/copy/test/copy.test.ts @@ -1,6 +1,6 @@ import { describe, expect, test } from "vitest"; import { readFileSync } from "node:fs"; -import { OUTCOMES, outcomeCopyKey } from "@hermit/core"; +import { APPROVAL_KEY_LEVELS, OUTCOMES, outcomeCopyKey } from "@hermit/core"; import { BIOMETRIC_KINDS, biometricWords, createTranslator, CopyError, IOS_PURPOSE_KEYS, KEY_PATTERN, placeholders, resolveLocale, type Dictionary } from "../src/index.ts"; const load = (name: string): Dictionary => JSON.parse(readFileSync(new URL(`../locales/${name}.json`, import.meta.url), "utf8")); @@ -41,6 +41,13 @@ describe("locale files (CT-10)", () => { } }); + test("every place an approval key can be kept has its line on the approval key screen", () => { + for (const level of APPROVAL_KEY_LEVELS) { + expect(en[`HM-APPR-01.key.level.${level}`], level).toBeTruthy(); + expect(es[`HM-APPR-01.key.level.${level}`], level).toBeTruthy(); + } + }); + test("no em or en dashes in copy (house style)", () => { for (const [k, v] of [...Object.entries(en), ...Object.entries(es)]) expect(v, k).not.toMatch(/[–—]/); }); diff --git a/packages/core/src/approval-key.ts b/packages/core/src/approval-key.ts index 2dcafad..1e5faec 100644 --- a/packages/core/src/approval-key.ts +++ b/packages/core/src/approval-key.ts @@ -69,13 +69,18 @@ export interface SignedApprovalRequest { message: string; } -/** Where the key is kept. Software keys are refused at enrollment, so there is no "software" level. */ -export type ApprovalKeyLevel = "strongbox" | "tee"; +/** + * Where the key is kept: Android's StrongBox or TEE, or an iPhone's Secure Enclave. Software keys are refused at + * enrollment, so there is no "software" level. + */ +export const APPROVAL_KEY_LEVELS = ["strongbox", "tee", "secure_enclave"] as const; +export type ApprovalKeyLevel = (typeof APPROVAL_KEY_LEVELS)[number]; /** * The Keystore key as the native module sees it, read without a prompt. * - none: never set up (or erased). - * - lost: Android retired it because a fingerprint was added or removed (`KeyPermanentlyInvalidatedException`). + * - lost: retired because a fingerprint (or on iOS a face or a finger) was added or removed (Android's + * `KeyPermanentlyInvalidatedException`, iOS's `.biometryCurrentSet`). * - no_biometric: the phone has no strong biometric enrolled, so a key that needs one can't be made or used. * - ready: usable; `publicKey` is the X.509 SubjectPublicKeyInfo in lowercase hex. */ diff --git a/packages/runtime/src/approval-key.ts b/packages/runtime/src/approval-key.ts index eb33ee7..665021d 100644 --- a/packages/runtime/src/approval-key.ts +++ b/packages/runtime/src/approval-key.ts @@ -1,4 +1,4 @@ -import type { ApprovalKeyLevel, ApprovalKeyPort, ApprovalKeyState, SqlPort } from "@hermit/core"; +import { APPROVAL_KEY_LEVELS, type ApprovalKeyLevel, type ApprovalKeyPort, type ApprovalKeyState, type SqlPort } from "@hermit/core"; import { createNonceStore, createSignedApprovals, enrollmentMessage, verifyEnrollment, type AuditLog, type SignedApprovals } from "@hermit/cage"; const bytesToHex = (b: Uint8Array) => Array.from(b, (x) => x.toString(16).padStart(2, "0")).join(""); @@ -46,8 +46,8 @@ function parseEnrolled(raw: string | undefined): EnrolledApprovalKey | undefined if (!raw) return undefined; try { const v = JSON.parse(raw) as Partial; - if (typeof v.publicKey !== "string" || (v.level !== "strongbox" && v.level !== "tee") || typeof v.enrolledAt !== "number") return undefined; - return { publicKey: v.publicKey, level: v.level, enrolledAt: v.enrolledAt }; + if (typeof v.publicKey !== "string" || !APPROVAL_KEY_LEVELS.includes(v.level as ApprovalKeyLevel) || typeof v.enrolledAt !== "number") return undefined; + return { publicKey: v.publicKey, level: v.level as ApprovalKeyLevel, enrolledAt: v.enrolledAt }; } catch { return undefined; } diff --git a/packages/runtime/test/approval-key.test.ts b/packages/runtime/test/approval-key.test.ts index 49e2f20..60b0ff1 100644 --- a/packages/runtime/test/approval-key.test.ts +++ b/packages/runtime/test/approval-key.test.ts @@ -5,7 +5,7 @@ import { describe, expect, test } from "vitest"; import { webcrypto } from "node:crypto"; import { nodeSql } from "@hermit/sql-node"; -import { migrate, type ApprovalKeyPort, type ApprovalKeyState } from "@hermit/core"; +import { migrate, type ApprovalKeyLevel, type ApprovalKeyPort, type ApprovalKeyState } from "@hermit/core"; import { createAuditLog, ed25519Signer } from "@hermit/cage"; import { softwareApprovalKey } from "@hermit/cage/testing"; import { profileById } from "@hermit/model"; @@ -18,13 +18,13 @@ const random = (n: number) => webcrypto.getRandomValues(new Uint8Array(n)); function fakeKeystore() { let seed = 10; let key: ReturnType | undefined; - const s = { next: "ok" as "ok" | "cancelled" | "no_secure_hardware" | "forge", retired: false, noBiometric: false, destroyed: 0 }; + const s = { next: "ok" as "ok" | "cancelled" | "no_secure_hardware" | "forge", retired: false, noBiometric: false, destroyed: 0, level: "strongbox" as ApprovalKeyLevel }; const port: ApprovalKeyPort = { async state(): Promise { if (s.noBiometric) return { state: "no_biometric" }; if (!key) return { state: "none" }; if (s.retired) return { state: "lost" }; - return { state: "ready", publicKey: key.spki, level: "strongbox" }; + return { state: "ready", publicKey: key.spki, level: s.level }; }, async enroll(message) { key = undefined; @@ -38,7 +38,7 @@ function fakeKeystore() { // "forge": a key that returns a signature not made over the challenge (a broken or hostile native side). const signature = s.next === "forge" ? softwareApprovalKey(99).sign(message) : key.sign(message); s.next = "ok"; - return { publicKey: key.spki, level: "strongbox", signature }; + return { publicKey: key.spki, level: s.level, signature }; }, async destroy() { key = undefined; @@ -109,6 +109,17 @@ describe("createApprovalKey", () => { expect(await service.enroll(prompt)).toEqual({ ok: false, reason: "no_secure_hardware" }); }); + test("an iPhone's Secure Enclave key is pinned with its level and reads back as ready", async () => { + const { service, store, ks } = await setup(); + ks.s.level = "secure_enclave"; + expect(await service.enroll(prompt)).toEqual({ ok: true, view: { kind: "ready", level: "secure_enclave" } }); + expect(JSON.parse(store.get("approval.key")!)).toEqual({ publicKey: ks.key()!.spki, level: "secure_enclave", enrolledAt: 5_000 }); + expect(await service.view()).toEqual({ kind: "ready", level: "secure_enclave" }); + // A level nobody makes is not a pin: the screen asks to set the key up, never trusts it. + store.set("approval.key", JSON.stringify({ publicKey: ks.key()!.spki, level: "software", enrolledAt: 5_000 })); + expect(await service.view()).toEqual({ kind: "not_set_up" }); + }); + test("an enrollment whose signature isn't the new key's over the challenge is refused and the key destroyed", async () => { const { service, ks, store } = await setup(); ks.s.next = "forge"; From 00932008643d367118a11880c3453ff4a05d3f6d Mon Sep 17 00:00:00 2001 From: Daniel Bejarano Date: Mon, 30 Nov 2026 16:41:48 -0600 Subject: [PATCH 2/2] iOS: the approval key's set-up prompt names Face ID or Touch ID, not fingerprint (#125) ApprovalText.swift was a port of Android's text and its enrollment line said fingerprint. It now names this iPhone's biometric from LAContext.biometryType, as the app's copy does (common.biometric.*): Face ID, Touch ID, or both names when the phone doesn't say. The payment and password prompts had no biometric word and are unchanged. Signed-off-by: Daniel Bejarano --- .../ios/ApprovalText.swift | 30 +++++++++++++++++-- .../ios/HermitApprovalKeyModule.swift | 15 +++++++++- 2 files changed, 41 insertions(+), 4 deletions(-) diff --git a/apps/mobile/modules/hermit-approval-key/ios/ApprovalText.swift b/apps/mobile/modules/hermit-approval-key/ios/ApprovalText.swift index f99ac8a..fc313b7 100644 --- a/apps/mobile/modules/hermit-approval-key/ios/ApprovalText.swift +++ b/apps/mobile/modules/hermit-approval-key/ios/ApprovalText.swift @@ -34,7 +34,9 @@ enum ApprovalText { let payTitle: String let passwordTitle: String let enrollTitle: String - let enrollDescription: String + /** The enrollment line, around the biometric's name (Face ID, Touch ID, or both). */ + let enrollDescription: (String) -> String + let faceOrTouchId: String let cancel: String let amount: String let to: String @@ -49,7 +51,8 @@ enum ApprovalText { payTitle: "Approve this payment", passwordTitle: "Approve using this password", enrollTitle: "Set up your approval key", - enrollDescription: "Payments and passwords will need your fingerprint, every time.", + enrollDescription: { "Payments and passwords will need your \($0), every time." }, + faceOrTouchId: "Face ID or Touch ID", cancel: "Cancel", amount: "Amount", to: "To", @@ -64,7 +67,8 @@ enum ApprovalText { payTitle: "Aprueba este pago", passwordTitle: "Aprueba usar esta contraseña", enrollTitle: "Configura tu clave de aprobación", - enrollDescription: "Los pagos y las contraseñas pedirán tu huella, cada vez.", + enrollDescription: { "Los pagos y las contraseñas pedirán tu \($0), cada vez." }, + faceOrTouchId: "Face ID o Touch ID", cancel: "Cancelar", amount: "Monto", to: "Para", @@ -78,6 +82,26 @@ enum ApprovalText { /** Only the two locales Hermit ships; anything else is English. */ static func strings(_ locale: String) -> Strings { locale == "es-419" ? es419 : en } + /** + The biometric an iPhone has, named as the app's copy names it (common.biometric.*, biometric-name.ts): Face ID, + Touch ID, or both names when the phone doesn't say. An iPhone never says fingerprint. + */ + enum Biometric { + case faceId + case touchId + case faceOrTouchId + } + + /** The enrollment prompt's line, naming this iPhone's biometric. */ + static func enrollDescription(_ locale: String, _ biometric: Biometric) -> String { + let s = strings(locale) + switch biometric { + case .faceId: return s.enrollDescription("Face ID") + case .touchId: return s.enrollDescription("Touch ID") + case .faceOrTouchId: return s.enrollDescription(s.faceOrTouchId) + } + } + /** The payload of an approval message, or nil when it isn't one (wrong domain, not JSON, not USD₮). */ static func parse(_ message: String) -> Approval? { let prefix = "\(approvalDomain)\n" diff --git a/apps/mobile/modules/hermit-approval-key/ios/HermitApprovalKeyModule.swift b/apps/mobile/modules/hermit-approval-key/ios/HermitApprovalKeyModule.swift index e9ad158..347bd41 100644 --- a/apps/mobile/modules/hermit-approval-key/ios/HermitApprovalKeyModule.swift +++ b/apps/mobile/modules/hermit-approval-key/ios/HermitApprovalKeyModule.swift @@ -54,6 +54,18 @@ public class HermitApprovalKeyModule: Module { return .none } + /** Which biometric this iPhone has, for the prompt's words (biometryType is set once canEvaluatePolicy has run). */ + private func biometricName() -> ApprovalText.Biometric { + let context = LAContext() + defer { context.invalidate() } + _ = context.canEvaluatePolicy(.deviceOwnerAuthenticationWithBiometrics, error: nil) + switch context.biometryType { + case .faceID: return .faceId + case .touchID: return .touchId + default: return .faceOrTouchId + } + } + private func biometryQuery() -> [String: Any] { [ kSecClass as String: kSecClassGenericPassword, @@ -277,7 +289,8 @@ public class HermitApprovalKeyModule: Module { let key = try self.generate() guard let pub = self.publicKey(key) else { throw Failure(code: "failed", message: "No public key.") } let s = ApprovalText.strings(locale) - let signature = try self.signOnce(message, reason: "\(s.enrollTitle)\n\(s.enrollDescription)", cancel: s.cancel) + let line = ApprovalText.enrollDescription(locale, self.biometricName()) + let signature = try self.signOnce(message, reason: "\(s.enrollTitle)\n\(line)", cancel: s.cancel) guard self.recordBiometry(set) else { throw Failure(code: "failed", message: "The biometric set wasn't recorded.") } return ["publicKey": pub, "level": Self.level, "signature": signature] } catch {