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
2 changes: 1 addition & 1 deletion Bitkit/MainNavView.swift
Original file line number Diff line number Diff line change
Expand Up @@ -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
)
Expand Down
29 changes: 22 additions & 7 deletions Bitkit/ViewModels/AppViewModel.swift
Original file line number Diff line number Diff line change
Expand Up @@ -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?,
Expand All @@ -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) {
Expand Down Expand Up @@ -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 {
Expand Down Expand Up @@ -1480,10 +1498,7 @@ extension AppViewModel {
return
}
if !hasIdentity {
sheetViewModel.showSheet(
.pubkyAuthApproval,
data: PubkyAuthApprovalConfig(request: request)
)
showScannedRouteSheet(.pubkyAuthApproval, data: PubkyAuthApprovalConfig(request: request))
return
}
} catch {
Expand All @@ -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) {
Expand Down
8 changes: 7 additions & 1 deletion Bitkit/ViewModels/SheetViewModel.swift
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -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)
Expand Down
123 changes: 123 additions & 0 deletions BitkitTests/ScannerManagerTests.swift
Original file line number Diff line number Diff line change
Expand Up @@ -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())
Comment thread
jvsena42 marked this conversation as resolved.
Resolved
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<BitkitCore.Scanner, Error>?
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<BitkitCore.Scanner, Error>?
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,
Expand Down
17 changes: 17 additions & 0 deletions BitkitTests/SheetViewModelTests.swift
Original file line number Diff line number Diff line change
Expand Up @@ -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()

Expand Down
1 change: 1 addition & 0 deletions changelog.d/next/1433.fixed.md
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
A setup or sign-in sheet opened by a scan just before Bitkit locked no longer appears after you unlock.
Loading