importCottonKitimportFoundation/// "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.@MainActorpublicfinalclassDeviceRekey {privatelet core: any CottonCallingprivatelet current: any DeviceKeyStoreprivatelet successor: any DeviceKeyStoreprivatelet 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).privatelet reopen: (@MainActor () async -> Void)?privatevar watching: Task<Void, Never>?publicinit( core: any CottonCalling, current: any DeviceKeyStore, successor: any DeviceKeyStore, keyring: VaultKeyring = VaultKeyring(), reopen: (@MainActor () async -> Void)? ) {self.core = coreself.current = currentself.successor = successorself.keyring = keyringself.reopen = reopen }privatestructStart: Encodable {let successorSecret: Stringlet vaultPublicKey: String? }privatestructResume: Encodable {let successorSecret: String }privatestructStage: 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.publicfunc start() async -> Bool {guard reopen != nilelse { returnfalse }let successor = self.successorlet keyring = self.keyringlet minted = awaitTask.detached(priority: .userInitiated) { () -> (String, String?)? inguardlet seed = try? DeviceKey.seed(store: successor) else { returnnil }return (seed, try? keyring.publicKey()) }.valueguardlet (seed, vault) = minted else { returnfalse }do { _ = tryawait core.call("device.rekey.start", Start(successorSecret: seed, vaultPublicKey: vault), as: JSONValue.self) } catchlet refusal asCottonCallErrorwhere refusal.code == "rekey_running" {// Already asking: keep watching the one in flight. } catch {Log.write("re-key: \((error as? CottonCallError)?.code ?? "refused")")returnfalse } watch()returntrue }/// 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.publicfunc resumeAtLaunch() async {let successor = self.successorlet current = self.currentlet pending = awaitTask.detached(priority: .utility) {DeviceKey.successorPending(successor: successor, current: current) }.valueguardlet pending, reopen != nilelse { return }guardlet answer = try? await core.call("device.rekey.resume", Resume(successorSecret: pending), as: Stage.self), answer.stage == "live"else { return }await finish() }privatefunc watch() {guard watching == nilelse { return } watching = Task { @MainActor [weakself] indefer { self?.watching = nil }while !Task.isCancelled {guardletselfelse { return }let stage = try? awaitself.core.call("device.rekey.status", as: Stage.self).stageswitch stage {case"live":awaitself.finish()returncase"failed", "idle":returndefault:try? awaitTask.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.privatefunc finish() async {let successor = self.successorlet current = self.currentlet promoted = awaitTask.detached(priority: .userInitiated) { () -> Boolin (try? DeviceKey.promote(successor: successor, into: current)) ?? false }.valueguard promoted else {Log.write("re-key: the new key could not be kept; the old key stays in use")return }await reopen?() }}