Cache TOTP discovery and report progress (#74)

This commit is contained in:
2026-08-11 23:15:23 +02:00
parent 6edcb5fc86
commit 9759162eff
12 changed files with 1577 additions and 198 deletions

View File

@@ -654,7 +654,11 @@ private final class ShellViewController: UITableViewController, MobileTabRoot {
)
if failure.kind == .authentication || failure.kind == .secureStorage {
alert.addAction(UIAlertAction(title: "Preferences", style: .default) { [weak self] _ in
self?.tabBarController?.selectedIndex = 3
guard let tabs = self?.tabBarController else { return }
tabs.selectedIndex = tabs.viewControllers?.firstIndex { controller in
guard let navigation = controller as? UINavigationController else { return false }
return (navigation.viewControllers.first as? MobileTabRoot)?.shellTab == .preferences
} ?? tabs.selectedIndex
})
}
alert.addAction(UIAlertAction(title: "OK", style: .cancel))
@@ -1577,6 +1581,76 @@ private final class KeyQrView: UIView {
}
}
@MainActor
private final class TotpDiscoveryView: UIView {
private let spinner = UIActivityIndicatorView(style: .medium)
private let titleLabel = UILabel()
private let detailLabel = UILabel()
private let progressView = UIProgressView(progressViewStyle: .default)
init(cancel: @escaping () -> Void) {
super.init(frame: .zero)
titleLabel.font = .preferredFont(forTextStyle: .headline)
titleLabel.adjustsFontForContentSizeCategory = true
titleLabel.textAlignment = .center
detailLabel.font = .preferredFont(forTextStyle: .subheadline)
detailLabel.adjustsFontForContentSizeCategory = true
detailLabel.textColor = .secondaryLabel
detailLabel.textAlignment = .center
detailLabel.numberOfLines = 0
progressView.accessibilityLabel = "TOTP discovery progress"
let cancelButton = UIButton(type: .system, primaryAction: UIAction(title: "Cancel") { _ in
cancel()
})
let progressRow = UIStackView(arrangedSubviews: [spinner, progressView])
progressRow.alignment = .center
progressRow.spacing = 12
let stack = UIStackView(arrangedSubviews: [titleLabel, detailLabel, progressRow, cancelButton])
stack.axis = .vertical
stack.alignment = .fill
stack.spacing = 12
stack.translatesAutoresizingMaskIntoConstraints = false
addSubview(stack)
NSLayoutConstraint.activate([
stack.centerXAnchor.constraint(equalTo: centerXAnchor),
stack.topAnchor.constraint(equalTo: topAnchor, constant: 24),
stack.bottomAnchor.constraint(equalTo: bottomAnchor, constant: -24),
stack.leadingAnchor.constraint(greaterThanOrEqualTo: readableContentGuide.leadingAnchor),
stack.trailingAnchor.constraint(lessThanOrEqualTo: readableContentGuide.trailingAnchor),
progressView.widthAnchor.constraint(greaterThanOrEqualToConstant: 180),
])
}
@available(*, unavailable)
required init?(coder: NSCoder) {
fatalError("init(coder:) is not supported")
}
func apply(_ progress: MobileTotpDiscoveryProgress) {
titleLabel.text = switch progress.phase {
case .preparing: "Preparing TOTP Discovery"
case .inspecting: "Discovering TOTP Entries"
case .saving: "Saving Protected Cache"
case .complete: "TOTP Discovery Complete"
case .cancelled: "Cancelling TOTP Discovery"
}
if progress.total == 0 {
spinner.startAnimating()
progressView.isHidden = true
detailLabel.text = "Reading the password-store inventory."
} else {
spinner.stopAnimating()
progressView.isHidden = false
progressView.progress = Float(progress.inspected) / Float(progress.total)
progressView.accessibilityValue = "\(progress.inspected) of \(progress.total)"
detailLabel.text =
"\(progress.inspected) of \(progress.total) inspected • "
+ "\(progress.cacheHits) cached • \(progress.matches) TOTP"
+ (progress.unavailable == 0 ? "" : "\(progress.unavailable) unavailable")
}
}
}
@MainActor
private final class TotpListViewController: UITableViewController, MobileTabRoot {
fileprivate let shellTab = MobileTab.totp
@@ -1585,6 +1659,11 @@ private final class TotpListViewController: UITableViewController, MobileTabRoot
private var page: MobileTotpPage?
private var loadTask: Task<Void, Never>?
private var unlockTask: Task<Void, Never>?
private var shellTask: Task<Void, Never>?
private var progressTask: Task<Void, Never>?
private var operation: MobileTotpOperation?
private var loadGeneration = 0
private var refreshAfterUnlock = false
init(shellPage: MobilePage, authentication: MobileAuthentication?) {
self.shellPage = shellPage
@@ -1602,8 +1681,11 @@ private final class TotpListViewController: UITableViewController, MobileTabRoot
}
deinit {
operation?.cancel()
loadTask?.cancel()
unlockTask?.cancel()
shellTask?.cancel()
progressTask?.cancel()
NotificationCenter.default.removeObserver(self)
}
@@ -1632,7 +1714,7 @@ private final class TotpListViewController: UITableViewController, MobileTabRoot
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
refreshState()
reloadShell()
}
override func numberOfSections(in tableView: UITableView) -> Int { 1 }
@@ -1649,7 +1731,8 @@ private final class TotpListViewController: UITableViewController, MobileTabRoot
let unavailable = page.unavailableEntries == 0
? ""
: " \(page.unavailableEntries) entries could not be inspected with the active key."
return page.watch.detail + unavailable
let cache = page.cacheNotice.map { " \($0)" } ?? ""
return page.watch.detail + unavailable + cache
}
override func tableView(
@@ -1677,7 +1760,16 @@ private final class TotpListViewController: UITableViewController, MobileTabRoot
override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
tableView.deselectRow(at: indexPath, animated: true)
guard let row = page?.rows[indexPath.row], let authentication else { return }
guard let row = page?.rows[indexPath.row] else { return }
guard (try? authentication?.state().unlocked) == true else {
unlock(passphrase: nil, row: row)
return
}
open(row)
}
private func open(_ row: MobileTotpRow) {
guard let authentication else { return }
loadTask?.cancel()
loadTask = Task { [weak self] in
let result = await Task.detached(priority: .userInitiated) {
@@ -1709,20 +1801,36 @@ private final class TotpListViewController: UITableViewController, MobileTabRoot
}
@objc private func refreshRequested() {
refreshState(force: true)
if (try? authentication?.state().unlocked) == true {
loadPage()
} else {
refreshAfterUnlock = true
refreshControl?.endRefreshing()
unlockRequested()
}
}
@objc private func authenticationDidChange() {
if (try? authentication?.state().unlocked) != true {
operation?.cancel()
}
refreshState()
}
@objc private func localStoreDidChange() {
guard (try? authentication?.state().unlocked) == true else { return }
loadPage()
operation?.cancel()
loadTask?.cancel()
progressTask?.cancel()
loadGeneration += 1
operation = nil
progressTask = nil
tableView.tableHeaderView = nil
page = nil
loadCachedPage()
}
@objc private func unlockRequested() {
unlock(passphrase: nil)
unlock(passphrase: nil, row: nil)
}
@objc private func lockRequested() {
@@ -1750,29 +1858,30 @@ private final class TotpListViewController: UITableViewController, MobileTabRoot
)
return
}
if (try? authentication?.state().unlocked) == true {
if page == nil || force { loadPage() }
} else {
loadTask?.cancel()
page = nil
tableView.reloadData()
navigationItem.rightBarButtonItem = nil
var configuration = UIContentUnavailableConfiguration.empty()
configuration.image = UIImage(systemName: "lock.fill")
configuration.text = "TOTP Is Locked"
configuration.secondaryText =
"Authenticate to scan password entries for time-based one-time passwords."
configuration.button = .filled()
configuration.button.title = "Unlock"
configuration.buttonProperties.primaryAction = UIAction { [weak self] _ in
self?.unlockRequested()
}
contentUnavailableConfiguration = configuration
refreshControl?.endRefreshing()
if force, (try? authentication?.state().unlocked) == true {
loadPage()
} else if page == nil, loadTask == nil {
loadCachedPage()
} else if page != nil {
configureLockButton()
}
}
private func unlock(passphrase: String?) {
private func reloadShell() {
shellTask?.cancel()
shellTask = Task { [weak self] in
let shell = await Task.detached(priority: .userInitiated) { mobileShell() }.value
guard
!Task.isCancelled,
let self,
let page = shell.pages.first(where: { $0.tab == .totp })
else { return }
shellPage = page
refreshState()
}
}
private func unlock(passphrase: String?, row: MobileTotpRow?) {
guard let authentication else {
presentAuthenticationFailure(.unavailable)
return
@@ -1782,8 +1891,13 @@ private final class TotpListViewController: UITableViewController, MobileTabRoot
unlockTask = Task { [weak self] in
let result = await Task.detached(priority: .userInitiated) {
do {
return Result<MobileAuthenticationState, AuthenticationFailure>.success(
let state = if let row {
try authentication.unlockEntry(path: row.path, passphrase: passphrase)
} else {
try authentication.unlockTotp(passphrase: passphrase)
}
return Result<MobileAuthenticationState, AuthenticationFailure>.success(
state
)
} catch let error as MobileAuthenticationFfiError {
return .failure(AuthenticationFailure(error))
@@ -1792,26 +1906,34 @@ private final class TotpListViewController: UITableViewController, MobileTabRoot
}
}.value
guard !Task.isCancelled, let self else { return }
contentUnavailableConfiguration = nil
switch result {
case .success:
NotificationCenter.default.post(
name: .ironStorageAuthenticationDidChange,
object: authentication
)
loadPage()
if refreshAfterUnlock || page == nil {
refreshAfterUnlock = false
loadPage()
} else if let row {
open(row)
} else {
configureLockButton()
}
UIAccessibility.post(notification: .announcement, argument: "TOTP unlocked")
case let .failure(failure)
where passphrase == nil
&& (failure.kind == .passphraseRequired
|| failure.kind == .biometryUnavailable):
promptForPassphrase(message: failure.detail)
promptForPassphrase(message: failure.detail, row: row)
case let .failure(failure):
if failure.kind != .cancelled { handle(failure) }
}
}
}
private func promptForPassphrase(message: String) {
private func promptForPassphrase(message: String, row: MobileTotpRow?) {
let alert = UIAlertController(
title: "GPG Key Passphrase",
message: message,
@@ -1829,7 +1951,7 @@ private final class TotpListViewController: UITableViewController, MobileTabRoot
alert.addAction(UIAlertAction(title: "Unlock", style: .default) { [weak self, weak alert] _ in
guard let value = alert?.textFields?.first?.text, !value.isEmpty else { return }
alert?.textFields?.first?.text = nil
self?.unlock(passphrase: value)
self?.unlock(passphrase: value, row: row)
})
present(alert, animated: true)
}
@@ -1839,13 +1961,75 @@ private final class TotpListViewController: UITableViewController, MobileTabRoot
presentAuthenticationFailure(.unavailable)
return
}
operation?.cancel()
loadTask?.cancel()
showLoading("Loading TOTP")
progressTask?.cancel()
loadGeneration += 1
let current = loadGeneration
let operation = mobileTotpOperation()
self.operation = operation
navigationItem.rightBarButtonItems = nil
let discoveryView = TotpDiscoveryView { [weak self] in
self?.cancelDiscovery()
}
apply(operation.progress(), to: discoveryView)
tableView.tableHeaderView = discoveryView
contentUnavailableConfiguration = nil
progressTask = Task { [weak self] in
while !Task.isCancelled {
do {
try await Task.sleep(for: .milliseconds(150))
} catch {
return
}
guard !Task.isCancelled, let self, current == loadGeneration else { return }
apply(operation.progress(), to: discoveryView)
}
}
loadTask = Task { [weak self] in
let result = await Task.detached(priority: .userInitiated) {
do {
return Result<MobileTotpPage, AuthenticationFailure>.success(
try authentication.totpPage()
try authentication.totpPage(operation: operation)
)
} catch let error as MobileAuthenticationFfiError {
return .failure(AuthenticationFailure(error))
} catch {
return .failure(.unexpected)
}
}.value
guard !Task.isCancelled, let self, current == loadGeneration else { return }
progressTask?.cancel()
progressTask = nil
self.operation = nil
loadTask = nil
tableView.tableHeaderView = nil
refreshControl?.endRefreshing()
configureLockButton()
switch result {
case let .success(page):
apply(page)
case let .failure(failure):
if failure.kind == .cancelled {
loadCachedPage()
} else {
handle(failure)
}
}
}
}
private func loadCachedPage() {
guard let authentication else {
presentAuthenticationFailure(.unavailable)
return
}
loadTask?.cancel()
loadTask = Task { [weak self] in
let result = await Task.detached(priority: .userInitiated) {
do {
return Result<MobileTotpPage?, AuthenticationFailure>.success(
try authentication.cachedTotpPage()
)
} catch let error as MobileAuthenticationFfiError {
return .failure(AuthenticationFailure(error))
@@ -1854,26 +2038,15 @@ private final class TotpListViewController: UITableViewController, MobileTabRoot
}
}.value
guard !Task.isCancelled, let self else { return }
refreshControl?.endRefreshing()
loadTask = nil
switch result {
case let .success(page):
self.page = page
navigationItem.rightBarButtonItem = UIBarButtonItem(
image: UIImage(systemName: "lock.fill"),
style: .plain,
target: self,
action: #selector(lockRequested)
)
navigationItem.rightBarButtonItem?.accessibilityLabel = "Lock IronStorage"
tableView.reloadData()
if page.rows.isEmpty {
showUnavailable(
title: "No TOTP Codes",
detail: "No valid time-based OTP entries were found in the password store.",
image: "timer"
)
case let .success(.some(page)):
apply(page)
case .success(.none):
if (try? authentication.state().unlocked) == true {
loadPage()
} else {
contentUnavailableConfiguration = nil
showLocked()
}
case let .failure(failure):
handle(failure)
@@ -1881,6 +2054,69 @@ private final class TotpListViewController: UITableViewController, MobileTabRoot
}
}
private func apply(_ page: MobileTotpPage) {
self.page = page
configureLockButton()
tableView.reloadData()
if page.rows.isEmpty {
showUnavailable(
title: "No TOTP Codes",
detail: "No valid time-based OTP entries were found in the password store.",
image: "timer"
)
} else {
contentUnavailableConfiguration = nil
}
}
private func configureLockButton() {
let unlocked = (try? authentication?.state().unlocked) == true
navigationItem.rightBarButtonItem = UIBarButtonItem(
image: UIImage(systemName: unlocked ? "lock.fill" : "lock.open.fill"),
style: .plain,
target: self,
action: unlocked ? #selector(lockRequested) : #selector(unlockRequested)
)
navigationItem.rightBarButtonItem?.accessibilityLabel =
unlocked ? "Lock IronStorage" : "Unlock IronStorage"
}
private func showLocked() {
page = nil
tableView.reloadData()
navigationItem.rightBarButtonItem = nil
var configuration = UIContentUnavailableConfiguration.empty()
configuration.image = UIImage(systemName: "lock.fill")
configuration.text = "TOTP Is Locked"
configuration.secondaryText =
"Unlock once to discover time-based one-time-password entries."
configuration.button = .filled()
configuration.button.title = "Unlock"
configuration.buttonProperties.primaryAction = UIAction { [weak self] _ in
self?.unlockRequested()
}
contentUnavailableConfiguration = configuration
refreshControl?.endRefreshing()
}
private func cancelDiscovery() {
operation?.cancel()
}
private func apply(_ progress: MobileTotpDiscoveryProgress, to view: TotpDiscoveryView) {
view.apply(progress)
let width = tableView.bounds.width
let height = view.systemLayoutSizeFitting(
CGSize(width: width, height: UIView.layoutFittingCompressedSize.height),
withHorizontalFittingPriority: .required,
verticalFittingPriority: .fittingSizeLevel
).height
view.frame = CGRect(x: 0, y: 0, width: width, height: height)
if tableView.tableHeaderView === view {
tableView.tableHeaderView = view
}
}
private func handle(_ failure: AuthenticationFailure) {
if failure.kind == .expired {
NotificationCenter.default.post(
@@ -1895,6 +2131,7 @@ private final class TotpListViewController: UITableViewController, MobileTabRoot
}
private func showLoading(_ title: String) {
tableView.backgroundView = nil
var configuration = UIContentUnavailableConfiguration.loading()
configuration.text = title
configuration.secondaryText = "Reading OTP metadata in secure storage."
@@ -1902,6 +2139,7 @@ private final class TotpListViewController: UITableViewController, MobileTabRoot
}
private func showUnavailable(title: String, detail: String, image: String) {
tableView.backgroundView = nil
var configuration = UIContentUnavailableConfiguration.empty()
configuration.image = UIImage(systemName: image)
configuration.text = title