From d5e82c49fcda08ef29f7faf7ab9a3074d99fb1e3 Mon Sep 17 00:00:00 2001 From: ykisana Date: Thu, 12 Nov 2026 13:27:03 -0600 Subject: [PATCH] fix: tie key checks to the request that started them A widget link that arrived while a key check was open could reuse that screen for a different action: Block Without Key could run the unlock, and the duration or location sheet could switch to another group. Each check now belongs to the request that opened it and restarts when a newer one arrives, and QR scans only complete the scan they validated. --- .../Modifiers/ProtectedActionModifier.swift | 10 ++- .../Modifiers/ScreenTimeGuardModifier.swift | 2 +- Normal/Modifiers/WidgetActionResponder.swift | 16 ++-- Normal/Services/Keys/NFCKeyMethod.swift | 9 +- Normal/Services/QRService.swift | 8 +- .../KeySelect/KeySelectModifier.swift | 82 +++++++++++++++---- NormalTests/Services/NFCKeyMethodTests.swift | 21 +++-- NormalTests/Services/QRServiceTests.swift | 39 +++++++++ 8 files changed, 151 insertions(+), 36 deletions(-) create mode 100644 NormalTests/Services/QRServiceTests.swift diff --git a/Normal/Modifiers/ProtectedActionModifier.swift b/Normal/Modifiers/ProtectedActionModifier.swift index b4915b5..989775d 100644 --- a/Normal/Modifiers/ProtectedActionModifier.swift +++ b/Normal/Modifiers/ProtectedActionModifier.swift @@ -5,6 +5,7 @@ struct ProtectedActionModifier: ViewModifier { var allowBypass: Bool var defaultKeyType: KeyType? var keyGroupID: UUID? + var requestID: UUID? func body(content: Content) -> some View { content @@ -13,7 +14,8 @@ struct ProtectedActionModifier: ViewModifier { action: $action, allowBypass: allowBypass, defaultKeyType: defaultKeyType, - keyGroupID: keyGroupID + keyGroupID: keyGroupID, + requestID: requestID ) } } @@ -23,13 +25,15 @@ extension View { _ action: Binding<(@MainActor () -> Void)?>, allowBypass: Bool = false, defaultKeyType: KeyType? = nil, - keyGroupID: UUID? = nil + keyGroupID: UUID? = nil, + requestID: UUID? = nil ) -> some View { modifier(ProtectedActionModifier( action: action, allowBypass: allowBypass, defaultKeyType: defaultKeyType, - keyGroupID: keyGroupID + keyGroupID: keyGroupID, + requestID: requestID )) } } diff --git a/Normal/Modifiers/ScreenTimeGuardModifier.swift b/Normal/Modifiers/ScreenTimeGuardModifier.swift index 0fa2370..cb64974 100644 --- a/Normal/Modifiers/ScreenTimeGuardModifier.swift +++ b/Normal/Modifiers/ScreenTimeGuardModifier.swift @@ -14,7 +14,7 @@ struct ScreenTimeGuardModifier: ViewModifier { deferred = pending action = nil Task { - if await screenTimeService.ensureAuthorized() { + if await screenTimeService.ensureAuthorized(), action == nil { action = deferred } deferred = nil diff --git a/Normal/Modifiers/WidgetActionResponder.swift b/Normal/Modifiers/WidgetActionResponder.swift index 1f92631..1130300 100644 --- a/Normal/Modifiers/WidgetActionResponder.swift +++ b/Normal/Modifiers/WidgetActionResponder.swift @@ -16,7 +16,8 @@ private struct WidgetActionResponder: ViewModifier { @State private var actionGroup: AppGroup? @State private var keyType: KeyType? @State private var allowBypass = false - @State private var showDurationSheet = false + @State private var requestID: UUID? + @State private var durationGroup: AppGroup? private var unblockDurations: [TimedUnblockDuration] { allSettings.first?.unblockDurations ?? TimedUnblockDuration.presets @@ -36,12 +37,11 @@ private struct WidgetActionResponder: ViewModifier { $authAction, allowBypass: allowBypass, defaultKeyType: keyType, - keyGroupID: actionGroup?.id + keyGroupID: actionGroup?.id, + requestID: requestID ) - .sheet(isPresented: $showDurationSheet) { - if let actionGroup { - GroupTimedUnblockSheet(group: actionGroup) - } + .sheet(item: $durationGroup) { group in + GroupTimedUnblockSheet(group: group) } .onOpenURL { coordinator.handle(url: $0) } .onChange(of: coordinator.pendingGroupAction) { _, request in resolve(request) } @@ -68,6 +68,7 @@ private struct WidgetActionResponder: ViewModifier { private func resolve(_ request: GroupActionRequest?) { guard let request, + durationGroup == nil, allSettings.first?.hasCompletedOnboarding == true, let group = groups.first(where: { $0.id == request.groupID }) else { @@ -76,6 +77,7 @@ private struct WidgetActionResponder: ViewModifier { } selectedTab = .groups actionGroup = group + requestID = request.token switch request.action { case let .unlock(duration, requestedKeyType): @@ -106,7 +108,7 @@ private struct WidgetActionResponder: ViewModifier { screenTimeService: screenTimeService ) } else { - showDurationSheet = true + durationGroup = group } } diff --git a/Normal/Services/Keys/NFCKeyMethod.swift b/Normal/Services/Keys/NFCKeyMethod.swift index 6210fc5..74a5385 100644 --- a/Normal/Services/Keys/NFCKeyMethod.swift +++ b/Normal/Services/Keys/NFCKeyMethod.swift @@ -19,9 +19,14 @@ struct QRKeyMethod: KeyMethod { } private func performScanCheck(using scanner: any KeyScanning, against keys: [Key]) async -> KeyResult { + var verified: String? do { - _ = try await scanner.scan { Key.matchingKeyExists(keys: keys, unhashedId: $0) } - return .success + let value = try await scanner.scan { candidate in + guard Key.matchingKeyExists(keys: keys, unhashedId: candidate) else { return false } + verified = candidate + return true + } + return value == verified ? .success : .failure } catch ScanError.userCanceled { return .cancelled } catch ScanError.invalidKey { diff --git a/Normal/Services/QRService.swift b/Normal/Services/QRService.swift index 7a66aca..cc09956 100644 --- a/Normal/Services/QRService.swift +++ b/Normal/Services/QRService.swift @@ -17,10 +17,11 @@ final class QRService { private var continuation: CheckedContinuation? private var validator: ((String) -> Bool)? + private var scanID = UUID() private static let badgeDisplayDelay: Duration = .seconds(0.6) - private init() {} + init() {} func scan() async throws -> String { try await scan(validate: nil) @@ -36,6 +37,7 @@ final class QRService { guard !isScanning else { throw ScanError.alreadyScanning } return try await withCheckedThrowingContinuation { continuation in + self.scanID = UUID() self.continuation = continuation self.validator = validate self.scanResult = .none @@ -54,9 +56,11 @@ final class QRService { if validator(value) { scanResult = .valid + let scan = scanID Task { @MainActor in try? await Task.sleep(for: Self.badgeDisplayDelay) - continuation?.resume(returning: value) + guard scan == scanID, let continuation else { return } + continuation.resume(returning: value) cleanup() } } else { diff --git a/Normal/Views/BlockUnblockViews/KeySelect/KeySelectModifier.swift b/Normal/Views/BlockUnblockViews/KeySelect/KeySelectModifier.swift index 021511a..d35b5b0 100644 --- a/Normal/Views/BlockUnblockViews/KeySelect/KeySelectModifier.swift +++ b/Normal/Views/BlockUnblockViews/KeySelect/KeySelectModifier.swift @@ -13,18 +13,34 @@ struct KeySelectModifier: ViewModifier { var allowBypass: Bool var defaultKeyType: KeyType? var keyGroupID: UUID? + var requestID: UUID? + @State private var flowID = UUID() @State private var keySelectToken: PresentationToken? - @State private var locationToken: PresentationToken? + @State private var locationCheck: LocationCheck? + @State private var pendingLocationCheck: LocationCheck? + @State private var presentedLocationFlowID: UUID? + @State private var locationAction: (@MainActor () -> Void)? + @State private var qrScanFlowID: UUID? @State private var showQRScanner = false @State private var showNoKeysAlert = false @State private var showBypassConfirm = false - @State private var pendingLocationAction: (@MainActor () -> Void)? private struct PresentationToken: Identifiable { let id = UUID() } + private struct LocationCheck: Identifiable { + let id = UUID() + let flowID: UUID + let keys: [Key] + } + + private struct Trigger: Equatable { + let hasAction: Bool + let requestID: UUID? + } + private var settings: Settings { allSettings.unwrapped } @@ -39,9 +55,9 @@ struct KeySelectModifier: ViewModifier { func body(content: Content) -> some View { content - .onChange(of: action != nil) { _, hasAction in - if hasAction { - applyDecision() + .onChange(of: Trigger(hasAction: action != nil, requestID: requestID)) { _, trigger in + if trigger.hasAction { + startFlow() } } .alert("No Keys Available", isPresented: $showNoKeysAlert) { @@ -56,11 +72,11 @@ struct KeySelectModifier: ViewModifier { .sheet(item: $keySelectToken, onDismiss: onSheetDismiss) { _ in keySelectSheet } - .sheet(item: $locationToken, onDismiss: finishLocation) { _ in + .sheet(item: $locationCheck, onDismiss: finishLocation) { check in LocationUnlockSheet( - keys: scopedKeys, + keys: check.keys, provider: locationService, - onVerified: { pendingLocationAction?() } + onVerified: { verifyLocation(check) } ) } } @@ -110,6 +126,17 @@ struct KeySelectModifier: ViewModifier { return [.medium] } + private func startFlow() { + pendingLocationCheck = nil + locationCheck = nil + locationAction = nil + if qrScanFlowID != nil { + qrService.cancel() + } + flowID = UUID() + applyDecision() + } + private func applyDecision() { let decision = KeySelectLogic.decide( availableKeyTypes: availableKeyTypes, @@ -143,22 +170,37 @@ struct KeySelectModifier: ViewModifier { keySelectToken = nil Task { await authenticate(with: .nfc, action: pending) } case .qr: + guard qrScanFlowID != flowID else { return } + qrScanFlowID = flowID let pending = action showQRScanner = true Task { await authenticate(with: .qr, action: pending) } case .location: - pendingLocationAction = action + locationAction = action + let check = LocationCheck(flowID: flowID, keys: scopedKeys) if keySelectToken != nil { + pendingLocationCheck = check keySelectToken = nil } else { - locationToken = PresentationToken() + present(check) } } } + private func present(_ check: LocationCheck) { + presentedLocationFlowID = check.flowID + locationCheck = check + } + + private func verifyLocation(_ check: LocationCheck) { + guard check.flowID == flowID else { return } + locationAction?() + } + /// Leaves `showBypassConfirm` alone: flipping it here would swap the key /// picker back in while the sheet is still animating away. private func bypassNow() { + guard allowBypass else { return } action?() action = nil keySelectToken = nil @@ -166,30 +208,38 @@ struct KeySelectModifier: ViewModifier { private func authenticate(with choice: KeyType, action pending: (@MainActor () -> Void)?) async { guard let pending else { return } + let flow = flowID let method: KeyMethod = switch choice { case .nfc: NFCKeyMethod(nfcService: nfcService, keys: scopedKeys) case .qr: QRKeyMethod(qrService: qrService, keys: scopedKeys) case .location: preconditionFailure("location uses its own popup") } _ = await keyManager.performWithKeyCheck(using: method) { pending() } + if qrScanFlowID == flow { + qrScanFlowID = nil + } + guard flow == flowID else { return } keySelectToken = nil action = nil } private func onSheetDismiss() { + guard keySelectToken == nil else { return } if qrService.isScanning { qrService.cancel() } - if pendingLocationAction != nil { - locationToken = PresentationToken() + if let pending = pendingLocationCheck { + pendingLocationCheck = nil + present(pending) return } action = nil } private func finishLocation() { - pendingLocationAction = nil + guard locationCheck == nil, presentedLocationFlowID == flowID else { return } + locationAction = nil action = nil } } @@ -199,13 +249,15 @@ extension View { action: Binding<(@MainActor () -> Void)?>, allowBypass: Bool = false, defaultKeyType: KeyType? = nil, - keyGroupID: UUID? = nil + keyGroupID: UUID? = nil, + requestID: UUID? = nil ) -> some View { modifier(KeySelectModifier( action: action, allowBypass: allowBypass, defaultKeyType: defaultKeyType, - keyGroupID: keyGroupID + keyGroupID: keyGroupID, + requestID: requestID )) } } diff --git a/NormalTests/Services/NFCKeyMethodTests.swift b/NormalTests/Services/NFCKeyMethodTests.swift index e9d1c46..a8647cc 100644 --- a/NormalTests/Services/NFCKeyMethodTests.swift +++ b/NormalTests/Services/NFCKeyMethodTests.swift @@ -2,10 +2,11 @@ import Testing struct NFCKeyMethodTests { - @Test func successOnValidScan() async { - let scanner = FakeKeyScanning(outcome: .acceptAny) - let method = NFCKeyMethod(nfcService: scanner, keys: []) - #expect(await method.checkKey() == .success) + @Test func unvalidatedScanIsRejected() async { + let key = Key(name: "k", type: .nfc, rawValue: "abc") + let scanner = FakeKeyScanning(outcome: .acceptAny, rawValue: "abc") + let method = NFCKeyMethod(nfcService: scanner, keys: [key]) + #expect(await method.checkKey() == .failure) } @Test func cancelledOnUserCancel() async { @@ -43,11 +44,19 @@ struct NFCKeyMethodTests { struct QRKeyMethodTests { @Test func successOnValidScan() async { - let scanner = FakeKeyScanning(outcome: .acceptAny) - let method = QRKeyMethod(qrService: scanner, keys: []) + let key = Key(name: "k", type: .qr, rawValue: "code") + let scanner = FakeKeyScanning(outcome: .acceptMatching, rawValue: "code") + let method = QRKeyMethod(qrService: scanner, keys: [key]) #expect(await method.checkKey() == .success) } + @Test func unvalidatedScanIsRejected() async { + let key = Key(name: "k", type: .qr, rawValue: "code") + let scanner = FakeKeyScanning(outcome: .acceptAny, rawValue: "code") + let method = QRKeyMethod(qrService: scanner, keys: [key]) + #expect(await method.checkKey() == .failure) + } + @Test func cancelledOnUserCancel() async { let scanner = FakeKeyScanning(outcome: .cancel) let method = QRKeyMethod(qrService: scanner, keys: []) diff --git a/NormalTests/Services/QRServiceTests.swift b/NormalTests/Services/QRServiceTests.swift new file mode 100644 index 0000000..c07259a --- /dev/null +++ b/NormalTests/Services/QRServiceTests.swift @@ -0,0 +1,39 @@ +@testable import Normal +import Testing + +@MainActor +struct QRServiceTests { + private func waitUntilScanning(_ service: QRService) async { + while !service.isScanning { + await Task.yield() + } + } + + @Test func validScanCompletesAfterTheBadge() async throws { + let service = QRService() + let scan = Task { try await service.scan { $0 == "code" } } + await waitUntilScanning(service) + + service.handleScan("code", kind: .qr) + + #expect(try await scan.value == "code") + #expect(!service.isScanning) + } + + @Test func validatedCodeDoesNotCompleteALaterScan() async throws { + let service = QRService() + let first = Task { try await service.scan { $0 == "group-code" } } + await waitUntilScanning(service) + service.handleScan("group-code", kind: .qr) + service.cancel() + + let second = Task { try await service.scan { $0 == "global-code" } } + await waitUntilScanning(service) + try await Task.sleep(for: .seconds(1.5)) + + #expect(service.isScanning) + service.cancel() + await #expect(throws: ScanError.self) { try await first.value } + await #expect(throws: ScanError.self) { try await second.value } + } +}