Files
ios/iOSClient/AppDelegate.swift
Marino Faggiana 48d27f2ca9 refactor: migrate app passcode flows to SwiftUI (#4419)
* feat: add shared SwiftUI passcode component

Support passcode authentication, creation, changes and removal with biometrics and shared lockout protection. Keep the existing passcode flow active until callers are migrated.

Signed-off-by: Marino Faggiana <[email protected]>

* feat: migrate settings to SwiftUI passcode flow

Update lock settings after passcode completion and handle reset results. Add toolbar dismissal and require the current passcode when changing it.

Signed-off-by: Marino Faggiana <[email protected]>

* fix: authenticate E2EE actions with the shared passcode view

Require authentication in Debug builds and verify the account before executing E2EE actions. Present cancellable passcode flows as sheets and handle completion during dismissal.

Signed-off-by: Marino Faggiana <[email protected]>

* refactor: migrate app passcode flows to NCPasscodeView

Use the shared passcode view for app unlock and enforced setup. Scope lifecycle handling to the presenting window scene and cancel optional operations when backgrounded.

Signed-off-by: Marino Faggiana <[email protected]>

* refactor: migrate passcode flows to shared SwiftUI components

Replace TOPasscode in the main app and Share Extension, remove the legacy implementation, and add passcode UI tests.

Signed-off-by: Marino Faggiana <[email protected]>

* Acknowledgements update

Signed-off-by: Marino Faggiana <[email protected]>

* fix

Signed-off-by: Marino Faggiana <[email protected]>

* fix: preserve passcode reset threshold across lockouts

Clear only the retry counter and lockout deadline when the delay expires. Add UI coverage verifying app reset after ten failures across lockouts.

Signed-off-by: Marino Faggiana <[email protected]>

* fix: keep app passcode lock above sheets and alerts

Present the mandatory lock in a dedicated window per scene and preserve underlying UI after unlocking.

Add UI regression coverage, improve authentication test handling, and enforce CI test timeouts with retained diagnostics.

Signed-off-by: Marino Faggiana <[email protected]>

* fix: wait for HTTP fallback in UI test login

Allow the initial HTTPS request to time out before expecting the localhost authentication page, and skip UI queries against authentication services that are not running.

Signed-off-by: Marino Faggiana <[email protected]>
Assisted-by: Codex:GPT-6

* CI

Signed-off-by: Marino Faggiana <[email protected]>

* CI

Signed-off-by: Marino Faggiana <[email protected]>

* CI

Signed-off-by: Marino Faggiana <[email protected]>

* CI

Signed-off-by: Marino Faggiana <[email protected]>

* size button

Signed-off-by: Marino Faggiana <[email protected]>

* fix: avoid redundant transfer and auto-upload state updates

Preserve the auto-upload suspension message until all reads finish, and discard cancelled or stale refreshes.

Signed-off-by: Marino Faggiana <[email protected]>

* added NCPasscodeView.embed

Signed-off-by: Marino Faggiana <[email protected]>

* fix: correct share extension passcode layout

Embed the passcode view in the content controller while hiding the enclosing navigation bar, and constrain its width to the available space.

Signed-off-by: Marino Faggiana <[email protected]>

* fix: enforce app lock after failed passcode attempts

Preserve mandatory authentication across scenes and relaunches after lockout. Require biometric authorization before enabling Touch ID or Face ID, add passcode error feedback, and update lockout UI tests.

Signed-off-by: Marino Faggiana <[email protected]>

* fix: stabilize passcode UI tests and run them for relevant changes

Shorten reset-test lockouts and let XCTest terminate the app after observing completed cleanup to avoid TSan exit issues. Run passcode UI tests when related files change and increase CI test timeouts.

Signed-off-by: Marino Faggiana <[email protected]>

---------

Signed-off-by: Marino Faggiana <[email protected]>
2026-10-28 07:57:01 +01:00

352 lines
15 KiB
Swift

// SPDX-FileCopyrightText: Nextcloud GmbH
// SPDX-FileCopyrightText: 2014 Marino Faggiana [Start 04/09/14]
// SPDX-FileCopyrightText: 2021 Marino Faggiana [Swift 19/02/21]
// SPDX-License-Identifier: GPL-3.0-or-later
import UIKit
import BackgroundTasks
import NextcloudKit
import LocalAuthentication
import Firebase
import WidgetKit
import EasyTipView
import SwiftUI
import RealmSwift
import Photos
class AppDelegate: UIResponder, UIApplicationDelegate, UNUserNotificationCenterDelegate {
var backgroundSessionCompletionHandler: (() -> Void)?
var isUiTestingEnabled: Bool {
return ProcessInfo.processInfo.arguments.contains("UI_TESTING")
}
var notificationSettings: UNNotificationSettings?
var loginFlowV2Token = ""
var loginFlowV2Endpoint = ""
var loginFlowV2Login = ""
let backgroundQueue = DispatchQueue(label: "com.nextcloud.bgTaskQueue")
let global = NCGlobal.shared
var bgTask: UIBackgroundTaskIdentifier = .invalid
var pushSubscriptionTask: Task<Void, Never>?
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
#if DEBUG
// Give security UI tests a repeatable starting state on their dedicated simulator.
if isUiTestingEnabled && ProcessInfo.processInfo.arguments.contains("UI_TESTING_PASSCODE") {
let preferences = NCPreferences()
preferences.passcode = nil
preferences.clearPasscodeFailures()
preferences.touchFaceID = false
preferences.requestPasscodeAtStart = true
preferences.resetAppCounterFail = false
}
#endif
let utilityFileSystem = NCUtilityFileSystem()
let utility = NCUtility()
utilityFileSystem.createDirectoryStandard()
utilityFileSystem.emptyTemporaryDirectory()
utilityFileSystem.clearCacheDirectory("com.limit-point.LivePhoto")
let versionNextcloudiOS = String(format: NCBrandOptions.shared.textCopyrightNextcloudiOS, utility.getVersionBuild())
NCAppVersionManager.shared.checkAndUpdateInstallState()
NCSettingsBundleHelper.checkAndExecuteSettings(delay: 0)
UserDefaults.standard.register(defaults: ["UserAgent": userAgent])
if !NCPreferences().disableCrashservice, !NCBrandOptions.shared.disable_crash_service {
FirebaseApp.configure()
}
NCBrandColor.shared.createUserColors()
// Setup Networking
//
NextcloudKit.shared.setup(groupIdentifier: NCBrandOptions.shared.capabilitiesGroup,
delegate: NCNetworking.shared)
NCNetworking.shared.setupTransferDelegate()
NextcloudKit.configureLogger(
logLevel: NCBrandOptions.shared.disable_log ? .disabled : NCPreferences().log,
logDirectory: NCPreferences.sharedLogDirectory
)
#if DEBUG
// For the tags look NCGlobal LOG TAG
// var black: [String] = []
// black.append("NETWORKING TASKS")
// NextcloudKit.configureLoggerBlacklist(blacklist: black)
// var white: [String] = []
// white.append("SYNC METADATA")
// NextcloudKit.configureLoggerWhitelist(whitelist: white)
#endif
nkLog(start: "Start session with level \(NCPreferences().log) " + versionNextcloudiOS)
// Push Notification & display notification
UNUserNotificationCenter.current().getNotificationSettings { settings in
self.notificationSettings = settings
}
application.registerForRemoteNotifications()
UNUserNotificationCenter.current().delegate = self
UNUserNotificationCenter.current().requestAuthorization(options: [.alert, .badge, .sound]) { _, _ in }
#if !targetEnvironment(simulator)
let review = NCStoreReview()
review.incrementAppRuns()
review.showStoreReview()
#endif
BGTaskScheduler.shared.register(forTaskWithIdentifier: global.refreshTask, using: backgroundQueue) { task in
guard let appRefreshTask = task as? BGAppRefreshTask else {
task.setTaskCompleted(success: false)
return
}
self.handleAppRefresh(appRefreshTask)
}
scheduleAppRefresh()
BGTaskScheduler.shared.register(forTaskWithIdentifier: global.processingTask, using: backgroundQueue) { task in
guard let processingTask = task as? BGProcessingTask else {
task.setTaskCompleted(success: false)
return
}
self.handleProcessingTask(processingTask)
}
scheduleAppProcessing()
if NCBrandOptions.shared.enforce_passcode_lock {
NCPreferences().requestPasscodeAtStart = true
}
return true
}
func applicationWillTerminate(_ application: UIApplication) {
if self.notificationSettings?.authorizationStatus != .denied && UIApplication.shared.backgroundRefreshStatus == .available {
let content = UNMutableNotificationContent()
content.title = NCBrandOptions.shared.brand
content.body = NSLocalizedString("_keep_running_", comment: "")
let req = UNNotificationRequest(identifier: UUID().uuidString, content: content, trigger: nil)
let notificationCenter = UNUserNotificationCenter.current()
notificationCenter.add(req)
}
nkLog(debug: "App is terminating")
}
// MARK: - UISceneSession Lifecycle
func application(_ application: UIApplication, configurationForConnecting connectingSceneSession: UISceneSession, options: UIScene.ConnectionOptions) -> UISceneConfiguration {
// Called when a new scene session is being created.
// Use this method to select a configuration to create the new scene with.
return UISceneConfiguration(name: "Default Configuration", sessionRole: connectingSceneSession.role)
}
func application(_ application: UIApplication, didDiscardSceneSessions sceneSessions: Set<UISceneSession>) {
// Called when the user discards a scene session.
// If any sessions were discarded while the application was not running, this will be called shortly after application:didFinishLaunchingWithOptions.
// Use this method to release any resources that were specific to the discarded scenes, as they will not return.
}
// MARK: - Background Networking Session
func application(_ application: UIApplication, handleEventsForBackgroundURLSession identifier: String, completionHandler: @escaping () -> Void) {
nkLog(debug: "Handle events For background URLSession: \(identifier)")
NCManageDatabase.shared.openRealmBackground()
backgroundSessionCompletionHandler = completionHandler
}
// MARK: - Push Notifications
func userNotificationCenter(_ center: UNUserNotificationCenter, willPresent notification: UNNotification, withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void) {
completionHandler([.list, .banner, .sound])
}
func userNotificationCenter(_ center: UNUserNotificationCenter, didReceive response: UNNotificationResponse, withCompletionHandler completionHandler: @escaping () -> Void) {
if let pref = UserDefaults(suiteName: NCBrandOptions.shared.capabilitiesGroup),
let data = pref.object(forKey: "NOTIFICATION_DATA") as? [String: AnyObject] {
nextcloudPushNotificationAction(data: data)
pref.set(nil, forKey: "NOTIFICATION_DATA")
}
completionHandler()
}
func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) {
guard !isXcodeRunningForPreviews,
application.applicationState != .background else {
return
}
if let deviceToken = NCPushNotificationEncryption.shared().string(withDeviceToken: deviceToken) {
NCPreferences().deviceTokenPushNotification = deviceToken
pushSubscriptionTask = Task.detached {
// Wait bounded time for maintenance to be OFF
let canProceed = await NCAppStateManager.shared.waitForMaintenanceOffAsync()
guard canProceed else {
nkLog(error: "[PUSH] Skipping subscription: maintenance mode still ON after timeout")
return
}
try? await Task.sleep(for: .seconds(1))
let tblAccounts = await NCManageDatabase.shared.getAllTableAccountAsync()
for tblAccount in tblAccounts {
await NCPushNotification.shared.subscribingNextcloudServerPushNotification(account: tblAccount.account, urlBase: tblAccount.urlBase)
}
}
}
}
func application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable: Any], fetchCompletionHandler completionHandler: @escaping (UIBackgroundFetchResult) -> Void) {
NCPushNotification.shared.applicationdidReceiveRemoteNotification(userInfo: userInfo) { result in
completionHandler(result)
}
}
func nextcloudPushNotificationAction(data: [String: AnyObject]) {
let account = data["account"] as? String ?? "unavailable"
let app = data["app"] as? String
func openNotification(controller: NCMainTabBarController) {
if app == NCGlobal.shared.termsOfServiceName {
Task {
await NCNetworking.shared.transferDispatcher.notifyAllDelegatesAsync { delegate in
try? await Task.sleep(for: .seconds(0.5))
delegate.transferReloadDataSource(serverUrl: nil, requestData: true, status: nil)
}
}
} else if let navigationController = UIStoryboard(name: "NCNotification", bundle: nil).instantiateInitialViewController() as? UINavigationController,
let viewController = navigationController.topViewController as? NCNotification {
viewController.modalPresentationStyle = .pageSheet
viewController.session = NCSession.shared.getSession(account: account)
DispatchQueue.main.asyncAfter(deadline: .now() + 1) {
controller.present(navigationController, animated: true, completion: nil)
}
}
}
if let controller = SceneManager.shared.getControllers().first(where: { $0.account == account }) {
openNotification(controller: controller)
} else if let tblAccount = NCManageDatabase.shared.getAllTableAccount().first(where: { $0.account == account }),
let controller = SceneManager.shared.getController(window: UIApplication.shared.mainAppWindow) {
Task { @MainActor in
await NCAccount().changeAccount(tblAccount.account, userProfile: nil, controller: controller)
openNotification(controller: controller)
}
} else {
let message = String(
format: NSLocalizedString("account_does_not_exist", comment: ""),
account
)
let alertController = UIAlertController(title: NSLocalizedString("_info_", comment: ""), message: message, preferredStyle: .alert)
alertController.addAction(UIAlertAction(title: NSLocalizedString("_ok_", comment: ""), style: .default, handler: { _ in }))
UIApplication.shared.mainAppWindow?.rootViewController?.present(alertController, animated: true, completion: { })
}
}
// MARK: -
func trustCertificateError(host: String) {
guard let activeTblAccount = NCManageDatabase.shared.getActiveTableAccount(),
let currentHost = URL(string: activeTblAccount.urlBase)?.host,
let pushNotificationServerProxyHost = URL(string: NCBrandOptions.shared.pushNotificationServerProxy)?.host,
host != pushNotificationServerProxyHost,
host == currentHost
else { return }
let certificateHostSavedPath = NCUtilityFileSystem().directoryCertificates + "/" + host + ".der"
var title = NSLocalizedString("_ssl_certificate_changed_", comment: "")
if !FileManager.default.fileExists(atPath: certificateHostSavedPath) {
title = NSLocalizedString("_connect_server_anyway_", comment: "")
}
let alertController = UIAlertController(title: title, message: NSLocalizedString("_server_is_trusted_", comment: ""), preferredStyle: .alert)
alertController.addAction(UIAlertAction(title: NSLocalizedString("_yes_", comment: ""), style: .default, handler: { _ in
NCNetworking.shared.writeCertificate(host: host)
}))
alertController.addAction(UIAlertAction(title: NSLocalizedString("_no_", comment: ""), style: .default, handler: { _ in }))
alertController.addAction(UIAlertAction(title: NSLocalizedString("_certificate_details_", comment: ""), style: .default, handler: { _ in
if let navigationController = UIStoryboard(name: "NCViewCertificateDetails", bundle: nil).instantiateInitialViewController() as? UINavigationController,
let viewController = navigationController.topViewController as? NCViewCertificateDetails {
viewController.delegate = self
viewController.host = host
UIApplication.shared.mainAppWindow?.rootViewController?.present(navigationController, animated: true)
}
}))
UIApplication.shared.mainAppWindow?.rootViewController?.present(alertController, animated: true)
}
// MARK: - Reset Application
func resetApplication() {
let utilityFileSystem = NCUtilityFileSystem()
NCNetworking.shared.cancelAllTask()
URLCache.shared.removeAllCachedResponses()
utilityFileSystem.removeGroupDirectoryProviderStorage()
utilityFileSystem.removeGroupApplicationSupport()
utilityFileSystem.removeDocumentsDirectory()
utilityFileSystem.removeTemporaryDirectory()
NCPreferences().removeAll()
#if DEBUG
// Let UI tests observe the completed reset before terminating the process themselves.
if isUiTestingEnabled,
ProcessInfo.processInfo.arguments.contains("UI_TESTING_NO_EXIT"),
let window = UIApplication.shared.mainAppWindow {
let controller = UIViewController()
controller.view.backgroundColor = .systemBackground
controller.view.isAccessibilityElement = true
controller.view.accessibilityIdentifier = "uiTesting.resetCompleted"
controller.view.accessibilityLabel = "Reset completed"
window.rootViewController = controller
window.makeKeyAndVisible()
return
}
#endif
exit(0)
}
// MARK: - Universal Links
func application(_ application: UIApplication, continue userActivity: NSUserActivity, restorationHandler: @escaping ([UIUserActivityRestoring]?) -> Void) -> Bool {
return false
}
}
// MARK: - Extension
extension AppDelegate: NCViewCertificateDetailsDelegate {
func viewCertificateDetailsDismiss(host: String) {
trustCertificateError(host: host)
}
}
extension AppDelegate: NCCreateFormUploadConflictDelegate {
func dismissCreateFormUploadConflict(metadatas: [tableMetadata]?) {
if let metadatas {
Task {
await NCManageDatabase.shared.addMetadatasAsync(metadatas)
}
}
}
}