Skip to content
Open
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
22 changes: 22 additions & 0 deletions Bitkit/AppScene.swift
Original file line number Diff line number Diff line change
Expand Up @@ -146,6 +146,7 @@ struct AppScene: View {
.onChange(of: wallet.nodeLifecycleState) { _, newValue in handleNodeLifecycleChange(newValue) }
.onChange(of: scenePhase, initial: true) { _, newValue in handleScenePhaseChange(newValue) }
.onChange(of: network.isConnected) { _, isConnected in handleNetworkChange(isConnected) }
.onOpenURL { url in app.retainDeepLink(url) }
// Bridge Trezor device state into the watch-only manager without coupling the two:
// TrezorManager bumps devicesRevision on any device/connection change.
.onChange(of: trezorManager.devicesRevision) { _, _ in pushHardwareDevices() }
Expand Down Expand Up @@ -283,6 +284,10 @@ struct AppScene: View {
isPinVerified = true
}

if let url = DeepLinkRouter.shared.consume() {
app.retainDeepLink(url)
}

// Listen for quick action notifications
NotificationCenter.default.addObserver(
forName: .quickActionSelected,
Expand All @@ -291,6 +296,13 @@ struct AppScene: View {
) { notification in
handleQuickAction(notification)
}
NotificationCenter.default.addObserver(
forName: .deepLinkReceived,
object: nil,
queue: .main
) { notification in
handleDeepLinkNotification(notification)
}
}
.onReceive(BackupService.shared.backupFailurePublisher) { intervalMinutes in
handleBackupFailure(intervalMinutes: intervalMinutes)
Expand All @@ -301,6 +313,16 @@ struct AppScene: View {
}
}

private func handleDeepLinkNotification(_ notification: Notification) {
if let retainedURL = DeepLinkRouter.shared.consume() {
app.retainDeepLink(retainedURL)
return
}
if let receivedURL = notification.object as? URL {
app.retainDeepLink(receivedURL)
}
}

private var mainContent: some View {
ZStack {
if Env.isTrezorEmulatorTesting {
Expand Down
10 changes: 10 additions & 0 deletions Bitkit/BitkitApp.swift
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ import SwiftUI
/// Communication bridge between delegates and SwiftUI views
extension Notification.Name {
static let quickActionSelected = Notification.Name("quickActionSelected")
static let deepLinkReceived = Notification.Name("deepLinkReceived")
}

class AppDelegate: NSObject, UIApplicationDelegate {
Expand Down Expand Up @@ -39,6 +40,15 @@ class AppDelegate: NSObject, UIApplicationDelegate {
return config
}

func application(
_ application: UIApplication,
open url: URL,
options: [UIApplication.OpenURLOptionsKey: Any] = [:]
) -> Bool {
DeepLinkRouter.shared.forward(url)
return true
}

// MARK: - App Termination

func applicationWillTerminate(_ application: UIApplication) {
Expand Down
2 changes: 1 addition & 1 deletion Bitkit/Info.plist
Original file line number Diff line number Diff line change
Expand Up @@ -37,7 +37,7 @@
<string>$(TREZOR_ELECTRUM_URL)</string>
<key>LSApplicationQueriesSchemes</key>
<array>
<string>pubkyauth</string>
<string>pubkyring</string>
</array>
<key>NSAppTransportSecurity</key>
<dict>
Expand Down
148 changes: 85 additions & 63 deletions Bitkit/MainNavView.swift
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
import SwiftUI

struct MainNavView: View {
private let canHandleDeepLinks: Bool

@AppStorage(PaykitFeatureFlags.uiEnabledKey) private var isPaykitUIEnabled = false

@EnvironmentObject private var app: AppViewModel
Expand All @@ -21,6 +23,10 @@ struct MainNavView: View {
@State private var showClipboardAlert = false
@State private var clipboardUri: String?

init(canHandleDeepLinks: Bool = true) {
self.canHandleDeepLinks = canHandleDeepLinks
}

private var isPaykitUIActive: Bool {
PaykitFeatureFlags.isUIAvailable && isPaykitUIEnabled
}
Expand Down Expand Up @@ -317,69 +323,13 @@ struct MainNavView: View {
notificationManager.unregister()
}
}
.onOpenURL { url in
Task {
Logger.info("Received deeplink: \(sanitizedDeeplinkDescription(url))")

// Web URLs from widgets (e.g. news article tap) bypass payment handling
if let scheme = url.scheme?.lowercased(), scheme == "http" || scheme == "https" {
await UIApplication.shared.open(url)
return
}

if let callback = PubkyRingAuthCallback.parse(url: url) {
guard isPaykitUIActive else {
app.toast(
type: .error,
title: t("profile__auth_error_title"),
description: t("other__qr_error_text")
)
return
}

let handlingResult = await pubkyProfile.handleAuthCallback(callback)

switch handlingResult {
case let .trustedError(message):
app.toast(
type: .error,
title: t("profile__auth_error_title"),
description: message ?? t("other__qr_error_text")
)
case .untrustedError:
app.toast(
type: .error,
title: t("profile__auth_error_title")
)
case .handled, .ignored:
break
}

return
}

do {
try await app.handleScannedData(
url.absoluteString,
alternativeOnchainBalanceSats: hwWalletManager.maximumFundingBalanceSats
)
if shouldOpenPaymentSheet(for: url.absoluteString) {
PaymentNavigationHelper.openPaymentSheet(
app: app,
currency: currency,
settings: settings,
sheetViewModel: sheets
)
}
} catch {
Logger.error(error, context: "Failed to handle deeplink")
app.toast(
type: .error,
title: t("other__qr_error_header"),
description: t("other__qr_error_text")
)
}
}
.task(id: [canHandleDeepLinks, wallet.nodeLifecycleState == .running]) {
guard canHandleDeepLinks else { return }
await handlePendingDeepLink()
}
.onChange(of: app.pendingDeepLinkURL) { _, url in
guard canHandleDeepLinks, url != nil else { return }
Task { await handlePendingDeepLink() }
}
.alert(
t("other__clipboard_redirect_title"),
Expand Down Expand Up @@ -698,6 +648,78 @@ struct MainNavView: View {
!SamRockSetupRequest.isProtocolURL(uri) && !PubkyAuthRequest.isProtocolURL(uri)
}

private func handlePendingDeepLink() async {
await app.routePendingDeepLinkIfReady(
canHandleDeepLinks,
nodeIsRunning: wallet.nodeLifecycleState == .running
) { url in
await handleDeepLink(url)
}
}

private func handleDeepLink(_ url: URL) async {
Logger.info("Received deeplink: \(sanitizedDeeplinkDescription(url))")

// Web URLs from widgets (e.g. news article tap) bypass payment handling
if let scheme = url.scheme?.lowercased(), scheme == "http" || scheme == "https" {
await UIApplication.shared.open(url)
return
}

if let callback = PubkyRingAuthCallback.parse(url: url) {
guard isPaykitUIActive else {
app.toast(
type: .error,
title: t("profile__auth_error_title"),
description: t("other__qr_error_text")
)
return
}

let handlingResult = await pubkyProfile.handleAuthCallback(callback)

switch handlingResult {
case let .trustedError(message):
app.toast(
type: .error,
title: t("profile__auth_error_title"),
description: message ?? t("other__qr_error_text")
)
case .untrustedError:
app.toast(
type: .error,
title: t("profile__auth_error_title")
)
case .handled, .ignored:
break
}

return
}

do {
try await app.handleScannedData(
url.absoluteString,
alternativeOnchainBalanceSats: hwWalletManager.maximumFundingBalanceSats
)
if shouldOpenPaymentSheet(for: url.absoluteString) {
PaymentNavigationHelper.openPaymentSheet(
app: app,
currency: currency,
settings: settings,
sheetViewModel: sheets
)
}
} catch {
Logger.error(error, context: "Failed to handle deeplink")
app.toast(
type: .error,
title: t("other__qr_error_header"),
description: t("other__qr_error_text")
)
}
}

private func sanitizedDeeplinkDescription(_ url: URL) -> String {
if let description = SamRockSetupRequest.sanitizedDescription(url.absoluteString) {
return description
Expand Down
15 changes: 13 additions & 2 deletions Bitkit/Managers/PubkyProfileManager.swift
Original file line number Diff line number Diff line change
Expand Up @@ -95,6 +95,17 @@ enum PubkyRingAuthURLBuilder {
return components.url?.absoluteString
}

static func ringHandoffURL(from authUrl: String) -> URL? {
guard var components = URLComponents(string: authUrl), components.scheme?.lowercased() == "pubkyauth" else {
return nil
}

components.scheme = "pubkyring"
components.host = "signin"
components.path = ""
return components.url
}

private static func callbackUrl(_ baseUrl: String, nonce: UUID?) -> String {
guard let nonce else {
return baseUrl
Expand Down Expand Up @@ -389,7 +400,7 @@ class PubkyProfileManager: ObservableObject {
}

static func isRingAvailable() -> Bool {
guard let url = URL(string: "pubkyauth://check") else {
guard let url = URL(string: "pubkyring://check") else {
return false
}

Expand Down Expand Up @@ -477,7 +488,7 @@ class PubkyProfileManager: ObservableObject {

let callbackAuthUrl = PubkyRingAuthURLBuilder.addingCallbacks(to: authUrl, nonce: attemptID) ?? authUrl

guard let url = URL(string: callbackAuthUrl) else {
guard let url = PubkyRingAuthURLBuilder.ringHandoffURL(from: callbackAuthUrl) else {
await cancelPendingAuthSetup()
activeAuthAttemptID = nil
restoreAuthStateAfterAuthFlow()
Expand Down
Loading
Loading