Repository Public
1// SP Vault Dev — development-only plumbing. This whole file is compiled ONLY with the SPV_DEV flag (Debug builds,2// "SP Vault Dev"); none of it exists in a Release binary (Scripts/release-*.sh check for it).3//4// It lets automated runs drive the real engine against the real server started locally (Scripts/dev-server.sh):5// * a software WebAuthn authenticator instead of the system passkey sheet (which needs Associated Domains);6// * software device keys kept in a file instead of Secure Enclave keys behind a biometric prompt;7// * a profile directory, so that two "devices" can run side by side on one machine.8// Environment variables (XCUIApplication.launchEnvironment, or SIMCTL_CHILD_… with simctl):9// SPV_DEV_SERVER base URL of the test server (default http://localhost:8781)10// SPV_DEV_PROFILE name of the local profile directory (default "default")11// SPV_DEV_PASSKEY_FILE host path of the software passkey file shared by the "devices" of one account12// SPV_DEV_PAIRING_FILE host path where the pairing code + fingerprint shown by a new device are also written13// SPV_DEV_RESET=1 erase the profile at launch14// SPV_DEV_APPEARANCE "light" or "dark": force the appearance (screenshots)15// SPV_DEV_ALLOW_CAPTURE=1 macOS: do not hide the window from screen capture nor blur it when inactive (screenshots)16// SPV_DEV_IMPORT_FILE host path of a CSV / JSON file that Settings ▸ Import reads instead of showing the file picker17#if SPV_DEV18import CryptoKit19import Foundation20import LocalAuthentication21import SharedVaultKit2223enum DevSupport {24 static let env = ProcessInfo.processInfo.environment2526 static var serverURL: URL { URL(string: env["SPV_DEV_SERVER"] ?? "http://localhost:8781") ?? URL(string: "http://localhost:8781")! }27 static var profile: String {28 let p = (env["SPV_DEV_PROFILE"] ?? "default").filter { $0.isLetter || $0.isNumber || $0 == "-" }29 return p.isEmpty ? "default" : p30 }31 static var importFile: URL? { env["SPV_DEV_IMPORT_FILE"].map { URL(fileURLWithPath: $0) } }32 /// "light" / "dark" / nil (follow the system).33 static var appearance: String? { env["SPV_DEV_APPEARANCE"] }34 static var pairingFile: URL? { env["SPV_DEV_PAIRING_FILE"].map { URL(fileURLWithPath: $0) } }3536 static func sharedDirectory() throws -> URL {37 let fm = FileManager.default38 var base: URL39 #if os(macOS)40 base = try fm.url(for: .applicationSupportDirectory, in: .userDomainMask, appropriateFor: nil, create: true).appendingPathComponent("SPVaultDev", isDirectory: true)41 #else42 if let group = fm.containerURL(forSecurityApplicationGroupIdentifier: AppEnvironment.appGroup) { base = group.appendingPathComponent("SPVaultDev", isDirectory: true) }43 else { base = try fm.url(for: .applicationSupportDirectory, in: .userDomainMask, appropriateFor: nil, create: true).appendingPathComponent("SPVaultDev", isDirectory: true) }44 #endif45 base.appendPathComponent(profile, isDirectory: true)46 try fm.createDirectory(at: base, withIntermediateDirectories: true)47 return base48 }4950 /// Erases the profile when SPV_DEV_RESET=1 (called once, before anything opens the store).51 static func resetIfAsked() {52 guard env["SPV_DEV_RESET"] == "1", let dir = try? sharedDirectory() else { return }53 try? FileManager.default.removeItem(at: dir)54 if let d = UserDefaults.standard.persistentDomain(forName: Bundle.main.bundleIdentifier ?? "") {55 for k in d.keys where k.hasPrefix("spv.") { UserDefaults.standard.removeObject(forKey: k) }56 }57 }5859 static func makeKeyStore() throws -> any DeviceKeyStore { DevFileKeyStore(url: try sharedDirectory().appendingPathComponent("dev-device-keys.json")) }6061 static func makePasskeys() throws -> DevSoftwarePasskeys {62 let url = try env["SPV_DEV_PASSKEY_FILE"].map { URL(fileURLWithPath: $0) } ?? sharedDirectory().appendingPathComponent("dev-passkeys.json")63 return DevSoftwarePasskeys(file: url, origin: AppEnvironment.origin)64 }6566 /// Lets a test harness read what a new device displays (code + 6-digit fingerprint) without OCR.67 static func publishPairing(code: String, sas: String) {68 guard let f = pairingFile else { return }69 try? FileManager.default.createDirectory(at: f.deletingLastPathComponent(), withIntermediateDirectories: true)70 try? Data("\(code)\n\(sas)\n".utf8).write(to: f, options: .atomic)71 }72}7374/// Software device keys in a JSON file. No presence check: never used for a real vault.75final class DevFileKeyStore: DeviceKeyStore, @unchecked Sendable {76 private struct Disk: Codable { var identity: DeviceIdentity?; var enc: Data?; var sig: Data?; var token: String? }77 private let url: URL78 private let lock = NSLock()79 init(url: URL) { self.url = url }8081 private func read() -> Disk { (try? JSONDecoder().decode(Disk.self, from: Data(contentsOf: url))) ?? Disk() }82 private func write(_ d: Disk) throws { try JSONEncoder().encode(d).write(to: url, options: .atomic) }8384 func generateDeviceKeys() throws -> GeneratedDeviceKeys {85 let enc = SoftwareKEMKey(), sig = SoftwareSigningKey()86 return GeneratedDeviceKeys(keys: DeviceKeys(enc: enc, sig: sig), encBlob: enc.x963Representation, sigBlob: sig.x963Representation, hardware: false)87 }88 func save(identity: DeviceIdentity, keys: GeneratedDeviceKeys?) throws {89 lock.lock(); defer { lock.unlock() }90 var d = read()91 d.identity = identity92 if let keys { d.enc = keys.encBlob; d.sig = keys.sigBlob }93 try write(d)94 }95 func loadIdentity() throws -> DeviceIdentity? { lock.lock(); defer { lock.unlock() }; return read().identity }96 func loadKeys(context: LAContext?) throws -> DeviceKeys? {97 lock.lock(); defer { lock.unlock() }98 let d = read()99 guard let enc = d.enc, let sig = d.sig else { return nil }100 return DeviceKeys(enc: try SoftwareKEMKey(x963Representation: enc), sig: try SoftwareSigningKey(x963Representation: sig))101 }102 func saveSessionToken(_ token: String?) throws { lock.lock(); defer { lock.unlock() }; var d = read(); d.token = token; try write(d) }103 func loadSessionToken() throws -> String? { lock.lock(); defer { lock.unlock() }; return read().token }104 func clear() throws { lock.lock(); defer { lock.unlock() }; try? FileManager.default.removeItem(at: url) }105}106107/// Software WebAuthn authenticator (ES256, "none" attestation, user verified), credentials kept in a file so that108/// several dev "devices" share the passkey of one account. A port of SharedVaultKit's test `SoftwarePasskeys`.109final class DevSoftwarePasskeys: PasskeyProvider, @unchecked Sendable {110 private struct Credential: Codable { var id: String; var key: Data; var userHandle: String; var counter: UInt32 }111 private let file: URL112 private let origin: String113 private let lock = NSLock()114115 init(file: URL, origin: String) { self.file = file; self.origin = origin }116117 private func load() -> [Credential] { (try? JSONDecoder().decode([Credential].self, from: Data(contentsOf: file))) ?? [] }118 private func save(_ c: [Credential]) {119 try? FileManager.default.createDirectory(at: file.deletingLastPathComponent(), withIntermediateDirectories: true)120 try? JSONEncoder().encode(c).write(to: file, options: .atomic)121 }122123 private func clientData(_ type: String, _ challenge: String) -> Data {124 (["type": .string(type), "challenge": .string(challenge), "origin": .string(origin), "crossOrigin": false] as JSONValue).serialized()125 }126127 // minimal CBOR (definite lengths below 2^16 are all an attestation object needs)128 private static func head(_ major: UInt8, _ n: Int) -> Data {129 let m = major << 5130 if n < 24 { return Data([m | UInt8(n)]) }131 if n < 0x100 { return Data([m | 24, UInt8(n)]) }132 return Data([m | 25, UInt8(n >> 8), UInt8(n & 0xff)])133 }134 private static func text(_ s: String) -> Data { head(3, s.utf8.count) + Data(s.utf8) }135 private static func bytes(_ d: Data) -> Data { head(2, d.count) + d }136137 func create(options: JSONValue) async throws -> JSONValue {138 guard let rpId = options["rp"]?["id"]?.stringValue, let challenge = options["challenge"]?.stringValue, let userId = options["user"]?["id"]?.stringValue else {139 throw PasskeyError.invalidOptions("registration")140 }141 let key = P256.Signing.PrivateKey(), id = SPV1.random(16), pub = key.publicKey.x963Representation142 var authData = SPV1.sha256(SPV1.utf8(rpId))143 authData.append(0x5d) // UP | UV | BE | BS | AT144 authData.append(Data(count: 4)); authData.append(Data(count: 16))145 authData.append(contentsOf: [0, UInt8(id.count)]); authData.append(id)146 authData.append(try PasskeyCrypto.coseKey(publicKeyX963: pub))147 let attestation = Self.head(5, 3) + Self.text("fmt") + Self.text("none") + Self.text("attStmt") + Self.head(5, 0) + Self.text("authData") + Self.bytes(authData)148 lock.withLock { save(load() + [Credential(id: SPV1.b64u(id), key: key.rawRepresentation, userHandle: userId, counter: 0)]) }149 return [150 "id": .string(SPV1.b64u(id)), "rawId": .string(SPV1.b64u(id)), "type": "public-key", "clientExtensionResults": .object(JSONObject()), "authenticatorAttachment": "platform",151 "response": ["clientDataJSON": .string(SPV1.b64u(clientData("webauthn.create", challenge))), "attestationObject": .string(SPV1.b64u(attestation)), "transports": ["internal"]],152 ]153 }154155 func get(options: JSONValue) async throws -> JSONValue {156 guard let rpId = options["rpId"]?.stringValue, let challenge = options["challenge"]?.stringValue else { throw PasskeyError.invalidOptions("authentication") }157 let allowed = (options["allowCredentials"]?.arrayValue ?? []).compactMap { $0["id"]?.stringValue }158 let picked: Credential? = lock.withLock {159 var all = load()160 guard let idx = all.lastIndex(where: { allowed.isEmpty || allowed.contains($0.id) }) else { return nil }161 all[idx].counter += 1162 save(all)163 return all[idx]164 }165 guard let c = picked else { throw PasskeyError.failed("no passkey for this site") }166 let key = try P256.Signing.PrivateKey(rawRepresentation: c.key)167 var authData = SPV1.sha256(SPV1.utf8(rpId))168 authData.append(0x1d) // UP | UV | BE | BS169 authData.append(contentsOf: [UInt8(c.counter >> 24), UInt8((c.counter >> 16) & 255), UInt8((c.counter >> 8) & 255), UInt8(c.counter & 255)])170 let cdj = clientData("webauthn.get", challenge)171 let signature = try key.signature(for: authData + SPV1.sha256(cdj)).derRepresentation172 return [173 "id": .string(c.id), "rawId": .string(c.id), "type": "public-key", "clientExtensionResults": .object(JSONObject()), "authenticatorAttachment": "platform",174 "response": ["clientDataJSON": .string(SPV1.b64u(cdj)), "authenticatorData": .string(SPV1.b64u(authData)), "signature": .string(SPV1.b64u(signature)), "userHandle": .string(c.userHandle)],175 ]176 }177}178#endif179