diff --git a/Package.swift b/Package.swift index 295cf097..31714495 100644 --- a/Package.swift +++ b/Package.swift @@ -50,6 +50,6 @@ let package = Package( dependencies: ["NextcloudKit", "Mocker"]), .testTarget( name: "NextcloudKitUITests", - dependencies: ["NextcloudKit", "NextcloudKitUI", "Mocker"]), + dependencies: ["NextcloudKit", "NextcloudKitUI", "CodeScanner", "Mocker"]), ] ) diff --git a/Sources/NextcloudKitUI/Color+readable.swift b/Sources/NextcloudKitUI/Color+readable.swift index 9982bb95..102e0188 100644 --- a/Sources/NextcloudKitUI/Color+readable.swift +++ b/Sources/NextcloudKitUI/Color+readable.swift @@ -21,7 +21,6 @@ extension Color { } } - #if os(iOS) let uiColor = UIColor(self) var red: CGFloat = 0, green: CGFloat = 0, blue: CGFloat = 0, alpha: CGFloat = 0 @@ -29,17 +28,6 @@ extension Color { guard uiColor.getRed(&red, green: &green, blue: &blue, alpha: &alpha) else { return .primary } - #endif - - #if os(macOS) - guard let rgbColor = NSColor(self).usingColorSpace(.sRGB) else { - return .primary - } - - let red = rgbColor.redComponent - let green = rgbColor.greenComponent - let blue = rgbColor.blueComponent - #endif let luminance = 0.2126 * adjust(red) + 0.7152 * adjust(green) + 0.0722 * adjust(blue) diff --git a/Sources/NextcloudKitUI/Documentation.docc/Documentation.md b/Sources/NextcloudKitUI/Documentation.docc/Documentation.md index 366cfacd..307f4a13 100644 --- a/Sources/NextcloudKitUI/Documentation.docc/Documentation.md +++ b/Sources/NextcloudKitUI/Documentation.docc/Documentation.md @@ -1,15 +1,15 @@ # ``SwiftNextcloudUI`` -A multi-platform package to provide common user interface elements of apps by Nextcloud written in SwiftUI. +A package to provide common user interface elements of apps by Nextcloud written in SwiftUI. ## Overview Key traits of this package: - **Swift 6.1**. Latest language features independent from the consuming projects. -- **Multiplatform**. With iOS and iPad OS being targeted primarily, macOS is supported to and checked for compatibility and appearance. +- **iOS and iPadOS**. Other platforms are not supported for now. - **Strict concurrency checks enabled**. Avoiding technical debt from the start as far as possible. -- **Built for the future**. Minimum requirements are iOS 17 and macOS 15. This enables the use of modern APIs which improve code and work significantly. [Nextcloud Notes](http://github.com/nextcloud/notes-ios) is the first app to adopt this and already requires iOS 17 by itself. macOS support is not planned officially but maintained as much as possible to keep the door open. +- **Built for the future**. The minimum requirement is iOS 17. This enables the use of modern APIs which improve code and work significantly. [Nextcloud Notes](http://github.com/nextcloud/notes-ios) is the first app to adopt this and already requires iOS 17 by itself. - **SwiftLint**. SwiftLint is used as a build tool plugin to enforce certain code style and quality. - **Unit tests**. Existing projects did lack test coverage so these are considered where possible. - **Separation of concerns**. This is a user interface package. Business logic such as account persistence and post-login bootstrap is left to consumers through closures. The shared Login Flow v2 (server status, login flow request and polling) is provided here on top of [NextcloudKit](https://github.com/nextcloud/nextcloudkit) so every app shares one implementation. @@ -26,8 +26,11 @@ Key traits of this package: ### Login +Apps with branding, managed configuration or their own certificate handling pass a ``LoginFlowConfiguration`` to ``ServerAddressView``. The view stays busy until the ``AddAccountHandler`` returns and shows the error it throws. With ``LoginFlowConfiguration/providerSignUp`` and ``LoginFlowConfiguration/hostingInformation`` it also offers to sign up with a provider and to read about hosting a server. + - ``ServerAddressView`` - ``AddAccountHandler`` +- ``LoginFlowConfiguration`` ### Account Menu diff --git a/Sources/NextcloudKitUI/Features/LoginPollingPolicy.swift b/Sources/NextcloudKitUI/Features/LoginPollingPolicy.swift new file mode 100644 index 00000000..459b9dcd --- /dev/null +++ b/Sources/NextcloudKitUI/Features/LoginPollingPolicy.swift @@ -0,0 +1,22 @@ +// SPDX-FileCopyrightText: Nextcloud GmbH +// SPDX-FileCopyrightText: 2026 Milen Pivchev +// SPDX-License-Identifier: GPL-3.0-or-later + +import NextcloudKit + +/// +/// Decides whether a failed login flow poll keeps the flow alive. +/// +enum LoginPollingPolicy { + /// + /// Network blips while the user is in the browser, e.g. after switching apps for a second factor, should not end the login. + /// + static func isTransient(_ error: NKError) -> Bool { + switch error.kind { + case .offline, .timeout, .serverUnreachable, .unavailable, .rateLimited, .cancelled: + true + default: + false + } + } +} diff --git a/Sources/NextcloudKitUI/Features/QRCodeParsing.swift b/Sources/NextcloudKitUI/Features/QRCodeParsing.swift index 0399f7ec..a1395371 100644 --- a/Sources/NextcloudKitUI/Features/QRCodeParsing.swift +++ b/Sources/NextcloudKitUI/Features/QRCodeParsing.swift @@ -5,20 +5,33 @@ import Foundation /// -/// Errors specific to the parsing of Nextcloud login QR codes. +/// Errors specific to the parsing of Nextcloud login codes, as in QR codes or login callback URLs. /// -enum QRCodeError: Error { +enum QRCodeError: Error, LocalizedError { case implausibleLength case invalidPrefix case missingHost case missingPassword case missingUser + + var errorDescription: String? { + switch self { + case .implausibleLength, .invalidPrefix: + String(localized: "This is not a valid login code.", bundle: .module, comment: "Error message when a scanned QR code is not a Nextcloud login code.") + case .missingHost: + String(localized: "The login code is missing the server address.", bundle: .module, comment: "Error message when a login QR code has no server address.") + case .missingPassword: + String(localized: "The login code is missing the password.", bundle: .module, comment: "Error message when a login QR code has no password.") + case .missingUser: + String(localized: "The login code is missing the user name.", bundle: .module, comment: "Error message when a login QR code has no user name.") + } + } } /// -/// Credentials parsed from a login QR code, tagged with which login variant they represent. +/// Credentials parsed from a login code, tagged with which login variant they represent. /// -struct ParsedLoginCredentials { +struct LoginCredentials { /// /// Whether the password is a ready-to-use app password (`login`) or a onetime token that /// still has to be exchanged for an app password (`onetimeLogin`). @@ -41,32 +54,18 @@ struct ParsedLoginCredentials { /// /// Logic for parsing the atomic data values from a composite string as provided through a QR code for logging in. /// -protocol QRCodeParsing { - /// - /// Extract individual bits from a composite string as in an QR code for logging in. - /// - /// - Parameters: - /// - code: The raw string which is attained from a scanned QR code. - /// - /// - Returns: A tuple consisting of the user name, app password and server address in this exact order. - /// - func parse(_ code: String) throws -> (user: String, password: String, host: URL) -} +protocol QRCodeParsing {} extension QRCodeParsing { - func parse(_ code: String) throws -> (user: String, password: String, host: URL) { - try decomposeLoginCode(code, prefix: "nc://login/") - } - /// - /// Parse a login QR code into ``ParsedLoginCredentials``, distinguishing direct logins - /// (`nc://login/…`) from onetime logins (`nc://onetime-login/…`). + /// Parse a login QR code into ``LoginCredentials``, distinguishing direct logins + /// (`://login/…`) from onetime logins (`://onetime-login/…`). /// - func parseLogin(_ code: String) throws -> ParsedLoginCredentials { - let onetimePrefix = "nc://onetime-login/" - let loginPrefix = "nc://login/" + func parseLogin(_ code: String, scheme: String = "nc") throws -> LoginCredentials { + let onetimePrefix = "\(scheme)://onetime-login/" + let loginPrefix = "\(scheme)://login/" - let kind: ParsedLoginCredentials.Kind + let kind: LoginCredentials.Kind let prefix: String if code.hasPrefix(onetimePrefix) { @@ -80,14 +79,27 @@ extension QRCodeParsing { } let (user, password, host) = try decomposeLoginCode(code, prefix: prefix) - return ParsedLoginCredentials(kind: kind, user: user, password: password, host: host) + + return LoginCredentials(kind: kind, user: user, password: password, host: host) + } + + /// + /// Parse the `://login/…` URL a server or sign-up provider redirects to after a successful login. + /// + func parseLoginCallback(_ url: URL, scheme: String = "nc") throws -> LoginCredentials { + let (user, password, host) = try decomposeLoginCode(url.absoluteString, prefix: "\(scheme)://login/", decodingValues: true) + + return LoginCredentials(kind: .login, user: user, password: password, host: host) } } /// -/// Decompose a `user:…&password:…&server:…` login code into its values. +/// Decompose a `user:…&password:…&server:…` login code into its values, in any order. +/// +/// - Parameters: +/// - decodingValues: Whether values are percent-decoded and `+` in the user name means a space, as in the URL the server redirects to after a login. /// -private func decomposeLoginCode(_ code: String, prefix loginCodePrefix: String) throws -> (user: String, password: String, host: URL) { +private func decomposeLoginCode(_ code: String, prefix loginCodePrefix: String, decodingValues: Bool = false) throws -> (user: String, password: String, host: URL) { guard code.count > loginCodePrefix.count else { throw QRCodeError.implausibleLength } @@ -108,11 +120,7 @@ private func decomposeLoginCode(_ code: String, prefix loginCodePrefix: String) throw QRCodeError.missingHost } - guard let prefixRange = code.range(of: loginCodePrefix) else { - throw QRCodeError.invalidPrefix - } - - let compositeKeyValuePairs = code[prefixRange.upperBound...].components(separatedBy: "&") + let compositeKeyValuePairs = code.dropFirst(loginCodePrefix.count).components(separatedBy: "&") var decomposedKeyValuePairs = [String: String]() compositeKeyValuePairs.forEach { compositeKeyValuePair in @@ -122,7 +130,18 @@ private func decomposeLoginCode(_ code: String, prefix loginCodePrefix: String) return } - decomposedKeyValuePairs[String(parts[0])] = String(parts[1]) + let key = String(parts[0]) + var value = String(parts[1]) + + if decodingValues { + if key == "user" { + value = value.replacingOccurrences(of: "+", with: " ") + } + + value = value.removingPercentEncoding ?? value + } + + decomposedKeyValuePairs[key] = value } guard let user = decomposedKeyValuePairs["user"] else { @@ -133,7 +152,7 @@ private func decomposeLoginCode(_ code: String, prefix loginCodePrefix: String) throw QRCodeError.missingPassword } - guard let hostString = decomposedKeyValuePairs["server"], let host = URL(string: hostString) else { + guard let hostString = decomposedKeyValuePairs["server"], let host = URL(string: hostString), host.host != nil else { throw QRCodeError.missingHost } diff --git a/Sources/NextcloudKitUI/Features/URLSanitizing.swift b/Sources/NextcloudKitUI/Features/URLSanitizing.swift index aa0c31f1..55f5262d 100644 --- a/Sources/NextcloudKitUI/Features/URLSanitizing.swift +++ b/Sources/NextcloudKitUI/Features/URLSanitizing.swift @@ -7,51 +7,52 @@ import Foundation /// /// Turn user input of a server address into a sanitized URL. /// -/// - Returns: If `input` is a valid URL, then the sanitized `URL` and otherwise `nil`. -/// -protocol URLSanitizing { - func sanitize(_ input: String) -> URL? -} +protocol URLSanitizing {} extension URLSanitizing { - func sanitize(_ input: String) -> URL? { - guard input.isEmpty == false else { - return nil + /// + /// - Parameters: + /// - input: The server address as typed, with or without scheme, port, path or a trailing `index.php`. + /// - upgradingInsecureHTTP: Whether an explicit `http` scheme is replaced with `https`. + /// + /// - Returns: If `input` is a valid HTTP(S) address, then the sanitized `URL` ending in `/` and otherwise `nil`. + /// + func sanitize(_ input: String, upgradingInsecureHTTP: Bool = false) -> URL? { + var address = input.trimmingCharacters(in: .whitespacesAndNewlines) + + // Repair a scheme typed with fewer than two slashes, such as "https:/host". + if let range = address.range(of: #"^https?:/?(?!/)"#, options: [.regularExpression, .caseInsensitive]) { + let scheme = address[range].prefix { $0 != ":" } + address.replaceSubrange(range, with: "\(scheme)://") } - guard var components = URLComponents(string: input) else { - return nil + // Without a scheme, URLComponents reads "host" as a path and "host:8080" as a scheme. + if address.hasPrefix("//") { + address = "https:\(address)" + } else if address.contains("://") == false { + address = "https://\(address)" } - // Ensure HTTP(S) is used. - if let givenScheme = components.scheme { - if ["http", "https"].contains(givenScheme) == false { - return nil - } - } else { - components.scheme = "https" + guard var components = URLComponents(string: address), + let scheme = components.scheme?.lowercased(), + ["http", "https"].contains(scheme), + let host = components.host, + host.isEmpty == false else { + return nil } - if components.path.isEmpty { - components.path = "/" - } else { - // Drop last path component, if it is a PHP script. - let pathComponents = components.path.split(separator: "/") + components.scheme = upgradingInsecureHTTP ? "https" : scheme + components.query = nil + components.fragment = nil - if let lastPathComponent = pathComponents.last, lastPathComponent == "index.php" { - components.path = pathComponents.dropLast().joined(separator: "/") - } + var pathComponents = components.path.split(separator: "/") - // Add trailing slash, if missing. - if components.path.hasSuffix("/") == false { - components.path = "\(components.path)/" - } + if pathComponents.last == "index.php" { + pathComponents.removeLast() } - guard let url = components.url else { - return nil - } + components.path = "/" + pathComponents.map { "\($0)/" }.joined() - return url + return components.url } } diff --git a/Sources/NextcloudKitUI/Image+appIcon.swift b/Sources/NextcloudKitUI/Image+appIcon.swift index 2a49befc..95e68053 100644 --- a/Sources/NextcloudKitUI/Image+appIcon.swift +++ b/Sources/NextcloudKitUI/Image+appIcon.swift @@ -9,15 +9,11 @@ extension Image { /// The app's own icon, loaded from the largest icon file the build lists in the Info.plist. /// public static var appIcon: Image? { - #if canImport(UIKit) let icons = Bundle.main.object(forInfoDictionaryKey: "CFBundleIcons") as? [String: Any] let primaryIcon = icons?["CFBundlePrimaryIcon"] as? [String: Any] guard let name = (primaryIcon?["CFBundleIconFiles"] as? [String])?.last, let image = UIImage(named: name) else { return nil } return Image(uiImage: image) - #else - return nil - #endif } } diff --git a/Sources/NextcloudKitUI/Localizable.xcstrings b/Sources/NextcloudKitUI/Localizable.xcstrings index 8e2d7d6d..159a6562 100644 --- a/Sources/NextcloudKitUI/Localizable.xcstrings +++ b/Sources/NextcloudKitUI/Localizable.xcstrings @@ -1794,8 +1794,11 @@ } } }, + "Camera access is required to scan QR codes. Allow it in Settings." : { + "comment" : "Error message when the app may not use the camera to scan a login QR code." + }, "Cancel" : { - "comment" : "Button that dismisses a confirmation dialog without making changes.", + "comment" : "Button label", "localizations" : { "af" : { "stringUnit" : { @@ -6063,6 +6066,9 @@ } } }, + "Flashlight" : { + "comment" : "Accessibility label of the button which toggles the flashlight while scanning a QR code." + }, "For people who already have access" : { "comment" : "Subtitle explaining that an internal link works only for people who already have access.", "localizations" : { @@ -7114,6 +7120,15 @@ } } }, + "Log in" : { + "comment" : "Accessibility label of the button which starts the login." + }, + "Log in with QR code" : { + "comment" : "Button label which opens the QR code scanner in the login view." + }, + "Logging in to this server is not allowed." : { + "comment" : "Login error message when a QR code or sign-up points to a server other than the ones the app is limited to." + }, "Login Failed" : { "comment" : "Alert title", "localizations" : { @@ -7667,6 +7682,12 @@ } } }, + "Open Settings" : { + "comment" : "Button label in the login error alert which opens the system settings of the app." + }, + "or" : { + "comment" : "Separator between the server address field and the other ways to log in." + }, "Participants" : { "comment" : "Label above the permission selector in the unified share view.", "localizations" : { @@ -9487,7 +9508,7 @@ } }, "Scan QR Code" : { - "comment" : "Button label\nNavigation bar title", + "comment" : "Navigation bar title", "localizations" : { "da" : { "stringUnit" : { @@ -9599,6 +9620,9 @@ } } }, + "Select a server" : { + "comment" : "Label of the server picker in the login view before a server was picked." + }, "Send" : { "comment" : "Primary action button title in the unified share view.", "localizations" : { @@ -11613,6 +11637,9 @@ } } }, + "The camera is not available." : { + "comment" : "Error message when the camera cannot be used to scan a login QR code." + }, "The entered server address is invalid." : { "comment" : "This is an error message.", "localizations" : { @@ -11827,6 +11854,18 @@ } } }, + "The login code is missing the password." : { + "comment" : "Error message when a login QR code has no password." + }, + "The login code is missing the server address." : { + "comment" : "Error message when a login QR code has no server address." + }, + "The login code is missing the user name." : { + "comment" : "Error message when a login QR code has no user name." + }, + "The login timed out. Please try again." : { + "comment" : "Error message when the user did not finish the login in the browser in time." + }, "This change will replace the individual permission settings of all recipients in this share." : { "comment" : "Explanation shown before propagating top-level permission changes to every recipient.", "localizations" : { @@ -11934,6 +11973,9 @@ } } }, + "This is not a valid login code." : { + "comment" : "Error message when a scanned QR code is not a Nextcloud login code." + }, "This recipient will be removed from the share." : { "comment" : "Message of the recipient removal confirmation dialog.", "localizations" : { diff --git a/Sources/NextcloudKitUI/Models/SharedAccount.swift b/Sources/NextcloudKitUI/Models/SharedAccount.swift index 55813a87..28b90302 100644 --- a/Sources/NextcloudKitUI/Models/SharedAccount.swift +++ b/Sources/NextcloudKitUI/Models/SharedAccount.swift @@ -26,21 +26,28 @@ public struct SharedAccount: Identifiable, Sendable { public let host: URL /// - /// The login name of this shared account. + /// The name to display for this shared account. /// public let name: String + /// + /// The login name of this shared account, shown next to ``name`` when set. + /// + public let user: String? + /// /// Create a new instance. /// /// - Parameters: /// - name: See ``name``. + /// - user: See ``user``. /// - host: See ``host``. /// - image: See ``image``. /// - public init(_ name: String, on host: URL, with image: Image) { + public init(_ name: String, user: String? = nil, on host: URL, with image: Image) { self.id = UUID() self.name = name + self.user = user self.host = host self.image = image } diff --git a/Sources/NextcloudKitUI/Modifiers/CodeScannerSheet.swift b/Sources/NextcloudKitUI/Modifiers/CodeScannerSheet.swift index 6a767585..f886d99b 100644 --- a/Sources/NextcloudKitUI/Modifiers/CodeScannerSheet.swift +++ b/Sources/NextcloudKitUI/Modifiers/CodeScannerSheet.swift @@ -5,31 +5,70 @@ import CodeScanner import SwiftUI -#if os(iOS) - /// /// A sheet with a camera view to scan QR codes for logging in. -/// Includes toolbar configuration and its appearance. +/// It stays open and busy while a scanned code logs in, and closes on an error, which the login view shows. /// struct CodeScannerSheet: ViewModifier { - @Environment(\.dismiss) private var dismiss - - @Binding var isPresentingCodeScanner: Bool - let completionHandler: (Result) -> Void - - init(isPresented: Binding, _ completionHandler: @escaping (Result) -> Void) { - self._isPresentingCodeScanner = isPresented - self.completionHandler = completionHandler - } + let model: LoginFlowModel + @State private var isTorchOn = false func body(content: Content) -> some View { - content.sheet(isPresented: $isPresentingCodeScanner) { + @Bindable var model = model + + return content.sheet(isPresented: $model.isPresentingCodeScanner) { + model.codeScannerDidClose() + } content: { NavigationStack { - CodeScannerView(codeTypes: [.qr], scanMode: .once, showViewfinder: true, completion: completionHandler) + ZStack { + // One code per opening: an error closes the scanner. + CodeScannerView(codeTypes: [.qr], scanMode: .once, showViewfinder: true, isTorchOn: isTorchOn) { result in + model.handleQRCodeScan(result) + } + + if model.isActive { + Color.black.opacity(0.5) + + ProgressView() + .progressViewStyle(.circular) + .controlSize(.large) + .tint(.white) + .accessibilityIdentifier("codeScannerProgress") + } + } .ignoresSafeArea() .toolbarTitleDisplayMode(.inline) + // The camera cannot scroll, so no scroll edge effect keeps the title readable over it. + .toolbarBackground(.ultraThinMaterial, for: .navigationBar) + .toolbarBackground(.visible, for: .navigationBar) .navigationTitle(String(localized: "Scan QR Code", bundle: .module, comment: "Navigation bar title")) + .toolbar { + ToolbarItem(placement: .cancellationAction) { + Button { + model.isPresentingCodeScanner = false + } label: { + Text("Cancel", bundle: .module, comment: "Button label") + } + .disabled(model.isActive) + .accessibilityIdentifier("cancelCodeScanner") + } + + ToolbarItem(placement: .primaryAction) { + Button { + isTorchOn.toggle() + } label: { + Label { + Text("Flashlight", bundle: .module, comment: "Accessibility label of the button which toggles the flashlight while scanning a QR code.") + } icon: { + Image(systemName: isTorchOn ? "flashlight.on.fill" : "flashlight.off.fill") + } + } + .disabled(model.isActive) + .accessibilityIdentifier("toggleTorch") + } + } } + .interactiveDismissDisabled(model.isActive) } } } @@ -40,9 +79,7 @@ extension View { /// /// See ``CodeScannerSheet`` for its implementation. /// - func codeScannerSheet(isPresented: Binding, _ completionHandler: @escaping (Result) -> Void) -> some View { - modifier(CodeScannerSheet(isPresented: isPresented, completionHandler)) + func codeScannerSheet(model: LoginFlowModel) -> some View { + modifier(CodeScannerSheet(model: model)) } } - -#endif diff --git a/Sources/NextcloudKitUI/ViewRepresentable.swift b/Sources/NextcloudKitUI/ViewRepresentable.swift deleted file mode 100644 index 62709b5b..00000000 --- a/Sources/NextcloudKitUI/ViewRepresentable.swift +++ /dev/null @@ -1,14 +0,0 @@ -// SPDX-FileCopyrightText: Nextcloud GmbH -// SPDX-FileCopyrightText: 2025 Iva Horn -// SPDX-License-Identifier: GPL-3.0-or-later - -import SwiftUI - -/// -/// A multiplatform type alias for `NSViewRepresentable` and `UIViewRepresentable`. -/// -#if os(macOS) -typealias ViewRepresentable = NSViewRepresentable -#else -typealias ViewRepresentable = UIViewRepresentable -#endif diff --git a/Sources/NextcloudKitUI/Views/Login/LoginFlowConfiguration.swift b/Sources/NextcloudKitUI/Views/Login/LoginFlowConfiguration.swift new file mode 100644 index 00000000..6c7a8be4 --- /dev/null +++ b/Sources/NextcloudKitUI/Views/Login/LoginFlowConfiguration.swift @@ -0,0 +1,122 @@ +// SPDX-FileCopyrightText: Nextcloud GmbH +// SPDX-FileCopyrightText: 2026 Milen Pivchev +// SPDX-License-Identifier: GPL-3.0-or-later + +import NextcloudKit +import SwiftUI + +/// +/// Host app options for ``ServerAddressView``. The defaults reproduce the plain login screen. +/// +public struct LoginFlowConfiguration: Sendable { + /// + /// A server the user may pick instead of typing an address. + /// + public struct Server: Identifiable, Hashable, Sendable { + public let name: String + public let url: URL + + public var id: URL { + url + } + + public init(name: String, url: URL) { + self.name = name + self.url = url + } + } + + /// + /// A web page the login view offers below the server address. + /// + public struct WebLink: Sendable { + public let title: String + public let url: URL + + public init(title: String, url: URL) { + self.title = title + self.url = url + } + } + + /// + /// How the login flow continues after the server status check failed. + /// + public enum Recovery: Sendable { + /// Start over with this address, e.g. after trusting a certificate or falling back to `http`. + case retry(URL) + + /// End the login silently, e.g. when the user declined. + case cancel + + /// Show the error in the login view. + case presentError + } + + public typealias ServerErrorHandler = @MainActor @Sendable (_ error: NKError, _ serverURL: URL) async -> Recovery + public typealias CancelHandler = @MainActor @Sendable () -> Void + + /// + /// Text and tint color on top of the background. Derived from the background color when `nil`. + /// + public var foregroundColor: Color? + + /// + /// Replaces the placeholder of the server address field. + /// + public var serverAddressPrompt: String? + + /// + /// Replaces the hint below the server address field. + /// + public var serverAddressDescription: String? + + /// + /// Replaces the label of the server picker shown for ``enforcedServers`` until one is picked. + /// + public var enforcedServersPrompt: String? + + /// + /// Prefills the server address field. + /// + public var initialServerAddress: String? + + public var isServerAddressEditable = true + + /// + /// When not empty, a picker over these servers replaces the server address field, and QR codes, sign-ups and shared accounts for other hosts are refused. + /// + public var enforcedServers: [Server] = [] + + /// + /// A provider's sign-up page, which must end on the login callback URL with ``loginURLScheme``. + /// + public var providerSignUp: WebLink? + + /// + /// Information about hosting a server, opened in the browser. + /// + public var hostingInformation: WebLink? + + /// + /// Whether an explicit `http` scheme typed by the user is replaced with `https`. + /// + public var upgradesInsecureHTTP = false + + /// + /// The scheme of login QR codes and of the URL the login page redirects to, without `://`. + /// + public var loginURLScheme = "nc" + + /// + /// Shows a cancel button, which ends the login and then calls this. The host dismisses the view. + /// + public var onCancel: CancelHandler? + + /// + /// Lets the host resolve a failed server check, e.g. with its own certificate trust prompt. Without it, the error is shown. + /// + public var onServerError: ServerErrorHandler? + + public init() {} +} diff --git a/Sources/NextcloudKitUI/Views/Login/LoginFlowModel.swift b/Sources/NextcloudKitUI/Views/Login/LoginFlowModel.swift index 4550536b..1d59fccb 100644 --- a/Sources/NextcloudKitUI/Views/Login/LoginFlowModel.swift +++ b/Sources/NextcloudKitUI/Views/Login/LoginFlowModel.swift @@ -3,9 +3,8 @@ // SPDX-License-Identifier: GPL-3.0-or-later import AuthenticationServices -#if os(iOS) +import AVFoundation import CodeScanner -#endif import NextcloudKit import SwiftUI @@ -20,34 +19,52 @@ import SwiftUI @Observable final class LoginFlowModel: QRCodeParsing, URLSanitizing { private let userAgent: String? + private let configuration: LoginFlowConfiguration private let addAccount: AddAccountHandler - init(userAgent: String?, addAccount: @escaping AddAccountHandler) { + init(userAgent: String?, configuration: LoginFlowConfiguration = LoginFlowConfiguration(), addAccount: @escaping AddAccountHandler) { self.userAgent = userAgent + self.configuration = configuration self.addAccount = addAccount + self.enteredServerAddress = configuration.initialServerAddress ?? "" } // MARK: - State observed by the view /// The unsanitized user input. - var enteredServerAddress = "" + var enteredServerAddress: String /// Message to display in case of error. var errorMessage: String? + /// Whether the error alert offers to open the system settings. + var alertOffersSettings = false + /// Whether an activity currently requires disabling the user interface. var isActive = false + /// Whether the account is being added, after which the login can no longer be cancelled. + var isAddingAccount = false + /// State toggle for presenting the error alert. var isPresentingAlert = false /// State toggle for presenting the login page in the system browser. var isPresentingLoginPage = false + /// State toggle for presenting the QR code scanner, which stays open while a scanned code logs in. + var isPresentingCodeScanner = false + + /// An error of the QR code scanner, shown by the login view once the scanner has closed. + private var codeScannerError: (message: String?, offersSettings: Bool)? + /// The login address acquired from the server through the login flow API. var loginAddress: URL? - private var pollingTask: Task? + private var loginTask: Task? + + /// Matches the lifetime of a login flow token on the server. + private static let pollingTimeout: Duration = .seconds(20 * 60) // MARK: - Login flow @@ -55,15 +72,16 @@ final class LoginFlowModel: QRCodeParsing, URLSanitizing { /// Sanitize the entered server address and start the login flow. /// func logIn() { - guard enteredServerAddress.trimmingCharacters(in: .whitespaces).isEmpty == false else { + guard enteredServerAddress.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty == false else { return } - guard let sanitizedServerAddress = sanitize(enteredServerAddress) else { + guard let sanitizedServerAddress = sanitize(enteredServerAddress, upgradingInsecureHTTP: configuration.upgradesInsecureHTTP) else { present(error: String(localized: "The entered server address is invalid.", bundle: .module, comment: "This is an error message.")) return } + enteredServerAddress = sanitizedServerAddress.absoluteString start(serverURL: sanitizedServerAddress) } @@ -71,63 +89,103 @@ final class LoginFlowModel: QRCodeParsing, URLSanitizing { /// Check the server, request the login flow, present its web page and begin polling. /// func start(serverURL: URL) { + loginTask?.cancel() isActive = true - Task { - do { - let options = NKRequestOptions(customUserAgent: userAgent) + loginTask = Task { + let options = NKRequestOptions(customUserAgent: userAgent) + + let (_, statusResult) = await NextcloudKit.shared.getServerStatusAsync(serverUrl: serverURL.absoluteString, options: options) - let (_, statusResult) = await NextcloudKit.shared.getServerStatusAsync(serverUrl: serverURL.absoluteString, options: options) + guard Task.isCancelled == false else { return } - if case .failure(let error) = statusResult { - throw error - } + if case .failure(let error) = statusResult { + await recover(from: error, serverURL: serverURL) + return + } + do { let (endpoint, login, token) = try await NextcloudKit.shared.getLoginFlowV2(serverUrl: serverURL.absoluteString, options: options) - startPolling(token: token, endpoint: endpoint) + guard Task.isCancelled == false else { return } loginAddress = login isPresentingLoginPage = true + + await poll(token: token, endpoint: endpoint, options: options) } catch { + guard Task.isCancelled == false else { return } + endLogin(error) } } } - private func startPolling(token: String, endpoint: URL) { - pollingTask?.cancel() + private func recover(from error: NKError, serverURL: URL) async { + nkLog(error: "Login server check failed: \(error.logDescription)") - pollingTask = Task { [weak self] in - guard let self else { return } + let recovery = await configuration.onServerError?(error, serverURL) ?? .presentError - let options = NKRequestOptions(customUserAgent: self.userAgent) + // The user may have cancelled while the host was asking how to recover. + guard Task.isCancelled == false else { return } - while Task.isCancelled == false { - let poll = await NextcloudKit.shared.getLoginFlowV2PollAsync(token: token, endpoint: endpoint.absoluteString, options: options) + switch recovery { + case .retry(let url): + enteredServerAddress = url.absoluteString + start(serverURL: url) + case .cancel: + cancel() + case .presentError: + endLogin(error) + } + } + + private func poll(token: String, endpoint: URL, options: NKRequestOptions) async { + let deadline = ContinuousClock.now + Self.pollingTimeout + + while Task.isCancelled == false { + guard ContinuousClock.now < deadline else { + cancel() + present(error: String(localized: "The login timed out. Please try again.", bundle: .module, comment: "Error message when the user did not finish the login in the browser in time.")) + return + } - if poll.error == .success, - let server = poll.server, let host = URL(string: server), - let loginName = poll.loginName, - let appPassword = poll.appPassword { - self.complete(host: host, name: loginName, password: appPassword) - return - } + let result = await NextcloudKit.shared.getLoginFlowV2PollAsync(token: token, endpoint: endpoint.absoluteString, options: options) - // HTTP 404 means the flow is still pending; any other failure is terminal. - if poll.error != .success, poll.responseData?.response?.statusCode != 404 { - self.endLogin(poll.error) - return - } + guard Task.isCancelled == false else { return } - try? await Task.sleep(for: .seconds(1)) + if result.error == .success, + let server = result.server, let host = URL(string: server), + let loginName = result.loginName, + let appPassword = result.appPassword { + complete(host: host, name: loginName, password: appPassword) + return } + + // HTTP 404 means the flow is still pending, as do network blips while the user is in the browser. + let isPending = result.error == .success || result.responseData?.response?.statusCode == 404 || LoginPollingPolicy.isTransient(result.error) + + if isPending == false { + endLogin(result.error) + return + } + + try? await Task.sleep(for: .seconds(1)) } } func presentLoginPage(_ url: URL, using session: WebAuthenticationSession) async { do { - _ = try await session.authenticate(using: url, callbackURLScheme: "nc", preferredBrowserSession: .ephemeral) + let callbackURL = try await session.authenticate(using: url, callbackURLScheme: configuration.loginURLScheme, preferredBrowserSession: .ephemeral) + + // A login page that redirects to the callback URL hands over the credentials directly. Otherwise polling continues. + guard isPresentingLoginPage, + let credentials = try? parseLoginCallback(callbackURL, scheme: configuration.loginURLScheme) else { + return + } + + loginTask?.cancel() + complete(host: credentials.host, name: credentials.user, password: credentials.password) } catch { // Already handled when the login completed or was cancelled. guard isPresentingLoginPage else { return } @@ -140,19 +198,46 @@ final class LoginFlowModel: QRCodeParsing, URLSanitizing { } } - private func complete(host: URL, name: String, password: String) { - pollingTask = nil - isActive = false + /// + /// Hand the credentials to the host. The view stays busy until the host has added the account. + /// + /// - Parameter restartsLoginIfUnauthorized: Start the login for the server when it refuses the credentials. + /// + private func complete(host: URL, name: String, password: String, restartsLoginIfUnauthorized: Bool = false) { + loginTask = nil isPresentingLoginPage = false - addAccount(host, name, password) + isActive = true + isAddingAccount = true + + // Not a child of the login or presentation task, which end when the login page closes. + Task { + do { + try await addAccount(host, name, password) + isPresentingCodeScanner = false + } catch let error as NKError where restartsLoginIfUnauthorized && error.kind == .unauthorized { + nkLog(error: "The server refused the credentials, starting the login: \(error.logDescription)") + + isAddingAccount = false + isActive = false + enteredServerAddress = host.absoluteString + logIn() + return + } catch { + nkLog(error: "Adding the account failed: \(error)") + present(error: (error as? NKError).map { message(for: $0, whileAddingAccount: true) } ?? error.localizedDescription) + } + + isAddingAccount = false + isActive = false + } } /// - /// Stop polling. Called when the login page is closed, regardless of the reason. + /// Stop the login. Called when the login page is closed, regardless of the reason. /// func cancel() { - pollingTask?.cancel() - pollingTask = nil + loginTask?.cancel() + loginTask = nil isActive = false isPresentingLoginPage = false } @@ -170,9 +255,10 @@ final class LoginFlowModel: QRCodeParsing, URLSanitizing { /// /// A 404 or an unreadable response during login means there is no Nextcloud instance at the entered address. + /// While adding the account an unreadable response can come from a proxy in front of the server, so only a 404 counts. /// - private func message(for error: NKError) -> String { - let isInstanceNotFound = error.kind == .notFound || error.kind == .invalidResponse + private func message(for error: NKError, whileAddingAccount: Bool = false) -> String { + let isInstanceNotFound = error.kind == .notFound || (error.kind == .invalidResponse && !whileAddingAccount) if isInstanceNotFound { return String(localized: "No server was found at this address.", bundle: .module, comment: "Login error message when the entered address does not point to a Nextcloud server.") @@ -181,31 +267,84 @@ final class LoginFlowModel: QRCodeParsing, URLSanitizing { return error.localizedGenericMessage } - private func present(error: String?) { + private func present(error: String?, offersSettings: Bool = false) { + // The scanner closes first; the user opens it again to scan another code. + if isPresentingCodeScanner { + codeScannerError = (error, offersSettings) + isPresentingCodeScanner = false + return + } + errorMessage = error + alertOffersSettings = offersSettings isPresentingAlert = true } // MARK: - QR code - #if os(iOS) + func presentCodeScanner() { + codeScannerError = nil + + #if !targetEnvironment(simulator) + // The scanner reports neither of these, and a denial only while it is still sliding in. + switch AVCaptureDevice.authorizationStatus(for: .video) { + case .denied, .restricted: + present(error: Self.cameraAccessMessage, offersSettings: true) + return + default: + break + } + + guard AVCaptureDevice.default(for: .video) != nil else { + present(error: Self.cameraUnavailableMessage) + return + } + #endif + + isPresentingCodeScanner = true + } + + /// + /// Show the error the scanner closed with. + /// + func codeScannerDidClose() { + guard let codeScannerError else { return } + + self.codeScannerError = nil + present(error: codeScannerError.message, offersSettings: codeScannerError.offersSettings) + } + func handleQRCodeScan(_ result: Result) { switch result { case .success(let result): handleLoginCode(result.string) - case .failure(let error): - present(error: error.localizedDescription) + case .failure(.permissionDenied): + present(error: Self.cameraAccessMessage, offersSettings: true) + case .failure: + present(error: Self.cameraUnavailableMessage) } } - #endif + + private static var cameraAccessMessage: String { + String(localized: "Camera access is required to scan QR codes. Allow it in Settings.", bundle: .module, comment: "Error message when the app may not use the camera to scan a login QR code.") + } + + private static var cameraUnavailableMessage: String { + String(localized: "The camera is not available.", bundle: .module, comment: "Error message when the camera cannot be used to scan a login QR code.") + } func handleLoginCode(_ code: String) { do { - let credentials = try parseLogin(code) + let credentials = try parseLogin(code, scheme: configuration.loginURLScheme) + + guard isAllowed(credentials.host) else { + present(error: Self.serverNotAllowedMessage) + return + } switch credentials.kind { case .login: - addAccount(credentials.host, credentials.user, credentials.password) + complete(host: credentials.host, name: credentials.user, password: credentials.password) case .onetimeLogin: exchangeOnetimeToken(credentials) } @@ -214,23 +353,82 @@ final class LoginFlowModel: QRCodeParsing, URLSanitizing { } } - private func exchangeOnetimeToken(_ credentials: ParsedLoginCredentials) { + private func exchangeOnetimeToken(_ credentials: LoginCredentials) { isActive = true + isAddingAccount = true Task { let result = await NextcloudKit.shared.getAppPasswordOnetimeAsync(url: credentials.host.absoluteString, user: credentials.user, onetimeToken: credentials.password, userAgent: userAgent) - isActive = false - if result.error == .success, let token = result.token { - addAccount(credentials.host, credentials.user, token) + complete(host: credentials.host, name: credentials.user, password: token) } else { + isAddingAccount = false + isActive = false nkLog(error: "One-time login failed: \(result.error.logDescription)") present(error: message(for: result.error)) } } } + // MARK: - Provider sign-up + + /// The provider sign-up page while it is open. + var providerSignUp: ProviderSignUpModel? + + /// The login callback URL the sign-up ended on, handled once its page has closed. + private var providerSignUpCallbackURL: URL? + + func presentProviderSignUp(_ url: URL) { + providerSignUpCallbackURL = nil + providerSignUp = ProviderSignUpModel(url: url, callbackScheme: configuration.loginURLScheme, userAgent: userAgent) { [weak self] callbackURL in + self?.finishProviderSignUp(callbackURL: callbackURL) + } + } + + func finishProviderSignUp(callbackURL: URL) { + providerSignUpCallbackURL = callbackURL + providerSignUp = nil + } + + /// + /// Add the account the sign-up ended on, once its page has closed. + /// + func providerSignUpDidClose() { + guard let callbackURL = providerSignUpCallbackURL else { return } + + providerSignUpCallbackURL = nil + + do { + let credentials = try parseLoginCallback(callbackURL, scheme: configuration.loginURLScheme) + + guard isAllowed(credentials.host) else { + present(error: Self.serverNotAllowedMessage) + return + } + + // Providers may hand over a session token, which servers refuse, so the user logs in to the new account instead. + complete(host: credentials.host, name: credentials.user, password: credentials.password, restartsLoginIfUnauthorized: true) + } catch { + present(error: error.localizedDescription) + } + } + + // MARK: - Enforced servers + + private static var serverNotAllowedMessage: String { + String(localized: "Logging in to this server is not allowed.", bundle: .module, comment: "Login error message when a QR code or sign-up points to a server other than the ones the app is limited to.") + } + + /// + /// Whether the app may log in to this server: any server, unless ``LoginFlowConfiguration/enforcedServers`` limits it to their hosts. + /// + func isAllowed(_ server: URL) -> Bool { + guard configuration.enforcedServers.isEmpty == false else { return true } + + return configuration.enforcedServers.contains { $0.url.host?.lowercased() == server.host?.lowercased() } + } + // MARK: - Shared accounts func selectSharedAccount(_ account: SharedAccount) { diff --git a/Sources/NextcloudKitUI/Views/Login/ProviderSignUpModel.swift b/Sources/NextcloudKitUI/Views/Login/ProviderSignUpModel.swift new file mode 100644 index 00000000..16bed31a --- /dev/null +++ b/Sources/NextcloudKitUI/Views/Login/ProviderSignUpModel.swift @@ -0,0 +1,276 @@ +// SPDX-FileCopyrightText: Nextcloud GmbH +// SPDX-FileCopyrightText: 2026 Milen Pivchev +// SPDX-License-Identifier: GPL-3.0-or-later + +import NextcloudKit +import SwiftUI +import UIKit +@preconcurrency import WebKit + +/// +/// Loads the sign-up page of a provider and reports the login callback URL the sign-up ends on. +/// +/// A web view instead of a browser session, because the sign-up page only hands over credentials to page loads with the OCS API header. +/// +@MainActor +@Observable +final class ProviderSignUpModel: NSObject, Identifiable, WKNavigationDelegate { + /// + /// What happens to a page load the web view is about to start. + /// + enum Policy: Equatable { + case allow + case cancel + + /// The sign-up ended on the login callback URL. + case finish(URL) + + /// The page load starts again with this request, which has the OCS API header. + case reissue(URLRequest) + + /// A link the web view cannot show, such as `mailto:`, opens in its app. + case openExternally(URL) + } + + /// Schemes the web view shows itself. + private static let webSchemes: Set = ["http", "https", "about", "data", "blob"] + + static let apiHeader = "OCS-APIRequest" + + let url: URL + let webView: WKWebView + + /// Whether the web view is loading a page. + private(set) var isLoading = false + + /// Why the page did not load. Shown instead of the page. + private(set) var errorMessage: String? + + /// The color the page asks for, as Safari colors its bar: its theme color, otherwise its background. + private(set) var pageColor: Color? + + @ObservationIgnored private let callbackScheme: String + @ObservationIgnored private let onCallback: @MainActor (URL) -> Void + @ObservationIgnored private var observations: [NSKeyValueObservation] = [] + @ObservationIgnored private var reissuedURLs: Set = [] + @ObservationIgnored private var requestedURL: URL? + @ObservationIgnored private var hasStarted = false + @ObservationIgnored private var hasReloadedAfterTermination = false + @ObservationIgnored private var isFinished = false + + /// + /// - Parameters: + /// - url: The sign-up page. + /// - callbackScheme: The scheme of the login callback URL, without `://`. + /// - userAgent: An optional user agent for the page loads. + /// - onCallback: Called once with the login callback URL. + /// + init(url: URL, callbackScheme: String, userAgent: String?, onCallback: @escaping @MainActor (URL) -> Void) { + self.url = url + self.callbackScheme = callbackScheme.lowercased() + self.onCallback = onCallback + + let configuration = WKWebViewConfiguration() + configuration.websiteDataStore = .nonPersistent() + webView = WKWebView(frame: .zero, configuration: configuration) + + webView.customUserAgent = userAgent + + super.init() + + webView.navigationDelegate = self + + observations = [ + webView.observe(\.isLoading, options: [.initial, .new]) { [weak self] webView, _ in + MainActor.assumeIsolated { + self?.isLoading = webView.isLoading + } + }, + webView.observe(\.themeColor, options: [.new]) { [weak self] webView, _ in + MainActor.assumeIsolated { + self?.pageColor = Color(uiColor: webView.themeColor ?? webView.underPageBackgroundColor) + } + } + ] + } + + // MARK: - Loading + + /// + /// Load the sign-up page, once. + /// + func start() { + guard hasStarted == false else { return } + + hasStarted = true + webView.load(Self.request(for: Self.uncachedURL(url))) + } + + /// + /// Load the page that failed again, or the sign-up page when none was requested yet. + /// + func retry() { + errorMessage = nil + reissuedURLs.removeAll() + webView.load(Self.request(for: requestedURL ?? Self.uncachedURL(url))) + } + + /// + /// nextcloud.com serves its sign-up page from a cache that ignores the header, unless the address has a query. + /// + static func uncachedURL(_ url: URL) -> URL { + guard var components = URLComponents(url: url, resolvingAgainstBaseURL: false) else { return url } + + components.queryItems = (components.queryItems ?? []) + [URLQueryItem(name: "ocsapi", value: "1")] + + return components.url ?? url + } + + /// + /// Fails after 20 seconds without data instead of a minute, so an unreachable server is reported soon. + /// + static func request(for url: URL) -> URLRequest { + var request = URLRequest(url: url, timeoutInterval: 20) + request.setValue("true", forHTTPHeaderField: apiHeader) + + return request + } + + // MARK: - Decisions + + func policy(for request: URLRequest, isMainFrame: Bool) -> Policy { + guard let url = request.url, let scheme = url.scheme?.lowercased() else { return .cancel } + + if scheme == callbackScheme { + return .finish(url) + } + + guard Self.webSchemes.contains(scheme) else { + return isMainFrame ? .openExternally(url) : .cancel + } + + if isMainFrame, request.httpMethod == "GET" { + // Redirects and links lose the header, so such page loads are started again with it, once per page. + if request.value(forHTTPHeaderField: Self.apiHeader) == nil, reissuedURLs.insert(url).inserted { + return .reissue(Self.request(for: url)) + } + + requestedURL = url + } + + return .allow + } + + /// + /// Error pages and empty responses would otherwise load as if nothing went wrong. + /// + /// - Returns: Why the page must not be shown, or `nil` to show it. + /// + static func error(for response: URLResponse, canShowMIMEType: Bool) -> NKError? { + if let response = response as? HTTPURLResponse, response.statusCode >= 400 { + return error(forStatusCode: response.statusCode) + } + + if canShowMIMEType == false || response.expectedContentLength == 0 { + return .invalidResponseError + } + + return nil + } + + /// + /// Picks a kind whose NextcloudKit text fits a web page, unlike the file-related ones for 403 or 404. + /// + static func error(forStatusCode statusCode: Int) -> NKError { + let kind: NKError.Kind + + switch statusCode { + case 408, 504: + kind = .timeout + case 429: + kind = .rateLimited + case 503: + kind = .unavailable + case 500, 501, 505...599: + kind = .serverError + default: + kind = .serverUnreachable + } + + return NKError(errorCode: statusCode, errorDescription: HTTPURLResponse.localizedString(forStatusCode: statusCode), kind: kind) + } + + func showLoadError(_ error: Error) { + // Page loads this model replaces end as interrupted or cancelled. + let nsError = error as NSError + let isInterrupted = nsError.domain == "WebKitErrorDomain" && nsError.code == 102 + let nkError = error as? NKError ?? NKError(error: error) + + guard isFinished == false, isInterrupted == false, nkError.kind != .cancelled else { return } + + errorMessage = nkError.localizedGenericMessage + } + + private func finish(callbackURL: URL) { + guard isFinished == false else { return } + + isFinished = true + onCallback(callbackURL) + } + + // MARK: - WKNavigationDelegate + + func webView(_ webView: WKWebView, decidePolicyFor navigationAction: WKNavigationAction, decisionHandler: @escaping (WKNavigationActionPolicy) -> Void) { + switch policy(for: navigationAction.request, isMainFrame: navigationAction.targetFrame?.isMainFrame == true) { + case .allow: + decisionHandler(.allow) + case .cancel: + decisionHandler(.cancel) + case .finish(let callbackURL): + decisionHandler(.cancel) + finish(callbackURL: callbackURL) + case .reissue(let request): + decisionHandler(.cancel) + webView.load(request) + case .openExternally(let url): + decisionHandler(.cancel) + UIApplication.shared.open(url) + } + } + + func webView(_ webView: WKWebView, decidePolicyFor navigationResponse: WKNavigationResponse, decisionHandler: @escaping (WKNavigationResponsePolicy) -> Void) { + guard navigationResponse.isForMainFrame, + let error = Self.error(for: navigationResponse.response, canShowMIMEType: navigationResponse.canShowMIMEType) else { + decisionHandler(.allow) + return + } + + decisionHandler(.cancel) + showLoadError(error) + } + + func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!) { + pageColor = Color(uiColor: webView.themeColor ?? webView.underPageBackgroundColor) + reissuedURLs.removeAll() + hasReloadedAfterTermination = false + } + + func webView(_ webView: WKWebView, didFailProvisionalNavigation navigation: WKNavigation!, withError error: Error) { + showLoadError(error) + } + + func webView(_ webView: WKWebView, didFail navigation: WKNavigation!, withError error: Error) { + showLoadError(error) + } + + func webViewWebContentProcessDidTerminate(_ webView: WKWebView) { + // WebKit stops reloading by itself once the delegate handles this, so reload once and report a repeat. + guard hasReloadedAfterTermination else { + hasReloadedAfterTermination = true + retry() + return + } + + showLoadError(NKError(errorCode: WKError.Code.webContentProcessTerminated.rawValue, errorDescription: "Web content process terminated", kind: .unknown)) + } +} diff --git a/Sources/NextcloudKitUI/Views/Login/ProviderSignUpView.swift b/Sources/NextcloudKitUI/Views/Login/ProviderSignUpView.swift new file mode 100644 index 00000000..b0fd3fe7 --- /dev/null +++ b/Sources/NextcloudKitUI/Views/Login/ProviderSignUpView.swift @@ -0,0 +1,61 @@ +// SPDX-FileCopyrightText: Nextcloud GmbH +// SPDX-FileCopyrightText: 2026 Milen Pivchev +// SPDX-License-Identifier: GPL-3.0-or-later + +import SwiftUI + +/// +/// The sign-up page of a provider. It closes by itself once the sign-up reached the login callback URL. +/// +struct ProviderSignUpView: View { + let model: ProviderSignUpModel + + @Environment(\.dismiss) private var dismiss + + var body: some View { + NavigationStack { + page + // Colored like the page, as in Safari, since the bar does not track the web view's scrolling. + .toolbarBackground(model.pageColor ?? Color(uiColor: .systemBackground), for: .navigationBar) + .toolbarBackground(.visible, for: .navigationBar) + .toolbarColorScheme(model.pageColor.map { $0.readable == .white ? .dark : .light }, for: .navigationBar) + } + .onAppear { + model.start() + } + } + + private var page: some View { + ZStack { + WebView(webView: model.webView) + .ignoresSafeArea(edges: .bottom) + + if let errorMessage = model.errorMessage { + ContentUnavailableView { + Label(errorMessage, systemImage: "exclamationmark.triangle") + } actions: { + Button(String(localized: "Retry", bundle: .module)) { + model.retry() + } + .accessibilityIdentifier("retryProviderSignUp") + } + .background(Color(uiColor: .systemBackground)) + } else if model.isLoading { + ProgressView() + .controlSize(.large) + } + } + .navigationTitle(model.url.host ?? "") + .navigationBarTitleDisplayMode(.inline) + .toolbar { + ToolbarItem(placement: .cancellationAction) { + Button { + dismiss() + } label: { + Text("Cancel", bundle: .module, comment: "Button label") + } + .accessibilityIdentifier("cancelProviderSignUp") + } + } + } +} diff --git a/Sources/NextcloudKitUI/Views/Login/ServerAddressView.swift b/Sources/NextcloudKitUI/Views/Login/ServerAddressView.swift index 3f1e3930..a5c8a646 100644 --- a/Sources/NextcloudKitUI/Views/Login/ServerAddressView.swift +++ b/Sources/NextcloudKitUI/Views/Login/ServerAddressView.swift @@ -1,5 +1,6 @@ // SPDX-FileCopyrightText: Nextcloud GmbH // SPDX-FileCopyrightText: 2025 Iva Horn +// SPDX-FileCopyrightText: 2026 Milen Pivchev // SPDX-License-Identifier: GPL-3.0-or-later import AuthenticationServices @@ -9,9 +10,10 @@ import SwiftUI /// A new remote user account should be added locally in the persistence of the app. /// /// This is called once the login flow (or a QR code scan) has produced credentials. The consumer -/// is responsible for persisting the account and any post-login bootstrap. +/// is responsible for persisting the account and any post-login bootstrap. The view stays busy +/// until this returns and shows a thrown error. /// -public typealias AddAccountHandler = (_ host: URL, _ name: String, _ password: String) -> Void +public typealias AddAccountHandler = @MainActor (_ host: URL, _ name: String, _ password: String) async throws -> Void /// /// The full screen view in which a user enters the address of the server to log in on. @@ -19,22 +21,27 @@ public typealias AddAccountHandler = (_ host: URL, _ name: String, _ password: S public struct ServerAddressView: View { let brandImage: Image var sharedAccounts: [SharedAccount] + let configuration: LoginFlowConfiguration /// /// Create a new server address view. /// /// - Parameters: /// - backgroundColor: The main theme color the view should use. Foreground color will be adapted automatically based on this. - /// - brandImage: The image to display on top of the server address view. Falls back to an SF Symbol placeholder in case of `nil`. + /// - brandImage: The image to display on top of the server address view. /// - sharedAccounts: Any shared accounts from the app group being available for selection and faster login. /// - userAgent: An optional user agent for server requests. + /// - configuration: See ``LoginFlowConfiguration``. /// - addAccount: see ``AddAccountHandler``. /// - public init(backgroundColor: Binding, brandImage: Image, sharedAccounts: [SharedAccount], userAgent: String? = nil, addAccount: @escaping AddAccountHandler) { + public init(backgroundColor: Binding, brandImage: Image, sharedAccounts: [SharedAccount], userAgent: String? = nil, configuration: LoginFlowConfiguration = LoginFlowConfiguration(), addAccount: @escaping AddAccountHandler) { self._backgroundColor = backgroundColor self.brandImage = brandImage - self.sharedAccounts = sharedAccounts - self._model = State(initialValue: LoginFlowModel(userAgent: userAgent, addAccount: addAccount)) + let model = LoginFlowModel(userAgent: userAgent, configuration: configuration, addAccount: addAccount) + + self.sharedAccounts = sharedAccounts.filter { model.isAllowed($0.host) } + self.configuration = configuration + self._model = State(initialValue: model) } // MARK: - Environment @@ -42,6 +49,8 @@ public struct ServerAddressView: View { @Environment(\.horizontalSizeClass) var horizontalSizeClass @Environment(\.verticalSizeClass) var verticalSizeClass @Environment(\.webAuthenticationSession) private var webAuthenticationSession + @Environment(\.openURL) private var openURL + @Environment(\.dynamicTypeSize) private var dynamicTypeSize // MARK: - Bindings @@ -54,22 +63,19 @@ public struct ServerAddressView: View { /// @State private var model: LoginFlowModel - #if os(iOS) /// - /// State toggle for presenting the QR code scanner sheet. + /// State toggle for presenting the sheet to select accounts shared among apps of the same group. /// - @State private var isPresentingCodeScanner = false - #endif + @State private var isPresentingSharedAccounts = false /// - /// State toggle whether the shared accounts have been suggested once during lifetime of this view. + /// The server picked from ``LoginFlowConfiguration/enforcedServers``. /// - @State private var hasSuggestedSharedAccounts = false + @State private var selectedServer: LoginFlowConfiguration.Server? - /// - /// State toggle for presenting the sheet to select accounts shared among apps of the same group. - /// - @State private var isPresentingSharedAccounts = false + private var foregroundColor: Color { + configuration.foregroundColor ?? backgroundColor.readable + } // MARK: - Implementation @@ -80,134 +86,30 @@ public struct ServerAddressView: View { ZStack { backgroundColor - VStack { - Spacer(minLength: 40) - - // Brand image binding or fallback symbol. - brandImage - .resizable() - .aspectRatio(contentMode: .fit) - .foregroundStyle(backgroundColor.readable) - .frame(width: 240, height: 120) - .padding(.vertical, 40) - - // Some space between brand logo and server address field. - if verticalSizeClass == .regular { - Spacer() - .frame(height: 50) - } - - // Container to add horizontal spacers for regular size classes. - HStack { - if horizontalSizeClass == .regular { - Spacer(minLength: 100) - } - - // Container for the server address input and button. - HStack { - TextField( - text: $model.enteredServerAddress, - prompt: Text(verbatim: "https://example.org/").foregroundColor(backgroundColor.readable.opacity(0.5)) - ) { - Text("Server Address", bundle: .module, comment: "Label for text field.") - } - .textContentType(.URL) - .autocorrectionDisabled() - #if os(iOS) - .foregroundStyle(backgroundColor.readable) - .keyboardType(.URL) - .textInputAutocapitalization(.never) - .submitLabel(.done) - #endif - .onSubmit { - model.logIn() - } - - if model.isActive { - ProgressView() - .progressViewStyle(.circular) - .tint(backgroundColor.readable) - } else { - Button { - model.logIn() - } label: { - #if !os(macOS) - Image(systemName: "arrow.right") - #else - Image(systemName: "arrow.right.circle") - .font(.title) - .foregroundStyle(.white) - #endif - } - #if os(macOS) - .buttonStyle(.plain) - #endif - } - } - #if !os(macOS) - .padding(EdgeInsets(top: 8, leading: 10, bottom: 8, trailing: 10)) - .overlay( - RoundedRectangle(cornerRadius: 8) - .stroke(backgroundColor.readable, lineWidth: 1) - ) - #endif - - if horizontalSizeClass == .regular { - Spacer(minLength: 100) - } - } - - Text("The address of your Nextcloud web interface when you open it in your browser.", bundle: .module, comment: "Label below the server address field in the login view.") - .foregroundStyle(backgroundColor.readable) - .font(.footnote) - .padding(4) - - Spacer() - - #if os(iOS) // Camera usually is available on iOS devices only. - Button { - isPresentingCodeScanner = true - } label: { - Image(systemName: "qrcode.viewfinder") - .resizable() - .scaledToFit() - .frame(width: 32, height: 32) - - Text(String(localized: "Scan QR Code", bundle: .module, comment: "Button label")) - } - .padding() - .codeScannerSheet(isPresented: $isPresentingCodeScanner) { - model.handleQRCodeScan($0) + // Scrolls only where the form does not fit, such as on small phones in landscape. + GeometryReader { proxy in + if #available(iOS 26.0, *) { + scrollingForm(minHeight: proxy.size.height) + .scrollEdgeEffectHidden() + } else { + scrollingForm(minHeight: proxy.size.height) } - #endif - - Spacer() } - .disabled(model.isActive) - .tint(backgroundColor.readable) - .padding() - .safeAreaPadding(.all) } .ignoresSafeArea() .toolbar { - if sharedAccounts.isEmpty == false { - if #available(iOS 26.0, macOS 26.0, *) { - sharedAccountsToolbarItem - .sharedBackgroundVisibility(.hidden) - } else { - sharedAccountsToolbarItem - } + if configuration.onCancel != nil { + cancelToolbarItem } } - #if os(iOS) .toolbarBackground(.hidden, for: .navigationBar) - #endif .sharedAccountsSheet(isPresented: $isPresentingSharedAccounts, sharedAccounts: sharedAccounts, selectionHandler: { model.selectSharedAccount($0) }) - .onAppear { - if sharedAccounts.isEmpty == false && hasSuggestedSharedAccounts == false { - isPresentingSharedAccounts = true - hasSuggestedSharedAccounts = true - } + // Outside the form, whose disabled state and brand tint would carry over into the sheet, the page and their alerts. + .codeScannerSheet(model: model) + .fullScreenCover(item: $model.providerSignUp) { + model.providerSignUpDidClose() + } content: { providerSignUp in + ProviderSignUpView(model: providerSignUp) } .task(id: model.isPresentingLoginPage) { // Clearing the flag cancels this task, which closes the browser sheet. @@ -216,9 +118,17 @@ public struct ServerAddressView: View { await model.presentLoginPage(loginAddress, using: webAuthenticationSession) } .alert(String(localized: "Login Failed", bundle: .module, comment: "Alert title"), isPresented: $model.isPresentingAlert) { - Button(role: .cancel) { - model.errorMessage = nil - } label: { + if model.alertOffersSettings { + Button { + if let settingsURL = URL(string: UIApplication.openSettingsURLString) { + openURL(settingsURL) + } + } label: { + Text("Open Settings", bundle: .module, comment: "Button label in the login error alert which opens the system settings of the app.") + } + } + + Button(role: .cancel) {} label: { Text("OK", bundle: .module, comment: "Button label for error alert dismissal.") } } message: { @@ -227,21 +137,229 @@ public struct ServerAddressView: View { } } + private func scrollingForm(minHeight: CGFloat) -> some View { + ScrollView { + form + .frame(minHeight: minHeight) + } + .scrollBounceBehavior(.basedOnSize) + } + + private var form: some View { + VStack { + Spacer().frame(minHeight: 10, maxHeight: 50) + + brandImage + .resizable() + .aspectRatio(contentMode: .fit) + .foregroundStyle(foregroundColor) + .frame(width: 240, height: 120) + .padding(.vertical, 40) + + // Some space between brand logo and server address field. + if verticalSizeClass == .regular { + Spacer() + .frame(height: 50) + } + + // Container to add horizontal spacers for regular size classes. + HStack { + if horizontalSizeClass == .regular { + Spacer(minLength: 100) + } + + // Container for the server address input and button. + HStack { + if configuration.enforcedServers.isEmpty { + serverAddressField + } else { + enforcedServersPicker + } + + if model.isActive { + ProgressView() + .progressViewStyle(.circular) + .tint(foregroundColor) + } else { + Button { + model.logIn() + } label: { + Image(systemName: "arrow.right") + } + .accessibilityLabel(Text("Log in", bundle: .module, comment: "Accessibility label of the button which starts the login.")) + .accessibilityIdentifier("submitServerAddress") + } + } + .padding(EdgeInsets(top: 8, leading: 10, bottom: 8, trailing: 10)) + .overlay( + RoundedRectangle(cornerRadius: 8) + .stroke(foregroundColor, lineWidth: 1) + ) + + if horizontalSizeClass == .regular { + Spacer(minLength: 100) + } + } + + Text(verbatim: configuration.serverAddressDescription ?? String(localized: "The address of your Nextcloud web interface when you open it in your browser.", bundle: .module, comment: "Label below the server address field in the login view.")) + .foregroundStyle(foregroundColor) + .font(.footnote) + .multilineTextAlignment(.center) + .padding(4) + + Spacer().frame(height: 30) + + actions + + Spacer() + + if let hostingInformation = configuration.hostingInformation { + Button(hostingInformation.title) { + openURL(hostingInformation.url) + } + .buttonStyle(.borderless) + .font(.subheadline) + .accessibilityIdentifier("hostYourOwnServer") + } + } + .disabled(model.isActive) + .tint(foregroundColor) + // Dark appearance with light text on the background, so the controls match it. + .environment(\.colorScheme, foregroundColor.readable == .black ? .dark : .light) + .padding() + .safeAreaPadding(.all) + } + + /// + /// The other ways to log in, below an "or", side by side when the height is compact. + /// + @ViewBuilder + private var actions: some View { + let isSideBySide = verticalSizeClass == .compact && dynamicTypeSize.isAccessibilitySize == false + let layout = isSideBySide ? AnyLayout(HStackLayout(spacing: 12)) : AnyLayout(VStackLayout(spacing: 12)) + + VStack(spacing: 37) { + orSeparator + + layout { + actionButton(String(localized: "Log in with QR code", bundle: .module, comment: "Button label which opens the QR code scanner in the login view."), systemImage: "qrcode.viewfinder", identifier: "scanQRCode") { + model.presentCodeScanner() + } + + if sharedAccounts.isEmpty == false { + actionButton(String(localized: "Accounts from other Apps", bundle: .module, comment: "Button label"), systemImage: "person.badge.plus", identifier: "sharedAccounts") { + isPresentingSharedAccounts = true + } + } + + if let providerSignUp = configuration.providerSignUp { + actionButton(providerSignUp.title, systemImage: "person.crop.circle.badge.plus", identifier: "signUpWithProvider") { + model.presentProviderSignUp(providerSignUp.url) + } + } + } + } + .frame(maxWidth: horizontalSizeClass == .regular ? 500 : .infinity) + } + + private var orSeparator: some View { + HStack(spacing: 12) { + Rectangle() + .frame(height: 1) + + Text("or", bundle: .module, comment: "Separator between the server address field and the other ways to log in.") + .font(.footnote) + + Rectangle() + .frame(height: 1) + } + .foregroundStyle(foregroundColor.opacity(0.7)) + .accessibilityHidden(true) + } + /// - /// The toolbar entry point for accounts from other apps, as in the login view of the Files app. + /// A secondary button tinted with the foreground color, so the server address stays the main way to log in. /// - private var sharedAccountsToolbarItem: some ToolbarContent { - ToolbarItem(placement: .primaryAction) { + private func actionButton(_ title: String, systemImage: String, identifier: String, action: @escaping () -> Void) -> some View { + Button(action: action) { + Label { + Text(verbatim: title) + .lineLimit(2) + .multilineTextAlignment(.center) + } icon: { + Image(systemName: systemImage) + } + .font(.headline) + .frame(maxWidth: .infinity) + .padding(.vertical, -3) + } + .buttonStyle(.bordered) + .controlSize(.large) + .accessibilityIdentifier(identifier) + } + + private var serverAddressField: some View { + @Bindable var model = model + + return TextField( + text: $model.enteredServerAddress, + prompt: Text(verbatim: configuration.serverAddressPrompt ?? "https://example.org/").foregroundColor(foregroundColor.opacity(0.5)) + ) { + Text("Server Address", bundle: .module, comment: "Label for text field.") + } + .textContentType(.URL) + .autocorrectionDisabled() + .foregroundStyle(foregroundColor) + .keyboardType(.URL) + .textInputAutocapitalization(.never) + .submitLabel(.done) + .onSubmit { + model.logIn() + } + .disabled(configuration.isServerAddressEditable == false) + .opacity(configuration.isServerAddressEditable ? 1 : 0.5) + .padding(.vertical, 5) + .accessibilityIdentifier("serverAddress") + } + + private var enforcedServersPicker: some View { + Menu { + ForEach(configuration.enforcedServers) { server in + Button(server.name) { + selectedServer = server + model.enteredServerAddress = server.url.absoluteString + } + } + } label: { + HStack { + Text(verbatim: selectedServer?.name ?? configuration.enforcedServersPrompt ?? String(localized: "Select a server", bundle: .module, comment: "Label of the server picker in the login view before a server was picked.")) + .lineLimit(1) + + Spacer() + + Image(systemName: "chevron.down") + } + .foregroundStyle(foregroundColor) + } + .padding(.vertical, 5) + .accessibilityIdentifier("enforcedServers") + } + + private var cancelToolbarItem: some ToolbarContent { + ToolbarItem(placement: .cancellationAction) { Button { - isPresentingSharedAccounts = true + model.cancel() + configuration.onCancel?() } label: { Label { - Text("Accounts from other Apps", bundle: .module, comment: "Button label") + Text("Cancel", bundle: .module, comment: "Button label") } icon: { - Image(systemName: "person.badge.plus") + Image(systemName: "xmark") } } - .tint(backgroundColor.readable) + .tint(foregroundColor) + .disabled(model.isAddingAccount) + .accessibilityIdentifier("cancelLogin") } } } @@ -264,7 +382,7 @@ public struct ServerAddressView: View { let backgroundColor: Binding = .constant(.accentColor) let brandImage = Image(systemName: "questionmark.square.dashed") let sharedAccounts = [ - SharedAccount("Jane Doe", on: URL(string: "http://localhost:8080")!, with: Image(systemName: "person.circle.fill")) + SharedAccount("Jane Doe", user: "jane", on: URL(string: "http://localhost:8080")!, with: Image(systemName: "person.circle.fill")) ] ServerAddressView(backgroundColor: backgroundColor, brandImage: brandImage, sharedAccounts: sharedAccounts) { _, _, _ in @@ -272,4 +390,29 @@ public struct ServerAddressView: View { } } +#Preview("With Links") { + var configuration = LoginFlowConfiguration() + configuration.providerSignUp = LoginFlowConfiguration.WebLink(title: "Sign up with provider", url: URL(string: "https://nextcloud.com/signup-ios")!) + configuration.hostingInformation = LoginFlowConfiguration.WebLink(title: "Host your own server", url: URL(string: "https://nextcloud.com/install")!) + + return ServerAddressView(backgroundColor: .constant(.accentColor), brandImage: Image(systemName: "photo"), sharedAccounts: [], configuration: configuration) { _, _, _ in + print("Add account!") + } +} + +#Preview("Branded") { + var configuration = LoginFlowConfiguration() + configuration.foregroundColor = .white + configuration.serverAddressDescription = "The link to your Example Cloud web interface when you open it in the browser." + configuration.enforcedServers = [ + LoginFlowConfiguration.Server(name: "Example Cloud", url: URL(string: "https://cloud.example.com")!), + LoginFlowConfiguration.Server(name: "Example Cloud EU", url: URL(string: "https://eu.cloud.example.com")!) + ] + configuration.onCancel = {} + + return ServerAddressView(backgroundColor: .constant(.orange), brandImage: Image(systemName: "cloud"), sharedAccounts: [], configuration: configuration) { _, _, _ in + print("Add account!") + } +} + #endif diff --git a/Sources/NextcloudKitUI/Views/Login/SharedAccountsView.swift b/Sources/NextcloudKitUI/Views/Login/SharedAccountsView.swift index 5ed9ebd2..d86b5010 100644 --- a/Sources/NextcloudKitUI/Views/Login/SharedAccountsView.swift +++ b/Sources/NextcloudKitUI/Views/Login/SharedAccountsView.swift @@ -39,7 +39,12 @@ struct SharedAccountsView: View { VStack(alignment: .leading) { - Text(sharedAccount.name) + if let user = sharedAccount.user, user != sharedAccount.name { + Text(verbatim: "\(sharedAccount.name) (\(user))") + } else { + Text(sharedAccount.name) + } + Text(sharedAccount.host.absoluteString) .foregroundStyle(.secondary) .font(.subheadline) @@ -55,9 +60,7 @@ struct SharedAccountsView: View { .padding(.horizontal) } .navigationTitle(String(localized: "Accounts from other Apps", bundle: .module, comment: "Navigation bar title")) -#if os(iOS) .navigationBarTitleDisplayMode(.inline) -#endif } .contentMargins(.top, 20, for: .scrollContent) } diff --git a/Sources/NextcloudKitUI/Views/Login/WebView.swift b/Sources/NextcloudKitUI/Views/Login/WebView.swift index d1edb6f7..4a20d785 100644 --- a/Sources/NextcloudKitUI/Views/Login/WebView.swift +++ b/Sources/NextcloudKitUI/Views/Login/WebView.swift @@ -15,27 +15,39 @@ import WebKit /// /// All of the web view session data is not persistent. /// -public struct WebView: ViewRepresentable { +public struct WebView: UIViewRepresentable { /// Loaded once when the web view is created, so SwiftUI updates don't reload the page. let initialURL: URL? let userAgent: String? + /// A web view its owner configures and drives, shown as it is. + private let webView: WKWebView? + public init(initialURL: URL?, userAgent: String? = nil) { self.initialURL = initialURL self.userAgent = userAgent + self.webView = nil + } + + init(webView: WKWebView) { + self.initialURL = nil + self.userAgent = nil + self.webView = webView } - func makeView() -> WKWebView { + public func makeUIView(context: Context) -> WKWebView { + if let webView { + return webView + } + let configuration = WKWebViewConfiguration() configuration.websiteDataStore = .nonPersistent() let webView = WKWebView(frame: CGRect.zero, configuration: configuration) webView.isInspectable = true - if let userAgent { - webView.customUserAgent = userAgent - } + webView.customUserAgent = userAgent if let initialURL { webView.load(URLRequest(url: initialURL)) @@ -44,27 +56,7 @@ public struct WebView: ViewRepresentable { return webView } - // MARK: - macOS - - #if os(macOS) - - public func makeNSView(context: Context) -> WKWebView { - makeView() - } - - public func updateNSView(_ webView: WKWebView, context: Context) {} - - // MARK: - iOS - - #else - - public func makeUIView(context: Context) -> WKWebView { - makeView() - } - public func updateUIView(_ webView: WKWebView, context: Context) {} - - #endif } #Preview { diff --git a/Sources/NextcloudKitUI/Views/Onboarding/OnboardingView.swift b/Sources/NextcloudKitUI/Views/Onboarding/OnboardingView.swift index c4d64879..9ed5e021 100644 --- a/Sources/NextcloudKitUI/Views/Onboarding/OnboardingView.swift +++ b/Sources/NextcloudKitUI/Views/Onboarding/OnboardingView.swift @@ -38,6 +38,10 @@ public struct OnboardingView: View { // MARK: - Environment @Environment(\.dynamicTypeSize) private var dynamicTypeSize + @Environment(\.accessibilityReduceMotion) private var reduceMotion + + /// Fades the text in once the view appears. + @State private var isTextShown = false @ScaledMetric(relativeTo: .largeTitle) private var iconSize: CGFloat = 64 @@ -75,10 +79,12 @@ public struct OnboardingView: View { .accessibilityAddTraits(.isHeader) .fixedSize(horizontal: false, vertical: true) .padding(.bottom, 32) + .fadeIn(isShown: isTextShown, order: 0, slides: reduceMotion == false) VStack(alignment: .leading, spacing: 24) { - ForEach(Array(features.enumerated()), id: \.offset) { _, feature in + ForEach(Array(features.enumerated()), id: \.offset) { index, feature in featureRow(feature) + .fadeIn(isShown: isTextShown, order: index + 1, slides: reduceMotion == false) } } } @@ -90,6 +96,9 @@ public struct OnboardingView: View { .frame(maxWidth: .infinity) } .scrollBounceBehavior(.basedOnSize) + .onAppear { + isTextShown = true + } Button(action: continueHandler) { Group { @@ -106,6 +115,7 @@ public struct OnboardingView: View { .buttonStyle(.borderedProminent) .controlSize(.large) .tint(tint) + .accessibilityIdentifier("continueOnboarding") .padding(.horizontal, horizontalPadding) .padding(.vertical) .frame(maxWidth: 520) @@ -138,6 +148,17 @@ public struct OnboardingView: View { } } +private extension View { + /// + /// Fades in after the views before it, sliding up slightly when `slides` is set. + /// + func fadeIn(isShown: Bool, order: Int, slides: Bool) -> some View { + opacity(isShown ? 1 : 0) + .offset(y: isShown || slides == false ? 0 : 8) + .animation(.easeOut(duration: 0.5).delay(Double(order) * 0.1), value: isShown) + } +} + #if DEBUG #Preview { diff --git a/Sources/NextcloudKitUI/Views/Unified Share/Edit/UnifiedShareEditView.swift b/Sources/NextcloudKitUI/Views/Unified Share/Edit/UnifiedShareEditView.swift index b5fbca09..ce58c50c 100644 --- a/Sources/NextcloudKitUI/Views/Unified Share/Edit/UnifiedShareEditView.swift +++ b/Sources/NextcloudKitUI/Views/Unified Share/Edit/UnifiedShareEditView.swift @@ -5,9 +5,7 @@ import SwiftUI import NextcloudKit -#if canImport(UIKit) import UIKit -#endif /// View used for Unified Sharing. public struct UnifiedShareEditView: View { @@ -815,9 +813,7 @@ public struct UnifiedShareEditView: View { } private func copyToPasteboard(_ string: String) { - #if canImport(UIKit) UIPasteboard.general.string = string - #endif } } diff --git a/Tests/NextcloudKitUITests/LoginFlowModelTests.swift b/Tests/NextcloudKitUITests/LoginFlowModelTests.swift new file mode 100644 index 00000000..ba48ee34 --- /dev/null +++ b/Tests/NextcloudKitUITests/LoginFlowModelTests.swift @@ -0,0 +1,388 @@ +// SPDX-FileCopyrightText: Nextcloud GmbH +// SPDX-FileCopyrightText: 2026 Milen Pivchev +// SPDX-License-Identifier: GPL-3.0-or-later + +import CodeScanner +import Foundation +import NextcloudKit +@testable import NextcloudKitUI +import Testing + +/// +/// Tests for ``LoginFlowModel`` which need no Nextcloud server. +/// +/// Serialized, because parallel requests through the shared `NextcloudKit` sessions drop each other. +/// +@MainActor +@Suite(.serialized) +struct LoginFlowModelTests { + /// + /// Records what the model hands to the host app. + /// + @MainActor + final class Recorder { + var addedAccounts: [(host: URL, name: String, password: String)] = [] + var serverErrors: [(error: NKError, url: URL)] = [] + var isActiveDuringAddAccount: Bool? + var isAddingAccountDuringAddAccount: Bool? + var isPresentingCodeScannerDuringAddAccount: Bool? + var addAccountError: Error? + weak var model: LoginFlowModel? + } + + private let loginCode = "nc://login/user:jane&password:secret&server:https://cloud.example.com" + + private func makeModel(configuration: LoginFlowConfiguration = LoginFlowConfiguration(), recorder: Recorder) -> LoginFlowModel { + let model = LoginFlowModel(userAgent: nil, configuration: configuration) { host, name, password in + recorder.isActiveDuringAddAccount = recorder.model?.isActive + recorder.isAddingAccountDuringAddAccount = recorder.model?.isAddingAccount + recorder.isPresentingCodeScannerDuringAddAccount = recorder.model?.isPresentingCodeScanner + recorder.addedAccounts.append((host, name, password)) + + if let error = recorder.addAccountError { + throw error + } + } + + recorder.model = model + + return model + } + + private func waitUntil(_ condition: @MainActor () -> Bool) async throws { + let deadline = ContinuousClock.now + .seconds(10) + + while condition() == false { + guard ContinuousClock.now < deadline else { + Issue.record("Timed out waiting for the condition.") + return + } + + try await Task.sleep(for: .milliseconds(20)) + } + } + + @Test func prefillsInitialServerAddress() async throws { + var configuration = LoginFlowConfiguration() + configuration.initialServerAddress = "https://cloud.example.com" + + let model = makeModel(configuration: configuration, recorder: Recorder()) + + #expect(model.enteredServerAddress == "https://cloud.example.com") + } + + @Test func emptyAddressDoesNothing() async throws { + let model = makeModel(recorder: Recorder()) + model.enteredServerAddress = " " + + model.logIn() + + #expect(model.isActive == false) + #expect(model.isPresentingAlert == false) + } + + @Test func invalidAddressPresentsAlert() async throws { + let model = makeModel(recorder: Recorder()) + model.enteredServerAddress = "ssh://cloud.example.com" + + model.logIn() + + #expect(model.isActive == false) + #expect(model.isPresentingAlert) + #expect(model.errorMessage?.isEmpty == false) + } + + @Test func addAccountFailureWording() async throws { + let unauthorized = NKError(errorCode: 401) + let notFound = NKError(errorCode: 404) + let invalidResponse = NKError.invalidResponseError + + let unauthorizedMessage = try await addAccountMessage(for: unauthorized) + let notFoundMessage = try await addAccountMessage(for: notFound) + let invalidResponseMessage = try await addAccountMessage(for: invalidResponse) + + // QR code logins are not restarted when the server refuses the credentials. + #expect(unauthorizedMessage == unauthorized.localizedGenericMessage) + + // A 404 means a wrong address, while an unreadable reply may come from a proxy in front of a server that exists. + #expect(notFoundMessage != notFound.localizedGenericMessage) + #expect(invalidResponseMessage == invalidResponse.localizedGenericMessage) + } + + private func addAccountMessage(for error: NKError) async throws -> String? { + let recorder = Recorder() + recorder.addAccountError = error + let model = makeModel(recorder: recorder) + + model.handleLoginCode(loginCode) + + try await waitUntil { model.isPresentingAlert } + + #expect(model.isActive == false) + + return model.errorMessage + } + + @Test func loginCodeUsesConfiguredScheme() async throws { + let recorder = Recorder() + var configuration = LoginFlowConfiguration() + configuration.loginURLScheme = "abc" + let model = makeModel(configuration: configuration, recorder: recorder) + + model.handleLoginCode(loginCode) + + #expect(model.isPresentingAlert) + #expect(model.errorMessage == QRCodeError.invalidPrefix.localizedDescription) + + model.handleLoginCode("abc://login/user:jane&password:secret&server:https://cloud.example.com") + + try await waitUntil { recorder.addedAccounts.count == 1 } + } + + @Test func enforcedServersRefuseOtherHosts() async throws { + let recorder = Recorder() + var configuration = LoginFlowConfiguration() + configuration.enforcedServers = [.init(name: "Example", url: URL(string: "https://Cloud.Example.com/nextcloud")!)] + let model = makeModel(configuration: configuration, recorder: recorder) + + model.handleLoginCode("nc://login/user:jane&password:secret&server:https://evil.example.org") + + #expect(model.isPresentingAlert) + #expect(recorder.addedAccounts.isEmpty) + + model.finishProviderSignUp(callbackURL: URL(string: "nc://login/server:https://evil.example.org&user:jane&password:secret")!) + model.providerSignUpDidClose() + + #expect(recorder.addedAccounts.isEmpty) + #expect(model.isAllowed(URL(string: "https://evil.example.org")!) == false) + + model.isPresentingAlert = false + model.handleLoginCode(loginCode) + + try await waitUntil { recorder.addedAccounts.count == 1 } + } + + @Test func withoutEnforcedServersAnyHostIsAllowed() { + let model = makeModel(recorder: Recorder()) + + #expect(model.isAllowed(URL(string: "https://evil.example.org")!)) + } + + @Test func cancelResetsState() async throws { + let model = makeModel(recorder: Recorder()) + model.isActive = true + model.isPresentingLoginPage = true + + model.cancel() + + #expect(model.isActive == false) + #expect(model.isPresentingLoginPage == false) + } + + @Test func serverErrorWithoutHandlerIsPresented() async throws { + let model = makeModel(recorder: Recorder()) + + // Nothing listens on port 1, so the connection is refused right away. + model.enteredServerAddress = "http://127.0.0.1:1" + model.logIn() + + #expect(model.enteredServerAddress == "http://127.0.0.1:1/") + #expect(model.isActive) + + try await waitUntil { model.isPresentingAlert } + + #expect(model.isActive == false) + } + + @Test func serverErrorHandlerCanRetryAndCancel() async throws { + let recorder = Recorder() + var configuration = LoginFlowConfiguration() + + configuration.onServerError = { error, url in + recorder.serverErrors.append((error, url)) + + if recorder.serverErrors.count == 1 { + return .retry(URL(string: "http://127.0.0.1:2/")!) + } + + return .cancel + } + + let model = makeModel(configuration: configuration, recorder: recorder) + model.enteredServerAddress = "127.0.0.1:1" + model.logIn() + + try await waitUntil { recorder.serverErrors.count == 2 && model.isActive == false } + + #expect(recorder.serverErrors.map(\.url.absoluteString) == ["https://127.0.0.1:1/", "http://127.0.0.1:2/"]) + #expect(model.enteredServerAddress == "http://127.0.0.1:2/") + #expect(model.isPresentingAlert == false) + } + + @Test func scannedCodeAddsAccountWhileScannerStaysOpen() async throws { + let recorder = Recorder() + let model = makeModel(recorder: recorder) + + model.presentCodeScanner() + model.handleLoginCode(loginCode) + + try await waitUntil { recorder.addedAccounts.count == 1 && model.isActive == false } + + let account = try #require(recorder.addedAccounts.first) + #expect(account.host.absoluteString == "https://cloud.example.com") + #expect(account.name == "jane") + #expect(account.password == "secret") + #expect(recorder.isActiveDuringAddAccount == true) + #expect(recorder.isAddingAccountDuringAddAccount == true) + #expect(recorder.isPresentingCodeScannerDuringAddAccount == true) + #expect(model.isAddingAccount == false) + #expect(model.isPresentingCodeScanner == false) + #expect(model.isPresentingAlert == false) + } + + @Test func invalidScannedCodeClosesScannerThenShowsError() async throws { + let model = makeModel(recorder: Recorder()) + + model.presentCodeScanner() + model.handleLoginCode("https://cloud.example.com") + + #expect(model.isPresentingCodeScanner == false) + #expect(model.isPresentingAlert == false) + + model.codeScannerDidClose() + + #expect(model.isPresentingAlert) + #expect(model.errorMessage == QRCodeError.invalidPrefix.localizedDescription) + } + + @Test func failedLoginFromScannedCodeClosesScannerThenShowsError() async throws { + let recorder = Recorder() + recorder.addAccountError = NKError(errorCode: 401) + let model = makeModel(recorder: recorder) + + model.presentCodeScanner() + model.handleLoginCode(loginCode) + + try await waitUntil { model.isPresentingCodeScanner == false && model.isActive == false } + + #expect(recorder.isPresentingCodeScannerDuringAddAccount == true) + + model.codeScannerDidClose() + + #expect(model.isPresentingAlert) + } + + @Test func reopenedScannerForgetsTheLastError() async throws { + let model = makeModel(recorder: Recorder()) + + model.presentCodeScanner() + model.handleLoginCode("https://cloud.example.com") + model.presentCodeScanner() + model.codeScannerDidClose() + + #expect(model.isPresentingAlert == false) + } + + @Test func providerSignUpAddsAccountOnceItsPageClosed() async throws { + let recorder = Recorder() + let model = makeModel(recorder: recorder) + + model.presentProviderSignUp(URL(string: "http://127.0.0.1:1/signup")!) + model.finishProviderSignUp(callbackURL: URL(string: "nc://login/server:https://cloud.example.com&user:jane&password:secret")!) + + #expect(model.providerSignUp == nil) + #expect(recorder.addedAccounts.isEmpty) + + model.providerSignUpDidClose() + + try await waitUntil { recorder.addedAccounts.count == 1 && model.isActive == false } + + let account = try #require(recorder.addedAccounts.first) + #expect(account.host.absoluteString == "https://cloud.example.com") + #expect(account.name == "jane") + #expect(account.password == "secret") + #expect(recorder.isActiveDuringAddAccount == true) + #expect(model.isPresentingAlert == false) + } + + @Test func closedProviderSignUpWithoutCallbackDoesNothing() async throws { + let recorder = Recorder() + let model = makeModel(recorder: recorder) + + model.presentProviderSignUp(URL(string: "http://127.0.0.1:1/signup")!) + model.providerSignUp = nil + model.providerSignUpDidClose() + + #expect(model.isActive == false) + #expect(model.isPresentingAlert == false) + #expect(recorder.addedAccounts.isEmpty) + } + + @Test func refusedSignUpCredentialsRestartTheLogin() async throws { + let recorder = Recorder() + let refusal = NKError(errorCode: 401) + recorder.addAccountError = refusal + let model = makeModel(recorder: recorder) + + // Nothing listens on port 1, so the restarted login fails at its server check. + model.finishProviderSignUp(callbackURL: URL(string: "nc://login/server:http://127.0.0.1:1&user:jane&password:token")!) + model.providerSignUpDidClose() + + try await waitUntil { model.isPresentingAlert } + + #expect(recorder.addedAccounts.count == 1) + #expect(model.enteredServerAddress == "http://127.0.0.1:1/") + #expect(model.errorMessage != refusal.localizedGenericMessage) + #expect(model.isActive == false) + #expect(model.isAddingAccount == false) + } + + @Test func malformedSignUpCallbackShowsError() async throws { + let recorder = Recorder() + let model = makeModel(recorder: recorder) + + model.finishProviderSignUp(callbackURL: URL(string: "nc://login/user:jane")!) + model.providerSignUpDidClose() + + #expect(model.isPresentingAlert) + #expect(recorder.addedAccounts.isEmpty) + } + + @Test func cameraFailureClosesScannerWithAlert() async throws { + let model = makeModel(recorder: Recorder()) + + model.presentCodeScanner() + model.handleQRCodeScan(.failure(.permissionDenied)) + + #expect(model.isPresentingCodeScanner == false) + + model.codeScannerDidClose() + + #expect(model.isPresentingAlert) + #expect(model.alertOffersSettings) + } + + @Test func cancelWhileRecoveringStopsTheLogin() async throws { + let recorder = Recorder() + var configuration = LoginFlowConfiguration() + + configuration.onServerError = { error, url in + recorder.serverErrors.append((error, url)) + recorder.model?.cancel() + + return .retry(URL(string: "http://127.0.0.1:2/")!) + } + + let model = makeModel(configuration: configuration, recorder: recorder) + model.enteredServerAddress = "127.0.0.1:1" + model.logIn() + + try await waitUntil { recorder.serverErrors.count == 1 && model.isActive == false } + try await Task.sleep(for: .milliseconds(200)) + + #expect(recorder.serverErrors.count == 1) + #expect(model.enteredServerAddress == "https://127.0.0.1:1/") + #expect(model.isActive == false) + #expect(model.isPresentingAlert == false) + } +} diff --git a/Tests/NextcloudKitUITests/LoginPollingPolicyTests.swift b/Tests/NextcloudKitUITests/LoginPollingPolicyTests.swift new file mode 100644 index 00000000..a894a61c --- /dev/null +++ b/Tests/NextcloudKitUITests/LoginPollingPolicyTests.swift @@ -0,0 +1,30 @@ +// SPDX-FileCopyrightText: Nextcloud GmbH +// SPDX-FileCopyrightText: 2026 Milen Pivchev +// SPDX-License-Identifier: GPL-3.0-or-later + +import Foundation +import NextcloudKit +@testable import NextcloudKitUI +import Testing + +/// +/// Tests for ``LoginPollingPolicy``. +/// +struct LoginPollingPolicyTests { + @Test(arguments: [ + NSURLErrorNotConnectedToInternet, + NSURLErrorTimedOut, + NSURLErrorNetworkConnectionLost, + NSURLErrorCannotConnectToHost, + NSURLErrorCancelled, + 502, + 503, + 429 + ]) func transientErrors(_ errorCode: Int) async throws { + #expect(LoginPollingPolicy.isTransient(NKError(errorCode: errorCode))) + } + + @Test(arguments: [400, 401, 403, 500, NSURLErrorServerCertificateUntrusted, NSURLErrorBadServerResponse]) func terminalErrors(_ errorCode: Int) async throws { + #expect(LoginPollingPolicy.isTransient(NKError(errorCode: errorCode)) == false) + } +} diff --git a/Tests/NextcloudKitUITests/ProviderSignUpModelTests.swift b/Tests/NextcloudKitUITests/ProviderSignUpModelTests.swift new file mode 100644 index 00000000..1f954d1d --- /dev/null +++ b/Tests/NextcloudKitUITests/ProviderSignUpModelTests.swift @@ -0,0 +1,139 @@ +// SPDX-FileCopyrightText: Nextcloud GmbH +// SPDX-FileCopyrightText: 2026 Milen Pivchev +// SPDX-License-Identifier: GPL-3.0-or-later + +import Foundation +import NextcloudKit +@testable import NextcloudKitUI +import Testing +import WebKit + +/// +/// Tests for the page load rules of ``ProviderSignUpModel``, which need no page to load. +/// +@MainActor +@Suite +struct ProviderSignUpModelTests { + // Nothing listens on port 1, so a load the model starts by itself goes nowhere. + private let signUpURL = URL(string: "http://127.0.0.1:1/signup")! + private let pageURL = URL(string: "https://provider.example.com/register")! + + private func makeModel() -> ProviderSignUpModel { + ProviderSignUpModel(url: signUpURL, callbackScheme: "nc", userAgent: nil) { _ in } + } + + @Test func requestHasTheAPIHeaderAndAShortTimeout() { + let request = ProviderSignUpModel.request(for: pageURL) + + #expect(request.value(forHTTPHeaderField: "OCS-APIRequest") == "true") + #expect(request.timeoutInterval == 20) + } + + @Test func uncachedURLAddsAQueryItem() { + let withQuery = URL(string: "https://nextcloud.com/signup-ios?lang=de")! + + #expect(ProviderSignUpModel.uncachedURL(pageURL).absoluteString == "https://provider.example.com/register?ocsapi=1") + #expect(ProviderSignUpModel.uncachedURL(withQuery).absoluteString == "https://nextcloud.com/signup-ios?lang=de&ocsapi=1") + } + + @Test func callbackURLFinishesInAnyLetterCase() { + let model = makeModel() + let callbackURL = URL(string: "NC://login/server:https://cloud.example.com&user:jane&password:secret")! + + #expect(model.policy(for: URLRequest(url: callbackURL), isMainFrame: false) == .finish(callbackURL)) + } + + @Test func pageLoadWithoutHeaderIsRepeatedOncePerPage() { + let model = makeModel() + let request = URLRequest(url: pageURL) + + #expect(model.policy(for: request, isMainFrame: true) == .reissue(ProviderSignUpModel.request(for: pageURL))) + #expect(model.policy(for: request, isMainFrame: true) == .allow) + + model.webView(model.webView, didFinish: nil) + + #expect(model.policy(for: request, isMainFrame: true) == .reissue(ProviderSignUpModel.request(for: pageURL))) + + model.retry() + + #expect(model.policy(for: request, isMainFrame: true) == .reissue(ProviderSignUpModel.request(for: pageURL))) + } + + @Test func pageLoadWithHeaderSubframesAndPostsPass() { + let model = makeModel() + var post = URLRequest(url: pageURL) + post.httpMethod = "POST" + + #expect(model.policy(for: ProviderSignUpModel.request(for: pageURL), isMainFrame: true) == .allow) + #expect(model.policy(for: URLRequest(url: pageURL), isMainFrame: false) == .allow) + #expect(model.policy(for: post, isMainFrame: true) == .allow) + } + + @Test func linksTheWebViewCannotShowOpenInTheirApp() { + let model = makeModel() + let mail = URL(string: "mailto:support@provider.example.com")! + let blank = URL(string: "about:blank")! + + #expect(model.policy(for: URLRequest(url: mail), isMainFrame: true) == .openExternally(mail)) + #expect(model.policy(for: URLRequest(url: mail), isMainFrame: false) == .cancel) + #expect(model.policy(for: URLRequest(url: blank), isMainFrame: false) == .allow) + } + + @Test("Error statuses map to kinds whose texts fit a web page", arguments: [ + (408, NKError.Kind.timeout), + (504, .timeout), + (429, .rateLimited), + (503, .unavailable), + (500, .serverError), + (501, .serverError), + (599, .serverError), + (403, .serverUnreachable), + (404, .serverUnreachable) + ]) + func statusMapping(statusCode: Int, kind: NKError.Kind) throws { + let response = try #require(HTTPURLResponse(url: pageURL, statusCode: statusCode, httpVersion: nil, headerFields: nil)) + let error = try #require(ProviderSignUpModel.error(for: response, canShowMIMEType: true)) + + #expect(error.errorCode == statusCode) + #expect(error.kind == kind) + } + + @Test func emptyAndUnshowableResponsesFail() throws { + let page = try #require(HTTPURLResponse(url: pageURL, statusCode: 200, httpVersion: nil, headerFields: ["Content-Length": "120"])) + let empty = try #require(HTTPURLResponse(url: pageURL, statusCode: 200, httpVersion: nil, headerFields: ["Content-Length": "0"])) + + #expect(ProviderSignUpModel.error(for: page, canShowMIMEType: true) == nil) + #expect(ProviderSignUpModel.error(for: page, canShowMIMEType: false)?.kind == .invalidResponse) + #expect(ProviderSignUpModel.error(for: empty, canShowMIMEType: true)?.kind == .invalidResponse) + } + + @Test func webContentProcessEndReloadsOnceThenFails() { + let model = makeModel() + + model.webViewWebContentProcessDidTerminate(model.webView) + + #expect(model.errorMessage == nil) + + model.webViewWebContentProcessDidTerminate(model.webView) + + #expect(model.errorMessage != nil) + + model.webView(model.webView, didFinish: nil) + model.webViewWebContentProcessDidTerminate(model.webView) + + #expect(model.errorMessage == nil) + } + + @Test func cancelledAndInterruptedLoadsShowNothing() { + let model = makeModel() + + model.showLoadError(NSError(domain: NSURLErrorDomain, code: NSURLErrorCancelled)) + model.showLoadError(NSError(domain: "WebKitErrorDomain", code: 102)) + + #expect(model.errorMessage == nil) + + model.showLoadError(NSError(domain: NSURLErrorDomain, code: NSURLErrorTimedOut)) + + #expect(model.errorMessage == NKError(errorCode: NSURLErrorTimedOut).localizedGenericMessage) + } +} diff --git a/Tests/NextcloudKitUITests/QRCodeParsingTests.swift b/Tests/NextcloudKitUITests/QRCodeParsingTests.swift index 791b82f2..e569a5e0 100644 --- a/Tests/NextcloudKitUITests/QRCodeParsingTests.swift +++ b/Tests/NextcloudKitUITests/QRCodeParsingTests.swift @@ -2,6 +2,7 @@ // SPDX-FileCopyrightText: 2025 Iva Horn // SPDX-License-Identifier: GPL-3.0-or-later +import Foundation @testable import NextcloudKitUI import Testing @@ -20,39 +21,72 @@ struct QRCodeParsingTests { testSubject = QRCodeParsingTestSubject() } - @Test func emptyCode() async throws { - #expect(throws: QRCodeError.implausibleLength) { - try testSubject.parse("") + @Test(arguments: [ + ("nc://login/", QRCodeError.implausibleLength), + ("nope://login/user:test&password:secret&server:http://localhost:8080", .invalidPrefix), + ("nc://login/password:secret&server:http://localhost:8080", .missingUser), + ("nc://login/user:&password:secret&server:https://cloud.example.com", .missingUser), + ("nc://login/user:test&server:http://localhost:8080", .missingPassword), + ("nc://login/user:test&password:secret", .missingHost) + ]) func invalidCode(_ code: String, _ error: QRCodeError) async throws { + #expect(throws: error) { + try testSubject.parseLogin(code) } } - @Test func invalidPrefix() async throws { - #expect(throws: QRCodeError.invalidPrefix) { - try testSubject.parse("nope://login/&user:test&password:secret&server:http://localhost:8080") - } + @Test func fieldsInAnyOrder() async throws { + let credentials = try testSubject.parseLogin("nc://login/server:https://cloud.example.com&password:secret&user:jane") + + #expect(credentials.kind == .login) + #expect(credentials.user == "jane") + #expect(credentials.password == "secret") + #expect(credentials.host.absoluteString == "https://cloud.example.com") } - @Test func missingUser() async throws { - #expect(throws: QRCodeError.missingUser) { - try testSubject.parse("nc://login/&password:secret&server:http://localhost:8080") - } + @Test func onetimeLogin() async throws { + let credentials = try testSubject.parseLogin("nc://onetime-login/user:jane&password:token&server:https://cloud.example.com") + + #expect(credentials.kind == .onetimeLogin) + #expect(credentials.password == "token") } - @Test func missingPassword() async throws { - #expect(throws: QRCodeError.missingPassword) { - try testSubject.parse("nc://login/&user:test&server:http://localhost:8080") - } + @Test func validCallback() async throws { + let url = try #require(URL(string: "nc://login/server:https://cloud.example.com/nextcloud&user:jane&password:secret")) + let credentials = try testSubject.parseLoginCallback(url) + + #expect(credentials.kind == .login) + #expect(credentials.user == "jane") + #expect(credentials.password == "secret") + #expect(credentials.host.absoluteString == "https://cloud.example.com/nextcloud") } - @Test func missingHost() async throws { - #expect(throws: QRCodeError.missingHost) { - try testSubject.parse("nc://login/&user:test&password:secret") - } + @Test func callbackPlusInUserIsSpace() async throws { + let url = try #require(URL(string: "nc://login/server:https://cloud.example.com&user:jane+doe&password:secret")) + + #expect(try testSubject.parseLoginCallback(url).user == "jane doe") } - @Test func validCode() async throws { - #expect(throws: Never.self) { - try testSubject.parse("nc://login/&user:test&password:secret&server:http://localhost:8080") + @Test func callbackPercentEncodedValues() async throws { + let url = try #require(URL(string: "nc://login/server:https://cloud.example.com&user:jane%40example.com&password:se%2Bcret")) + let credentials = try testSubject.parseLoginCallback(url) + + #expect(credentials.user == "jane@example.com") + #expect(credentials.password == "se+cret") + } + + @Test func callbackCustomScheme() async throws { + let url = try #require(URL(string: "abc://login/server:https://cloud.example.com&user:jane&password:secret")) + + #expect(try testSubject.parseLoginCallback(url, scheme: "abc").user == "jane") + + #expect(throws: QRCodeError.invalidPrefix) { + try testSubject.parseLoginCallback(url) } } + + @Test(arguments: [QRCodeError.implausibleLength, .invalidPrefix, .missingHost, .missingPassword, .missingUser]) func localizedDescription(_ error: QRCodeError) async throws { + let description = try #require(error.errorDescription) + #expect(description.isEmpty == false) + #expect(error.localizedDescription == description) + } } diff --git a/Tests/NextcloudKitUITests/URLSanitizingTests.swift b/Tests/NextcloudKitUITests/URLSanitizingTests.swift index ca04a1b4..10454ef2 100644 --- a/Tests/NextcloudKitUITests/URLSanitizingTests.swift +++ b/Tests/NextcloudKitUITests/URLSanitizingTests.swift @@ -20,12 +20,16 @@ struct URLSanitizingTests { testSubject = URLSanitizingTestSubject() } - @Test func emptyString() async throws { - try #require(testSubject.sanitize("") == nil) + @Test(arguments: ["", " ", "\n"]) func emptyInput(_ input: String) async throws { + #expect(testSubject.sanitize(input) == nil) } - @Test func invalidScheme() async throws { - try #require(testSubject.sanitize("ssh://www.nextcloud.com") == nil) + @Test(arguments: ["ssh://www.nextcloud.com", "ftp://www.nextcloud.com"]) func invalidScheme(_ input: String) async throws { + #expect(testSubject.sanitize(input) == nil) + } + + @Test(arguments: ["https://", "http:///nextcloud"]) func missingHost(_ input: String) async throws { + #expect(testSubject.sanitize(input) == nil) } @Test func validURL() async throws { @@ -46,4 +50,50 @@ struct URLSanitizingTests { let sanitized = try #require(testSubject.sanitize(pathPrefix)) #expect(sanitized.absoluteString == "https://www.nextcloud.com/") } + + @Test(arguments: ["https://www.nextcloud.com/nextcloud/index.php", "https://www.nextcloud.com/nextcloud/index.php/"]) func phpPathSuffixBelowPathPrefix(_ input: String) async throws { + let sanitized = try #require(testSubject.sanitize(input)) + #expect(sanitized.absoluteString == "https://www.nextcloud.com/nextcloud/") + } + + @Test(arguments: [ + ("cloud.example.com", "https://cloud.example.com/"), + ("cloud.example.com/nextcloud", "https://cloud.example.com/nextcloud/"), + ("localhost:8080", "https://localhost:8080/"), + ("cloud.example.com:8443/nextcloud", "https://cloud.example.com:8443/nextcloud/"), + ("//cloud.example.com", "https://cloud.example.com/") + ]) func missingScheme(_ input: String, _ expected: String) async throws { + let sanitized = try #require(testSubject.sanitize(input)) + #expect(sanitized.absoluteString == expected) + } + + @Test(arguments: [ + ("https:/cloud.example.com", "https://cloud.example.com/"), + ("https:cloud.example.com", "https://cloud.example.com/"), + ("HTTPS:/cloud.example.com/nextcloud", "https://cloud.example.com/nextcloud/"), + ("http:/localhost:8080", "http://localhost:8080/") + ]) func mistypedSchemeSlashes(_ input: String, _ expected: String) async throws { + let sanitized = try #require(testSubject.sanitize(input)) + #expect(sanitized.absoluteString == expected) + } + + @Test func trimsWhitespaceAndNewlines() async throws { + let sanitized = try #require(testSubject.sanitize(" https://cloud.example.com \n")) + #expect(sanitized.absoluteString == "https://cloud.example.com/") + } + + @Test func dropsQueryAndFragment() async throws { + let sanitized = try #require(testSubject.sanitize("https://cloud.example.com/nextcloud/?redirect=1#top")) + #expect(sanitized.absoluteString == "https://cloud.example.com/nextcloud/") + } + + @Test func keepsInsecureHTTPByDefault() async throws { + let sanitized = try #require(testSubject.sanitize("http://localhost:8080")) + #expect(sanitized.absoluteString == "http://localhost:8080/") + } + + @Test func upgradesInsecureHTTP() async throws { + let sanitized = try #require(testSubject.sanitize("http://cloud.example.com/nextcloud", upgradingInsecureHTTP: true)) + #expect(sanitized.absoluteString == "https://cloud.example.com/nextcloud/") + } }