From b8fe6789640a653ad552349b086e22fe0a602d70 Mon Sep 17 00:00:00 2001 From: jvsena42 Date: Wed, 25 Nov 2026 11:25:28 -0300 Subject: [PATCH 1/4] fix: drop setup sheets a scan queued before the app locked A scan whose route opens a setup or approval sheet (BTCPay setup, LNURL login, Pubky login) replaces the open scanner or Send sheet after the replacement delay. If the app locked in that delay, the sheet opened after unlock. These routes now pass the app lock check to the sheet, which opens only if the app has not locked since the route asked for it. Fixes #1425 Co-Authored-By: Claude Opus 5.5 --- Bitkit/ViewModels/AppViewModel.swift | 17 ++++++---- Bitkit/ViewModels/SheetViewModel.swift | 8 ++++- BitkitTests/ScannerManagerTests.swift | 47 ++++++++++++++++++++++++++ BitkitTests/SheetViewModelTests.swift | 17 ++++++++++ 4 files changed, 81 insertions(+), 8 deletions(-) diff --git a/Bitkit/ViewModels/AppViewModel.swift b/Bitkit/ViewModels/AppViewModel.swift index 2abe27b8aa..af7b9eef26 100644 --- a/Bitkit/ViewModels/AppViewModel.swift +++ b/Bitkit/ViewModels/AppViewModel.swift @@ -1326,7 +1326,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 +1458,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 +1486,7 @@ extension AppViewModel { return } if !hasIdentity { - sheetViewModel.showSheet( - .pubkyAuthApproval, - data: PubkyAuthApprovalConfig(request: request) - ) + showScannedRouteSheet(.pubkyAuthApproval, data: PubkyAuthApprovalConfig(request: request)) return } } catch { @@ -1506,7 +1509,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 fe32f02e1c..183de50425 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 6c5c5c56c1..990dbcbee9 100644 --- a/BitkitTests/ScannerManagerTests.swift +++ b/BitkitTests/ScannerManagerTests.swift @@ -343,6 +343,53 @@ 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 + 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") + } + } + 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 7aaa4df751..94473a1d7d 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() From 444906eba5a33f94509cd6bd00c7097099c77b84 Mon Sep 17 00:00:00 2001 From: jvsena42 Date: Wed, 25 Nov 2026 11:33:59 -0300 Subject: [PATCH 2/4] chore: add changelog fragment Co-Authored-By: Claude Opus 5.5 --- changelog.d/next/1433.fixed.md | 1 + 1 file changed, 1 insertion(+) create mode 100644 changelog.d/next/1433.fixed.md diff --git a/changelog.d/next/1433.fixed.md b/changelog.d/next/1433.fixed.md new file mode 100644 index 0000000000..5016e9239b --- /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. From f5bcf5b87b3ccf7aff6f8810f3d37398b5867031 Mon Sep 17 00:00:00 2001 From: jvsena42 Date: Wed, 25 Nov 2026 12:27:33 -0300 Subject: [PATCH 3/4] fix: drop a deep link lookup that outlasts an app lock A deep link's LNURL lookup ran without a lock check, so a lock during the lookup let its sheet open after the unlock (the sheet's own check is taken when the route runs, after the lock). The lock check is now taken before the lookup and passed through. Co-Authored-By: Claude Opus 5.5 --- Bitkit/MainNavView.swift | 2 +- Bitkit/ViewModels/AppViewModel.swift | 7 +++++++ BitkitTests/ScannerManagerTests.swift | 26 ++++++++++++++++++++++++++ 3 files changed, 34 insertions(+), 1 deletion(-) diff --git a/Bitkit/MainNavView.swift b/Bitkit/MainNavView.swift index 640dd4d0c3..37ae518ce4 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 af7b9eef26..0697de4c01 100644 --- a/Bitkit/ViewModels/AppViewModel.swift +++ b/Bitkit/ViewModels/AppViewModel.swift @@ -1305,6 +1305,13 @@ 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 its sheet does not open after the unlock. + func handleDeepLinkData(_ uri: String, alternativeOnchainBalanceSats: UInt64 = 0) async throws { + let isBeforeLock = lockCheck() + try await handleScannedData(uri, alternativeOnchainBalanceSats: alternativeOnchainBalanceSats, isCurrentScan: isBeforeLock) + } + private func ensureScannedDataHandlingOwnership( _ handlingId: UUID, claimedContactPaymentContext: ContactPaymentContext?, diff --git a/BitkitTests/ScannerManagerTests.swift b/BitkitTests/ScannerManagerTests.swift index 990dbcbee9..0905150f25 100644 --- a/BitkitTests/ScannerManagerTests.swift +++ b/BitkitTests/ScannerManagerTests.swift @@ -390,6 +390,32 @@ final class ScannerManagerTests: XCTestCase { } } + 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) + } + private func imageTestLnurl(amount: UInt64) -> LnurlPayData { LnurlPayData(uri: "https://example.com/pay", callback: "https://example.com/callback", minSendable: amount, maxSendable: amount, From 992781549c4b8e92ae33eccb2f08480756c86617 Mon Sep 17 00:00:00 2001 From: jvsena42 Date: Wed, 25 Nov 2026 14:15:59 -0300 Subject: [PATCH 4/4] fix: drop a deep link lookup error after an app lock A deep link lookup that failed after the app locked still surfaced its error, so a stale toast showed after the unlock. The wrapper now turns any error after a lock into a cancellation. The setup-sheet test also clears and restores the Pubky session and secret key, which count as a stored identity. Co-Authored-By: Claude Opus 5.5 --- Bitkit/ViewModels/AppViewModel.swift | 9 +++-- BitkitTests/ScannerManagerTests.swift | 50 +++++++++++++++++++++++++++ 2 files changed, 57 insertions(+), 2 deletions(-) diff --git a/Bitkit/ViewModels/AppViewModel.swift b/Bitkit/ViewModels/AppViewModel.swift index 0697de4c01..1f41a72518 100644 --- a/Bitkit/ViewModels/AppViewModel.swift +++ b/Bitkit/ViewModels/AppViewModel.swift @@ -1306,10 +1306,15 @@ 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 its sheet does not open after the unlock. + /// dropped, so neither its sheet nor its error shows after the unlock. func handleDeepLinkData(_ uri: String, alternativeOnchainBalanceSats: UInt64 = 0) async throws { let isBeforeLock = lockCheck() - try await handleScannedData(uri, alternativeOnchainBalanceSats: alternativeOnchainBalanceSats, isCurrentScan: isBeforeLock) + do { + try await handleScannedData(uri, alternativeOnchainBalanceSats: alternativeOnchainBalanceSats, isCurrentScan: isBeforeLock) + } catch { + guard isBeforeLock() else { throw CancellationError() } + throw error + } } private func ensureScannedDataHandlingOwnership( diff --git a/BitkitTests/ScannerManagerTests.swift b/BitkitTests/ScannerManagerTests.swift index 0905150f25..ab2b5e50c1 100644 --- a/BitkitTests/ScannerManagerTests.swift +++ b/BitkitTests/ScannerManagerTests.swift @@ -351,6 +351,19 @@ final class ScannerManagerTests: XCTestCase { 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), @@ -416,6 +429,43 @@ final class ScannerManagerTests: XCTestCase { 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,