From e5ed7c0f56ec262ccc2b828e248c132baa8b3dbf Mon Sep 17 00:00:00 2001 From: sudoHG Date: Mon, 16 Nov 2026 00:09:18 +0800 Subject: [PATCH 1/2] Retire Approve Requests and Stop Approving on the iPhone Pairing makes the iPhone an approver (ADR 0014, amended by #336), so the iPhone app drops the approver confirmation flow (ApproverConfirmationFlow, startApproverConfirmation, confirmApprover, confirmationSaved and its screen), Stop Approving for This Mac, the outbox's confirmation purpose and revocationCount, whose only reader was confirmationSaved. Mac detail shows a status line, Rename and Remove. A Mac paired before #336 without the flag says to remove it and pair again, and only such a row is marked on the list. Remove's confirmation says this iPhone stops at once, drops the pending requests and tells the Mac, which stops trusting the iPhone only when it processes the unpair notice. A removal whose list write fails is reported on the detail screen. Tests replace Stop Approving with removal in the race tests and cover the status, re-pairing a Mac without the flag and a failed removal. Renders add the Mac detail states and the removal confirmation and drop the approver screens. --- iOS/AskKeyiOSKit/App/AppModel+Approvals.swift | 38 +- iOS/AskKeyiOSKit/App/AppModel+Decisions.swift | 29 +- iOS/AskKeyiOSKit/App/AppModel+Macs.swift | 167 +------- iOS/AskKeyiOSKit/App/AppModel.swift | 18 +- iOS/AskKeyiOSKit/App/AppStates.swift | 4 +- .../Resources/Localizable.xcstrings | 403 +----------------- .../Services/DeviceServices.swift | 7 +- .../Views/ApproverConfirmationView.swift | 98 ----- iOS/AskKeyiOSKit/Views/MacDetailView.swift | 81 ++-- iOS/AskKeyiOSKit/Views/PairedMacsView.swift | 22 +- .../ApprovalDecisionTests.swift | 5 +- iOS/AskKeyiOSKitTests/ApprovalRaceTests.swift | 26 +- .../ApprovalRequestTests.swift | 5 +- iOS/AskKeyiOSKitTests/ApproverTests.swift | 126 +++--- .../Fakes/ApprovalFakes.swift | 17 - iOS/AskKeyiOSKitTests/Fakes/TestWorld.swift | 2 +- iOS/AskKeyiOSKitTests/LocalizationTests.swift | 12 + .../OpenedRequestTests.swift | 13 +- iOS/AskKeyiOSKitTests/ScreenRenderTests.swift | 95 +++-- .../UnknownLayoutTests.swift | 1 - 20 files changed, 250 insertions(+), 919 deletions(-) delete mode 100644 iOS/AskKeyiOSKit/Views/ApproverConfirmationView.swift diff --git a/iOS/AskKeyiOSKit/App/AppModel+Approvals.swift b/iOS/AskKeyiOSKit/App/AppModel+Approvals.swift index 794c769..707cf18 100644 --- a/iOS/AskKeyiOSKit/App/AppModel+Approvals.swift +++ b/iOS/AskKeyiOSKit/App/AppModel+Approvals.swift @@ -1,17 +1,11 @@ import AskKeyDevices import Foundation -/// A message sealed once and sent until CloudKit saves it. +/// A receipt sealed once and sent until CloudKit saves it. struct OutgoingMessage: Hashable, Sendable { - enum Purpose: Hashable, Sendable { - /// The receipt for the request with this record name. - case receipt(request: String) - /// An approver confirmation; once saved, the flag for this pairing is set. - case confirmation(mac: DeviceID, pairingID: PairingID) - } - let envelope: DeviceEnvelope - let purpose: Purpose + /// The record name of the request it acknowledges. + let request: String } /// The approver's inbox side (ADR 0014 → iPhone app): which verified @@ -31,7 +25,8 @@ extension AppModel { // MARK: Handler - /// Verified kinds 10–14. `AskKeyDevices` checked the envelope, the + /// Verified kinds 10–13 (a retired kind 14 approver confirmation is + /// refused as unexpected). `AskKeyDevices` checked the envelope, the /// signatures, the payload and the pairing ID; this checks the /// direction and the approval flag: a Mac sends only requests and /// closed messages, and only a Mac whose entry carries this iPhone's @@ -129,8 +124,7 @@ extension AppModel { openedContent[recordName] = message forget(expired) if let receipt = try? services.sealer.sealApprovalReceipt(answering: message) { - outbox[receipt.envelope.recordName] = OutgoingMessage(envelope: receipt.envelope, - purpose: .receipt(request: recordName)) + outbox[receipt.envelope.recordName] = OutgoingMessage(envelope: receipt.envelope, request: recordName) } rebuildRequests() settleRequestNotifications(also: expired) @@ -194,13 +188,12 @@ extension AppModel { /// Runs before any removal of a Mac commits: an unpair notice, a /// removal here, or pairing again. Its requests are refused from now on. func macWillBeRemoved(_ entry: PairedDevice) async { - revocationCount += 1 revokedPairings.insert(entry.pairingID) dropApprovals(forMac: entry.deviceID.text) } /// Drops a Mac's requests, stored decisions, markers, unsent receipts - /// and confirmations, and their notifications. + /// and their notifications. func dropApprovals(forMac mac: String) { var state = approvals let dropped = state.requests.filter { $0.macID == mac }.map(\.recordName) @@ -208,25 +201,11 @@ extension AppModel { state.markers.removeAll { $0.macID == mac } if state != approvals { commitApprovals(state) } forget(dropped) - outbox = outbox.filter { _, message in - switch message.purpose { - case .receipt(let request): return !dropped.contains(request) - case .confirmation(let target, _): return target.text != mac - } - } - if approverConfirmation?.macID == mac { stopSendingConfirmation() } + outbox = outbox.filter { _, message in !dropped.contains(message.request) } rebuildRequests() settleRequestNotifications(also: dropped) } - /// A confirmation that will no longer be sent leaves its sheet waiting - /// for the person again. - private func stopSendingConfirmation() { - guard approverConfirmation?.stage == .sending else { return } - approverConfirmation?.stage = .entering - approverConfirmation?.problem = .notSent - } - /// After an account change, a sign-out or an identity reset: every /// stored request, decision and marker goes. func dropAllApprovals() { @@ -240,7 +219,6 @@ extension AppModel { // `loadApprovals` drops. AppLog.failure("Deleting the stored requests", error) } - stopSendingConfirmation() approvals = StoredApprovals() openedContent = [:] outbox = [:] diff --git a/iOS/AskKeyiOSKit/App/AppModel+Decisions.swift b/iOS/AskKeyiOSKit/App/AppModel+Decisions.swift index 28ab21f..3dc17c4 100644 --- a/iOS/AskKeyiOSKit/App/AppModel+Decisions.swift +++ b/iOS/AskKeyiOSKit/App/AppModel+Decisions.swift @@ -135,8 +135,7 @@ extension AppModel { /// Sends what is due: stored decisions until CloudKit saves them (every /// 2 seconds or after CloudKit's retry-after, "recipient unreachable" /// included) and again every 30 seconds without a closed message while - /// the countdown runs; receipts and approver confirmations until saved - /// or expired. Calls made while sending wait and send once more. + /// the countdown runs; receipts until saved or expired. Calls made while sending wait and send once more. func sendDueMessages() async { if let running = sendWork { sendAgain = true @@ -187,24 +186,16 @@ extension AppModel { let now = environment.clock.now() guard let message = outbox[name], message.envelope.expiresAt > now, (nextAttempts[name] ?? .distantPast) <= now else { continue } - if case .receipt(let request) = message.purpose { - // A request already closed needs no receipt; one a tapped - // fetch found waits until a zone poll checked it (#337). - guard let index = approvals.index(of: request), approvals.requests[index].closed == nil else { - outbox[name] = nil - continue - } - if uncheckedRequests.contains(request) { continue } + // A request already closed needs no receipt; one a tapped fetch + // found waits until a zone poll checked it (#337). + guard let index = approvals.index(of: message.request), approvals.requests[index].closed == nil else { + outbox[name] = nil + continue } + if uncheckedRequests.contains(message.request) { continue } let saved = await send(message.envelope, retryKey: name, services: services) guard self.services === services else { return } - if case .confirmation(let mac, _) = message.purpose, !saved, approverConfirmation?.macID == mac.text { - approverConfirmation?.problem = .retrying - } - guard saved, outbox.removeValue(forKey: name) != nil else { continue } - if case .confirmation(let mac, let pairingID) = message.purpose { - await confirmationSaved(mac: mac, pairingID: pairingID, services: services) - } + if saved { outbox[name] = nil } } } @@ -257,10 +248,6 @@ extension AppModel { for (name, message) in outbox where message.envelope.expiresAt <= now { outbox[name] = nil nextAttempts[name] = nil - if case .confirmation(let mac, _) = message.purpose, approverConfirmation?.macID == mac.text { - approverConfirmation?.stage = .entering - approverConfirmation?.problem = .notSent - } } rebuildRequests() settleRequestNotifications(also: expired) diff --git a/iOS/AskKeyiOSKit/App/AppModel+Macs.swift b/iOS/AskKeyiOSKit/App/AppModel+Macs.swift index b1c30de..76eb241 100644 --- a/iOS/AskKeyiOSKit/App/AppModel+Macs.swift +++ b/iOS/AskKeyiOSKit/App/AppModel+Macs.swift @@ -1,171 +1,10 @@ import AskKeyDevices import Foundation -/// The approver confirmation while its sheet is open (ADR 0014 → Approvers, step 2). -public struct ApproverConfirmationFlow: Identifiable, Hashable, Sendable { - public enum Stage: Hashable, Sendable { - /// Typing the code. - case entering - /// Checking, and the Face ID prompt. - case confirming - /// Sealed; sending until CloudKit saves it. - case sending - /// Saved, and this iPhone's approval flag for the Mac is set. - case sent - } - - public var id: String { macID } - public let macID: String - public let macName: String - public internal(set) var stage: Stage = .entering - public internal(set) var problem: ApproverProblem? - - public init(macID: String, macName: String, stage: Stage = .entering, problem: ApproverProblem? = nil) { - self.macID = macID - self.macName = macName - self.stage = stage - self.problem = problem - } -} - -/// Why the confirmation is not sent, or not sent yet. -public enum ApproverProblem: Hashable, Sendable { - /// Not exactly six digits once white space is removed; nothing was sent. - case invalidCode - case cancelled - case failed - case unavailable - case account - /// CloudKit has not saved it yet; it is tried again. - case retrying - /// It expired before CloudKit saved it. - case notSent - case other -} - -/// The paired Macs on this iPhone: names, approval, removal. +/// The paired Macs on this iPhone: their names. Removal is in `AppModel`; +/// pairing is what makes this iPhone approve a Mac's requests (ADR 0014, +/// amended by #336). extension AppModel { - // MARK: Approval - - public func startApproverConfirmation(macID: String) { - guard stage == .ready, approverConfirmation == nil, let row = pairedMacs.first(where: { $0.id == macID }) else { - return - } - approverConfirmation = ApproverConfirmationFlow(macID: row.id, macName: row.name) - } - - /// Closes the sheet. A confirmation already sealed is still sent, and - /// the flag set once CloudKit saves it. - public func closeApproverConfirmation() { - approverConfirmation = nil - } - - /// **Approve Requests from This Mac**: sends nothing unless exactly six - /// ASCII digits remain once white space is removed; then signs the code - /// proof with the approval key (Face ID), and once CloudKit saved the - /// confirmation, sets this iPhone's approval flag for the Mac. It - /// cannot learn whether the Mac accepted. - public func confirmApprover(typed text: String) async { - guard let flow = approverConfirmation, flow.stage == .entering, let services, - let mac = DeviceID(text: flow.macID) else { return } - guard let code = ApproverCode(typed: text) else { - approverConfirmation?.problem = .invalidCode - return - } - approverConfirmation?.problem = nil - approverConfirmation?.stage = .confirming - func stop(_ problem: ApproverProblem) { - guard approverConfirmation?.macID == flow.macID else { return } - approverConfirmation?.stage = .entering - approverConfirmation?.problem = problem - } - guard await accountAllowsSending(services) else { return stop(.account) } - guard let list = try? await services.registry.list(), self.services === services, - let entry = list.device(mac) else { return stop(.other) } - let sealed: SealedDeviceMessage - do { - isAuthenticating = true - defer { isAuthenticating = false } - let reason = String(localized: "approver.reason \(entry.displayName)", bundle: .kit) - sealed = try await services.sealer.sealApproverConfirmation(code, to: entry, approvalReason: reason) - } catch let error as DeviceIdentityError { - switch error { - case .authenticationCancelled: return stop(.cancelled) - case .authenticationFailed: return stop(.failed) - case .authenticationUnavailable: return stop(.unavailable) - case .unusable, .secureEnclaveUnavailable, .keyCreationFailed: - approverConfirmation = nil - return identityBecameUnusable() - } - } catch { - AppLog.failure("Sealing an approver confirmation", error) - return stop(.other) - } - // The prompt may have outlasted the Mac's entry. - guard self.services === services, let after = try? await services.registry.list(), - after.device(mac)?.pairingID == entry.pairingID else { return stop(.other) } - outbox[sealed.envelope.recordName] = OutgoingMessage(envelope: sealed.envelope, - purpose: .confirmation(mac: mac, pairingID: entry.pairingID)) - if approverConfirmation?.macID == flow.macID { approverConfirmation?.stage = .sending } - await sendDueMessages() - } - - /// CloudKit saved the confirmation: the flag for that pairing is set. - /// A revocation that happened meanwhile wins: the flag is cleared again - /// and the revocation stays. - func confirmationSaved(mac: DeviceID, pairingID: PairingID, services: DeviceServices) async { - let revocations = revocationCount - do { - guard try await services.registry.apply(.setApprover(mac, pairingID: pairingID, enabled: true)) == .applied else { - if approverConfirmation?.macID == mac.text { approverConfirmation = nil } - return - } - guard revocationCount == revocations else { - _ = try await services.registry.apply(.setApprover(mac, pairingID: pairingID, enabled: false)) - if approverConfirmation?.macID == mac.text { approverConfirmation = nil } - return await refreshList() - } - revokedPairings.remove(pairingID) - if approverConfirmation?.macID == mac.text { - approverConfirmation?.stage = .sent - approverConfirmation?.problem = nil - } - } catch { - AppLog.failure("Setting the approval flag", error) - if approverConfirmation?.macID == mac.text { - approverConfirmation?.stage = .entering - approverConfirmation?.problem = .other - } - } - await refreshList() - } - - /// **Stop Approving for This Mac**: its requests are refused at once, - /// and its cards, stored decisions and notifications are dropped before - /// anything waits; then the flag is cleared. The Mac's own setting - /// changes on the Mac. Returns false when the flag could not be cleared, - /// so the person can try again; until then this process refuses the - /// Mac's requests. - @discardableResult - public func stopApproving(macID: String) async -> Bool { - guard let services, let mac = DeviceID(text: macID) else { return false } - var known = knownList?.device(mac) - if known == nil { known = try? await services.registry.list().device(mac) } - guard let entry = known else { return false } - revocationCount += 1 - revokedPairings.insert(entry.pairingID) - dropApprovals(forMac: macID) - do { - try await services.registry.apply(.setApprover(mac, pairingID: entry.pairingID, enabled: false)) - } catch { - AppLog.failure("Clearing the approval flag", error) - await refreshList() - return false - } - await refreshList() - return true - } - // MARK: Names /// Renames a Mac on this iPhone. Names stay unique: a name another Mac diff --git a/iOS/AskKeyiOSKit/App/AppModel.swift b/iOS/AskKeyiOSKit/App/AppModel.swift index 8274160..9dc8100 100644 --- a/iOS/AskKeyiOSKit/App/AppModel.swift +++ b/iOS/AskKeyiOSKit/App/AppModel.swift @@ -31,8 +31,6 @@ public final class AppModel { public var openedRequest: OpenedRequest? /// The tapped record while its request has no card yet. public internal(set) var opening: OpeningRequest? - /// The approver confirmation while its sheet is open. - public var approverConfirmation: ApproverConfirmationFlow? /// A newly paired Mac got a numbered name; the person may rename it. public var renamePrompt: RenamePrompt? @@ -53,8 +51,6 @@ public final class AppModel { /// False while the stored state exists but cannot be read; nothing is /// then accepted, decided or written, so it is never overwritten. @ObservationIgnored var approvalsReadable = true - /// Grows whenever a Mac's approval ends here, so work that awaited can tell. - @ObservationIgnored var revocationCount = 0 /// Requests settled in this process, so a notification found later for /// one of them is removed at once. @ObservationIgnored var settledRequests: Set = [] @@ -64,12 +60,11 @@ public final class AppModel { @ObservationIgnored var namedFetchNotBefore: Date? /// Opened requests by record name, in memory only. @ObservationIgnored var openedContent: [String: VerifiedApprovalMessage] = [:] - /// Pairings whose approval ended in this process: turned off here, or - /// the Mac removed. Their requests are refused even before the list - /// write that clears the flag commits. + /// Pairings whose Mac was removed in this process: here, by its unpair + /// notice or by pairing again. Their requests are refused from the + /// moment the removal starts, even if its list write then fails. @ObservationIgnored var revokedPairings: Set = [] - /// Messages sealed once and sent until saved: receipts and approver - /// confirmations, by record name. + /// Receipts sealed once and sent until saved, by record name. @ObservationIgnored var outbox: [String: OutgoingMessage] = [:] /// When a failed send may be tried again, by record name. @ObservationIgnored var nextAttempts: [String: Date] = [:] @@ -394,7 +389,10 @@ public final class AppModel { // MARK: Paired Macs - /// Removes the Mac at once, then sends it an unpair notice. + /// Removes the Mac at once, then sends it an unpair notice. The removal + /// hook has already stopped this iPhone approving the Mac's requests + /// and dropped them before the list write; the Mac stops trusting this + /// iPhone only when it processes the notice (ADR 0014 → Revocation). public func removeMac(id: String) async { guard let services, let deviceID = DeviceID(text: id), let row = pairedMacs.first(where: { $0.id == id }) else { return } diff --git a/iOS/AskKeyiOSKit/App/AppStates.swift b/iOS/AskKeyiOSKit/App/AppStates.swift index eab4392..2a230c8 100644 --- a/iOS/AskKeyiOSKit/App/AppStates.swift +++ b/iOS/AskKeyiOSKit/App/AppStates.swift @@ -56,7 +56,9 @@ public struct PairedMacRow: Identifiable, Hashable, Sendable { public let pairedAt: Date /// Nil until the first delivery check from that Mac arrived. public let lastReachedAt: Date? - /// This iPhone accepts approval requests from this Mac. + /// This iPhone accepts approval requests from this Mac. Pairing sets + /// it; only a Mac paired before #336 without approval lacks it, and + /// has to be removed and paired again. public let isApprover: Bool public init(id: String, name: String, pairedAt: Date, lastReachedAt: Date?, isApprover: Bool = false) { diff --git a/iOS/AskKeyiOSKit/Resources/Localizable.xcstrings b/iOS/AskKeyiOSKit/Resources/Localizable.xcstrings index bd1851f..e095d29 100644 --- a/iOS/AskKeyiOSKit/Resources/Localizable.xcstrings +++ b/iOS/AskKeyiOSKit/Resources/Localizable.xcstrings @@ -1,244 +1,6 @@ { "sourceLanguage": "en", "strings": { - "approver.confirm": { - "extractionState": "manual", - "localizations": { - "en": { - "stringUnit": { - "state": "translated", - "value": "Confirm" - } - }, - "zh-Hans": { - "stringUnit": { - "state": "translated", - "value": "确认" - } - } - } - }, - "approver.confirming": { - "extractionState": "manual", - "localizations": { - "en": { - "stringUnit": { - "state": "translated", - "value": "Confirming…" - } - }, - "zh-Hans": { - "stringUnit": { - "state": "translated", - "value": "正在确认…" - } - } - } - }, - "approver.field": { - "extractionState": "manual", - "localizations": { - "en": { - "stringUnit": { - "state": "translated", - "value": "Approver code" - } - }, - "zh-Hans": { - "stringUnit": { - "state": "translated", - "value": "审批码" - } - } - } - }, - "approver.onlyOnMac": { - "extractionState": "manual", - "localizations": { - "en": { - "stringUnit": { - "state": "translated", - "value": "The approver code appears only on that Mac's screen. Never enter a code that someone sends you." - } - }, - "zh-Hans": { - "stringUnit": { - "state": "translated", - "value": "审批码只会显示在那台 Mac 的屏幕上。别人发给你的代码,一律不要输入。" - } - } - } - }, - "approver.problem.invalidCode": { - "extractionState": "manual", - "localizations": { - "en": { - "stringUnit": { - "state": "translated", - "value": "Enter the six digits shown on the Mac. Nothing was sent." - } - }, - "zh-Hans": { - "stringUnit": { - "state": "translated", - "value": "请输入 Mac 上显示的六位数字。没有发送任何内容。" - } - } - } - }, - "approver.problem.notSent": { - "extractionState": "manual", - "localizations": { - "en": { - "stringUnit": { - "state": "translated", - "value": "The confirmation couldn't be sent in time. Start again on the Mac." - } - }, - "zh-Hans": { - "stringUnit": { - "state": "translated", - "value": "确认未能及时发送。请在 Mac 上重新开始。" - } - } - } - }, - "approver.problem.other": { - "extractionState": "manual", - "localizations": { - "en": { - "stringUnit": { - "state": "translated", - "value": "Something went wrong. Try again." - } - }, - "zh-Hans": { - "stringUnit": { - "state": "translated", - "value": "出了点问题,请重试。" - } - } - } - }, - "approver.problem.retrying": { - "extractionState": "manual", - "localizations": { - "en": { - "stringUnit": { - "state": "translated", - "value": "iCloud hasn't saved the confirmation yet. Ask Key keeps trying for a few minutes." - } - }, - "zh-Hans": { - "stringUnit": { - "state": "translated", - "value": "iCloud 还没有保存这个确认。请旨会在几分钟内继续尝试。" - } - } - } - }, - "approver.reason %@": { - "extractionState": "manual", - "localizations": { - "en": { - "stringUnit": { - "state": "translated", - "value": "Approve requests from “%@”" - } - }, - "zh-Hans": { - "stringUnit": { - "state": "translated", - "value": "审批“%@”的请求" - } - } - } - }, - "approver.sending": { - "extractionState": "manual", - "localizations": { - "en": { - "stringUnit": { - "state": "translated", - "value": "Sending the confirmation…" - } - }, - "zh-Hans": { - "stringUnit": { - "state": "translated", - "value": "正在发送确认…" - } - } - } - }, - "approver.sent %@": { - "extractionState": "manual", - "localizations": { - "en": { - "stringUnit": { - "state": "translated", - "value": "Sent to “%@”. If the code matched, the Mac turns approval on and starts sending this iPhone its requests. This iPhone can't tell whether it did; check the Mac." - } - }, - "zh-Hans": { - "stringUnit": { - "state": "translated", - "value": "已发送给“%@”。如果审批码正确,Mac 会开启审批,并开始把请求发到这台 iPhone。这台 iPhone 无法得知是否开启成功,请在 Mac 上查看。" - } - } - } - }, - "approver.subtitle %@": { - "extractionState": "manual", - "localizations": { - "en": { - "stringUnit": { - "state": "translated", - "value": "Enter the approver code that Ask Key shows on “%@”." - } - }, - "zh-Hans": { - "stringUnit": { - "state": "translated", - "value": "请输入“%@”上的请旨显示的审批码。" - } - } - } - }, - "approver.title": { - "extractionState": "manual", - "localizations": { - "en": { - "stringUnit": { - "state": "translated", - "value": "Approve Requests" - } - }, - "zh-Hans": { - "stringUnit": { - "state": "translated", - "value": "审批请求" - } - } - } - }, - "approver.whatArrives": { - "extractionState": "manual", - "localizations": { - "en": { - "stringUnit": { - "state": "translated", - "value": "After this, the Mac sends this iPhone its agents' requests: the agent, the credential's name, the command, the folder and the delivered names, never a value. Allowing always needs Face ID or Touch ID." - } - }, - "zh-Hans": { - "stringUnit": { - "state": "translated", - "value": "之后,这台 Mac 会把 Agent 的请求发到这台 iPhone:包括 Agent、凭证名称、命令、目录和交出的名称,绝不包括凭证的值。允许时始终需要面容 ID 或触控 ID。" - } - } - } - }, "common.appName": { "extractionState": "manual", "localizations": { @@ -358,23 +120,6 @@ } } }, - "list.approver": { - "extractionState": "manual", - "localizations": { - "en": { - "stringUnit": { - "state": "translated", - "value": "Approves agent requests" - } - }, - "zh-Hans": { - "stringUnit": { - "state": "translated", - "value": "审批 Agent 请求" - } - } - } - }, "list.deliveries.polling %@": { "extractionState": "manual", "localizations": { @@ -460,6 +205,23 @@ } } }, + "list.notApprover": { + "extractionState": "manual", + "localizations": { + "en": { + "stringUnit": { + "state": "translated", + "value": "Can't approve its requests. Remove it and pair again." + } + }, + "zh-Hans": { + "stringUnit": { + "state": "translated", + "value": "不能审批它的请求。请移除后重新配对。" + } + } + } + }, "list.notReached": { "extractionState": "manual", "localizations": { @@ -619,13 +381,13 @@ "en": { "stringUnit": { "state": "translated", - "value": "This iPhone stops trusting this Mac at once. Ask Key also tells the Mac, which removes this iPhone when it next checks." + "value": "This iPhone stops approving this Mac's requests at once and drops the pending ones. Ask Key also tells the Mac, which stops trusting this iPhone when it next checks. To end approval on the Mac at once, remove this iPhone there too." } }, "zh-Hans": { "stringUnit": { "state": "translated", - "value": "这台 iPhone 会立即不再信任这台 Mac。请旨也会通知 Mac,Mac 下次检查时会移除这台 iPhone。" + "value": "这台 iPhone 会立即停止审批这台 Mac 的请求,并丢弃待处理的请求。请旨也会通知 Mac,Mac 下次检查时才会不再信任这台 iPhone。如需立即在 Mac 上结束审批,请也在 Mac 上的请旨中移除这台 iPhone。" } } } @@ -664,40 +426,6 @@ } } }, - "mac.approve": { - "extractionState": "manual", - "localizations": { - "en": { - "stringUnit": { - "state": "translated", - "value": "Approve Requests from This Mac" - } - }, - "zh-Hans": { - "stringUnit": { - "state": "translated", - "value": "审批这台 Mac 的请求" - } - } - } - }, - "mac.approveAgain": { - "extractionState": "manual", - "localizations": { - "en": { - "stringUnit": { - "state": "translated", - "value": "Enter a New Approval Code" - } - }, - "zh-Hans": { - "stringUnit": { - "state": "translated", - "value": "重新输入审批码" - } - } - } - }, "mac.rename": { "extractionState": "manual", "localizations": { @@ -891,13 +619,13 @@ "en": { "stringUnit": { "state": "translated", - "value": "This iPhone approves agent requests from this Mac. Allowing always needs Face ID or Touch ID." + "value": "This iPhone can approve agents' requests to use credentials on this Mac. Allowing always needs Face ID or Touch ID." } }, "zh-Hans": { "stringUnit": { "state": "translated", - "value": "这台 iPhone 会审批这台 Mac 上 Agent 的请求。允许时始终需要面容 ID 或触控 ID。" + "value": "这台 iPhone 可以审批 Agent 使用这台 Mac 上凭证的请求。允许时始终需要面容 ID 或触控 ID。" } } } @@ -908,98 +636,13 @@ "en": { "stringUnit": { "state": "translated", - "value": "This iPhone doesn't accept agent requests from this Mac." - } - }, - "zh-Hans": { - "stringUnit": { - "state": "translated", - "value": "这台 iPhone 不接受这台 Mac 上 Agent 的请求。" - } - } - } - }, - "mac.stop": { - "extractionState": "manual", - "localizations": { - "en": { - "stringUnit": { - "state": "translated", - "value": "Stop Approving for This Mac" - } - }, - "zh-Hans": { - "stringUnit": { - "state": "translated", - "value": "停止为这台 Mac 审批" - } - } - } - }, - "mac.stop.confirm": { - "extractionState": "manual", - "localizations": { - "en": { - "stringUnit": { - "state": "translated", - "value": "Stop Approving" - } - }, - "zh-Hans": { - "stringUnit": { - "state": "translated", - "value": "停止审批" - } - } - } - }, - "mac.stop.confirmMessage": { - "extractionState": "manual", - "localizations": { - "en": { - "stringUnit": { - "state": "translated", - "value": "This iPhone stops showing this Mac's requests at once and drops the pending ones. To turn approval off on the Mac too, use Ask Key on the Mac." - } - }, - "zh-Hans": { - "stringUnit": { - "state": "translated", - "value": "这台 iPhone 会立即不再显示这台 Mac 的请求,并丢弃待处理的请求。如需在 Mac 上也关闭审批,请在 Mac 上的请旨中操作。" - } - } - } - }, - "mac.stop.confirmTitle %@": { - "extractionState": "manual", - "localizations": { - "en": { - "stringUnit": { - "state": "translated", - "value": "Stop approving requests from “%@”?" - } - }, - "zh-Hans": { - "stringUnit": { - "state": "translated", - "value": "停止审批“%@”的请求?" - } - } - } - }, - "mac.stop.failed": { - "extractionState": "manual", - "localizations": { - "en": { - "stringUnit": { - "state": "translated", - "value": "Approval couldn't be turned off on this iPhone. Try again." + "value": "This iPhone can't approve agents' requests from this Mac. To approve them, remove this Mac and pair it again." } }, "zh-Hans": { "stringUnit": { "state": "translated", - "value": "无法在这台 iPhone 上关闭审批,请重试。" + "value": "这台 iPhone 不能审批这台 Mac 上 Agent 的请求。如需审批,请移除这台 Mac 后重新配对。" } } } diff --git a/iOS/AskKeyiOSKit/Services/DeviceServices.swift b/iOS/AskKeyiOSKit/Services/DeviceServices.swift index fe9f759..ae0b80b 100644 --- a/iOS/AskKeyiOSKit/Services/DeviceServices.swift +++ b/iOS/AskKeyiOSKit/Services/DeviceServices.swift @@ -98,9 +98,10 @@ final class DeviceServices { typealias Handler = @Sendable (VerifiedApprovalMessage, _ generation: Int) async -> ApprovalMessageHandling - /// `approvalHandler` receives verified kind 10–14 messages with the - /// messenger's generation, and `removalHook` runs before any removal - /// of a Mac commits. + /// `approvalHandler` receives verified approval messages (kinds 10–13, + /// and a retired kind 14, which it refuses) with the messenger's + /// generation, and `removalHook` runs before any removal of a Mac + /// commits. init(identity: any DeviceIdentity, transport: any InboxTransport, listStore: any PairedDeviceListStore, clock: any DeviceClock, inboxToken: InboxChangeToken?, approvalHandler: Handler? = nil, removalHook: PairedDeviceRemovalHook? = nil) { diff --git a/iOS/AskKeyiOSKit/Views/ApproverConfirmationView.swift b/iOS/AskKeyiOSKit/Views/ApproverConfirmationView.swift deleted file mode 100644 index e63f933..0000000 --- a/iOS/AskKeyiOSKit/Views/ApproverConfirmationView.swift +++ /dev/null @@ -1,98 +0,0 @@ -import SwiftUI - -/// **Approve Requests from This Mac**: the code from the Mac's screen in a -/// plain numeric field (not a one-time-code field), then Face ID. -struct ApproverConfirmationView: View { - let model: AppModel - let flow: ApproverConfirmationFlow - @State private var code = "" - @FocusState private var focused: Bool - - private var current: ApproverConfirmationFlow { model.approverConfirmation ?? flow } - - var body: some View { - ApproverConfirmationContent(flow: current, onConfirm: confirm, onClose: model.closeApproverConfirmation) { - TextField(text: $code) { Text("approver.field", bundle: .kit) } - .keyboardType(.numberPad) - .autocorrectionDisabled() - .textInputAutocapitalization(.never) - .font(.title2.monospaced()) - .focused($focused) - .submitLabel(.done) - .onSubmit(confirm) - } - .screenScaffold() - .privacyCover(isAuthenticating: model.isAuthenticating) - .interactiveDismissDisabled(current.stage == .confirming) - .onAppear { focused = true } - .onChange(of: current.stage) { _, stage in - // The typed code is not kept once it was used. - if stage != .entering && stage != .confirming { code = "" } - } - } - - private func confirm() { - let typed = code - Task { await model.confirmApprover(typed: typed) } - } -} - -struct ApproverConfirmationContent: View { - let flow: ApproverConfirmationFlow - let onConfirm: () -> Void - let onClose: () -> Void - @ViewBuilder var field: Field - - var body: some View { - ScreenContent(title: "approver.title", subtitle: "approver.subtitle \(flow.macName)") { - switch flow.stage { - case .entering, .confirming: - NoticeCard(symbol: "lock.shield", tone: .warning, text: Text("approver.onlyOnMac", bundle: .kit)) - NoticeCard(symbol: "iphone", text: Text("approver.whatArrives", bundle: .kit)) - field - .padding(14) - .background(RoundedRectangle(cornerRadius: 14, style: .continuous) - .fill(Color(uiColor: .secondarySystemGroupedBackground))) - if let problem = flow.problem { - NoticeCard(symbol: "exclamationmark.triangle.fill", tone: .warning, text: Self.text(problem)) - } - Button(action: onConfirm) { - Text(flow.stage == .confirming ? "approver.confirming" : "approver.confirm", bundle: .kit) - } - .buttonStyle(ActionButtonStyle()) - .disabled(flow.stage == .confirming) - Text("pairing.confirm.footnote", bundle: .kit) - .font(.footnote) - .foregroundStyle(.secondary) - Button(action: onClose) { Text("common.cancel", bundle: .kit) } - .buttonStyle(ActionButtonStyle(kind: .secondary)) - .disabled(flow.stage == .confirming) - case .sending: - NoticeCard(symbol: "arrow.up.circle", text: Text("approver.sending", bundle: .kit)) - if let problem = flow.problem { - NoticeCard(symbol: "exclamationmark.triangle.fill", tone: .warning, text: Self.text(problem)) - } - Button(action: onClose) { Text("common.done", bundle: .kit) } - .buttonStyle(ActionButtonStyle(kind: .secondary)) - case .sent: - NoticeCard(symbol: "checkmark.circle.fill", tone: .success, - text: Text("approver.sent \(Text(verbatim: flow.macName))", bundle: .kit)) - Button(action: onClose) { Text("common.done", bundle: .kit) } - .buttonStyle(ActionButtonStyle()) - } - } - } - - static func text(_ problem: ApproverProblem) -> Text { - switch problem { - case .invalidCode: return Text("approver.problem.invalidCode", bundle: .kit) - case .cancelled: return Text("pairing.confirm.cancelled", bundle: .kit) - case .failed: return Text("pairing.confirm.failed", bundle: .kit) - case .unavailable: return Text("pairing.confirm.unavailable", bundle: .kit) - case .account: return Text("request.problem.account", bundle: .kit) - case .retrying: return Text("approver.problem.retrying", bundle: .kit) - case .notSent: return Text("approver.problem.notSent", bundle: .kit) - case .other: return Text("approver.problem.other", bundle: .kit) - } - } -} diff --git a/iOS/AskKeyiOSKit/Views/MacDetailView.swift b/iOS/AskKeyiOSKit/Views/MacDetailView.swift index ebfae2d..9b3ce87 100644 --- a/iOS/AskKeyiOSKit/Views/MacDetailView.swift +++ b/iOS/AskKeyiOSKit/Views/MacDetailView.swift @@ -1,30 +1,28 @@ import SwiftUI /// One paired Mac: its name on this iPhone, whether this iPhone approves -/// its requests, and removal. +/// its requests, and removal, which is how approval stops (ADR 0014, +/// amended by #336). struct MacDetailView: View { @Bindable var model: AppModel let macID: String @Environment(\.dismiss) private var dismiss - @State private var confirmingStop = false @State private var confirmingRemoval = false @State private var renaming = false @State private var newName = "" @State private var renameProblem: RenameProblem? - @State private var stopFailed = false + @State private var removalFailed = false private var row: PairedMacRow? { model.pairedMacs.first { $0.id == macID } } var body: some View { Group { if let row { - MacDetailContent(row: row, renameProblem: renameProblem, stopFailed: stopFailed, + MacDetailContent(row: row, renameProblem: renameProblem, removalFailed: removalFailed, onRename: { newName = row.name renaming = true }, - onApprove: { model.startApproverConfirmation(macID: macID) }, - onStop: { confirmingStop = true }, onRemove: { confirmingRemoval = true }) } } @@ -45,41 +43,40 @@ struct MacDetailView: View { } message: { Text("mac.rename.message", bundle: .kit) } - .confirmationDialog(Text("mac.stop.confirmTitle \(row?.name ?? String())", bundle: .kit), - isPresented: $confirmingStop, titleVisibility: .visible) { + .confirmationDialog(MacRemovalText.title(row?.name ?? String()), isPresented: $confirmingRemoval, + titleVisibility: .visible) { Button(role: .destructive) { - Task { stopFailed = !(await model.stopApproving(macID: macID)) } - } label: { - Text("mac.stop.confirm", bundle: .kit) - } - Button(role: .cancel) {} label: { Text("common.cancel", bundle: .kit) } - } message: { - Text("mac.stop.confirmMessage", bundle: .kit) - } - .confirmationDialog(Text("list.remove.confirmTitle \(row?.name ?? String())", bundle: .kit), - isPresented: $confirmingRemoval, titleVisibility: .visible) { - Button(role: .destructive) { - Task { await model.removeMac(id: macID) } + removalFailed = false + Task { + await model.removeMac(id: macID) + // A removal that succeeded closes this screen. + removalFailed = row != nil && model.listNotice == .removalFailed + } } label: { - Text("list.remove.confirm", bundle: .kit) + MacRemovalText.confirm } Button(role: .cancel) {} label: { Text("common.cancel", bundle: .kit) } } message: { - Text("list.remove.confirmMessage", bundle: .kit) - } - .sheet(item: $model.approverConfirmation, onDismiss: model.closeApproverConfirmation) { flow in - ApproverConfirmationView(model: model, flow: flow) + MacRemovalText.message } } } +/// **Remove**'s confirmation, in the dialog and in its render: this iPhone +/// stops at once, drops the Mac's pending requests and tells the Mac, which +/// stops trusting this iPhone only when it processes the unpair notice +/// (ADR 0014 → Revocation, decision 3 of the #336 amendment). +enum MacRemovalText { + static func title(_ name: String) -> Text { Text("list.remove.confirmTitle \(name)", bundle: .kit) } + static var message: Text { Text("list.remove.confirmMessage", bundle: .kit) } + static var confirm: Text { Text("list.remove.confirm", bundle: .kit) } +} + struct MacDetailContent: View { let row: PairedMacRow var renameProblem: RenameProblem? - var stopFailed = false + var removalFailed = false let onRename: () -> Void - let onApprove: () -> Void - let onStop: () -> Void let onRemove: () -> Void var body: some View { @@ -104,22 +101,18 @@ struct MacDetailContent: View { if let renameProblem { NoticeCard(symbol: "exclamationmark.triangle.fill", tone: .warning, text: Self.text(renameProblem)) } - VStack(alignment: .leading, spacing: 12) { - if stopFailed { - NoticeCard(symbol: "exclamationmark.triangle.fill", tone: .warning, - text: Text("mac.stop.failed", bundle: .kit)) - } - NoticeCard(symbol: row.isApprover ? "checkmark.shield.fill" : "shield.slash", - tone: row.isApprover ? .success : .info, - text: Text(row.isApprover ? "mac.status.approving" : "mac.status.notApproving", bundle: .kit)) - // The iPhone cannot learn whether the Mac accepted; once its flag - // is on, the button only sends a new code. - Button(action: onApprove) { Text(row.isApprover ? "mac.approveAgain" : "mac.approve", bundle: .kit) } - .buttonStyle(ActionButtonStyle(kind: row.isApprover ? .secondary : .primary)) - if row.isApprover { - Button(action: onStop) { Text("mac.stop", bundle: .kit) } - .buttonStyle(ActionButtonStyle(kind: .destructive)) - } + // Pairing sets the flag; only a Mac paired before #336 without + // approval lacks it, and only pairing again can set it. + if row.isApprover { + NoticeCard(symbol: "checkmark.shield.fill", tone: .success, + text: Text("mac.status.approving", bundle: .kit)) + } else { + NoticeCard(symbol: "exclamationmark.shield.fill", tone: .warning, + text: Text("mac.status.notApproving", bundle: .kit)) + } + if removalFailed { + NoticeCard(symbol: "exclamationmark.triangle.fill", tone: .warning, + text: Text("list.notice.removalFailed", bundle: .kit)) } Button(action: onRemove) { Text("list.remove", bundle: .kit) } .buttonStyle(ActionButtonStyle(kind: .destructive)) diff --git a/iOS/AskKeyiOSKit/Views/PairedMacsView.swift b/iOS/AskKeyiOSKit/Views/PairedMacsView.swift index 140e253..8a03645 100644 --- a/iOS/AskKeyiOSKit/Views/PairedMacsView.swift +++ b/iOS/AskKeyiOSKit/Views/PairedMacsView.swift @@ -53,9 +53,10 @@ struct PairedMacsView: View { } } -/// The requests, then the paired Macs: name, paired date, last reached and -/// whether this iPhone approves its requests; the iCloud state and the -/// outcome of the last removal; and the delivery checks this iPhone answered. +/// The requests, then the paired Macs: name, paired date, last reached and, +/// for a Mac paired before #336 without approval, that this iPhone can't +/// approve its requests; the iCloud state and the outcome of the last +/// removal; and the delivery checks this iPhone answered. struct PairedMacsContent: View { let rows: [PairedMacRow] let accountNotice: AccountNotice? @@ -151,7 +152,9 @@ extension PairedMacsContent where Requests == EmptyView { } } -/// A Mac's row; tapping it opens the Mac's detail. +/// A Mac's row; tapping it opens the Mac's detail. Pairing makes this iPhone +/// approve a Mac's requests, so only the exception is marked: an entry +/// without the flag. private struct MacRow: View { let row: PairedMacRow let onSelect: () -> Void @@ -181,10 +184,13 @@ private struct MacRow: View { .font(.footnote) .foregroundStyle(.orange) } - if row.isApprover { - Label { Text("list.approver", bundle: .kit) } icon: { Image(systemName: "checkmark.shield.fill") } - .font(.footnote.weight(.semibold)) - .foregroundStyle(.green) + if !row.isApprover { + Label { Text("list.notApprover", bundle: .kit) } icon: { + Image(systemName: "exclamationmark.shield.fill") + } + .font(.footnote.weight(.semibold)) + .foregroundStyle(.orange) + .multilineTextAlignment(.leading) } } Spacer(minLength: 8) diff --git a/iOS/AskKeyiOSKitTests/ApprovalDecisionTests.swift b/iOS/AskKeyiOSKitTests/ApprovalDecisionTests.swift index 7408e41..0cfe34e 100644 --- a/iOS/AskKeyiOSKitTests/ApprovalDecisionTests.swift +++ b/iOS/AskKeyiOSKitTests/ApprovalDecisionTests.swift @@ -11,7 +11,6 @@ final class ApprovalDecisionTests: XCTestCase { world = TestWorld() await world.setUpPhone() try await world.pair() - await world.approveMac() } override func tearDown() async throws { @@ -109,11 +108,11 @@ final class ApprovalDecisionTests: XCTestCase { XCTAssertTrue(world.model.requests.isEmpty, "the account change drops the stored requests") } - func testAMacWhoseApprovalEndedDuringThePromptGetsNothing() async throws { + func testAMacRemovedDuringThePromptGetsNothing() async throws { let phone = try world.phone let (_, id) = try await receive() let macID = world.macIdentity.deviceID.text - phone.duringApprovalPrompt = { [model = world.model] in await model.stopApproving(macID: macID) } + phone.duringApprovalPrompt = { [model = world.model] in await model.removeMac(id: macID) } await world.model.decide(.allowOnce, requestID: id) XCTAssertTrue(try world.decisionAttempts().isEmpty) XCTAssertTrue(world.model.requests.isEmpty) diff --git a/iOS/AskKeyiOSKitTests/ApprovalRaceTests.swift b/iOS/AskKeyiOSKitTests/ApprovalRaceTests.swift index 3cbb761..58b24af 100644 --- a/iOS/AskKeyiOSKitTests/ApprovalRaceTests.swift +++ b/iOS/AskKeyiOSKitTests/ApprovalRaceTests.swift @@ -12,7 +12,6 @@ final class ApprovalRaceTests: XCTestCase { world = TestWorld() await world.setUpPhone() try await world.pair() - await world.approveMac() } override func tearDown() async throws { @@ -28,7 +27,7 @@ final class ApprovalRaceTests: XCTestCase { return sealed.sealed.messageID.text } - func testStopApprovingDuringASendKeepsTheNextStoredDecisionFromLeaving() async throws { + func testRemovingTheMacDuringASendKeepsTheNextStoredDecisionFromLeaving() async throws { let first = try await receive() let second = try await receive() world.cloud.failSends { $0.kind == Self.decisionKind } @@ -40,7 +39,7 @@ final class ApprovalRaceTests: XCTestCase { world.cloud.sendHook = { [model = world.model, macID] envelope in guard envelope.kind == Self.decisionKind, !fired.value else { return } fired.value = true - _ = await model.stopApproving(macID: macID) + await model.removeMac(id: macID) } world.clock.advance(by: 2) await world.model.processInbox() @@ -141,16 +140,6 @@ final class ApprovalRaceTests: XCTestCase { XCTAssertEqual(world.approvalStore.storedData, stored) } - func testStopApprovingReportsAFlagThatCouldNotBeCleared() async throws { - world.keychain.writesFail = true - let stopped = await world.model.stopApproving(macID: macID) - XCTAssertFalse(stopped) - world.keychain.writesFail = false - try await world.sendRequest() - await world.model.processInbox() - XCTAssertTrue(world.model.requests.isEmpty, "this process refuses the Mac's requests anyway") - } - func testStoredRequestsAreCappedPerMacFinishedOnesIncluded() async throws { for _ in 0..<2 { var sealed: [SealedApprovalRequest] = [] @@ -194,15 +183,4 @@ final class ApprovalRaceTests: XCTestCase { await world.model.processInbox() XCTAssertEqual(Set(world.notifications.removedIdentifiers), ["first", "second"]) } - - func testAnAccountChangeWhileAConfirmationIsSendingResetsTheSheet() async throws { - world.cloud.failSends { $0.kind == Int64(MessageKind.approverConfirmation.rawValue) } - world.model.startApproverConfirmation(macID: macID) - await world.model.confirmApprover(typed: TestWorld.approverCode) - XCTAssertEqual(world.model.approverConfirmation?.stage, .sending) - world.cloud.accountState = .available(userRecordName: "_user-b") - await world.model.refreshAccount() - XCTAssertEqual(world.model.approverConfirmation?.stage, .entering) - XCTAssertEqual(world.model.approverConfirmation?.problem, .notSent) - } } diff --git a/iOS/AskKeyiOSKitTests/ApprovalRequestTests.swift b/iOS/AskKeyiOSKitTests/ApprovalRequestTests.swift index 3800255..9f28f34 100644 --- a/iOS/AskKeyiOSKitTests/ApprovalRequestTests.swift +++ b/iOS/AskKeyiOSKitTests/ApprovalRequestTests.swift @@ -11,7 +11,6 @@ final class ApprovalRequestTests: XCTestCase { world = TestWorld() await world.setUpPhone() try await world.pair() - await world.approveMac() } override func tearDown() async throws { @@ -144,7 +143,7 @@ final class ApprovalRequestTests: XCTestCase { func testAClosedMessageFromAnotherSenderIsRefused() async throws { let other = world.makeMac(name: "Office Mac") - try await world.pairAndApprove(other) + try await world.pair(other) let sealed = try await world.sendRequest() await world.model.processInbox() try await world.sendClosed(.decidedOnMac, for: sealed, from: other) @@ -275,7 +274,7 @@ final class ApprovalRequestTests: XCTestCase { var macs = [world.primaryMac] for index in 1..<5 { let peer = world.makeMac(name: "Mac \(index)") - try await world.pairAndApprove(peer) + try await world.pair(peer) macs.append(peer) } for peer in macs.prefix(4) { diff --git a/iOS/AskKeyiOSKitTests/ApproverTests.swift b/iOS/AskKeyiOSKitTests/ApproverTests.swift index bce1346..b4e0924 100644 --- a/iOS/AskKeyiOSKitTests/ApproverTests.swift +++ b/iOS/AskKeyiOSKitTests/ApproverTests.swift @@ -3,8 +3,8 @@ import SwiftUI import XCTest @testable import AskKeyiOSKit -/// The approver confirmation, Mac names, removal, notifications and the -/// privacy cover (#314 acceptance 6, 7 and 8). +/// The Mac's approval status, Mac names, removal, notifications and the +/// privacy cover (#314 acceptance 6, 7 and 8; #336 decisions 3 and 5). @MainActor final class ApproverTests: XCTestCase { private var world: TestWorld! @@ -13,9 +13,6 @@ final class ApproverTests: XCTestCase { world = TestWorld() await world.setUpPhone() try await world.pair() - // The approver confirmation applies to a Mac paired before #336 - // without approval; pairing now sets the flag. - try await world.storeWithoutApprovalFlag() } override func tearDown() async throws { @@ -24,89 +21,73 @@ final class ApproverTests: XCTestCase { private var macID: String { world.macIdentity.deviceID.text } - // MARK: Approver confirmation - - func testApproveRequestsTakesTheCodeAsksForFaceIDSendsTheConfirmationAndSetsTheFlag() async throws { - let phone = try world.phone - XCTAssertEqual(world.model.pairedMacs.first?.isApprover, false, "off after pairing") - world.model.startApproverConfirmation(macID: macID) - XCTAssertEqual(world.model.approverConfirmation?.macName, TestWorld.macName) - let authenticating = Box(false) - phone.duringApprovalPrompt = { [model = world.model] in authenticating.value = await model.isAuthenticating } - await world.model.confirmApprover(typed: " 042 917\n") - XCTAssertTrue(authenticating.value) - XCTAssertEqual(phone.approvalReasons.last?.contains("“\(TestWorld.macName)”"), true) - XCTAssertEqual(world.model.approverConfirmation?.stage, .sent) + // MARK: Approval status + + func testPairingIsAllItTakesToApproveTheMacsRequests() async throws { XCTAssertEqual(world.model.pairedMacs.first?.isApprover, true) + try await world.sendRequest() + await world.model.processInbox() + XCTAssertEqual(world.model.requests.count, 1) + } + + func testAMacPairedBeforeTheRuleWithoutApprovalIsMarkedAndRefused() async throws { + try await world.storeWithoutApprovalFlag() + XCTAssertEqual(world.model.pairedMacs.first?.isApprover, false, "the row and the detail show the exception") + try await world.sendRequest() + await world.model.processInbox() + XCTAssertTrue(world.model.requests.isEmpty) + XCTAssertTrue(world.approvalStore.stored.requests.isEmpty) + } + func testPairingAMacWithoutTheFlagAgainMakesThisIPhoneApproveIt() async throws { + try await world.storeWithoutApprovalFlag() + await world.model.removeMac(id: macID) + XCTAssertTrue(world.model.pairedMacs.isEmpty) _ = try await world.mac.poll() - let confirmation = try XCTUnwrap(world.macInbox.messages.compactMap { message -> ApproverConfirmation? in - if case .confirmation(let confirmation) = message.message { return confirmation } - return nil - }.first) - let entry = try await world.phoneEntry() - let code = try XCTUnwrap(ApproverCode(typed: "042917")) - XCTAssertTrue(code.matches(proof: confirmation.codeProof, mac: world.macIdentity.deviceID, phone: phone.deviceID, - pairingID: entry.pairingID), "the Mac's check of the code proof passes") - } - - func testAnythingButSixDigitsSendsNothing() async throws { - let phone = try world.phone - let prompts = phone.approvalReasons.count - world.model.startApproverConfirmation(macID: macID) - for typed in ["12345", "1234567", "12345a", "123456"] { - await world.model.confirmApprover(typed: typed) - XCTAssertEqual(world.model.approverConfirmation?.problem, .invalidCode, typed) - XCTAssertEqual(world.model.approverConfirmation?.stage, .entering) - } - XCTAssertEqual(phone.approvalReasons.count, prompts) - XCTAssertTrue(world.cloud.sent(.approverConfirmation, from: phone.deviceID).isEmpty) - } - - func testACancelledPromptSendsNothing() async throws { - let phone = try world.phone - phone.approvalBehavior = .cancel - world.model.startApproverConfirmation(macID: macID) - await world.model.confirmApprover(typed: TestWorld.approverCode) - XCTAssertEqual(world.model.approverConfirmation?.problem, .cancelled) - XCTAssertTrue(world.cloud.sent(.approverConfirmation, from: phone.deviceID).isEmpty) - XCTAssertEqual(world.model.pairedMacs.first?.isApprover, false) - } - - func testTheFlagIsSetOnlyOnceCloudKitSavedTheConfirmation() async throws { - world.cloud.failSends { $0.kind == Int64(MessageKind.approverConfirmation.rawValue) } - world.model.startApproverConfirmation(macID: macID) - await world.model.confirmApprover(typed: TestWorld.approverCode) - XCTAssertEqual(world.model.approverConfirmation?.stage, .sending) - XCTAssertEqual(world.model.approverConfirmation?.problem, .retrying) - XCTAssertEqual(world.model.pairedMacs.first?.isApprover, false) - XCTAssertEqual(world.model.foregroundPollInterval, 2) - world.cloud.failSends(where: nil) - world.clock.advance(by: 2) + try await world.pair() + XCTAssertEqual(world.model.pairedMacs.map(\.isApprover), [true]) + try await world.sendRequest() await world.model.processInbox() - XCTAssertEqual(world.model.approverConfirmation?.stage, .sent) - XCTAssertEqual(world.model.pairedMacs.first?.isApprover, true) + XCTAssertEqual(world.model.requests.count, 1) } - func testStopApprovingClearsTheFlagAndDropsTheMacsCards() async throws { - await world.approveMac() + // MARK: Removal + + func testRemovingTheMacStopsThisIPhoneAtOnceAndTellsTheMac() async throws { + let phoneID = try world.phone.deviceID let sealed = try await world.sendRequest() world.notifications.delivered = [PushHint(recordName: sealed.sealed.messageID.text, arrivedAt: world.clock.now(), notificationIdentifier: "request")] await world.model.becameActive() XCTAssertEqual(world.model.requests.count, 1) - await world.model.stopApproving(macID: macID) - XCTAssertEqual(world.model.pairedMacs.first?.isApprover, false) + await world.model.removeMac(id: macID) + XCTAssertTrue(world.model.pairedMacs.isEmpty) XCTAssertTrue(world.model.requests.isEmpty) XCTAssertTrue(world.approvalStore.stored.requests.isEmpty) XCTAssertTrue(world.notifications.removedIdentifiers.contains("request")) + XCTAssertEqual(world.model.listNotice, .removed(name: TestWorld.macName, macWasTold: true)) + XCTAssertEqual(world.cloud.sent(.unpairNotice, from: phoneID).count, 1) + // The Mac trusts this iPhone until it processes the unpair notice. + _ = try await world.phoneEntry() + _ = try await world.mac.poll() + let entries = try await world.mac.pairedDevices() + XCTAssertFalse(entries.contains { $0.deviceID == phoneID }) + } + + func testARemovalWhoseListWriteFailsStillStopsThisIPhone() async throws { + world.keychain.writesFail = true + await world.model.removeMac(id: macID) + XCTAssertEqual(world.model.listNotice, .removalFailed) + XCTAssertEqual(world.model.pairedMacs.count, 1, "the entry stays, so Remove can be tried again") + world.keychain.writesFail = false try await world.sendRequest() await world.model.processInbox() - XCTAssertTrue(world.model.requests.isEmpty, "requests from it are refused") + XCTAssertTrue(world.model.requests.isEmpty, "this process refuses the Mac's requests anyway") + await world.model.removeMac(id: macID) + XCTAssertTrue(world.model.pairedMacs.isEmpty) } func testRemovingAMacOrItsUnpairNoticeDropsItsCards() async throws { - await world.approveMac() try await world.sendRequest() await world.model.processInbox() XCTAssertEqual(world.model.requests.count, 1) @@ -115,7 +96,7 @@ final class ApproverTests: XCTestCase { XCTAssertTrue(world.approvalStore.stored.requests.isEmpty) let other = world.makeMac(name: "Office Mac") - try await world.pairAndApprove(other) + try await world.pair(other) try await world.sendRequest(from: other) await world.model.processInbox() XCTAssertEqual(world.model.requests.count, 1) @@ -159,7 +140,6 @@ final class ApproverTests: XCTestCase { // MARK: Notifications func testTappingANotificationOpensItsRequest() async throws { - await world.approveMac() let phoneID = try world.phone.deviceID let sealed = try await world.sendRequest() let name = sealed.sealed.messageID.text @@ -169,7 +149,6 @@ final class ApproverTests: XCTestCase { } func testANotificationThatIsOnlyShownOpensNothing() async throws { - await world.approveMac() let phoneID = try world.phone.deviceID let sealed = try await world.sendRequest() await world.model.receivedPush(userInfo: TestWorld.alertPush(for: phoneID, record: sealed.sealed.messageID.text), @@ -178,7 +157,6 @@ final class ApproverTests: XCTestCase { } func testOpeningANotificationThatLaunchesTheAppOpensItsRequest() async throws { - await world.approveMac() let phoneID = try world.phone.deviceID let sealed = try await world.sendRequest() let name = sealed.sealed.messageID.text @@ -191,7 +169,6 @@ final class ApproverTests: XCTestCase { } func testSettledRequestsLoseTheirNotifications() async throws { - await world.approveMac() let sealed = try await world.sendRequest() world.notifications.delivered = [PushHint(recordName: sealed.sealed.messageID.text, arrivedAt: world.clock.now(), notificationIdentifier: "request")] @@ -204,7 +181,6 @@ final class ApproverTests: XCTestCase { } func testAnExpiredRequestLosesItsNotificationAtTheNextLaunch() async throws { - await world.approveMac() let sealed = try await world.sendRequest() await world.model.processInbox() world.clock.advance(by: 300) diff --git a/iOS/AskKeyiOSKitTests/Fakes/ApprovalFakes.swift b/iOS/AskKeyiOSKitTests/Fakes/ApprovalFakes.swift index bfcf477..0fc72a2 100644 --- a/iOS/AskKeyiOSKitTests/Fakes/ApprovalFakes.swift +++ b/iOS/AskKeyiOSKitTests/Fakes/ApprovalFakes.swift @@ -104,17 +104,6 @@ extension TestWorld { commandLine: "./deploy.sh --prod --region eu-west-1", workingDirectory: "~/src/app", executableName: "deploy.sh", deliveryRows: [ApprovalDeliveryRow(kind: .environmentVariable, label: "", variable: "GITHUB_TOKEN")]) static let macLaunch = Date(timeIntervalSince1970: 1_799_990_000) - static let approverCode = "123 456" - - /// Turns approval on for the Mac on this iPhone through the approver - /// confirmation: the code, Face ID, the confirmation, then the flag. - func approveMac(_ peer: MacPeer? = nil, file: StaticString = #filePath, line: UInt = #line) async { - let peer = peer ?? primaryMac - model.startApproverConfirmation(macID: peer.deviceID.text) - await model.confirmApprover(typed: Self.approverCode) - XCTAssertEqual(model.approverConfirmation?.stage, .sent, file: file, line: line) - model.closeApproverConfirmation() - } /// Stores the iPhone's entry for `peer` again without the approval flag, /// as a Mac paired before #336 without approval is stored: every pairing @@ -132,12 +121,6 @@ extension TestWorld { await model.refreshList() } - /// Pairs another Mac and turns approval on for it. - func pairAndApprove(_ peer: MacPeer) async throws { - try await pair(peer) - await approveMac(peer) - } - /// The Mac's entry for this iPhone. func phoneEntry(on peer: MacPeer? = nil) async throws -> PairedDevice { let peer = peer ?? primaryMac diff --git a/iOS/AskKeyiOSKitTests/Fakes/TestWorld.swift b/iOS/AskKeyiOSKitTests/Fakes/TestWorld.swift index d70d4f9..94423ac 100644 --- a/iOS/AskKeyiOSKitTests/Fakes/TestWorld.swift +++ b/iOS/AskKeyiOSKitTests/Fakes/TestWorld.swift @@ -28,7 +28,7 @@ final class TestWorld { let notifications = FakeNotifications() let approvalStore = InMemoryApprovalStore() let macClock: OffsetClock - /// What every Mac's messenger verified: decisions, receipts, confirmations. + /// What every Mac's messenger verified: decisions and receipts. let macInbox = MacInbox() private(set) lazy var model = AppModel(environment: environment) diff --git a/iOS/AskKeyiOSKitTests/LocalizationTests.swift b/iOS/AskKeyiOSKitTests/LocalizationTests.swift index 10c9f9f..e61775d 100644 --- a/iOS/AskKeyiOSKitTests/LocalizationTests.swift +++ b/iOS/AskKeyiOSKitTests/LocalizationTests.swift @@ -44,6 +44,18 @@ final class LocalizationTests: XCTestCase { } } + /// Pairing makes this iPhone an approver (#336): no approver code, + /// approver confirmation or Stop Approving remains (#342). + func testNoRetiredApproverStringRemains() throws { + let english = try table("en") + for key in english.keys { + XCTAssertFalse(key.hasPrefix("approver.") || key.hasPrefix("mac.approve") || key.hasPrefix("mac.stop"), key) + let value = try XCTUnwrap(english[key]) + XCTAssertFalse(value.localizedCaseInsensitiveContains("approver code"), key) + XCTAssertFalse(value.localizedCaseInsensitiveContains("stop approving for"), key) + } + } + func testAlertKeysMatchTheSubscription() { XCTAssertEqual(CloudKitInboxLayout.alertTitleLocalizationKey, "push.message.title") XCTAssertEqual(CloudKitInboxLayout.alertBodyLocalizationKey, "push.message.body") diff --git a/iOS/AskKeyiOSKitTests/OpenedRequestTests.swift b/iOS/AskKeyiOSKitTests/OpenedRequestTests.swift index a817df4..b79da7c 100644 --- a/iOS/AskKeyiOSKitTests/OpenedRequestTests.swift +++ b/iOS/AskKeyiOSKitTests/OpenedRequestTests.swift @@ -13,7 +13,6 @@ final class OpenedRequestTests: XCTestCase { world = TestWorld() await world.setUpPhone() try await world.pair() - await world.approveMac() await world.model.processInbox() } @@ -341,17 +340,17 @@ final class OpenedRequestTests: XCTestCase { XCTAssertTrue(world.cloud.records(in: try world.phone.deviceID).isEmpty, "refused and deleted") } - func testARequestFromAMacWhoseApprovalWasStoppedShowsUnavailable() async throws { + func testARequestFromARemovedMacShowsUnavailable() async throws { let sealed = try await world.sealRequest() - let stopped = await world.model.stopApproving(macID: world.macIdentity.deviceID.text) - XCTAssertTrue(stopped) + await world.model.removeMac(id: world.macIdentity.deviceID.text) + XCTAssertTrue(world.model.pairedMacs.isEmpty) try await world.deliver(sealed.sealed.envelope) try await tap(sealed.sealed.messageID.text) XCTAssertTrue(world.model.requests.isEmpty) XCTAssertEqual(world.model.opening?.phase(at: world.clock.now()), .unavailable) } - func testStopApprovingDuringTheFetchKeepsTheRequestFromBecomingACard() async throws { + func testRemovingTheMacDuringTheFetchKeepsTheRequestFromBecomingACard() async throws { let phone = try world.phone.deviceID let name = try await world.sendRequest().sealed.messageID.text let gate = Gate() @@ -361,8 +360,8 @@ final class OpenedRequestTests: XCTestCase { let model = world.model let tapped = Task { try await self.tap(name) } await waitUntil { self.world.cloud.calls(by: phone).contains(.namedFetch([name])) } - let stopped = await model.stopApproving(macID: world.macIdentity.deviceID.text) - XCTAssertTrue(stopped) + await model.removeMac(id: world.macIdentity.deviceID.text) + XCTAssertTrue(model.pairedMacs.isEmpty) gate.open() try await tapped.value XCTAssertTrue(model.requests.isEmpty) diff --git a/iOS/AskKeyiOSKitTests/ScreenRenderTests.swift b/iOS/AskKeyiOSKitTests/ScreenRenderTests.swift index 7edb5bc..7719a21 100644 --- a/iOS/AskKeyiOSKitTests/ScreenRenderTests.swift +++ b/iOS/AskKeyiOSKitTests/ScreenRenderTests.swift @@ -79,12 +79,12 @@ final class ScreenRenderTests: XCTestCase { } func testPairedMacs() throws { - let row = PairedMacRow(id: "mac", name: Self.mac, pairedAt: Self.pairedAt, lastReachedAt: nil) + let row = PairedMacRow(id: "mac", name: Self.mac, pairedAt: Self.pairedAt, lastReachedAt: nil, isApprover: true) try render("11-paired-macs-one-mac", PairedMacsContent(rows: [row], accountNotice: nil, listNotice: nil, records: [], onPair: {}, onSelect: { _ in }, onDismissNotice: {})) let reached = PairedMacRow(id: "mac", name: Self.mac, pairedAt: Self.pairedAt, - lastReachedAt: Self.pairedAt.addingTimeInterval(600)) + lastReachedAt: Self.pairedAt.addingTimeInterval(600), isApprover: true) let records = [ DeliveryRecord(recordName: "a", arrivedAt: Self.pairedAt.addingTimeInterval(300), source: .polling), DeliveryRecord(recordName: "b", arrivedAt: Self.pairedAt.addingTimeInterval(600), source: .push), @@ -127,6 +127,8 @@ final class ScreenRenderTests: XCTestCase { .padding(20)) } + /// The second Mac was paired before #336 without approval: its row is + /// the only one marked. func testRequestsHome() throws { let rows = [PairedMacRow(id: "mac", name: Self.mac, pairedAt: Self.pairedAt, lastReachedAt: Self.pairedAt.addingTimeInterval(600), isApprover: true), @@ -200,39 +202,74 @@ final class ScreenRenderTests: XCTestCase { }) } + /// #342: the status line, Rename and Remove; only a Mac paired before + /// #336 without approval lacks the flag. func testMacDetail() throws { - let row = PairedMacRow(id: "mac", name: Self.mac, pairedAt: Self.pairedAt, - lastReachedAt: Self.pairedAt.addingTimeInterval(600)) - try render("34-mac-detail-not-approving", - MacDetailContent(row: row, onRename: {}, onApprove: {}, onStop: {}, onRemove: {})) let approving = PairedMacRow(id: "mac", name: Self.mac, pairedAt: Self.pairedAt, lastReachedAt: Self.pairedAt.addingTimeInterval(600), isApprover: true) - try render("35-mac-detail-approving", - MacDetailContent(row: approving, renameProblem: .duplicate("Office Mac"), onRename: {}, onApprove: {}, - onStop: {}, onRemove: {})) - } - - func testApproverConfirmation() throws { - let field = Text("approver.field", bundle: .kit).font(.title2.monospaced()).foregroundStyle(.tertiary) - .frame(maxWidth: .infinity, alignment: .leading) - try render("36-approver-confirmation", - ApproverConfirmationContent(flow: ApproverConfirmationFlow(macID: "mac", macName: Self.mac), - onConfirm: {}, onClose: {}) { field }) - try render("37-approver-confirmation-invalid-code", - ApproverConfirmationContent(flow: ApproverConfirmationFlow(macID: "mac", macName: Self.mac, - problem: .invalidCode), - onConfirm: {}, onClose: {}) { field }) - try render("38-approver-confirmation-sending", - ApproverConfirmationContent(flow: ApproverConfirmationFlow(macID: "mac", macName: Self.mac, - stage: .sending, problem: .retrying), - onConfirm: {}, onClose: {}) { field }) - try render("39-approver-confirmation-sent", - ApproverConfirmationContent(flow: ApproverConfirmationFlow(macID: "mac", macName: Self.mac, - stage: .sent), - onConfirm: {}, onClose: {}) { field }) + try render("34-mac-detail-approving", MacDetailContent(row: approving, onRename: {}, onRemove: {})) + let withoutFlag = PairedMacRow(id: "mac", name: Self.mac, pairedAt: Self.pairedAt, + lastReachedAt: Self.pairedAt.addingTimeInterval(600)) + try render("35-mac-detail-without-approval-flag", MacDetailContent(row: withoutFlag, onRename: {}, onRemove: {})) + try render("36-mac-detail-remove-confirmation", + ActionSheetStandIn(title: MacRemovalText.title(Self.mac), message: MacRemovalText.message, + action: MacRemovalText.confirm) { + MacDetailContent(row: approving, onRename: {}, onRemove: {}) + }) + try render("37-mac-detail-rename-and-removal-failed", + MacDetailContent(row: approving, renameProblem: .duplicate("Office Mac"), removalFailed: true, + onRename: {}, onRemove: {})) } func testPrivacyCover() throws { try render("40-privacy-cover", PrivacyCoverView()) } } + +/// iOS draws a `confirmationDialog` itself, so `ImageRenderer` cannot capture +/// it. This stand-in lays out the dialog's own texts the way an action sheet +/// shows them, over the screen it opens from, for the wording review. +private struct ActionSheetStandIn: View { + let title: Text + let message: Text + let action: Text + @ViewBuilder var background: Background + + var body: some View { + ZStack(alignment: .bottom) { + background + .frame(maxHeight: .infinity, alignment: .top) + Color.black.opacity(0.2) + VStack(spacing: 8) { + VStack(spacing: 0) { + VStack(spacing: 6) { + title.font(.footnote.weight(.semibold)) + message.font(.footnote) + } + .foregroundStyle(.secondary) + .multilineTextAlignment(.center) + .fixedSize(horizontal: false, vertical: true) + .padding(.horizontal, 16) + .padding(.vertical, 14) + Divider() + action + .font(.title3) + .foregroundStyle(.red) + .frame(maxWidth: .infinity, minHeight: 56) + } + .background(RoundedRectangle(cornerRadius: 14, style: .continuous) + .fill(Color(uiColor: .secondarySystemBackground))) + Text("common.cancel", bundle: .kit) + .font(.title3.weight(.semibold)) + .foregroundStyle(Color.accentColor) + .frame(maxWidth: .infinity, minHeight: 56) + .background(RoundedRectangle(cornerRadius: 14, style: .continuous) + .fill(Color(uiColor: .systemBackground))) + } + .padding(.horizontal, 8) + .padding(.bottom, 8) + } + // A fixed height, the render's screen height, keeps the sheet at the bottom. + .frame(height: 852) + } +} diff --git a/iOS/AskKeyiOSKitTests/UnknownLayoutTests.swift b/iOS/AskKeyiOSKitTests/UnknownLayoutTests.swift index 9822168..d7af2d0 100644 --- a/iOS/AskKeyiOSKitTests/UnknownLayoutTests.swift +++ b/iOS/AskKeyiOSKitTests/UnknownLayoutTests.swift @@ -10,7 +10,6 @@ final class UnknownLayoutTests: XCTestCase { let world = TestWorld() await world.setUpPhone() try await world.pair() - await world.approveMac() let phoneID = try world.phone.deviceID let sealed = try await world.sealRequest() var payload = sealed.request.encoded From b778f99983b94d3db1b07cd543f5380bf837ad75 Mon Sep 17 00:00:00 2001 From: sudoHG Date: Mon, 16 Nov 2026 00:47:27 +0800 Subject: [PATCH 2/2] Stop approving before the removal waits, and correct Remove's copy Cross review of #354 found that removeMac revoked the pairing only in the removal hook, after the messenger's list reads, so a stored decision due for resend could still leave in between. removeMac now revokes the pairing and drops its requests before the first suspension, as the retired Stop Approving did; the hook does the same again. - Remove's confirmation says the Mac stops trusting this iPhone only when it receives the unpair notice, and that an earlier decision can apply until then. - Mac rows reflect an in-process revocation, so a removal whose list write failed no longer shows the Mac as approving. - removeMac returns whether the Mac was removed; the detail screen no longer reads the shared list notice, and a failed removal no longer hides a later unpair notice from that Mac. - Tests for the early revocation, unsent receipts on removal, the failed removal's status, and the Chinese table's retired term. --- iOS/AskKeyiOSKit/App/AppModel+Approvals.swift | 6 ++++ iOS/AskKeyiOSKit/App/AppModel+Decisions.swift | 3 +- iOS/AskKeyiOSKit/App/AppModel.swift | 23 +++++++++---- iOS/AskKeyiOSKit/App/AppStates.swift | 13 +++++--- .../Resources/Localizable.xcstrings | 8 ++--- iOS/AskKeyiOSKit/Views/MacDetailView.swift | 7 ++-- iOS/AskKeyiOSKitTests/ApprovalRaceTests.swift | 33 +++++++++++++++++++ iOS/AskKeyiOSKitTests/ApproverTests.swift | 17 ++++++++-- iOS/AskKeyiOSKitTests/LocalizationTests.swift | 3 ++ iOS/AskKeyiOSKitTests/ScreenRenderTests.swift | 3 +- 10 files changed, 92 insertions(+), 24 deletions(-) diff --git a/iOS/AskKeyiOSKit/App/AppModel+Approvals.swift b/iOS/AskKeyiOSKit/App/AppModel+Approvals.swift index 707cf18..0534a33 100644 --- a/iOS/AskKeyiOSKit/App/AppModel+Approvals.swift +++ b/iOS/AskKeyiOSKit/App/AppModel+Approvals.swift @@ -188,6 +188,12 @@ extension AppModel { /// Runs before any removal of a Mac commits: an unpair notice, a /// removal here, or pairing again. Its requests are refused from now on. func macWillBeRemoved(_ entry: PairedDevice) async { + revoke(entry) + } + + /// Refuses the pairing's messages from now on and drops the Mac's + /// requests, without suspending. Running it again changes nothing. + func revoke(_ entry: PairedDevice) { revokedPairings.insert(entry.pairingID) dropApprovals(forMac: entry.deviceID.text) } diff --git a/iOS/AskKeyiOSKit/App/AppModel+Decisions.swift b/iOS/AskKeyiOSKit/App/AppModel+Decisions.swift index 3dc17c4..b48aeba 100644 --- a/iOS/AskKeyiOSKit/App/AppModel+Decisions.swift +++ b/iOS/AskKeyiOSKit/App/AppModel+Decisions.swift @@ -135,7 +135,8 @@ extension AppModel { /// Sends what is due: stored decisions until CloudKit saves them (every /// 2 seconds or after CloudKit's retry-after, "recipient unreachable" /// included) and again every 30 seconds without a closed message while - /// the countdown runs; receipts until saved or expired. Calls made while sending wait and send once more. + /// the countdown runs; receipts until saved or expired. Calls made while + /// sending wait and send once more. func sendDueMessages() async { if let running = sendWork { sendAgain = true diff --git a/iOS/AskKeyiOSKit/App/AppModel.swift b/iOS/AskKeyiOSKit/App/AppModel.swift index 9dc8100..0f14529 100644 --- a/iOS/AskKeyiOSKit/App/AppModel.swift +++ b/iOS/AskKeyiOSKit/App/AppModel.swift @@ -389,14 +389,19 @@ public final class AppModel { // MARK: Paired Macs - /// Removes the Mac at once, then sends it an unpair notice. The removal - /// hook has already stopped this iPhone approving the Mac's requests - /// and dropped them before the list write; the Mac stops trusting this - /// iPhone only when it processes the notice (ADR 0014 → Revocation). - public func removeMac(id: String) async { + /// Removes the Mac: this iPhone stops approving it before anything + /// waits, then the list write removes it and an unpair notice tells the + /// Mac, which stops trusting this iPhone only when it processes the + /// notice (ADR 0014 → Revocation). Returns false when the Mac could not + /// be removed; this process keeps refusing its requests anyway. + @discardableResult + public func removeMac(id: String) async -> Bool { guard let services, let deviceID = DeviceID(text: id), - let row = pairedMacs.first(where: { $0.id == id }) else { return } + let row = pairedMacs.first(where: { $0.id == id }) else { return false } locallyRemoved.insert(deviceID) + // The removal hook does the same again before the list write commits. + if let entry = knownList?.device(deviceID) { revoke(entry) } + var removed = true do { let told = try await services.messenger.removeDevice(deviceID) listNotice = .removed(name: row.name, macWasTold: told) @@ -405,8 +410,12 @@ public final class AppModel { } catch { AppLog.failure("Removing a paired Mac", error) listNotice = .removalFailed + // Still listed: if its unpair notice removes it later, that is reported. + locallyRemoved.remove(deviceID) + removed = false } await refreshList() + return removed } /// Reloads the list. Entries that disappeared since `previous` and were @@ -425,7 +434,7 @@ public final class AppModel { where list.device(device.deviceID) == nil && !locallyRemoved.contains(device.deviceID) { listNotice = .removedByMac(name: device.displayName) } - pairedMacs = list.devices.map(PairedMacRow.init) + pairedMacs = list.devices.map { PairedMacRow($0, revoked: revokedPairings.contains($0.pairingID)) } rebuildRequests(list: list) } catch PairedDeviceListError.malformed { identityBecameUnusable() diff --git a/iOS/AskKeyiOSKit/App/AppStates.swift b/iOS/AskKeyiOSKit/App/AppStates.swift index 2a230c8..8343ae0 100644 --- a/iOS/AskKeyiOSKit/App/AppStates.swift +++ b/iOS/AskKeyiOSKit/App/AppStates.swift @@ -56,9 +56,11 @@ public struct PairedMacRow: Identifiable, Hashable, Sendable { public let pairedAt: Date /// Nil until the first delivery check from that Mac arrived. public let lastReachedAt: Date? - /// This iPhone accepts approval requests from this Mac. Pairing sets - /// it; only a Mac paired before #336 without approval lacks it, and - /// has to be removed and paired again. + /// This iPhone accepts approval requests from this Mac: its entry + /// carries the flag pairing sets, and its approval has not ended in this + /// process. Only a Mac paired before #336 without approval lacks the + /// flag, and has to be removed and paired again; a Mac whose removal + /// failed is refused until it is removed or the app restarts. public let isApprover: Bool public init(id: String, name: String, pairedAt: Date, lastReachedAt: Date?, isApprover: Bool = false) { @@ -69,9 +71,10 @@ public struct PairedMacRow: Identifiable, Hashable, Sendable { self.isApprover = isApprover } - init(_ device: PairedDevice) { + /// `revoked`: this process already refuses the pairing's messages. + init(_ device: PairedDevice, revoked: Bool = false) { self.init(id: device.deviceID.text, name: device.displayName, pairedAt: device.pairedAt, - lastReachedAt: device.lastReachedAt, isApprover: device.isApprover) + lastReachedAt: device.lastReachedAt, isApprover: device.isApprover && !revoked) } } diff --git a/iOS/AskKeyiOSKit/Resources/Localizable.xcstrings b/iOS/AskKeyiOSKit/Resources/Localizable.xcstrings index e095d29..6e73a75 100644 --- a/iOS/AskKeyiOSKit/Resources/Localizable.xcstrings +++ b/iOS/AskKeyiOSKit/Resources/Localizable.xcstrings @@ -381,13 +381,13 @@ "en": { "stringUnit": { "state": "translated", - "value": "This iPhone stops approving this Mac's requests at once and drops the pending ones. Ask Key also tells the Mac, which stops trusting this iPhone when it next checks. To end approval on the Mac at once, remove this iPhone there too." + "value": "This iPhone stops approving this Mac's requests at once and drops the pending ones. Ask Key also tells the Mac, which stops trusting this iPhone only when it receives that notice; until then, a decision already sent can still apply. To end approval on the Mac at once, remove this iPhone there too." } }, "zh-Hans": { "stringUnit": { "state": "translated", - "value": "这台 iPhone 会立即停止审批这台 Mac 的请求,并丢弃待处理的请求。请旨也会通知 Mac,Mac 下次检查时才会不再信任这台 iPhone。如需立即在 Mac 上结束审批,请也在 Mac 上的请旨中移除这台 iPhone。" + "value": "这台 iPhone 会立即停止审批这台 Mac 的请求,并丢弃待处理的请求。请旨也会通知 Mac,Mac 收到通知后才会不再信任这台 iPhone,在此之前已发出的决定仍可能生效。如需立即在 Mac 上结束审批,请也在 Mac 上的请旨中移除这台 iPhone。" } } } @@ -636,13 +636,13 @@ "en": { "stringUnit": { "state": "translated", - "value": "This iPhone can't approve agents' requests from this Mac. To approve them, remove this Mac and pair it again." + "value": "This iPhone can't approve agents' requests to use credentials on this Mac. To approve them, remove this Mac and pair it again." } }, "zh-Hans": { "stringUnit": { "state": "translated", - "value": "这台 iPhone 不能审批这台 Mac 上 Agent 的请求。如需审批,请移除这台 Mac 后重新配对。" + "value": "这台 iPhone 不能审批 Agent 使用这台 Mac 上凭证的请求。如需审批,请移除这台 Mac 后重新配对。" } } } diff --git a/iOS/AskKeyiOSKit/Views/MacDetailView.swift b/iOS/AskKeyiOSKit/Views/MacDetailView.swift index 9b3ce87..02a4882 100644 --- a/iOS/AskKeyiOSKit/Views/MacDetailView.swift +++ b/iOS/AskKeyiOSKit/Views/MacDetailView.swift @@ -48,9 +48,9 @@ struct MacDetailView: View { Button(role: .destructive) { removalFailed = false Task { - await model.removeMac(id: macID) + let removed = await model.removeMac(id: macID) // A removal that succeeded closes this screen. - removalFailed = row != nil && model.listNotice == .removalFailed + removalFailed = !removed && row != nil } } label: { MacRemovalText.confirm @@ -102,7 +102,8 @@ struct MacDetailContent: View { NoticeCard(symbol: "exclamationmark.triangle.fill", tone: .warning, text: Self.text(renameProblem)) } // Pairing sets the flag; only a Mac paired before #336 without - // approval lacks it, and only pairing again can set it. + // approval lacks it, and only pairing again can set it. A Mac + // whose removal failed is refused here too (`PairedMacRow`). if row.isApprover { NoticeCard(symbol: "checkmark.shield.fill", tone: .success, text: Text("mac.status.approving", bundle: .kit)) diff --git a/iOS/AskKeyiOSKitTests/ApprovalRaceTests.swift b/iOS/AskKeyiOSKitTests/ApprovalRaceTests.swift index 58b24af..f52ec30 100644 --- a/iOS/AskKeyiOSKitTests/ApprovalRaceTests.swift +++ b/iOS/AskKeyiOSKitTests/ApprovalRaceTests.swift @@ -48,6 +48,39 @@ final class ApprovalRaceTests: XCTestCase { XCTAssertTrue(world.model.requests.isEmpty) } + /// The pairing is refused and its requests dropped before the messenger + /// reads the list, so nothing waits between Remove and the refusal. + func testRemovalStopsThisIPhoneBeforeTheMessengerReadsTheList() async throws { + let id = try await receive() + world.cloud.failSends { $0.kind == Self.decisionKind } + await world.model.decide(.allowOnce, requestID: id) + XCTAssertEqual(try world.decisionAttempts().count, 1) + world.keychain.unreadableAccounts = ["paired-devices"] + let removed = await world.model.removeMac(id: macID) + XCTAssertFalse(removed, "the messenger could not read the list") + XCTAssertTrue(world.model.requests.isEmpty) + world.keychain.unreadableAccounts = [] + world.cloud.failSends(where: nil) + world.clock.advance(by: 2) + await world.model.processInbox() + XCTAssertEqual(try world.decisionAttempts().count, 1, "the stored decision is never sent again") + XCTAssertEqual(world.model.pairedMacs.map(\.isApprover), [false]) + } + + func testRemovingTheMacDropsItsUnsentReceipts() async throws { + let phoneID = try world.phone.deviceID + world.cloud.failSends { $0.kind == Int64(MessageKind.approvalReceipt.rawValue) } + _ = try await receive() + XCTAssertEqual(world.model.outbox.count, 1) + let attempts = world.cloud.sent(.approvalReceipt, from: phoneID).count + await world.model.removeMac(id: macID) + XCTAssertTrue(world.model.outbox.isEmpty) + world.cloud.failSends(where: nil) + world.clock.advance(by: 2) + await world.model.processInbox() + XCTAssertEqual(world.cloud.sent(.approvalReceipt, from: phoneID).count, attempts) + } + func testTheDecisionIsStoredBeforeItsFirstSend() async throws { let id = try await receive() let storedAtSend = Box(nil) diff --git a/iOS/AskKeyiOSKitTests/ApproverTests.swift b/iOS/AskKeyiOSKitTests/ApproverTests.swift index b4e0924..3d96f68 100644 --- a/iOS/AskKeyiOSKitTests/ApproverTests.swift +++ b/iOS/AskKeyiOSKitTests/ApproverTests.swift @@ -75,15 +75,26 @@ final class ApproverTests: XCTestCase { } func testARemovalWhoseListWriteFailsStillStopsThisIPhone() async throws { + let sealed = try await world.sendRequest() + world.notifications.delivered = [PushHint(recordName: sealed.sealed.messageID.text, arrivedAt: world.clock.now(), + notificationIdentifier: "request")] + await world.model.becameActive() + XCTAssertEqual(world.model.requests.count, 1) world.keychain.writesFail = true - await world.model.removeMac(id: macID) + let removed = await world.model.removeMac(id: macID) + XCTAssertFalse(removed) XCTAssertEqual(world.model.listNotice, .removalFailed) - XCTAssertEqual(world.model.pairedMacs.count, 1, "the entry stays, so Remove can be tried again") + XCTAssertEqual(world.model.pairedMacs.map(\.isApprover), [false], + "the entry stays, so Remove can be tried again, and no longer shows as approving") + XCTAssertTrue(world.model.requests.isEmpty) + XCTAssertTrue(world.approvalStore.stored.requests.isEmpty) + XCTAssertTrue(world.notifications.removedIdentifiers.contains("request")) world.keychain.writesFail = false try await world.sendRequest() await world.model.processInbox() XCTAssertTrue(world.model.requests.isEmpty, "this process refuses the Mac's requests anyway") - await world.model.removeMac(id: macID) + let retried = await world.model.removeMac(id: macID) + XCTAssertTrue(retried) XCTAssertTrue(world.model.pairedMacs.isEmpty) } diff --git a/iOS/AskKeyiOSKitTests/LocalizationTests.swift b/iOS/AskKeyiOSKitTests/LocalizationTests.swift index e61775d..5f0e8b9 100644 --- a/iOS/AskKeyiOSKitTests/LocalizationTests.swift +++ b/iOS/AskKeyiOSKitTests/LocalizationTests.swift @@ -48,7 +48,10 @@ final class LocalizationTests: XCTestCase { /// approver confirmation or Stop Approving remains (#342). func testNoRetiredApproverStringRemains() throws { let english = try table("en") + let chinese = try table("zh-Hans") + let chineseApproverCode = "\u{5BA1}\u{6279}\u{7801}" for key in english.keys { + XCTAssertFalse(try XCTUnwrap(chinese[key]).contains(chineseApproverCode), key) XCTAssertFalse(key.hasPrefix("approver.") || key.hasPrefix("mac.approve") || key.hasPrefix("mac.stop"), key) let value = try XCTUnwrap(english[key]) XCTAssertFalse(value.localizedCaseInsensitiveContains("approver code"), key) diff --git a/iOS/AskKeyiOSKitTests/ScreenRenderTests.swift b/iOS/AskKeyiOSKitTests/ScreenRenderTests.swift index 7719a21..e4f40cd 100644 --- a/iOS/AskKeyiOSKitTests/ScreenRenderTests.swift +++ b/iOS/AskKeyiOSKitTests/ScreenRenderTests.swift @@ -216,8 +216,9 @@ final class ScreenRenderTests: XCTestCase { action: MacRemovalText.confirm) { MacDetailContent(row: approving, onRename: {}, onRemove: {}) }) + // A failed removal leaves the entry, which this process refuses. try render("37-mac-detail-rename-and-removal-failed", - MacDetailContent(row: approving, renameProblem: .duplicate("Office Mac"), removalFailed: true, + MacDetailContent(row: withoutFlag, renameProblem: .duplicate("Office Mac"), removalFailed: true, onRename: {}, onRemove: {})) }