diff --git a/Bitkit/MainNavView.swift b/Bitkit/MainNavView.swift index 640dd4d0c..37ae518ce 100644 --- a/Bitkit/MainNavView.swift +++ b/Bitkit/MainNavView.swift @@ -971,7 +971,7 @@ struct MainNavView: View { await scannerManager.handleScan(publicKey, context: .main) return } - try await app.handleScannedData( + try await app.handleDeepLinkData( url.absoluteString, alternativeOnchainBalanceSats: hwWalletManager.maximumFundingBalanceSats ) diff --git a/Bitkit/ViewModels/AppViewModel.swift b/Bitkit/ViewModels/AppViewModel.swift index 2abe27b8a..1f41a7251 100644 --- a/Bitkit/ViewModels/AppViewModel.swift +++ b/Bitkit/ViewModels/AppViewModel.swift @@ -1305,6 +1305,18 @@ extension AppViewModel { } } + /// Handles the payment or sign-in data of a deep link. A lookup (e.g. an LNURL) that outlasts a PIN lock is + /// dropped, so neither its sheet nor its error shows after the unlock. + func handleDeepLinkData(_ uri: String, alternativeOnchainBalanceSats: UInt64 = 0) async throws { + let isBeforeLock = lockCheck() + do { + try await handleScannedData(uri, alternativeOnchainBalanceSats: alternativeOnchainBalanceSats, isCurrentScan: isBeforeLock) + } catch { + guard isBeforeLock() else { throw CancellationError() } + throw error + } + } + private func ensureScannedDataHandlingOwnership( _ handlingId: UUID, claimedContactPaymentContext: ContactPaymentContext?, @@ -1326,7 +1338,13 @@ extension AppViewModel { return } - sheetViewModel.showSheet(.btcpayConnection, data: BTCPayConnectionConfig(setup: setup)) + showScannedRouteSheet(.btcpayConnection, data: BTCPayConnectionConfig(setup: setup)) + } + + /// Opens the setup or approval sheet a scanned route asks for. When it replaces an open sheet (the scanner or Send), + /// it opens after the replacement delay; a PIN lock in that delay drops it, so it does not open after the unlock. + private func showScannedRouteSheet(_ id: SheetID, data: Any) { + sheetViewModel.showSheet(id, data: data, isCurrent: lockCheck()) } private func handleInvalidBTCPayConnection(_ uri: String) { @@ -1452,7 +1470,7 @@ extension AppViewModel { return } - sheetViewModel.showSheet(.lnurlAuth, data: LnurlAuthConfig(lnurl: lnurl, authData: data)) + showScannedRouteSheet(.lnurlAuth, data: LnurlAuthConfig(lnurl: lnurl, authData: data)) } private func handlePubkyAuthApproval(_ authUrl: String) async { @@ -1480,10 +1498,7 @@ extension AppViewModel { return } if !hasIdentity { - sheetViewModel.showSheet( - .pubkyAuthApproval, - data: PubkyAuthApprovalConfig(request: request) - ) + showScannedRouteSheet(.pubkyAuthApproval, data: PubkyAuthApprovalConfig(request: request)) return } } catch { @@ -1506,7 +1521,7 @@ extension AppViewModel { return } - sheetViewModel.showSheet(.pubkyAuthApproval, data: PubkyAuthApprovalConfig(request: request)) + showScannedRouteSheet(.pubkyAuthApproval, data: PubkyAuthApprovalConfig(request: request)) } private func handleNodeUri(_ url: String) { diff --git a/Bitkit/ViewModels/SheetViewModel.swift b/Bitkit/ViewModels/SheetViewModel.swift index fe32f02e1..183de5042 100644 --- a/Bitkit/ViewModels/SheetViewModel.swift +++ b/Bitkit/ViewModels/SheetViewModel.swift @@ -80,7 +80,9 @@ class SheetViewModel: ObservableObject { activeSheetConfiguration?.id == .pubkyAuthApproval || replacingSheetID == .pubkyAuthApproval } - func showSheet(_ id: SheetID, data: Any? = nil) { + /// Shows a sheet. When another sheet is open, it closes first and the new one opens after a delay; the new one opens + /// only if `isCurrent` still holds then (e.g. the app has not locked since the route asked for it). + func showSheet(_ id: SheetID, data: Any? = nil, isCurrent: @escaping () -> Bool = { true }) { if activeSheetConfiguration?.id == .send, id == .receivedTx { Logger.debug("Skipping received-transaction sheet while send is active", context: "SheetViewModel") return @@ -100,6 +102,10 @@ class SheetViewModel: ObservableObject { replacingSheetID = nil } guard pendingReplacements.remove(replacement) != nil else { return } + guard isCurrent() else { + Logger.debug("Dropped sheet \(id.rawValue): its route is no longer current", context: "SheetViewModel") + return + } Logger.debug("Showing sheet \(id.rawValue) after delay", context: "SheetViewModel") activeSheetConfiguration = SheetConfiguration(id: id, data: data) playHaptics(for: id) diff --git a/BitkitTests/ScannerManagerTests.swift b/BitkitTests/ScannerManagerTests.swift index 6c5c5c56c..ab2b5e50c 100644 --- a/BitkitTests/ScannerManagerTests.swift +++ b/BitkitTests/ScannerManagerTests.swift @@ -343,6 +343,129 @@ final class ScannerManagerTests: XCTestCase { XCTAssertNil(sheets.activeSheetConfiguration) } + func testSetupSheetQueuedBeforeALockDoesNotOpenAfterIt() async throws { + let defaults = UserDefaults.standard + let previousEnabled = defaults.object(forKey: PaykitFeatureFlags.uiEnabledKey) + defer { defaults.set(previousEnabled, forKey: PaykitFeatureFlags.uiEnabledKey) } + defaults.set(true, forKey: PaykitFeatureFlags.uiEnabledKey) + let previousAdopted = AdoptedPubkyReference.current + defer { AdoptedPubkyReference.current = previousAdopted } + AdoptedPubkyReference.current = nil + // Pubky sign-up opens its approval sheet only without a stored identity. + let previousSession = try Keychain.loadString(key: .paykitSession) + let previousSecretKey = try Keychain.loadString(key: .pubkySecretKey) + try Keychain.delete(key: .paykitSession) + try Keychain.delete(key: .pubkySecretKey) + defer { + if let previousSession { + try? Keychain.saveString(key: .paykitSession, str: previousSession) + } + if let previousSecretKey { + try? Keychain.saveString(key: .pubkySecretKey, str: previousSecretKey) + } + } + XCTAssertFalse(try PubkyProfileManager.hasStoredIdentity()) + let routes: [(uri: String, sheet: SheetID)] = [ + ("https://btcpay.example/plugins/store123/samrock/protocol?setup=btc-chain&otp=abc123", .btcpayConnection), + ( + "pubkyring://signup?hs=5jsjx1o6fzu6aeeo697r3i5rx15zq41kikcye8wtwdqm4nb4tryo" + + "&relay=https%3A%2F%2Frelay.example%2Finbox%2F" + + "&secret=e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3s&caps=%2Fpub%2Fexample%2F%3Arw", + .pubkyAuthApproval + ), + ] + + func scanFromTheScanner(_ uri: String, lockingBeforeTheSheetOpens: Bool) async throws -> SheetConfiguration? { + let sheets = SheetViewModel() + sheets.showSheet(.scanner) + let scanner = ScannerManager {} + let app = configure(scanner, sheets: sheets) + scanner.configure( + app: app, currency: CurrencyViewModel(currencyService: OfflineCurrencyService()), + settings: SettingsViewModel.shared, sheets: sheets + ) + await scanner.handleScan(uri, context: .main) + // The scanner sheet is closing; the setup sheet opens after the replacement delay. + XCTAssertNil(sheets.activeSheetConfiguration, uri) + if lockingBeforeTheSheetOpens { + scanner.invalidateScansForAppLock() + app.noteAppLocked() + } + try await Task.sleep(nanoseconds: UInt64((SheetViewModel.replacementDelaySeconds + 0.3) * 1_000_000_000)) + return sheets.activeSheetConfiguration + } + + for route in routes { + let unlocked = try await scanFromTheScanner(route.uri, lockingBeforeTheSheetOpens: false) + XCTAssertEqual(unlocked?.id, route.sheet, "Without a lock the scan opens its sheet") + let locked = try await scanFromTheScanner(route.uri, lockingBeforeTheSheetOpens: true) + XCTAssertNil(locked, "A \(route.sheet) sheet queued before the lock must not open after it") + } + } + + func testDeepLinkLookupFromBeforeALockIsDropped() async throws { + let decoded = try await decode(invoice: paymentURI) + let sheets = SheetViewModel() + let started = expectation(description: "Deep link lookup suspended") + var continuation: CheckedContinuation? + let app = configure(ScannerManager {}, sheets: sheets, decodeInvoice: { _ in + try await withCheckedThrowingContinuation { + continuation = $0 + started.fulfill() + } + }) + let link = Task { try await app.handleDeepLinkData(paymentURI) } + await fulfillment(of: [started], timeout: 2) + + // The app locks while the lookup runs, and the user unlocks before it returns. + app.noteAppLocked() + try XCTUnwrap(continuation).resume(returning: decoded) + do { + try await link.value + XCTFail("A deep link lookup from before the lock must be dropped") + } catch is CancellationError {} + + XCTAssertNil(app.scannedOnchainInvoice) + XCTAssertNil(sheets.activeSheetConfiguration) + } + + func testDeepLinkLookupFailingAfterALockIsDroppedWithoutItsError() async throws { + let sheets = SheetViewModel() + let started = expectation(description: "Deep link lookup suspended") + var continuation: CheckedContinuation? + let app = configure(ScannerManager {}, sheets: sheets, decodeInvoice: { _ in + try await withCheckedThrowingContinuation { + continuation = $0 + started.fulfill() + } + }) + let link = Task { try await app.handleDeepLinkData(paymentURI) } + await fulfillment(of: [started], timeout: 2) + + // The app locks while the lookup runs, and the lookup then fails. + app.noteAppLocked() + try XCTUnwrap(continuation).resume(throwing: URLError(.timedOut)) + do { + try await link.value + XCTFail("A deep link lookup from before the lock must be dropped") + } catch is CancellationError { + } catch { + XCTFail("A lookup failing after the lock must not surface its error: \(error)") + } + XCTAssertNil(sheets.activeSheetConfiguration) + } + + func testDeepLinkLookupFailingBeforeALockKeepsItsError() async { + let app = configure(ScannerManager {}, decodeInvoice: { _ in throw URLError(.timedOut) }) + + do { + try await app.handleDeepLinkData(paymentURI) + XCTFail("The lookup must fail") + } catch { + XCTAssertFalse(error is CancellationError, "Without a lock the error reaches the caller") + } + } + private func imageTestLnurl(amount: UInt64) -> LnurlPayData { LnurlPayData(uri: "https://example.com/pay", callback: "https://example.com/callback", minSendable: amount, maxSendable: amount, diff --git a/BitkitTests/SheetViewModelTests.swift b/BitkitTests/SheetViewModelTests.swift index 7aaa4df75..94473a1d7 100644 --- a/BitkitTests/SheetViewModelTests.swift +++ b/BitkitTests/SheetViewModelTests.swift @@ -69,6 +69,23 @@ final class SheetViewModelTests: XCTestCase { XCTAssertNil(sheets.activeSheetConfiguration) } + func testReplacementSheetOpensOnlyWhileItsRouteIsCurrent() async throws { + for isCurrentWhenDue in [true, false] { + let sheets = SheetViewModel() + sheets.showSheet(.scanner) + var isCurrent = true + + sheets.showSheet(.lnurlAuth, isCurrent: { isCurrent }) + XCTAssertNil(sheets.activeSheetConfiguration) + isCurrent = isCurrentWhenDue + try await Task.sleep(nanoseconds: UInt64((SheetViewModel.replacementDelaySeconds + 0.3) * 1_000_000_000)) + + XCTAssertEqual(sheets.activeSheetConfiguration?.id, isCurrentWhenDue ? .lnurlAuth : nil) + XCTAssertFalse(sheets.isReplacingSheet) + XCTAssertNil(sheets.replacingSheetID) + } + } + func testLateDismissOfReplacedSheetKeepsNewerSheetWithSameID() throws { let sheets = SheetViewModel() diff --git a/changelog.d/next/1433.fixed.md b/changelog.d/next/1433.fixed.md new file mode 100644 index 000000000..5016e9239 --- /dev/null +++ b/changelog.d/next/1433.fixed.md @@ -0,0 +1 @@ +A setup or sign-in sheet opened by a scan just before Bitkit locked no longer appears after you unlock.