import CottonKit import Foundation /// "Re-key this device" — the app's half of the act the core runs /// (`crates/cotton-ffi/src/phone/rekey.rs`). /// /// The app owns the Keychain and the core owns everything the key is for, so /// the act crosses the boundary three times: the successor is minted HERE, /// beside the key in use; the core pairs it (the first join's client, as a /// succession) and proves it at `/v1/me`; and only once the core answers /// `live` is the successor promoted over the old key and the core opened /// again on it. Until then the old key is untouched and in use, so an /// approval that never comes changes nothing. /// /// The seed crosses to the core as `deviceSecret` does on every open, and is /// never logged, shown or kept anywhere else. @MainActor public final class DeviceRekey { private let core: any CottonCalling private let current: any DeviceKeyStore private let successor: any DeviceKeyStore private let keyring: VaultKeyring /// Opens the core again on the key now in the slot — the app's, since only /// the app holds the core. `nil` where nothing can (a preview). private let reopen: (@MainActor () async -> Void)? private var watching: Task? public init( core: any CottonCalling, current: any DeviceKeyStore, successor: any DeviceKeyStore, keyring: VaultKeyring = VaultKeyring(), reopen: (@MainActor () async -> Void)? ) { self.core = core self.current = current self.successor = successor self.keyring = keyring self.reopen = reopen } private struct Start: Encodable { let successorSecret: String let vaultPublicKey: String? } private struct Resume: Encodable { let successorSecret: String } private struct Stage: Decodable { let stage: String } /// The platform action: mint (or find) the successor, ask the core to pair /// it, and watch until it is live. Answers whether the asking started; the /// page draws the digits off the device row the core fills. public func start() async -> Bool { guard reopen != nil else { return false } let successor = self.successor let keyring = self.keyring let minted = await Task.detached(priority: .userInitiated) { () -> (String, String?)? in guard let seed = try? DeviceKey.seed(store: successor) else { return nil } return (seed, try? keyring.publicKey()) }.value guard let (seed, vault) = minted else { return false } do { _ = try await core.call("device.rekey.start", Start(successorSecret: seed, vaultPublicKey: vault), as: JSONValue.self) } catch let refusal as CottonCallError where refusal.code == "rekey_running" { // Already asking: keep watching the one in flight. } catch { Log.write("re-key: \((error as? CottonCallError)?.code ?? "refused")") return false } watch() return true } /// A launch that finds a successor asks once whether it is already live — /// the app closed between the approval and the promotion. No pairing is /// asked for: a successor never approved stays where it is for the next /// press of the act. public func resumeAtLaunch() async { let successor = self.successor let current = self.current let pending = await Task.detached(priority: .utility) { DeviceKey.successorPending(successor: successor, current: current) }.value guard let pending, reopen != nil else { return } guard let answer = try? await core.call("device.rekey.resume", Resume(successorSecret: pending), as: Stage.self), answer.stage == "live" else { return } await finish() } private func watch() { guard watching == nil else { return } watching = Task { @MainActor [weak self] in defer { self?.watching = nil } while !Task.isCancelled { guard let self else { return } let stage = try? await self.core.call("device.rekey.status", as: Stage.self).stage switch stage { case "live": await self.finish() return case "failed", "idle": return default: try? await Task.sleep(for: .seconds(1)) } } } } /// The new key's row is live: promote it over the old one (which leaves /// the Keychain here and nowhere earlier) and open the core on it. private func finish() async { let successor = self.successor let current = self.current let promoted = await Task.detached(priority: .userInitiated) { () -> Bool in (try? DeviceKey.promote(successor: successor, into: current)) ?? false }.value guard promoted else { Log.write("re-key: the new key could not be kept; the old key stays in use") return } await reopen?() } }