Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
10 changes: 7 additions & 3 deletions Normal/Modifiers/ProtectedActionModifier.swift
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -13,7 +14,8 @@ struct ProtectedActionModifier: ViewModifier {
action: $action,
allowBypass: allowBypass,
defaultKeyType: defaultKeyType,
keyGroupID: keyGroupID
keyGroupID: keyGroupID,
requestID: requestID
)
}
}
Expand All @@ -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
))
}
}
2 changes: 1 addition & 1 deletion Normal/Modifiers/ScreenTimeGuardModifier.swift
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
16 changes: 9 additions & 7 deletions Normal/Modifiers/WidgetActionResponder.swift
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -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) }
Expand All @@ -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 {
Expand All @@ -76,6 +77,7 @@ private struct WidgetActionResponder: ViewModifier {
}
selectedTab = .groups
actionGroup = group
requestID = request.token

switch request.action {
case let .unlock(duration, requestedKeyType):
Expand Down Expand Up @@ -106,7 +108,7 @@ private struct WidgetActionResponder: ViewModifier {
screenTimeService: screenTimeService
)
} else {
showDurationSheet = true
durationGroup = group
}
}

Expand Down
9 changes: 7 additions & 2 deletions Normal/Services/Keys/NFCKeyMethod.swift
Original file line number Diff line number Diff line change
Expand Up @@ -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 {
Expand Down
8 changes: 6 additions & 2 deletions Normal/Services/QRService.swift
Original file line number Diff line number Diff line change
Expand Up @@ -17,10 +17,11 @@ final class QRService {

private var continuation: CheckedContinuation<String, Error>?
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)
Expand All @@ -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
Expand All @@ -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 {
Expand Down
82 changes: 67 additions & 15 deletions Normal/Views/BlockUnblockViews/KeySelect/KeySelectModifier.swift
Original file line number Diff line number Diff line change
Expand Up @@ -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
}
Expand All @@ -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) {
Expand All @@ -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) }
)
}
}
Expand Down Expand Up @@ -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,
Expand Down Expand Up @@ -143,53 +170,76 @@ 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
}

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
}
}
Expand All @@ -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
))
}
}
21 changes: 15 additions & 6 deletions NormalTests/Services/NFCKeyMethodTests.swift
Original file line number Diff line number Diff line change
Expand Up @@ -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 {
Expand Down Expand Up @@ -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: [])
Expand Down
Loading
Loading