From 89960a3e6b7ebb84a1220bdf41cbd582a47ded55 Mon Sep 17 00:00:00 2001 From: Milen Pivchev Date: Thu, 19 Nov 2026 17:02:57 +0100 Subject: [PATCH 01/33] fix(NextcloudKitUI): sanitize bare hosts and parse login callbacks - URL sanitizing trims whitespace, defaults bare hosts and host:port to https, keeps the leading slash when dropping a trailing index.php below a path prefix, drops query and fragment, and can upgrade http to https. - Login codes accept a custom scheme, reject empty values and report localized errors. - New public LoginCallbackParser for the ://login/ URL a server or sign-up provider redirects to, with percent and '+' decoding. - New LoginPollingPolicy classifying transient poll errors. Assisted-by: Claude Code:claude-opus-5-5 Co-Authored-By: Claude Opus 5.5 Signed-off-by: Milen Pivchev --- .../Features/LoginCallbackParser.swift | 20 +++++ .../Features/LoginPollingPolicy.swift | 22 ++++++ .../Features/QRCodeParsing.swift | 78 ++++++++++++------- .../Features/URLSanitizing.swift | 65 ++++++++-------- Sources/NextcloudKitUI/Localizable.xcstrings | 12 +++ .../Views/Login/LoginFlowModel.swift | 2 +- .../LoginCallbackParserTests.swift | 57 ++++++++++++++ .../LoginPollingPolicyTests.swift | 30 +++++++ .../QRCodeParsingTests.swift | 39 ++++++++++ .../URLSanitizingTests.swift | 53 ++++++++++++- 10 files changed, 315 insertions(+), 63 deletions(-) create mode 100644 Sources/NextcloudKitUI/Features/LoginCallbackParser.swift create mode 100644 Sources/NextcloudKitUI/Features/LoginPollingPolicy.swift create mode 100644 Tests/NextcloudKitUITests/LoginCallbackParserTests.swift create mode 100644 Tests/NextcloudKitUITests/LoginPollingPolicyTests.swift diff --git a/Sources/NextcloudKitUI/Features/LoginCallbackParser.swift b/Sources/NextcloudKitUI/Features/LoginCallbackParser.swift new file mode 100644 index 00000000..f1afaa24 --- /dev/null +++ b/Sources/NextcloudKitUI/Features/LoginCallbackParser.swift @@ -0,0 +1,20 @@ +// SPDX-FileCopyrightText: Nextcloud GmbH +// SPDX-FileCopyrightText: 2026 Milen Pivchev +// SPDX-License-Identifier: GPL-3.0-or-later + +import Foundation + +/// +/// Parses the `://login/server:…&user:…&password:…` URL a server or sign-up provider redirects to after a successful login. +/// +public enum LoginCallbackParser { + public static func parse(_ url: URL, scheme: String = "nc") throws -> LoginCredentials { + try parse(url.absoluteString, scheme: scheme) + } + + public static func parse(_ string: String, scheme: String = "nc") throws -> LoginCredentials { + let (user, password, host) = try decomposeLoginCode(string, prefix: "\(scheme)://login/", decodingValues: true) + + return LoginCredentials(kind: .login, user: user, password: password, host: host) + } +} 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..63a25b59 100644 --- a/Sources/NextcloudKitUI/Features/QRCodeParsing.swift +++ b/Sources/NextcloudKitUI/Features/QRCodeParsing.swift @@ -5,37 +5,50 @@ 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 { +public struct LoginCredentials: Sendable, Equatable { /// /// 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`). /// - enum Kind { + public enum Kind: Sendable { case login case onetimeLogin } - let kind: Kind - let user: String + public let kind: Kind + public let user: String /// /// The app password for ``Kind/login`` or the onetime token for ``Kind/onetimeLogin``. /// - let password: String - let host: URL + public let password: String + public let host: URL } /// @@ -59,14 +72,14 @@ extension QRCodeParsing { } /// - /// 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 +93,18 @@ 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) } } /// -/// 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) { +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 +125,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,18 +135,29 @@ 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 { + guard let user = decomposedKeyValuePairs["user"], user.isEmpty == false else { throw QRCodeError.missingUser } - guard let password = decomposedKeyValuePairs["password"] else { + guard let password = decomposedKeyValuePairs["password"], password.isEmpty == false else { 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..2d333f80 100644 --- a/Sources/NextcloudKitUI/Features/URLSanitizing.swift +++ b/Sources/NextcloudKitUI/Features/URLSanitizing.swift @@ -7,51 +7,54 @@ 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 { + /// + /// - 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) + + guard address.isEmpty == false else { return nil } - 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: "/").map(String.init) - // 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.joined(separator: "/") + + if components.path.hasSuffix("/") == false { + components.path += "/" } - return url + return components.url } } diff --git a/Sources/NextcloudKitUI/Localizable.xcstrings b/Sources/NextcloudKitUI/Localizable.xcstrings index 1092f8a8..27132112 100644 --- a/Sources/NextcloudKitUI/Localizable.xcstrings +++ b/Sources/NextcloudKitUI/Localizable.xcstrings @@ -11821,6 +11821,15 @@ } } }, + "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." + }, "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" : { @@ -11928,6 +11937,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/Views/Login/LoginFlowModel.swift b/Sources/NextcloudKitUI/Views/Login/LoginFlowModel.swift index 4550536b..d986e6b9 100644 --- a/Sources/NextcloudKitUI/Views/Login/LoginFlowModel.swift +++ b/Sources/NextcloudKitUI/Views/Login/LoginFlowModel.swift @@ -214,7 +214,7 @@ final class LoginFlowModel: QRCodeParsing, URLSanitizing { } } - private func exchangeOnetimeToken(_ credentials: ParsedLoginCredentials) { + private func exchangeOnetimeToken(_ credentials: LoginCredentials) { isActive = true Task { diff --git a/Tests/NextcloudKitUITests/LoginCallbackParserTests.swift b/Tests/NextcloudKitUITests/LoginCallbackParserTests.swift new file mode 100644 index 00000000..36b82daa --- /dev/null +++ b/Tests/NextcloudKitUITests/LoginCallbackParserTests.swift @@ -0,0 +1,57 @@ +// SPDX-FileCopyrightText: Nextcloud GmbH +// SPDX-FileCopyrightText: 2026 Milen Pivchev +// SPDX-License-Identifier: GPL-3.0-or-later + +import Foundation +@testable import NextcloudKitUI +import Testing + +/// +/// Tests for ``LoginCallbackParser``. +/// +struct LoginCallbackParserTests { + @Test func validCallback() async throws { + let url = try #require(URL(string: "nc://login/server:https://cloud.example.com&user:jane&password:secret")) + let credentials = try LoginCallbackParser.parse(url) + + #expect(credentials.kind == .login) + #expect(credentials.user == "jane") + #expect(credentials.password == "secret") + #expect(credentials.host.absoluteString == "https://cloud.example.com") + } + + @Test func serverPathIsKept() async throws { + let credentials = try LoginCallbackParser.parse("nc://login/server:https://cloud.example.com/nextcloud&user:jane&password:secret") + + #expect(credentials.host.absoluteString == "https://cloud.example.com/nextcloud") + } + + @Test func plusInUserIsSpace() async throws { + let credentials = try LoginCallbackParser.parse("nc://login/server:https://cloud.example.com&user:jane+doe&password:secret") + + #expect(credentials.user == "jane doe") + } + + @Test func percentEncodedValues() async throws { + let credentials = try LoginCallbackParser.parse("nc://login/server:https://cloud.example.com&user:jane%40example.com&password:se%2Bcret") + + #expect(credentials.user == "jane@example.com") + #expect(credentials.password == "se+cret") + } + + @Test func customScheme() async throws { + let callback = "abc://login/server:https://cloud.example.com&user:jane&password:secret" + + #expect(try LoginCallbackParser.parse(callback, scheme: "abc").user == "jane") + + #expect(throws: QRCodeError.invalidPrefix) { + try LoginCallbackParser.parse(callback) + } + } + + @Test func missingPassword() async throws { + #expect(throws: QRCodeError.missingPassword) { + try LoginCallbackParser.parse("nc://login/server:https://cloud.example.com&user:jane") + } + } +} 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/QRCodeParsingTests.swift b/Tests/NextcloudKitUITests/QRCodeParsingTests.swift index 791b82f2..d081c347 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 @@ -55,4 +56,42 @@ struct QRCodeParsingTests { try testSubject.parse("nc://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 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 customScheme() async throws { + let code = "abc://login/user:jane&password:secret&server:https://cloud.example.com" + + #expect(try testSubject.parseLogin(code, scheme: "abc").user == "jane") + + #expect(throws: QRCodeError.invalidPrefix) { + try testSubject.parseLogin(code) + } + } + + @Test func emptyValues() async throws { + #expect(throws: QRCodeError.missingUser) { + try testSubject.parseLogin("nc://login/user:&password:secret&server:https://cloud.example.com") + } + } + + @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..44cc17ee 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,45 @@ 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 func trimsWhitespaceAndNewlines() async throws { + let sanitized = try #require(testSubject.sanitize(" https://cloud.example.com \n")) + #expect(sanitized.absoluteString == "https://cloud.example.com/") + } + + @Test func lowercasesScheme() async throws { + let sanitized = try #require(testSubject.sanitize("HTTPS://cloud.example.com")) + #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/") + } } From e5cce445507ea7f20e9cc0ec6d031cb50a5857da Mon Sep 17 00:00:00 2001 From: Milen Pivchev Date: Thu, 19 Nov 2026 17:08:36 +0100 Subject: [PATCH 02/33] feat(NextcloudKitUI): configurable login flow for host apps ServerAddressView takes a LoginFlowConfiguration so apps with branding, managed configuration or their own certificate handling can adopt it: - Prefilled, read-only or picker-based server address, custom hint text and foreground color, optional cancel button. - onServerError hook to retry (e.g. after trusting a certificate or falling back to http), cancel or show the error. - Configurable callback scheme; a login page redirecting to it completes the login without waiting for the next poll. - AddAccountHandler is async throwing; the view stays busy until the host has added the account and shows a thrown error. - Polling survives network blips and ends after the token lifetime. - QR scanner closes on scan, has a flashlight and cancel button, and a denied camera permission offers Open Settings. - Accessibility identifiers for UI tests; the view can join an existing navigation stack. - SharedAccount optionally carries the login name. Existing callers keep compiling: the new parameter is defaulted and a synchronous closure still satisfies AddAccountHandler. Assisted-by: Claude Code:claude-opus-5-5 Co-Authored-By: Claude Opus 5.5 Signed-off-by: Milen Pivchev --- .../Documentation.docc/Documentation.md | 5 + Sources/NextcloudKitUI/Localizable.xcstrings | 21 + .../NextcloudKitUI/Models/SharedAccount.swift | 11 +- .../Modifiers/CodeScannerSheet.swift | 25 +- .../Views/Login/LoginFlowConfiguration.swift | 106 +++++ .../Views/Login/LoginFlowModel.swift | 122 +++++- .../Views/Login/ServerAddressView.swift | 381 ++++++++++++------ .../Views/Login/SharedAccountsView.swift | 7 +- .../LoginFlowModelTests.swift | 181 +++++++++ 9 files changed, 709 insertions(+), 150 deletions(-) create mode 100644 Sources/NextcloudKitUI/Views/Login/LoginFlowConfiguration.swift create mode 100644 Tests/NextcloudKitUITests/LoginFlowModelTests.swift diff --git a/Sources/NextcloudKitUI/Documentation.docc/Documentation.md b/Sources/NextcloudKitUI/Documentation.docc/Documentation.md index 366cfacd..c686a7ad 100644 --- a/Sources/NextcloudKitUI/Documentation.docc/Documentation.md +++ b/Sources/NextcloudKitUI/Documentation.docc/Documentation.md @@ -26,8 +26,13 @@ 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. + - ``ServerAddressView`` - ``AddAccountHandler`` +- ``LoginFlowConfiguration`` +- ``LoginCallbackParser`` +- ``LoginCredentials`` ### Account Menu diff --git a/Sources/NextcloudKitUI/Localizable.xcstrings b/Sources/NextcloudKitUI/Localizable.xcstrings index 27132112..ad63eb54 100644 --- a/Sources/NextcloudKitUI/Localizable.xcstrings +++ b/Sources/NextcloudKitUI/Localizable.xcstrings @@ -1788,6 +1788,9 @@ } } }, + "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.", "localizations" : { @@ -6057,6 +6060,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" : { @@ -7108,6 +7114,9 @@ } } }, + "Log in" : { + "comment" : "Accessibility label of the button which starts the login." + }, "Login Failed" : { "comment" : "Alert title", "localizations" : { @@ -7661,6 +7670,9 @@ } } }, + "Open Settings" : { + "comment" : "Button label in the login error alert which opens the system settings of the app." + }, "Participants" : { "comment" : "Label above the permission selector in the unified share view.", "localizations" : { @@ -9593,6 +9605,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" : { @@ -11607,6 +11622,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" : { @@ -11830,6 +11848,9 @@ "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" : { 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..0a876cc9 100644 --- a/Sources/NextcloudKitUI/Modifiers/CodeScannerSheet.swift +++ b/Sources/NextcloudKitUI/Modifiers/CodeScannerSheet.swift @@ -15,6 +15,7 @@ struct CodeScannerSheet: ViewModifier { @Environment(\.dismiss) private var dismiss @Binding var isPresentingCodeScanner: Bool + @State private var isTorchOn = false let completionHandler: (Result) -> Void init(isPresented: Binding, _ completionHandler: @escaping (Result) -> Void) { @@ -25,10 +26,32 @@ struct CodeScannerSheet: ViewModifier { func body(content: Content) -> some View { content.sheet(isPresented: $isPresentingCodeScanner) { NavigationStack { - CodeScannerView(codeTypes: [.qr], scanMode: .once, showViewfinder: true, completion: completionHandler) + CodeScannerView(codeTypes: [.qr], scanMode: .once, showViewfinder: true, isTorchOn: isTorchOn, completion: completionHandler) .ignoresSafeArea() .toolbarTitleDisplayMode(.inline) .navigationTitle(String(localized: "Scan QR Code", bundle: .module, comment: "Navigation bar title")) + .toolbar { + ToolbarItem(placement: .cancellationAction) { + Button { + isPresentingCodeScanner = false + } label: { + Text("Cancel", bundle: .module, comment: "Button label") + } + } + + 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") + } + } + .accessibilityIdentifier("toggleTorch") + } + } } } } diff --git a/Sources/NextcloudKitUI/Views/Login/LoginFlowConfiguration.swift b/Sources/NextcloudKitUI/Views/Login/LoginFlowConfiguration.swift new file mode 100644 index 00000000..bb5d107c --- /dev/null +++ b/Sources/NextcloudKitUI/Views/Login/LoginFlowConfiguration.swift @@ -0,0 +1,106 @@ +// 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 + } + } + + /// + /// How the login flow continues after the server check or the login flow request 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 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. + /// + public var enforcedServers: [Server] = [] + + /// + /// 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" + + /// + /// Set to `false` when the view is pushed onto an existing navigation stack, so its toolbar items join that navigation bar. + /// + public var embedsNavigationStack = true + + public var showsCancelButton = false + + /// + /// Called after the cancel button ended the login. 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? + + /// + /// Ends polling for the login result after this time. Matches the lifetime of a login flow token on the server. + /// + public var pollingTimeout: Duration = .seconds(20 * 60) + + public init() {} +} diff --git a/Sources/NextcloudKitUI/Views/Login/LoginFlowModel.swift b/Sources/NextcloudKitUI/Views/Login/LoginFlowModel.swift index d986e6b9..6a1a1609 100644 --- a/Sources/NextcloudKitUI/Views/Login/LoginFlowModel.swift +++ b/Sources/NextcloudKitUI/Views/Login/LoginFlowModel.swift @@ -19,22 +19,35 @@ import SwiftUI @MainActor @Observable final class LoginFlowModel: QRCodeParsing, URLSanitizing { + /// + /// An extra action offered by the error alert. + /// + enum AlertAction { + case openSettings + } + 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? + /// Extra action for the error alert. + var alertAction: AlertAction? + /// Whether an activity currently requires disabling the user interface. var isActive = false @@ -47,6 +60,7 @@ final class LoginFlowModel: QRCodeParsing, URLSanitizing { /// The login address acquired from the server through the login flow API. var loginAddress: URL? + private var startTask: Task? private var pollingTask: Task? // MARK: - Login flow @@ -55,15 +69,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,9 +86,12 @@ final class LoginFlowModel: QRCodeParsing, URLSanitizing { /// Check the server, request the login flow, present its web page and begin polling. /// func start(serverURL: URL) { + startTask?.cancel() + pollingTask?.cancel() + pollingTask = nil isActive = true - Task { + startTask = Task { do { let options = NKRequestOptions(customUserAgent: userAgent) @@ -85,18 +103,43 @@ final class LoginFlowModel: QRCodeParsing, URLSanitizing { let (endpoint, login, token) = try await NextcloudKit.shared.getLoginFlowV2(serverUrl: serverURL.absoluteString, options: options) + guard Task.isCancelled == false else { return } + startPolling(token: token, endpoint: endpoint) loginAddress = login isPresentingLoginPage = true } catch { - endLogin(error) + guard Task.isCancelled == false else { return } + + await recover(from: error, serverURL: serverURL) } } } + private func recover(from error: Error, serverURL: URL) async { + let nkError = error as? NKError ?? NKError(error: error) + + guard let onServerError = configuration.onServerError else { + endLogin(nkError) + return + } + + nkLog(error: "Login server check failed: \(nkError.logDescription)") + + switch await onServerError(nkError, serverURL) { + case .retry(let url): + enteredServerAddress = url.absoluteString + start(serverURL: url) + case .cancel: + cancel() + case .presentError: + endLogin(nkError) + } + } + private func startPolling(token: String, endpoint: URL) { - pollingTask?.cancel() + let deadline = ContinuousClock.now + configuration.pollingTimeout pollingTask = Task { [weak self] in guard let self else { return } @@ -104,8 +147,16 @@ final class LoginFlowModel: QRCodeParsing, URLSanitizing { let options = NKRequestOptions(customUserAgent: self.userAgent) while Task.isCancelled == false { + guard ContinuousClock.now < deadline else { + self.cancel() + self.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 + } + let poll = await NextcloudKit.shared.getLoginFlowV2PollAsync(token: token, endpoint: endpoint.absoluteString, options: options) + guard Task.isCancelled == false else { return } + if poll.error == .success, let server = poll.server, let host = URL(string: server), let loginName = poll.loginName, @@ -114,8 +165,10 @@ final class LoginFlowModel: QRCodeParsing, URLSanitizing { return } - // HTTP 404 means the flow is still pending; any other failure is terminal. - if poll.error != .success, poll.responseData?.response?.statusCode != 404 { + // HTTP 404 means the flow is still pending, as do network blips while the user is in the browser. + let isPending = poll.error == .success || poll.responseData?.response?.statusCode == 404 || LoginPollingPolicy.isTransient(poll.error) + + if isPending == false { self.endLogin(poll.error) return } @@ -127,7 +180,16 @@ final class LoginFlowModel: QRCodeParsing, URLSanitizing { 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? LoginCallbackParser.parse(callbackURL, scheme: configuration.loginURLScheme) else { + return + } + + pollingTask?.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,17 +202,33 @@ final class LoginFlowModel: QRCodeParsing, URLSanitizing { } } + /// + /// Hand the credentials to the host. The view stays busy until the host has added the account. + /// private func complete(host: URL, name: String, password: String) { pollingTask = nil - isActive = false isPresentingLoginPage = false - addAccount(host, name, password) + isActive = true + + // Not a child of the polling or presentation task, which end when the login page closes. + Task { + do { + try await addAccount(host, name, password) + } catch { + nkLog(error: "Adding the account failed: \(error)") + present(error: (error as? NKError)?.localizedGenericMessage ?? error.localizedDescription) + } + + 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() { + startTask?.cancel() + startTask = nil pollingTask?.cancel() pollingTask = nil isActive = false @@ -181,8 +259,9 @@ final class LoginFlowModel: QRCodeParsing, URLSanitizing { return error.localizedGenericMessage } - private func present(error: String?) { + private func present(error: String?, action: AlertAction? = nil) { errorMessage = error + alertAction = action isPresentingAlert = true } @@ -193,19 +272,21 @@ final class LoginFlowModel: QRCodeParsing, URLSanitizing { switch result { case .success(let result): handleLoginCode(result.string) - case .failure(let error): - present(error: error.localizedDescription) + case .failure(.permissionDenied): + present(error: 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."), action: .openSettings) + case .failure: + present(error: String(localized: "The camera is not available.", bundle: .module, comment: "Error message when the camera cannot be used to scan a login QR code.")) } } #endif func handleLoginCode(_ code: String) { do { - let credentials = try parseLogin(code) + let credentials = try parseLogin(code, scheme: configuration.loginURLScheme) 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) } @@ -220,11 +301,10 @@ final class LoginFlowModel: QRCodeParsing, URLSanitizing { 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 { + isActive = false nkLog(error: "One-time login failed: \(result.error.logDescription)") present(error: message(for: result.error)) } diff --git a/Sources/NextcloudKitUI/Views/Login/ServerAddressView.swift b/Sources/NextcloudKitUI/Views/Login/ServerAddressView.swift index 3f1e3930..62b4f4e9 100644 --- a/Sources/NextcloudKitUI/Views/Login/ServerAddressView.swift +++ b/Sources/NextcloudKitUI/Views/Login/ServerAddressView.swift @@ -9,9 +9,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 +20,25 @@ 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)) + self.configuration = configuration + self._model = State(initialValue: LoginFlowModel(userAgent: userAgent, configuration: configuration, addAccount: addAccount)) } // MARK: - Environment @@ -42,6 +46,7 @@ public struct ServerAddressView: View { @Environment(\.horizontalSizeClass) var horizontalSizeClass @Environment(\.verticalSizeClass) var verticalSizeClass @Environment(\.webAuthenticationSession) private var webAuthenticationSession + @Environment(\.openURL) private var openURL // MARK: - Bindings @@ -71,159 +76,268 @@ public struct ServerAddressView: View { /// @State private var isPresentingSharedAccounts = false + /// + /// The server picked from ``LoginFlowConfiguration/enforcedServers``. + /// + @State private var selectedServer: LoginFlowConfiguration.Server? + + private var foregroundColor: Color { + configuration.foregroundColor ?? backgroundColor.readable + } + // MARK: - Implementation public var body: some View { + if configuration.embedsNavigationStack { + NavigationStack { + content + } + } else { + content + } + } + + private var content: some View { @Bindable var model = model - return NavigationStack { - ZStack { - backgroundColor + return ZStack { + backgroundColor - VStack { - Spacer(minLength: 40) + 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) + 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 to add horizontal spacers for regular size classes. + // Container for the server address input and button. HStack { - if horizontalSizeClass == .regular { - Spacer(minLength: 100) + if configuration.enforcedServers.isEmpty { + serverAddressField + } else { + enforcedServersPicker } - // 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 { + if model.isActive { + ProgressView() + .progressViewStyle(.circular) + .tint(foregroundColor) + } else { + Button { 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) + } label: { + #if !os(macOS) + Image(systemName: "arrow.right") + #else + Image(systemName: "arrow.right.circle") + .font(.title) + .foregroundStyle(.white) #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) + #if os(macOS) + .buttonStyle(.plain) + #endif + .accessibilityLabel(Text("Log in", bundle: .module, comment: "Accessibility label of the button which starts the login.")) + .accessibilityIdentifier("submitServerAddress") } } + #if !os(macOS) + .padding(EdgeInsets(top: 8, leading: 10, bottom: 8, trailing: 10)) + .overlay( + RoundedRectangle(cornerRadius: 8) + .stroke(foregroundColor, lineWidth: 1) + ) + #endif - 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) + if horizontalSizeClass == .regular { + Spacer(minLength: 100) + } + } - Spacer() + Group { + if let serverAddressDescription = configuration.serverAddressDescription { + Text(verbatim: serverAddressDescription) + } else { + 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(foregroundColor) + .font(.footnote) + .multilineTextAlignment(.center) + .padding(4) - #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) + Spacer() - Text(String(localized: "Scan QR Code", bundle: .module, comment: "Button label")) - } - .padding() - .codeScannerSheet(isPresented: $isPresentingCodeScanner) { - model.handleQRCodeScan($0) - } - #endif + #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) - Spacer() + Text(String(localized: "Scan QR Code", bundle: .module, comment: "Button label")) } - .disabled(model.isActive) - .tint(backgroundColor.readable) .padding() - .safeAreaPadding(.all) + .accessibilityIdentifier("scanQRCode") + .codeScannerSheet(isPresented: $isPresentingCodeScanner) { result in + // Close the scanner first, so the host can present on top of this view. + isPresentingCodeScanner = false + model.handleQRCodeScan(result) + } + #endif + + Spacer() } - .ignoresSafeArea() - .toolbar { - if sharedAccounts.isEmpty == false { - if #available(iOS 26.0, macOS 26.0, *) { - sharedAccountsToolbarItem - .sharedBackgroundVisibility(.hidden) - } else { - sharedAccountsToolbarItem - } + .disabled(model.isActive) + .tint(foregroundColor) + .padding() + .safeAreaPadding(.all) + } + .ignoresSafeArea() + .toolbar { + if configuration.showsCancelButton { + cancelToolbarItem + } + + if sharedAccounts.isEmpty == false { + if #available(iOS 26.0, macOS 26.0, *) { + sharedAccountsToolbarItem + .sharedBackgroundVisibility(.hidden) + } else { + sharedAccountsToolbarItem } } + } + #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 + } + } + .task(id: model.isPresentingLoginPage) { + // Clearing the flag cancels this task, which closes the browser sheet. + guard model.isPresentingLoginPage, let loginAddress = model.loginAddress else { return } + + await model.presentLoginPage(loginAddress, using: webAuthenticationSession) + } + .alert(String(localized: "Login Failed", bundle: .module, comment: "Alert title"), isPresented: $model.isPresentingAlert) { #if os(iOS) - .toolbarBackground(.hidden, for: .navigationBar) + if model.alertAction == .openSettings { + Button { + model.errorMessage = nil + model.alertAction = nil + + 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.") + } + } #endif - .sharedAccountsSheet(isPresented: $isPresentingSharedAccounts, sharedAccounts: sharedAccounts, selectionHandler: { model.selectSharedAccount($0) }) - .onAppear { - if sharedAccounts.isEmpty == false && hasSuggestedSharedAccounts == false { - isPresentingSharedAccounts = true - hasSuggestedSharedAccounts = true + + Button(role: .cancel) { + model.errorMessage = nil + model.alertAction = nil + } label: { + Text("OK", bundle: .module, comment: "Button label for error alert dismissal.") + } + } message: { + Text(model.errorMessage ?? "?") + } + } + + private var serverAddressField: some View { + @Bindable var model = model + + return TextField( + text: $model.enteredServerAddress, + prompt: Text(verbatim: "https://example.org/").foregroundColor(foregroundColor.opacity(0.5)) + ) { + Text("Server Address", bundle: .module, comment: "Label for text field.") + } + .textContentType(.URL) + .autocorrectionDisabled() + #if os(iOS) + .foregroundStyle(foregroundColor) + .keyboardType(.URL) + .textInputAutocapitalization(.never) + .submitLabel(.done) + #endif + .onSubmit { + model.logIn() + } + .disabled(configuration.isServerAddressEditable == false) + .opacity(configuration.isServerAddressEditable ? 1 : 0.5) + .accessibilityIdentifier("serverAddress") + } + + private var enforcedServersPicker: some View { + Menu { + ForEach(configuration.enforcedServers) { server in + Button(server.name) { + selectedServer = server + model.enteredServerAddress = server.url.absoluteString } } - .task(id: model.isPresentingLoginPage) { - // Clearing the flag cancels this task, which closes the browser sheet. - guard model.isPresentingLoginPage, let loginAddress = model.loginAddress else { return } + } label: { + HStack { + Group { + if let selectedServer { + Text(verbatim: selectedServer.name) + } else if let enforcedServersPrompt = configuration.enforcedServersPrompt { + Text(verbatim: enforcedServersPrompt) + } else { + Text("Select a server", bundle: .module, comment: "Label of the server picker in the login view before a server was picked.") + } + } + .lineLimit(1) + + Spacer() - await model.presentLoginPage(loginAddress, using: webAuthenticationSession) + Image(systemName: "chevron.down") } - .alert(String(localized: "Login Failed", bundle: .module, comment: "Alert title"), isPresented: $model.isPresentingAlert) { - Button(role: .cancel) { - model.errorMessage = nil - } label: { - Text("OK", bundle: .module, comment: "Button label for error alert dismissal.") + .foregroundStyle(foregroundColor) + } + .accessibilityIdentifier("enforcedServers") + } + + private var cancelToolbarItem: some ToolbarContent { + ToolbarItem(placement: .cancellationAction) { + Button { + model.cancel() + configuration.onCancel?() + } label: { + Label { + Text("Cancel", bundle: .module, comment: "Button label") + } icon: { + Image(systemName: "xmark") } - } message: { - Text(model.errorMessage ?? "?") } + .tint(foregroundColor) + .disabled(model.isActive) + .accessibilityIdentifier("cancelLogin") } } @@ -241,7 +355,9 @@ public struct ServerAddressView: View { Image(systemName: "person.badge.plus") } } - .tint(backgroundColor.readable) + .tint(foregroundColor) + .disabled(model.isActive) + .accessibilityIdentifier("sharedAccounts") } } } @@ -264,7 +380,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 +388,19 @@ public struct ServerAddressView: View { } } +#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.showsCancelButton = true + + 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..0fb6e605 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) diff --git a/Tests/NextcloudKitUITests/LoginFlowModelTests.swift b/Tests/NextcloudKitUITests/LoginFlowModelTests.swift new file mode 100644 index 00000000..4b03aba8 --- /dev/null +++ b/Tests/NextcloudKitUITests/LoginFlowModelTests.swift @@ -0,0 +1,181 @@ +// 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 ``LoginFlowModel`` which need no Nextcloud server. +/// +@MainActor +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 addAccountError: Error? + weak var model: LoginFlowModel? + } + + 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.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 loginCodeAddsAccountWhileBusy() async throws { + let recorder = Recorder() + let model = makeModel(recorder: recorder) + + model.handleLoginCode("nc://login/user:jane&password:secret&server:https://cloud.example.com") + + 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 thrownAddAccountErrorIsPresented() async throws { + let recorder = Recorder() + let error = NKError(errorCode: 401) + recorder.addAccountError = error + let model = makeModel(recorder: recorder) + + model.handleLoginCode("nc://login/user:jane&password:secret&server:https://cloud.example.com") + + try await waitUntil { model.isPresentingAlert } + + #expect(model.errorMessage == error.localizedGenericMessage) + #expect(model.isActive == false) + } + + @Test func loginCodeUsesConfiguredScheme() async throws { + let recorder = Recorder() + var configuration = LoginFlowConfiguration() + configuration.loginURLScheme = "abc" + let model = makeModel(configuration: configuration, recorder: recorder) + + model.handleLoginCode("nc://login/user:jane&password:secret&server:https://cloud.example.com") + + #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 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/")!) // swiftlint:disable:this force_unwrapping + } + + 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) + } +} From 6519d639a12f8e7cb867f55d1a74c44aaad8c404 Mon Sep 17 00:00:00 2001 From: Milen Pivchev Date: Thu, 19 Nov 2026 17:11:20 +0100 Subject: [PATCH 03/33] fix(NextcloudKitUI): only hand server status failures to the host A failed login flow request after a reachable server check is shown directly, as an http fallback or certificate prompt would not help. Assisted-by: Claude Code:claude-opus-5-5 Co-Authored-By: Claude Opus 5.5 Signed-off-by: Milen Pivchev --- .../Views/Login/LoginFlowConfiguration.swift | 2 +- .../Views/Login/LoginFlowModel.swift | 29 ++++++++++--------- 2 files changed, 16 insertions(+), 15 deletions(-) diff --git a/Sources/NextcloudKitUI/Views/Login/LoginFlowConfiguration.swift b/Sources/NextcloudKitUI/Views/Login/LoginFlowConfiguration.swift index bb5d107c..394b6e8d 100644 --- a/Sources/NextcloudKitUI/Views/Login/LoginFlowConfiguration.swift +++ b/Sources/NextcloudKitUI/Views/Login/LoginFlowConfiguration.swift @@ -27,7 +27,7 @@ public struct LoginFlowConfiguration: Sendable { } /// - /// How the login flow continues after the server check or the login flow request failed. + /// 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`. diff --git a/Sources/NextcloudKitUI/Views/Login/LoginFlowModel.swift b/Sources/NextcloudKitUI/Views/Login/LoginFlowModel.swift index 6a1a1609..488c1ec7 100644 --- a/Sources/NextcloudKitUI/Views/Login/LoginFlowModel.swift +++ b/Sources/NextcloudKitUI/Views/Login/LoginFlowModel.swift @@ -92,15 +92,18 @@ final class LoginFlowModel: QRCodeParsing, URLSanitizing { isActive = true startTask = Task { - do { - let options = NKRequestOptions(customUserAgent: userAgent) + 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) - if case .failure(let error) = statusResult { - throw error - } + guard Task.isCancelled == false else { return } + + 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) guard Task.isCancelled == false else { return } @@ -112,29 +115,27 @@ final class LoginFlowModel: QRCodeParsing, URLSanitizing { } catch { guard Task.isCancelled == false else { return } - await recover(from: error, serverURL: serverURL) + endLogin(error) } } } - private func recover(from error: Error, serverURL: URL) async { - let nkError = error as? NKError ?? NKError(error: error) - + private func recover(from error: NKError, serverURL: URL) async { guard let onServerError = configuration.onServerError else { - endLogin(nkError) + endLogin(error) return } - nkLog(error: "Login server check failed: \(nkError.logDescription)") + nkLog(error: "Login server check failed: \(error.logDescription)") - switch await onServerError(nkError, serverURL) { + switch await onServerError(error, serverURL) { case .retry(let url): enteredServerAddress = url.absoluteString start(serverURL: url) case .cancel: cancel() case .presentError: - endLogin(nkError) + endLogin(error) } } From 058a7856b53f059205676f9e72e31c973e0ccd1d Mon Sep 17 00:00:00 2001 From: Milen Pivchev Date: Thu, 19 Nov 2026 19:28:26 +0100 Subject: [PATCH 04/33] fix(NextcloudKitUI): repair server addresses with a mistyped scheme "https:/host" and "https:host" were read as a host named "https". The scheme is now completed to "https://" before the address is parsed. Assisted-by: Claude Code:claude-opus-5-5 Co-Authored-By: Claude Opus 5.5 Signed-off-by: Milen Pivchev --- Sources/NextcloudKitUI/Features/URLSanitizing.swift | 6 ++++++ Tests/NextcloudKitUITests/URLSanitizingTests.swift | 10 ++++++++++ 2 files changed, 16 insertions(+) diff --git a/Sources/NextcloudKitUI/Features/URLSanitizing.swift b/Sources/NextcloudKitUI/Features/URLSanitizing.swift index 2d333f80..32944c0a 100644 --- a/Sources/NextcloudKitUI/Features/URLSanitizing.swift +++ b/Sources/NextcloudKitUI/Features/URLSanitizing.swift @@ -24,6 +24,12 @@ extension URLSanitizing { return nil } + // 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)://") + } + // Without a scheme, URLComponents reads "host" as a path and "host:8080" as a scheme. if address.hasPrefix("//") { address = "https:\(address)" diff --git a/Tests/NextcloudKitUITests/URLSanitizingTests.swift b/Tests/NextcloudKitUITests/URLSanitizingTests.swift index 44cc17ee..bab97aff 100644 --- a/Tests/NextcloudKitUITests/URLSanitizingTests.swift +++ b/Tests/NextcloudKitUITests/URLSanitizingTests.swift @@ -67,6 +67,16 @@ struct URLSanitizingTests { #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/") From b25f9b12c8c6ac1893deb432f6f283bb3927bbb6 Mon Sep 17 00:00:00 2001 From: Milen Pivchev Date: Thu, 19 Nov 2026 19:28:27 +0100 Subject: [PATCH 05/33] fix(NextcloudKitUI): allow cancelling the login until the account is added The cancel button was disabled for the whole login, so a slow server check could not be left. It is now only disabled while the host adds the account, and a cancel during the server error recovery is no longer overridden by its retry. Assisted-by: Claude Code:claude-opus-5-5 Co-Authored-By: Claude Opus 5.5 Signed-off-by: Milen Pivchev --- .../Views/Login/LoginFlowModel.swift | 14 +++++++++- .../Views/Login/ServerAddressView.swift | 2 +- .../LoginFlowModelTests.swift | 28 +++++++++++++++++++ 3 files changed, 42 insertions(+), 2 deletions(-) diff --git a/Sources/NextcloudKitUI/Views/Login/LoginFlowModel.swift b/Sources/NextcloudKitUI/Views/Login/LoginFlowModel.swift index 488c1ec7..91a0f077 100644 --- a/Sources/NextcloudKitUI/Views/Login/LoginFlowModel.swift +++ b/Sources/NextcloudKitUI/Views/Login/LoginFlowModel.swift @@ -51,6 +51,9 @@ final class LoginFlowModel: QRCodeParsing, URLSanitizing { /// 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 @@ -128,7 +131,12 @@ final class LoginFlowModel: QRCodeParsing, URLSanitizing { nkLog(error: "Login server check failed: \(error.logDescription)") - switch await onServerError(error, serverURL) { + let recovery = await onServerError(error, serverURL) + + // The user may have cancelled while the host was asking how to recover. + guard Task.isCancelled == false else { return } + + switch recovery { case .retry(let url): enteredServerAddress = url.absoluteString start(serverURL: url) @@ -210,6 +218,7 @@ final class LoginFlowModel: QRCodeParsing, URLSanitizing { pollingTask = nil isPresentingLoginPage = false isActive = true + isAddingAccount = true // Not a child of the polling or presentation task, which end when the login page closes. Task { @@ -220,6 +229,7 @@ final class LoginFlowModel: QRCodeParsing, URLSanitizing { present(error: (error as? NKError)?.localizedGenericMessage ?? error.localizedDescription) } + isAddingAccount = false isActive = false } } @@ -298,6 +308,7 @@ final class LoginFlowModel: QRCodeParsing, URLSanitizing { 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) @@ -305,6 +316,7 @@ final class LoginFlowModel: QRCodeParsing, URLSanitizing { if result.error == .success, let token = result.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)) diff --git a/Sources/NextcloudKitUI/Views/Login/ServerAddressView.swift b/Sources/NextcloudKitUI/Views/Login/ServerAddressView.swift index 62b4f4e9..1946aefb 100644 --- a/Sources/NextcloudKitUI/Views/Login/ServerAddressView.swift +++ b/Sources/NextcloudKitUI/Views/Login/ServerAddressView.swift @@ -336,7 +336,7 @@ public struct ServerAddressView: View { } } .tint(foregroundColor) - .disabled(model.isActive) + .disabled(model.isAddingAccount) .accessibilityIdentifier("cancelLogin") } } diff --git a/Tests/NextcloudKitUITests/LoginFlowModelTests.swift b/Tests/NextcloudKitUITests/LoginFlowModelTests.swift index 4b03aba8..3d1e534b 100644 --- a/Tests/NextcloudKitUITests/LoginFlowModelTests.swift +++ b/Tests/NextcloudKitUITests/LoginFlowModelTests.swift @@ -20,6 +20,7 @@ struct LoginFlowModelTests { var addedAccounts: [(host: URL, name: String, password: String)] = [] var serverErrors: [(error: NKError, url: URL)] = [] var isActiveDuringAddAccount: Bool? + var isAddingAccountDuringAddAccount: Bool? var addAccountError: Error? weak var model: LoginFlowModel? } @@ -27,6 +28,7 @@ struct LoginFlowModelTests { 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.addedAccounts.append((host, name, password)) if let error = recorder.addAccountError { @@ -95,6 +97,8 @@ struct LoginFlowModelTests { #expect(account.name == "jane") #expect(account.password == "secret") #expect(recorder.isActiveDuringAddAccount == true) + #expect(recorder.isAddingAccountDuringAddAccount == true) + #expect(model.isAddingAccount == false) #expect(model.isPresentingAlert == false) } @@ -178,4 +182,28 @@ struct LoginFlowModelTests { #expect(model.enteredServerAddress == "http://127.0.0.1:2/") #expect(model.isPresentingAlert == false) } + + @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/")!) // swiftlint:disable:this force_unwrapping + } + + 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) + } } From 0d142bd9ae7971f6b3f3f1a67c63fad5b9787ad6 Mon Sep 17 00:00:00 2001 From: Milen Pivchev Date: Mon, 23 Nov 2026 18:19:00 +0100 Subject: [PATCH 06/33] feat(NextcloudKitUI): keep the QR code scanner busy while its code logs in The scanner closed as soon as it read a code, so nothing showed that a login was in progress. It now stays open with a progress overlay, its buttons and swipe-to-close disabled, until the host has added the account. Errors are shown in the scanner, which then scans again; camera failures close it with the alert. Each code is read once, so a code that failed does not retry in a loop while it is still in view. The sheet moved out of the login form, so it no longer inherits the form's disabled state and brand tint. Assisted-by: Claude Code:claude-opus-5-5 Co-Authored-By: Claude Opus 5.5 Signed-off-by: Milen Pivchev --- Package.swift | 2 +- .../Modifiers/CodeScannerSheet.swift | 44 ++++++++---- .../Modifiers/LoginFlowAlert.swift | 47 ++++++++++++ .../Views/Login/LoginFlowModel.swift | 28 ++++++++ .../Views/Login/ServerAddressView.swift | 50 +++---------- .../LoginFlowModelTests.swift | 72 +++++++++++++++++++ 6 files changed, 188 insertions(+), 55 deletions(-) create mode 100644 Sources/NextcloudKitUI/Modifiers/LoginFlowAlert.swift 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/Modifiers/CodeScannerSheet.swift b/Sources/NextcloudKitUI/Modifiers/CodeScannerSheet.swift index 0a876cc9..4a2a397c 100644 --- a/Sources/NextcloudKitUI/Modifiers/CodeScannerSheet.swift +++ b/Sources/NextcloudKitUI/Modifiers/CodeScannerSheet.swift @@ -9,34 +9,45 @@ import SwiftUI /// /// 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 shows errors itself. /// struct CodeScannerSheet: ViewModifier { - @Environment(\.dismiss) private var dismiss - - @Binding var isPresentingCodeScanner: Bool + let model: LoginFlowModel @State private var isTorchOn = false - let completionHandler: (Result) -> Void - - init(isPresented: Binding, _ completionHandler: @escaping (Result) -> Void) { - self._isPresentingCodeScanner = isPresented - self.completionHandler = completionHandler - } func body(content: Content) -> some View { - content.sheet(isPresented: $isPresentingCodeScanner) { + @Bindable var model = model + + return content.sheet(isPresented: $model.isPresentingCodeScanner) { NavigationStack { - CodeScannerView(codeTypes: [.qr], scanMode: .once, showViewfinder: true, isTorchOn: isTorchOn, completion: completionHandler) + ZStack { + // Each code is read once, so one that did not work does not fail again while it is in view. + CodeScannerView(codeTypes: [.qr], scanMode: .oncePerCode, showViewfinder: true, isTorchOn: isTorchOn, isPaused: model.isActive || model.isPresentingAlert) { 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) .navigationTitle(String(localized: "Scan QR Code", bundle: .module, comment: "Navigation bar title")) .toolbar { ToolbarItem(placement: .cancellationAction) { Button { - isPresentingCodeScanner = false + model.isPresentingCodeScanner = false } label: { Text("Cancel", bundle: .module, comment: "Button label") } + .disabled(model.isActive) + .accessibilityIdentifier("cancelCodeScanner") } ToolbarItem(placement: .primaryAction) { @@ -49,10 +60,13 @@ struct CodeScannerSheet: ViewModifier { Image(systemName: isTorchOn ? "flashlight.on.fill" : "flashlight.off.fill") } } + .disabled(model.isActive) .accessibilityIdentifier("toggleTorch") } } } + .interactiveDismissDisabled(model.isActive) + .loginFlowAlert(model: model, isPresented: $model.isPresentingAlert) } } } @@ -63,8 +77,8 @@ 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)) } } diff --git a/Sources/NextcloudKitUI/Modifiers/LoginFlowAlert.swift b/Sources/NextcloudKitUI/Modifiers/LoginFlowAlert.swift new file mode 100644 index 00000000..c52a34b6 --- /dev/null +++ b/Sources/NextcloudKitUI/Modifiers/LoginFlowAlert.swift @@ -0,0 +1,47 @@ +// SPDX-FileCopyrightText: Nextcloud GmbH +// SPDX-FileCopyrightText: 2026 Milen Pivchev +// SPDX-License-Identifier: GPL-3.0-or-later + +import SwiftUI + +/// +/// The alert for errors of ``LoginFlowModel``, shown by the login view or the QR code scanner on top of it. +/// +struct LoginFlowAlert: ViewModifier { + @Environment(\.openURL) private var openURL + + let model: LoginFlowModel + @Binding var isPresented: Bool + + func body(content: Content) -> some View { + content.alert(String(localized: "Login Failed", bundle: .module, comment: "Alert title"), isPresented: $isPresented) { + #if os(iOS) + if model.alertAction == .openSettings { + Button { + model.dismissAlert() + + 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.") + } + } + #endif + + Button(role: .cancel) { + model.dismissAlert() + } label: { + Text("OK", bundle: .module, comment: "Button label for error alert dismissal.") + } + } message: { + Text(model.errorMessage ?? "?") + } + } +} + +extension View { + func loginFlowAlert(model: LoginFlowModel, isPresented: Binding) -> some View { + modifier(LoginFlowAlert(model: model, isPresented: isPresented)) + } +} diff --git a/Sources/NextcloudKitUI/Views/Login/LoginFlowModel.swift b/Sources/NextcloudKitUI/Views/Login/LoginFlowModel.swift index 91a0f077..08a48e90 100644 --- a/Sources/NextcloudKitUI/Views/Login/LoginFlowModel.swift +++ b/Sources/NextcloudKitUI/Views/Login/LoginFlowModel.swift @@ -60,6 +60,12 @@ final class LoginFlowModel: QRCodeParsing, URLSanitizing { /// 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 + + /// Whether the QR code scanner closes with the alert, because the camera cannot scan. + private var closesCodeScannerWithAlert = false + /// The login address acquired from the server through the login flow API. var loginAddress: URL? @@ -224,6 +230,7 @@ final class LoginFlowModel: QRCodeParsing, URLSanitizing { Task { do { try await addAccount(host, name, password) + isPresentingCodeScanner = false } catch { nkLog(error: "Adding the account failed: \(error)") present(error: (error as? NKError)?.localizedGenericMessage ?? error.localizedDescription) @@ -276,16 +283,37 @@ final class LoginFlowModel: QRCodeParsing, URLSanitizing { isPresentingAlert = true } + /// + /// Clear the alert, and close a QR code scanner that cannot scan. + /// + func dismissAlert() { + errorMessage = nil + alertAction = nil + isPresentingAlert = false + + if closesCodeScannerWithAlert { + isPresentingCodeScanner = false + closesCodeScannerWithAlert = false + } + } + // MARK: - QR code + func presentCodeScanner() { + closesCodeScannerWithAlert = false + isPresentingCodeScanner = true + } + #if os(iOS) func handleQRCodeScan(_ result: Result) { switch result { case .success(let result): handleLoginCode(result.string) case .failure(.permissionDenied): + closesCodeScannerWithAlert = true present(error: 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."), action: .openSettings) case .failure: + closesCodeScannerWithAlert = true present(error: String(localized: "The camera is not available.", bundle: .module, comment: "Error message when the camera cannot be used to scan a login QR code.")) } } diff --git a/Sources/NextcloudKitUI/Views/Login/ServerAddressView.swift b/Sources/NextcloudKitUI/Views/Login/ServerAddressView.swift index 1946aefb..acc3bef6 100644 --- a/Sources/NextcloudKitUI/Views/Login/ServerAddressView.swift +++ b/Sources/NextcloudKitUI/Views/Login/ServerAddressView.swift @@ -46,7 +46,6 @@ public struct ServerAddressView: View { @Environment(\.horizontalSizeClass) var horizontalSizeClass @Environment(\.verticalSizeClass) var verticalSizeClass @Environment(\.webAuthenticationSession) private var webAuthenticationSession - @Environment(\.openURL) private var openURL // MARK: - Bindings @@ -59,13 +58,6 @@ public struct ServerAddressView: View { /// @State private var model: LoginFlowModel - #if os(iOS) - /// - /// State toggle for presenting the QR code scanner sheet. - /// - @State private var isPresentingCodeScanner = false - #endif - /// /// State toggle whether the shared accounts have been suggested once during lifetime of this view. /// @@ -185,7 +177,7 @@ public struct ServerAddressView: View { #if os(iOS) // Camera usually is available on iOS devices only. Button { - isPresentingCodeScanner = true + model.presentCodeScanner() } label: { Image(systemName: "qrcode.viewfinder") .resizable() @@ -196,11 +188,6 @@ public struct ServerAddressView: View { } .padding() .accessibilityIdentifier("scanQRCode") - .codeScannerSheet(isPresented: $isPresentingCodeScanner) { result in - // Close the scanner first, so the host can present on top of this view. - isPresentingCodeScanner = false - model.handleQRCodeScan(result) - } #endif Spacer() @@ -229,6 +216,10 @@ public struct ServerAddressView: View { .toolbarBackground(.hidden, for: .navigationBar) #endif .sharedAccountsSheet(isPresented: $isPresentingSharedAccounts, sharedAccounts: sharedAccounts, selectionHandler: { model.selectSharedAccount($0) }) + #if os(iOS) + // Outside the form, whose disabled state and brand tint would carry over into the sheet and its alert. + .codeScannerSheet(model: model) + #endif .onAppear { if sharedAccounts.isEmpty == false && hasSuggestedSharedAccounts == false { isPresentingSharedAccounts = true @@ -241,31 +232,12 @@ public struct ServerAddressView: View { await model.presentLoginPage(loginAddress, using: webAuthenticationSession) } - .alert(String(localized: "Login Failed", bundle: .module, comment: "Alert title"), isPresented: $model.isPresentingAlert) { - #if os(iOS) - if model.alertAction == .openSettings { - Button { - model.errorMessage = nil - model.alertAction = nil - - 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.") - } - } - #endif - - Button(role: .cancel) { - model.errorMessage = nil - model.alertAction = nil - } label: { - Text("OK", bundle: .module, comment: "Button label for error alert dismissal.") - } - } message: { - Text(model.errorMessage ?? "?") - } + // The QR code scanner shows its own errors while it is open. + .loginFlowAlert(model: model, isPresented: Binding { + model.isPresentingAlert && model.isPresentingCodeScanner == false + } set: { + model.isPresentingAlert = $0 + }) } private var serverAddressField: some View { diff --git a/Tests/NextcloudKitUITests/LoginFlowModelTests.swift b/Tests/NextcloudKitUITests/LoginFlowModelTests.swift index 3d1e534b..6a61c6b1 100644 --- a/Tests/NextcloudKitUITests/LoginFlowModelTests.swift +++ b/Tests/NextcloudKitUITests/LoginFlowModelTests.swift @@ -2,6 +2,9 @@ // SPDX-FileCopyrightText: 2026 Milen Pivchev // SPDX-License-Identifier: GPL-3.0-or-later +#if os(iOS) +import CodeScanner +#endif import Foundation import NextcloudKit @testable import NextcloudKitUI @@ -10,7 +13,10 @@ 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. @@ -21,6 +27,7 @@ struct LoginFlowModelTests { var serverErrors: [(error: NKError, url: URL)] = [] var isActiveDuringAddAccount: Bool? var isAddingAccountDuringAddAccount: Bool? + var isPresentingCodeScannerDuringAddAccount: Bool? var addAccountError: Error? weak var model: LoginFlowModel? } @@ -29,6 +36,7 @@ struct LoginFlowModelTests { 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 { @@ -183,6 +191,70 @@ struct LoginFlowModelTests { #expect(model.isPresentingAlert == false) } + @Test func scannedCodeKeepsScannerOpenUntilAccountIsAdded() async throws { + let recorder = Recorder() + let model = makeModel(recorder: recorder) + + model.presentCodeScanner() + model.handleLoginCode("nc://login/user:jane&password:secret&server:https://cloud.example.com") + + try await waitUntil { recorder.addedAccounts.count == 1 && model.isActive == false } + + #expect(recorder.isPresentingCodeScannerDuringAddAccount == true) + #expect(model.isPresentingCodeScanner == false) + #expect(model.isPresentingAlert == false) + } + + @Test func invalidScannedCodeShowsErrorAndKeepsScanning() async throws { + let model = makeModel(recorder: Recorder()) + + model.presentCodeScanner() + model.handleLoginCode("https://cloud.example.com") + + #expect(model.isPresentingAlert) + #expect(model.isPresentingCodeScanner) + + model.dismissAlert() + + #expect(model.isPresentingAlert == false) + #expect(model.errorMessage == nil) + #expect(model.isPresentingCodeScanner) + } + + @Test func failedLoginFromScannedCodeShowsErrorInScanner() async throws { + let recorder = Recorder() + recorder.addAccountError = NKError(errorCode: 401) + let model = makeModel(recorder: recorder) + + model.presentCodeScanner() + model.handleLoginCode("nc://login/user:jane&password:secret&server:https://cloud.example.com") + + try await waitUntil { model.isPresentingAlert } + + #expect(model.isPresentingCodeScanner) + #expect(model.isActive == false) + + model.dismissAlert() + + #expect(model.isPresentingCodeScanner) + } + + #if os(iOS) + @Test func cameraFailureClosesScannerWithAlert() async throws { + let model = makeModel(recorder: Recorder()) + + model.presentCodeScanner() + model.handleQRCodeScan(.failure(.permissionDenied)) + + #expect(model.isPresentingAlert) + #expect(model.alertAction == .openSettings) + + model.dismissAlert() + + #expect(model.isPresentingCodeScanner == false) + } + #endif + @Test func cancelWhileRecoveringStopsTheLogin() async throws { let recorder = Recorder() var configuration = LoginFlowConfiguration() From 0a52286bafab394db1a5ed677c3d1b44a783cb46 Mon Sep 17 00:00:00 2001 From: Milen Pivchev Date: Tue, 24 Nov 2026 00:23:39 +0100 Subject: [PATCH 07/33] fix(NextcloudKitUI): keep the QR code scanner bar readable over the camera The camera preview runs under the scanner's navigation bar, so on a device its title and buttons could disappear against the dark image. The bar now has its own background. Assisted-by: Claude Code:claude-opus-5-5 Co-Authored-By: Claude Opus 5.5 Signed-off-by: Milen Pivchev --- Sources/NextcloudKitUI/Modifiers/CodeScannerSheet.swift | 2 ++ 1 file changed, 2 insertions(+) diff --git a/Sources/NextcloudKitUI/Modifiers/CodeScannerSheet.swift b/Sources/NextcloudKitUI/Modifiers/CodeScannerSheet.swift index 4a2a397c..910ace89 100644 --- a/Sources/NextcloudKitUI/Modifiers/CodeScannerSheet.swift +++ b/Sources/NextcloudKitUI/Modifiers/CodeScannerSheet.swift @@ -38,6 +38,8 @@ struct CodeScannerSheet: ViewModifier { } .ignoresSafeArea() .toolbarTitleDisplayMode(.inline) + // The camera preview runs under the bar, which keeps its title and buttons readable only with a background. + .toolbarBackground(.visible, for: .navigationBar) .navigationTitle(String(localized: "Scan QR Code", bundle: .module, comment: "Navigation bar title")) .toolbar { ToolbarItem(placement: .cancellationAction) { From b9392b1067412ab1184bea557e8971df26ad607b Mon Sep 17 00:00:00 2001 From: Milen Pivchev Date: Tue, 24 Nov 2026 10:21:34 +0100 Subject: [PATCH 08/33] fix(NextcloudKitUI): say no server was found when adding the account gets a 404 A 404 while adding the account showed "The file or folder could not be found on the server." It now uses the login's own "No server was found at this address.", while an unreadable reply keeps the generic text, as it can come from a proxy in front of a server that exists. Assisted-by: Claude Code:claude-opus-5-5 Co-Authored-By: Claude Opus 5.5 Signed-off-by: Milen Pivchev --- .../Views/Login/LoginFlowModel.swift | 7 +++--- .../LoginFlowModelTests.swift | 24 +++++++++++++++++++ 2 files changed, 28 insertions(+), 3 deletions(-) diff --git a/Sources/NextcloudKitUI/Views/Login/LoginFlowModel.swift b/Sources/NextcloudKitUI/Views/Login/LoginFlowModel.swift index 08a48e90..e180ea10 100644 --- a/Sources/NextcloudKitUI/Views/Login/LoginFlowModel.swift +++ b/Sources/NextcloudKitUI/Views/Login/LoginFlowModel.swift @@ -233,7 +233,7 @@ final class LoginFlowModel: QRCodeParsing, URLSanitizing { isPresentingCodeScanner = false } catch { nkLog(error: "Adding the account failed: \(error)") - present(error: (error as? NKError)?.localizedGenericMessage ?? error.localizedDescription) + present(error: (error as? NKError).map { message(for: $0, whileAddingAccount: true) } ?? error.localizedDescription) } isAddingAccount = false @@ -266,9 +266,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.") diff --git a/Tests/NextcloudKitUITests/LoginFlowModelTests.swift b/Tests/NextcloudKitUITests/LoginFlowModelTests.swift index 6a61c6b1..7c1de904 100644 --- a/Tests/NextcloudKitUITests/LoginFlowModelTests.swift +++ b/Tests/NextcloudKitUITests/LoginFlowModelTests.swift @@ -124,6 +124,30 @@ struct LoginFlowModelTests { #expect(model.isActive == false) } + @Test func addAccountFailureWording() async throws { + let notFound = NKError(errorCode: 404) + let invalidResponse = NKError.invalidResponseError + + let notFoundMessage = try await addAccountMessage(for: notFound) + let invalidResponseMessage = try await addAccountMessage(for: invalidResponse) + + // 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("nc://login/user:jane&password:secret&server:https://cloud.example.com") + + try await waitUntil { model.isPresentingAlert } + + return model.errorMessage + } + @Test func loginCodeUsesConfiguredScheme() async throws { let recorder = Recorder() var configuration = LoginFlowConfiguration() From db33986b6b62d7f1c25ab7466d8ae92b23764597 Mon Sep 17 00:00:00 2001 From: Milen Pivchev Date: Tue, 24 Nov 2026 11:28:23 +0100 Subject: [PATCH 09/33] feat(NextcloudKitUI): let the host start the login when the view appears LoginFlowConfiguration.startsLoginOnAppear starts the login for the initial server address once, as soon as the view appears, and skips the shared accounts suggestion. A host uses it for a server the user just signed up on but whose sign-up credentials don't work. Off by default. Assisted-by: Claude Code:claude-opus-5-5 Co-Authored-By: Claude Opus 5.5 Signed-off-by: Milen Pivchev --- .../Views/Login/LoginFlowConfiguration.swift | 5 +++ .../Views/Login/LoginFlowModel.swift | 12 +++++++ .../Views/Login/ServerAddressView.swift | 5 ++- .../LoginFlowModelTests.swift | 31 +++++++++++++++++++ 4 files changed, 52 insertions(+), 1 deletion(-) diff --git a/Sources/NextcloudKitUI/Views/Login/LoginFlowConfiguration.swift b/Sources/NextcloudKitUI/Views/Login/LoginFlowConfiguration.swift index 394b6e8d..2909af40 100644 --- a/Sources/NextcloudKitUI/Views/Login/LoginFlowConfiguration.swift +++ b/Sources/NextcloudKitUI/Views/Login/LoginFlowConfiguration.swift @@ -63,6 +63,11 @@ public struct LoginFlowConfiguration: Sendable { /// public var initialServerAddress: String? + /// + /// Starts the login for ``initialServerAddress`` when the view appears, e.g. for a server the user just signed up on. + /// + public var startsLoginOnAppear = false + public var isServerAddressEditable = true /// diff --git a/Sources/NextcloudKitUI/Views/Login/LoginFlowModel.swift b/Sources/NextcloudKitUI/Views/Login/LoginFlowModel.swift index e180ea10..10c37f34 100644 --- a/Sources/NextcloudKitUI/Views/Login/LoginFlowModel.swift +++ b/Sources/NextcloudKitUI/Views/Login/LoginFlowModel.swift @@ -66,6 +66,8 @@ final class LoginFlowModel: QRCodeParsing, URLSanitizing { /// Whether the QR code scanner closes with the alert, because the camera cannot scan. private var closesCodeScannerWithAlert = false + private var hasStartedLoginOnAppear = false + /// The login address acquired from the server through the login flow API. var loginAddress: URL? @@ -91,6 +93,16 @@ final class LoginFlowModel: QRCodeParsing, URLSanitizing { start(serverURL: sanitizedServerAddress) } + /// + /// Start the login once, when ``LoginFlowConfiguration/startsLoginOnAppear`` asks for it. + /// + func startLoginOnAppear() { + guard configuration.startsLoginOnAppear, hasStartedLoginOnAppear == false else { return } + + hasStartedLoginOnAppear = true + logIn() + } + /// /// Check the server, request the login flow, present its web page and begin polling. /// diff --git a/Sources/NextcloudKitUI/Views/Login/ServerAddressView.swift b/Sources/NextcloudKitUI/Views/Login/ServerAddressView.swift index acc3bef6..fbb678ef 100644 --- a/Sources/NextcloudKitUI/Views/Login/ServerAddressView.swift +++ b/Sources/NextcloudKitUI/Views/Login/ServerAddressView.swift @@ -221,7 +221,10 @@ public struct ServerAddressView: View { .codeScannerSheet(model: model) #endif .onAppear { - if sharedAccounts.isEmpty == false && hasSuggestedSharedAccounts == false { + model.startLoginOnAppear() + + // Not on top of a login that started by itself. + if configuration.startsLoginOnAppear == false && sharedAccounts.isEmpty == false && hasSuggestedSharedAccounts == false { isPresentingSharedAccounts = true hasSuggestedSharedAccounts = true } diff --git a/Tests/NextcloudKitUITests/LoginFlowModelTests.swift b/Tests/NextcloudKitUITests/LoginFlowModelTests.swift index 7c1de904..ece9ecdf 100644 --- a/Tests/NextcloudKitUITests/LoginFlowModelTests.swift +++ b/Tests/NextcloudKitUITests/LoginFlowModelTests.swift @@ -71,6 +71,37 @@ struct LoginFlowModelTests { #expect(model.enteredServerAddress == "https://cloud.example.com") } + @Test func startsLoginOnAppearOnceWhenConfigured() async throws { + var configuration = LoginFlowConfiguration() + configuration.initialServerAddress = "http://127.0.0.1:1" + configuration.startsLoginOnAppear = true + + let model = makeModel(configuration: configuration, recorder: Recorder()) + + model.startLoginOnAppear() + + #expect(model.isActive) + + // Nothing listens on port 1, so the login ends with an error right away. + try await waitUntil { model.isPresentingAlert } + + model.dismissAlert() + model.startLoginOnAppear() + + #expect(model.isActive == false) + } + + @Test func doesNotStartLoginOnAppearByDefault() async throws { + var configuration = LoginFlowConfiguration() + configuration.initialServerAddress = "https://cloud.example.com" + + let model = makeModel(configuration: configuration, recorder: Recorder()) + + model.startLoginOnAppear() + + #expect(model.isActive == false) + } + @Test func emptyAddressDoesNothing() async throws { let model = makeModel(recorder: Recorder()) model.enteredServerAddress = " " From d8480d0248fea6cb9c98b1b0fa207c29f17c90c9 Mon Sep 17 00:00:00 2001 From: Milen Pivchev Date: Tue, 24 Nov 2026 15:55:24 +0100 Subject: [PATCH 10/33] feat(NextcloudKitUI): identify the onboarding button for UI tests Assisted-by: Claude Code:claude-opus-5-5 Co-Authored-By: Claude Opus 5.5 Signed-off-by: Milen Pivchev --- Sources/NextcloudKitUI/Views/Onboarding/OnboardingView.swift | 1 + 1 file changed, 1 insertion(+) diff --git a/Sources/NextcloudKitUI/Views/Onboarding/OnboardingView.swift b/Sources/NextcloudKitUI/Views/Onboarding/OnboardingView.swift index c4d64879..47dd3b91 100644 --- a/Sources/NextcloudKitUI/Views/Onboarding/OnboardingView.swift +++ b/Sources/NextcloudKitUI/Views/Onboarding/OnboardingView.swift @@ -106,6 +106,7 @@ public struct OnboardingView: View { .buttonStyle(.borderedProminent) .controlSize(.large) .tint(tint) + .accessibilityIdentifier("continueOnboarding") .padding(.horizontal, horizontalPadding) .padding(.vertical) .frame(maxWidth: 520) From 179bd65b30dc0ff66e3820422f3b2c0ab2c3ff03 Mon Sep 17 00:00:00 2001 From: Milen Pivchev Date: Tue, 24 Nov 2026 15:55:25 +0100 Subject: [PATCH 11/33] feat(NextcloudKitUI): add the provider sign-up page A web view that sends the OCS API header with every page load, shows load errors with a retry, and reports the login callback URL the sign-up ends on. Ported from the Files app. Assisted-by: Claude Code:claude-opus-5-5 Co-Authored-By: Claude Opus 5.5 Signed-off-by: Milen Pivchev --- .../Views/Login/ProviderSignUpModel.swift | 285 ++++++++++++++++++ .../Views/Login/ProviderSignUpView.swift | 56 ++++ .../NextcloudKitUI/Views/Login/WebView.swift | 14 + .../ProviderSignUpModelTests.swift | 142 +++++++++ 4 files changed, 497 insertions(+) create mode 100644 Sources/NextcloudKitUI/Views/Login/ProviderSignUpModel.swift create mode 100644 Sources/NextcloudKitUI/Views/Login/ProviderSignUpView.swift create mode 100644 Tests/NextcloudKitUITests/ProviderSignUpModelTests.swift diff --git a/Sources/NextcloudKitUI/Views/Login/ProviderSignUpModel.swift b/Sources/NextcloudKitUI/Views/Login/ProviderSignUpModel.swift new file mode 100644 index 00000000..7573c340 --- /dev/null +++ b/Sources/NextcloudKitUI/Views/Login/ProviderSignUpModel.swift @@ -0,0 +1,285 @@ +// SPDX-FileCopyrightText: Nextcloud GmbH +// SPDX-FileCopyrightText: 2026 Milen Pivchev +// SPDX-License-Identifier: GPL-3.0-or-later + +#if os(iOS) + +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? + + @ObservationIgnored private let callbackScheme: String + @ObservationIgnored private let onCallback: @MainActor (URL) -> Void + @ObservationIgnored private var loadingObservation: 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) + + if let userAgent { + webView.customUserAgent = userAgent + } + + super.init() + + webView.navigationDelegate = self + + loadingObservation = webView.observe(\.isLoading, options: [.initial, .new]) { [weak self] webView, _ in + MainActor.assumeIsolated { + self?.isLoading = webView.isLoading + } + } + } + + // 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 pageDidFinish() { + reissuedURLs.removeAll() + hasReloadedAfterTermination = false + } + + func webContentProcessDidTerminate() { + // 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)) + } + + 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, didReceiveServerRedirectForProvisionalNavigation navigation: WKNavigation!) { + guard let url = webView.url, url.scheme?.lowercased() == callbackScheme else { return } + + finish(callbackURL: url) + } + + func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!) { + pageDidFinish() + } + + 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) { + webContentProcessDidTerminate() + } +} + +#endif diff --git a/Sources/NextcloudKitUI/Views/Login/ProviderSignUpView.swift b/Sources/NextcloudKitUI/Views/Login/ProviderSignUpView.swift new file mode 100644 index 00000000..47e9ed56 --- /dev/null +++ b/Sources/NextcloudKitUI/Views/Login/ProviderSignUpView.swift @@ -0,0 +1,56 @@ +// SPDX-FileCopyrightText: Nextcloud GmbH +// SPDX-FileCopyrightText: 2026 Milen Pivchev +// SPDX-License-Identifier: GPL-3.0-or-later + +#if os(iOS) + +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 { + ZStack { + WebView(webView: model.webView) + + 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") + } + } + } + .onAppear { + model.start() + } + } +} + +#endif diff --git a/Sources/NextcloudKitUI/Views/Login/WebView.swift b/Sources/NextcloudKitUI/Views/Login/WebView.swift index d1edb6f7..8fa9498d 100644 --- a/Sources/NextcloudKitUI/Views/Login/WebView.swift +++ b/Sources/NextcloudKitUI/Views/Login/WebView.swift @@ -21,12 +21,26 @@ public struct WebView: ViewRepresentable { 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 { + if let webView { + return webView + } + let configuration = WKWebViewConfiguration() configuration.websiteDataStore = .nonPersistent() diff --git a/Tests/NextcloudKitUITests/ProviderSignUpModelTests.swift b/Tests/NextcloudKitUITests/ProviderSignUpModelTests.swift new file mode 100644 index 00000000..cbf62128 --- /dev/null +++ b/Tests/NextcloudKitUITests/ProviderSignUpModelTests.swift @@ -0,0 +1,142 @@ +// SPDX-FileCopyrightText: Nextcloud GmbH +// SPDX-FileCopyrightText: 2026 Milen Pivchev +// SPDX-License-Identifier: GPL-3.0-or-later + +#if os(iOS) + +import Foundation +import NextcloudKit +@testable import NextcloudKitUI +import Testing + +/// +/// 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")! // swiftlint:disable:this force_unwrapping + private let pageURL = URL(string: "https://provider.example.com/register")! // swiftlint:disable:this force_unwrapping + + 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")! // swiftlint:disable:this force_unwrapping + + #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")! // swiftlint:disable:this force_unwrapping + + #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.pageDidFinish() + + #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")! // swiftlint:disable:this force_unwrapping + let blank = URL(string: "about:blank")! // swiftlint:disable:this force_unwrapping + + #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.webContentProcessDidTerminate() + + #expect(model.errorMessage == nil) + + model.webContentProcessDidTerminate() + + #expect(model.errorMessage != nil) + + model.pageDidFinish() + model.webContentProcessDidTerminate() + + #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) + } +} + +#endif From cc11e003d22a62cbf1f3dafb3bc98ba2363a8753 Mon Sep 17 00:00:00 2001 From: Milen Pivchev Date: Tue, 24 Nov 2026 15:55:26 +0100 Subject: [PATCH 12/33] feat(NextcloudKitUI): offer provider sign-up and hosting information on the login screen Both are optional links in the design of the Scan QR Code button. The sign-up result adds the account like a login QR code; when the server refuses its credentials, the login starts again for that server. The form scrolls where it does not fit, such as on phones in landscape. Assisted-by: Claude Code:claude-opus-5-5 Co-Authored-By: Claude Opus 5.5 Signed-off-by: Milen Pivchev --- .../Documentation.docc/Documentation.md | 2 +- .../Views/Login/LoginFlowConfiguration.swift | 23 ++ .../Views/Login/LoginFlowModel.swift | 52 +++- .../Views/Login/ServerAddressView.swift | 254 +++++++++++------- .../LoginFlowModelTests.swift | 65 +++++ 5 files changed, 294 insertions(+), 102 deletions(-) diff --git a/Sources/NextcloudKitUI/Documentation.docc/Documentation.md b/Sources/NextcloudKitUI/Documentation.docc/Documentation.md index c686a7ad..0a7f6cd7 100644 --- a/Sources/NextcloudKitUI/Documentation.docc/Documentation.md +++ b/Sources/NextcloudKitUI/Documentation.docc/Documentation.md @@ -26,7 +26,7 @@ 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. +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`` diff --git a/Sources/NextcloudKitUI/Views/Login/LoginFlowConfiguration.swift b/Sources/NextcloudKitUI/Views/Login/LoginFlowConfiguration.swift index 2909af40..83064d74 100644 --- a/Sources/NextcloudKitUI/Views/Login/LoginFlowConfiguration.swift +++ b/Sources/NextcloudKitUI/Views/Login/LoginFlowConfiguration.swift @@ -26,6 +26,19 @@ public struct LoginFlowConfiguration: Sendable { } } + /// + /// 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. /// @@ -75,6 +88,16 @@ public struct LoginFlowConfiguration: Sendable { /// public var enforcedServers: [Server] = [] + /// + /// A provider's sign-up page, which must end on the login callback URL with ``loginURLScheme``. iOS only. + /// + 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`. /// diff --git a/Sources/NextcloudKitUI/Views/Login/LoginFlowModel.swift b/Sources/NextcloudKitUI/Views/Login/LoginFlowModel.swift index 10c37f34..0a8efb19 100644 --- a/Sources/NextcloudKitUI/Views/Login/LoginFlowModel.swift +++ b/Sources/NextcloudKitUI/Views/Login/LoginFlowModel.swift @@ -232,7 +232,9 @@ final class LoginFlowModel: QRCodeParsing, URLSanitizing { /// /// Hand the credentials to the host. The view stays busy until the host has added the account. /// - private func complete(host: URL, name: String, password: String) { + /// - 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) { pollingTask = nil isPresentingLoginPage = false isActive = true @@ -243,6 +245,14 @@ final class LoginFlowModel: QRCodeParsing, URLSanitizing { 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) @@ -365,6 +375,46 @@ final class LoginFlowModel: QRCodeParsing, URLSanitizing { } } + // MARK: - Provider sign-up + + #if os(iOS) + /// 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 LoginCallbackParser.parse(callbackURL, scheme: configuration.loginURLScheme) + + // 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) + } + } + #endif + // MARK: - Shared accounts func selectSharedAccount(_ account: SharedAccount) { diff --git a/Sources/NextcloudKitUI/Views/Login/ServerAddressView.swift b/Sources/NextcloudKitUI/Views/Login/ServerAddressView.swift index fbb678ef..026d7d7e 100644 --- a/Sources/NextcloudKitUI/Views/Login/ServerAddressView.swift +++ b/Sources/NextcloudKitUI/Views/Login/ServerAddressView.swift @@ -46,6 +46,7 @@ public struct ServerAddressView: View { @Environment(\.horizontalSizeClass) var horizontalSizeClass @Environment(\.verticalSizeClass) var verticalSizeClass @Environment(\.webAuthenticationSession) private var webAuthenticationSession + @Environment(\.openURL) private var openURL // MARK: - Bindings @@ -95,107 +96,14 @@ public struct ServerAddressView: View { return ZStack { backgroundColor - VStack { - Spacer(minLength: 40) - - 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: { - #if !os(macOS) - Image(systemName: "arrow.right") - #else - Image(systemName: "arrow.right.circle") - .font(.title) - .foregroundStyle(.white) - #endif - } - #if os(macOS) - .buttonStyle(.plain) - #endif - .accessibilityLabel(Text("Log in", bundle: .module, comment: "Accessibility label of the button which starts the login.")) - .accessibilityIdentifier("submitServerAddress") - } - } - #if !os(macOS) - .padding(EdgeInsets(top: 8, leading: 10, bottom: 8, trailing: 10)) - .overlay( - RoundedRectangle(cornerRadius: 8) - .stroke(foregroundColor, lineWidth: 1) - ) - #endif - - if horizontalSizeClass == .regular { - Spacer(minLength: 100) - } + // Scrolls only where the form does not fit, such as on small phones in landscape. + GeometryReader { proxy in + ScrollView { + form + .frame(minHeight: proxy.size.height) } - - Group { - if let serverAddressDescription = configuration.serverAddressDescription { - Text(verbatim: serverAddressDescription) - } else { - 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(foregroundColor) - .font(.footnote) - .multilineTextAlignment(.center) - .padding(4) - - Spacer() - - #if os(iOS) // Camera usually is available on iOS devices only. - Button { - model.presentCodeScanner() - } label: { - Image(systemName: "qrcode.viewfinder") - .resizable() - .scaledToFit() - .frame(width: 32, height: 32) - - Text(String(localized: "Scan QR Code", bundle: .module, comment: "Button label")) - } - .padding() - .accessibilityIdentifier("scanQRCode") - #endif - - Spacer() + .scrollBounceBehavior(.basedOnSize) } - .disabled(model.isActive) - .tint(foregroundColor) - .padding() - .safeAreaPadding(.all) } .ignoresSafeArea() .toolbar { @@ -217,8 +125,13 @@ public struct ServerAddressView: View { #endif .sharedAccountsSheet(isPresented: $isPresentingSharedAccounts, sharedAccounts: sharedAccounts, selectionHandler: { model.selectSharedAccount($0) }) #if os(iOS) - // Outside the form, whose disabled state and brand tint would carry over into the sheet and its alert. + // 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) + } #endif .onAppear { model.startLoginOnAppear() @@ -243,6 +156,137 @@ public struct ServerAddressView: View { }) } + private var form: some View { + VStack { + Spacer(minLength: 40) + + 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: { + #if !os(macOS) + Image(systemName: "arrow.right") + #else + Image(systemName: "arrow.right.circle") + .font(.title) + .foregroundStyle(.white) + #endif + } + #if os(macOS) + .buttonStyle(.plain) + #endif + .accessibilityLabel(Text("Log in", bundle: .module, comment: "Accessibility label of the button which starts the login.")) + .accessibilityIdentifier("submitServerAddress") + } + } + #if !os(macOS) + .padding(EdgeInsets(top: 8, leading: 10, bottom: 8, trailing: 10)) + .overlay( + RoundedRectangle(cornerRadius: 8) + .stroke(foregroundColor, lineWidth: 1) + ) + #endif + + if horizontalSizeClass == .regular { + Spacer(minLength: 100) + } + } + + Group { + if let serverAddressDescription = configuration.serverAddressDescription { + Text(verbatim: serverAddressDescription) + } else { + 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(foregroundColor) + .font(.footnote) + .multilineTextAlignment(.center) + .padding(4) + + Spacer() + + actions + + Spacer() + } + .disabled(model.isActive) + .tint(foregroundColor) + .padding() + .safeAreaPadding(.all) + } + + /// + /// Scan QR Code and the links of the host app in one design, side by side when the height is compact. + /// + private var actions: some View { + let layout = verticalSizeClass == .compact ? AnyLayout(HStackLayout()) : AnyLayout(VStackLayout()) + + return layout { + #if os(iOS) // Camera usually is available on iOS devices only. + actionButton(String(localized: "Scan QR Code", bundle: .module, comment: "Button label"), systemImage: "qrcode.viewfinder", identifier: "scanQRCode") { + model.presentCodeScanner() + } + + if let providerSignUp = configuration.providerSignUp { + actionButton(providerSignUp.title, systemImage: "person.crop.circle.badge.plus", identifier: "signUpWithProvider") { + model.presentProviderSignUp(providerSignUp.url) + } + } + #endif + + if let hostingInformation = configuration.hostingInformation { + actionButton(hostingInformation.title, systemImage: "server.rack", identifier: "hostYourOwnServer") { + openURL(hostingInformation.url) + } + } + } + } + + private func actionButton(_ title: String, systemImage: String, identifier: String, action: @escaping () -> Void) -> some View { + Button(action: action) { + Image(systemName: systemImage) + .resizable() + .scaledToFit() + .frame(width: 32, height: 32) + + Text(verbatim: title) + } + .padding() + .accessibilityIdentifier(identifier) + } + private var serverAddressField: some View { @Bindable var model = model @@ -363,6 +407,16 @@ 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: "cloud"), sharedAccounts: [], configuration: configuration) { _, _, _ in + print("Add account!") + } +} + #Preview("Branded") { var configuration = LoginFlowConfiguration() configuration.foregroundColor = .white diff --git a/Tests/NextcloudKitUITests/LoginFlowModelTests.swift b/Tests/NextcloudKitUITests/LoginFlowModelTests.swift index ece9ecdf..3d7764a4 100644 --- a/Tests/NextcloudKitUITests/LoginFlowModelTests.swift +++ b/Tests/NextcloudKitUITests/LoginFlowModelTests.swift @@ -295,6 +295,71 @@ struct LoginFlowModelTests { } #if os(iOS) + @Test func providerSignUpAddsAccountOnceItsPageClosed() async throws { + let recorder = Recorder() + let model = makeModel(recorder: recorder) + + model.presentProviderSignUp(URL(string: "http://127.0.0.1:1/signup")!) // swiftlint:disable:this force_unwrapping + model.finishProviderSignUp(callbackURL: URL(string: "nc://login/server:https://cloud.example.com&user:jane&password:secret")!) // swiftlint:disable:this force_unwrapping + + #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")!) // swiftlint:disable:this force_unwrapping + 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")!) // swiftlint:disable:this force_unwrapping + 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")!) // swiftlint:disable:this force_unwrapping + model.providerSignUpDidClose() + + #expect(model.isPresentingAlert) + #expect(recorder.addedAccounts.isEmpty) + } + @Test func cameraFailureClosesScannerWithAlert() async throws { let model = makeModel(recorder: Recorder()) From 546163a814d92e1f6ff6725b5c23606c81ec3212 Mon Sep 17 00:00:00 2001 From: Milen Pivchev Date: Tue, 24 Nov 2026 16:01:26 +0100 Subject: [PATCH 13/33] refactor(NextcloudKitUI): drop the login options only the pushed login used Files no longer pushes a login, so startsLoginOnAppear and embedsNavigationStack have no user. Neither was released. Assisted-by: Claude Code:claude-opus-5-5 Co-Authored-By: Claude Opus 5.5 Signed-off-by: Milen Pivchev --- .../Views/Login/LoginFlowConfiguration.swift | 10 ------ .../Views/Login/LoginFlowModel.swift | 12 ------- .../Views/Login/ServerAddressView.swift | 11 ++----- .../LoginFlowModelTests.swift | 31 ------------------- 4 files changed, 2 insertions(+), 62 deletions(-) diff --git a/Sources/NextcloudKitUI/Views/Login/LoginFlowConfiguration.swift b/Sources/NextcloudKitUI/Views/Login/LoginFlowConfiguration.swift index 83064d74..e05a467b 100644 --- a/Sources/NextcloudKitUI/Views/Login/LoginFlowConfiguration.swift +++ b/Sources/NextcloudKitUI/Views/Login/LoginFlowConfiguration.swift @@ -76,11 +76,6 @@ public struct LoginFlowConfiguration: Sendable { /// public var initialServerAddress: String? - /// - /// Starts the login for ``initialServerAddress`` when the view appears, e.g. for a server the user just signed up on. - /// - public var startsLoginOnAppear = false - public var isServerAddressEditable = true /// @@ -108,11 +103,6 @@ public struct LoginFlowConfiguration: Sendable { /// public var loginURLScheme = "nc" - /// - /// Set to `false` when the view is pushed onto an existing navigation stack, so its toolbar items join that navigation bar. - /// - public var embedsNavigationStack = true - public var showsCancelButton = false /// diff --git a/Sources/NextcloudKitUI/Views/Login/LoginFlowModel.swift b/Sources/NextcloudKitUI/Views/Login/LoginFlowModel.swift index 0a8efb19..aa79541a 100644 --- a/Sources/NextcloudKitUI/Views/Login/LoginFlowModel.swift +++ b/Sources/NextcloudKitUI/Views/Login/LoginFlowModel.swift @@ -66,8 +66,6 @@ final class LoginFlowModel: QRCodeParsing, URLSanitizing { /// Whether the QR code scanner closes with the alert, because the camera cannot scan. private var closesCodeScannerWithAlert = false - private var hasStartedLoginOnAppear = false - /// The login address acquired from the server through the login flow API. var loginAddress: URL? @@ -93,16 +91,6 @@ final class LoginFlowModel: QRCodeParsing, URLSanitizing { start(serverURL: sanitizedServerAddress) } - /// - /// Start the login once, when ``LoginFlowConfiguration/startsLoginOnAppear`` asks for it. - /// - func startLoginOnAppear() { - guard configuration.startsLoginOnAppear, hasStartedLoginOnAppear == false else { return } - - hasStartedLoginOnAppear = true - logIn() - } - /// /// Check the server, request the login flow, present its web page and begin polling. /// diff --git a/Sources/NextcloudKitUI/Views/Login/ServerAddressView.swift b/Sources/NextcloudKitUI/Views/Login/ServerAddressView.swift index 026d7d7e..d25c1e9b 100644 --- a/Sources/NextcloudKitUI/Views/Login/ServerAddressView.swift +++ b/Sources/NextcloudKitUI/Views/Login/ServerAddressView.swift @@ -81,11 +81,7 @@ public struct ServerAddressView: View { // MARK: - Implementation public var body: some View { - if configuration.embedsNavigationStack { - NavigationStack { - content - } - } else { + NavigationStack { content } } @@ -134,10 +130,7 @@ public struct ServerAddressView: View { } #endif .onAppear { - model.startLoginOnAppear() - - // Not on top of a login that started by itself. - if configuration.startsLoginOnAppear == false && sharedAccounts.isEmpty == false && hasSuggestedSharedAccounts == false { + if sharedAccounts.isEmpty == false && hasSuggestedSharedAccounts == false { isPresentingSharedAccounts = true hasSuggestedSharedAccounts = true } diff --git a/Tests/NextcloudKitUITests/LoginFlowModelTests.swift b/Tests/NextcloudKitUITests/LoginFlowModelTests.swift index 3d7764a4..b9a96ac1 100644 --- a/Tests/NextcloudKitUITests/LoginFlowModelTests.swift +++ b/Tests/NextcloudKitUITests/LoginFlowModelTests.swift @@ -71,37 +71,6 @@ struct LoginFlowModelTests { #expect(model.enteredServerAddress == "https://cloud.example.com") } - @Test func startsLoginOnAppearOnceWhenConfigured() async throws { - var configuration = LoginFlowConfiguration() - configuration.initialServerAddress = "http://127.0.0.1:1" - configuration.startsLoginOnAppear = true - - let model = makeModel(configuration: configuration, recorder: Recorder()) - - model.startLoginOnAppear() - - #expect(model.isActive) - - // Nothing listens on port 1, so the login ends with an error right away. - try await waitUntil { model.isPresentingAlert } - - model.dismissAlert() - model.startLoginOnAppear() - - #expect(model.isActive == false) - } - - @Test func doesNotStartLoginOnAppearByDefault() async throws { - var configuration = LoginFlowConfiguration() - configuration.initialServerAddress = "https://cloud.example.com" - - let model = makeModel(configuration: configuration, recorder: Recorder()) - - model.startLoginOnAppear() - - #expect(model.isActive == false) - } - @Test func emptyAddressDoesNothing() async throws { let model = makeModel(recorder: Recorder()) model.enteredServerAddress = " " From 4c62c1c548306da78577dab195047879cd21bc8c Mon Sep 17 00:00:00 2001 From: Milen Pivchev Date: Tue, 24 Nov 2026 16:52:47 +0100 Subject: [PATCH 14/33] fix(NextcloudKitUI): let the QR code scanner read a code again after its error The scanner read each code only once while it was open, so a code that failed could not be tried again. It now reads continuously and ignores a failed code only while it stays in front of the camera. The camera preview stays below the bar, which kept no visible background over it. Assisted-by: Claude Code:claude-opus-5-5 Co-Authored-By: Claude Opus 5.5 Signed-off-by: Milen Pivchev --- .../Modifiers/CodeScannerSheet.swift | 8 ++-- .../Views/Login/LoginFlowModel.swift | 29 ++++++++++++- .../LoginFlowModelTests.swift | 41 +++++++++++++++++++ 3 files changed, 73 insertions(+), 5 deletions(-) diff --git a/Sources/NextcloudKitUI/Modifiers/CodeScannerSheet.swift b/Sources/NextcloudKitUI/Modifiers/CodeScannerSheet.swift index 910ace89..490a6231 100644 --- a/Sources/NextcloudKitUI/Modifiers/CodeScannerSheet.swift +++ b/Sources/NextcloudKitUI/Modifiers/CodeScannerSheet.swift @@ -21,8 +21,8 @@ struct CodeScannerSheet: ViewModifier { return content.sheet(isPresented: $model.isPresentingCodeScanner) { NavigationStack { ZStack { - // Each code is read once, so one that did not work does not fail again while it is in view. - CodeScannerView(codeTypes: [.qr], scanMode: .oncePerCode, showViewfinder: true, isTorchOn: isTorchOn, isPaused: model.isActive || model.isPresentingAlert) { result in + // Reads continuously; the model ignores a code that failed while it stays in view. + CodeScannerView(codeTypes: [.qr], scanMode: .continuous, scanInterval: 0.5, showViewfinder: true, isTorchOn: isTorchOn, isPaused: model.isActive || model.isPresentingAlert) { result in model.handleQRCodeScan(result) } @@ -36,9 +36,9 @@ struct CodeScannerSheet: ViewModifier { .accessibilityIdentifier("codeScannerProgress") } } - .ignoresSafeArea() + // Below the bar, which would otherwise be see-through over the camera. + .ignoresSafeArea(edges: .bottom) .toolbarTitleDisplayMode(.inline) - // The camera preview runs under the bar, which keeps its title and buttons readable only with a background. .toolbarBackground(.visible, for: .navigationBar) .navigationTitle(String(localized: "Scan QR Code", bundle: .module, comment: "Navigation bar title")) .toolbar { diff --git a/Sources/NextcloudKitUI/Views/Login/LoginFlowModel.swift b/Sources/NextcloudKitUI/Views/Login/LoginFlowModel.swift index aa79541a..39a91ee5 100644 --- a/Sources/NextcloudKitUI/Views/Login/LoginFlowModel.swift +++ b/Sources/NextcloudKitUI/Views/Login/LoginFlowModel.swift @@ -66,6 +66,15 @@ final class LoginFlowModel: QRCodeParsing, URLSanitizing { /// Whether the QR code scanner closes with the alert, because the camera cannot scan. private var closesCodeScannerWithAlert = false + /// The code the scanner read last. + private var lastScannedCode: String? + + /// A scanned code that failed, ignored while it stays in front of the camera so its error does not come right back. + private var failedCode: (code: String, lastSeen: ContinuousClock.Instant)? + + /// How long a failed code must be out of view before it counts again. + var failedCodeHoldTime: Duration = .seconds(1.5) + /// The login address acquired from the server through the login flow API. var loginAddress: URL? @@ -305,6 +314,8 @@ final class LoginFlowModel: QRCodeParsing, URLSanitizing { if closesCodeScannerWithAlert { isPresentingCodeScanner = false closesCodeScannerWithAlert = false + } else if isPresentingCodeScanner, let lastScannedCode { + failedCode = (lastScannedCode, .now) } } @@ -312,6 +323,8 @@ final class LoginFlowModel: QRCodeParsing, URLSanitizing { func presentCodeScanner() { closesCodeScannerWithAlert = false + lastScannedCode = nil + failedCode = nil isPresentingCodeScanner = true } @@ -319,7 +332,7 @@ final class LoginFlowModel: QRCodeParsing, URLSanitizing { func handleQRCodeScan(_ result: Result) { switch result { case .success(let result): - handleLoginCode(result.string) + handleScannedCode(result.string) case .failure(.permissionDenied): closesCodeScannerWithAlert = true present(error: 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."), action: .openSettings) @@ -330,6 +343,20 @@ final class LoginFlowModel: QRCodeParsing, URLSanitizing { } #endif + /// + /// The scanner reports a code again and again while it is in view. + /// + func handleScannedCode(_ code: String) { + if let failedCode, failedCode.code == code, ContinuousClock.now - failedCode.lastSeen < failedCodeHoldTime { + self.failedCode = (code, .now) + return + } + + failedCode = nil + lastScannedCode = code + handleLoginCode(code) + } + func handleLoginCode(_ code: String) { do { let credentials = try parseLogin(code, scheme: configuration.loginURLScheme) diff --git a/Tests/NextcloudKitUITests/LoginFlowModelTests.swift b/Tests/NextcloudKitUITests/LoginFlowModelTests.swift index b9a96ac1..5b26ea98 100644 --- a/Tests/NextcloudKitUITests/LoginFlowModelTests.swift +++ b/Tests/NextcloudKitUITests/LoginFlowModelTests.swift @@ -263,6 +263,47 @@ struct LoginFlowModelTests { #expect(model.isPresentingCodeScanner) } + @Test func failedScannedCodeCountsAgainOnceOutOfView() async throws { + let recorder = Recorder() + recorder.addAccountError = NKError(errorCode: 401) + let model = makeModel(recorder: recorder) + let code = "nc://login/user:jane&password:secret&server:https://cloud.example.com" + model.failedCodeHoldTime = .milliseconds(200) + + model.presentCodeScanner() + model.handleScannedCode(code) + + try await waitUntil { model.isPresentingAlert } + + model.dismissAlert() + + // Still in front of the camera. + model.handleScannedCode(code) + + #expect(recorder.addedAccounts.count == 1) + #expect(model.isPresentingAlert == false) + + try await Task.sleep(for: .milliseconds(300)) + model.handleScannedCode(code) + + try await waitUntil { recorder.addedAccounts.count == 2 } + } + + @Test func otherCodeScansRightAfterAFailure() async throws { + let recorder = Recorder() + let model = makeModel(recorder: recorder) + + model.presentCodeScanner() + model.handleScannedCode("https://cloud.example.com") + + #expect(model.isPresentingAlert) + + model.dismissAlert() + model.handleScannedCode("nc://login/user:jane&password:secret&server:https://cloud.example.com") + + try await waitUntil { recorder.addedAccounts.count == 1 } + } + #if os(iOS) @Test func providerSignUpAddsAccountOnceItsPageClosed() async throws { let recorder = Recorder() From a070188edd771f381bf9d0a8183a80bb727bb0f3 Mon Sep 17 00:00:00 2001 From: Milen Pivchev Date: Tue, 24 Nov 2026 16:52:48 +0100 Subject: [PATCH 15/33] fix(NextcloudKitUI): keep the login bars transparent on iOS 26 The scrolling form drew the scroll edge effect behind the bars. Assisted-by: Claude Code:claude-opus-5-5 Co-Authored-By: Claude Opus 5.5 Signed-off-by: Milen Pivchev --- .../Views/Login/ServerAddressView.swift | 17 +++++++++++++---- 1 file changed, 13 insertions(+), 4 deletions(-) diff --git a/Sources/NextcloudKitUI/Views/Login/ServerAddressView.swift b/Sources/NextcloudKitUI/Views/Login/ServerAddressView.swift index d25c1e9b..4ea6c052 100644 --- a/Sources/NextcloudKitUI/Views/Login/ServerAddressView.swift +++ b/Sources/NextcloudKitUI/Views/Login/ServerAddressView.swift @@ -94,11 +94,12 @@ public struct ServerAddressView: View { // Scrolls only where the form does not fit, such as on small phones in landscape. GeometryReader { proxy in - ScrollView { - form - .frame(minHeight: proxy.size.height) + if #available(iOS 26.0, macOS 26.0, *) { + scrollingForm(minHeight: proxy.size.height) + .scrollEdgeEffectHidden() + } else { + scrollingForm(minHeight: proxy.size.height) } - .scrollBounceBehavior(.basedOnSize) } } .ignoresSafeArea() @@ -149,6 +150,14 @@ 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(minLength: 40) From 39638c0071301488545dfd0a319888377e28bb60 Mon Sep 17 00:00:00 2001 From: Milen Pivchev Date: Tue, 24 Nov 2026 16:58:32 +0100 Subject: [PATCH 16/33] feat(NextcloudKitUI): show the login actions as prominent glass buttons Scan QR Code, the provider sign-up and the hosting link share one prominent button style in the foreground color, glass on iOS 26. Assisted-by: Claude Code:claude-opus-5-5 Co-Authored-By: Claude Opus 5.5 Signed-off-by: Milen Pivchev --- .../Views/Login/ServerAddressView.swift | 36 +++++++++++++------ 1 file changed, 26 insertions(+), 10 deletions(-) diff --git a/Sources/NextcloudKitUI/Views/Login/ServerAddressView.swift b/Sources/NextcloudKitUI/Views/Login/ServerAddressView.swift index 4ea6c052..d06a1f1c 100644 --- a/Sources/NextcloudKitUI/Views/Login/ServerAddressView.swift +++ b/Sources/NextcloudKitUI/Views/Login/ServerAddressView.swift @@ -250,10 +250,10 @@ public struct ServerAddressView: View { } /// - /// Scan QR Code and the links of the host app in one design, side by side when the height is compact. + /// Scan QR Code and the links of the host app as prominent buttons, side by side when the height is compact. /// private var actions: some View { - let layout = verticalSizeClass == .compact ? AnyLayout(HStackLayout()) : AnyLayout(VStackLayout()) + let layout = verticalSizeClass == .compact ? AnyLayout(HStackLayout(spacing: 12)) : AnyLayout(VStackLayout(spacing: 12)) return layout { #if os(iOS) // Camera usually is available on iOS devices only. @@ -274,19 +274,35 @@ public struct ServerAddressView: View { } } } + .frame(maxWidth: verticalSizeClass == .compact ? .infinity : 400) } + /// + /// Filled with the foreground color, so the label takes the background color. + /// + @ViewBuilder private func actionButton(_ title: String, systemImage: String, identifier: String, action: @escaping () -> Void) -> some View { - Button(action: action) { - Image(systemName: systemImage) - .resizable() - .scaledToFit() - .frame(width: 32, height: 32) - - Text(verbatim: title) + let button = Button(action: action) { + Label { + Text(verbatim: title) + .lineLimit(1) + .minimumScaleFactor(0.8) + } icon: { + Image(systemName: systemImage) + } + .font(.headline) + .foregroundStyle(backgroundColor) + .frame(maxWidth: .infinity) + .padding(.vertical, 6) } - .padding() + .controlSize(.large) .accessibilityIdentifier(identifier) + + if #available(iOS 26.0, macOS 26.0, *) { + button.buttonStyle(.glassProminent) + } else { + button.buttonStyle(.borderedProminent) + } } private var serverAddressField: some View { From d6c8055624c1f5e0049bb2d43a4b5eb5fabfc368 Mon Sep 17 00:00:00 2001 From: Milen Pivchev Date: Tue, 24 Nov 2026 17:37:56 +0100 Subject: [PATCH 17/33] fix(NextcloudKitUI): close the QR code scanner on an error The login view shows the error once the scanner has closed, and the user opens the scanner again to retry. Denied or restricted camera access and a missing camera are reported before the scanner opens, since the scanner reports them late or not at all. The camera runs under a material bar, which keeps the title readable over it. Assisted-by: Claude Code:claude-opus-5-5 Co-Authored-By: Claude Opus 5.5 Signed-off-by: Milen Pivchev --- .../Modifiers/CodeScannerSheet.swift | 14 +-- .../Modifiers/LoginFlowAlert.swift | 2 +- .../Views/Login/LoginFlowModel.swift | 88 ++++++++++--------- .../Views/Login/ServerAddressView.swift | 7 +- .../LoginFlowModelTests.swift | 72 +++++---------- 5 files changed, 77 insertions(+), 106 deletions(-) diff --git a/Sources/NextcloudKitUI/Modifiers/CodeScannerSheet.swift b/Sources/NextcloudKitUI/Modifiers/CodeScannerSheet.swift index 490a6231..5bc4a474 100644 --- a/Sources/NextcloudKitUI/Modifiers/CodeScannerSheet.swift +++ b/Sources/NextcloudKitUI/Modifiers/CodeScannerSheet.swift @@ -9,7 +9,7 @@ import SwiftUI /// /// A sheet with a camera view to scan QR codes for logging in. -/// It stays open and busy while a scanned code logs in, and shows errors itself. +/// It stays open and busy while a scanned code logs in, and closes on an error, which the login view shows. /// struct CodeScannerSheet: ViewModifier { let model: LoginFlowModel @@ -19,10 +19,12 @@ struct CodeScannerSheet: ViewModifier { @Bindable var model = model return content.sheet(isPresented: $model.isPresentingCodeScanner) { + model.codeScannerDidClose() + } content: { NavigationStack { ZStack { - // Reads continuously; the model ignores a code that failed while it stays in view. - CodeScannerView(codeTypes: [.qr], scanMode: .continuous, scanInterval: 0.5, showViewfinder: true, isTorchOn: isTorchOn, isPaused: model.isActive || model.isPresentingAlert) { result in + // One code per opening: an error closes the scanner. + CodeScannerView(codeTypes: [.qr], scanMode: .once, showViewfinder: true, isTorchOn: isTorchOn) { result in model.handleQRCodeScan(result) } @@ -36,9 +38,10 @@ struct CodeScannerSheet: ViewModifier { .accessibilityIdentifier("codeScannerProgress") } } - // Below the bar, which would otherwise be see-through over the camera. - .ignoresSafeArea(edges: .bottom) + .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 { @@ -68,7 +71,6 @@ struct CodeScannerSheet: ViewModifier { } } .interactiveDismissDisabled(model.isActive) - .loginFlowAlert(model: model, isPresented: $model.isPresentingAlert) } } } diff --git a/Sources/NextcloudKitUI/Modifiers/LoginFlowAlert.swift b/Sources/NextcloudKitUI/Modifiers/LoginFlowAlert.swift index c52a34b6..6c57ab68 100644 --- a/Sources/NextcloudKitUI/Modifiers/LoginFlowAlert.swift +++ b/Sources/NextcloudKitUI/Modifiers/LoginFlowAlert.swift @@ -5,7 +5,7 @@ import SwiftUI /// -/// The alert for errors of ``LoginFlowModel``, shown by the login view or the QR code scanner on top of it. +/// The alert for errors of ``LoginFlowModel``, shown by the login view. /// struct LoginFlowAlert: ViewModifier { @Environment(\.openURL) private var openURL diff --git a/Sources/NextcloudKitUI/Views/Login/LoginFlowModel.swift b/Sources/NextcloudKitUI/Views/Login/LoginFlowModel.swift index 39a91ee5..888cb8b3 100644 --- a/Sources/NextcloudKitUI/Views/Login/LoginFlowModel.swift +++ b/Sources/NextcloudKitUI/Views/Login/LoginFlowModel.swift @@ -4,6 +4,7 @@ import AuthenticationServices #if os(iOS) +import AVFoundation import CodeScanner #endif import NextcloudKit @@ -63,17 +64,8 @@ final class LoginFlowModel: QRCodeParsing, URLSanitizing { /// State toggle for presenting the QR code scanner, which stays open while a scanned code logs in. var isPresentingCodeScanner = false - /// Whether the QR code scanner closes with the alert, because the camera cannot scan. - private var closesCodeScannerWithAlert = false - - /// The code the scanner read last. - private var lastScannedCode: String? - - /// A scanned code that failed, ignored while it stays in front of the camera so its error does not come right back. - private var failedCode: (code: String, lastSeen: ContinuousClock.Instant)? - - /// How long a failed code must be out of view before it counts again. - var failedCodeHoldTime: Duration = .seconds(1.5) + /// An error of the QR code scanner, shown by the login view once the scanner has closed. + private var codeScannerError: (message: String?, action: AlertAction?)? /// The login address acquired from the server through the login flow API. var loginAddress: URL? @@ -298,64 +290,78 @@ final class LoginFlowModel: QRCodeParsing, URLSanitizing { } private func present(error: String?, action: AlertAction? = nil) { + // The scanner closes first; the user opens it again to scan another code. + if isPresentingCodeScanner { + codeScannerError = (error, action) + isPresentingCodeScanner = false + return + } + errorMessage = error alertAction = action isPresentingAlert = true } - /// - /// Clear the alert, and close a QR code scanner that cannot scan. - /// func dismissAlert() { errorMessage = nil alertAction = nil isPresentingAlert = false - - if closesCodeScannerWithAlert { - isPresentingCodeScanner = false - closesCodeScannerWithAlert = false - } else if isPresentingCodeScanner, let lastScannedCode { - failedCode = (lastScannedCode, .now) - } } // MARK: - QR code func presentCodeScanner() { - closesCodeScannerWithAlert = false - lastScannedCode = nil - failedCode = nil + codeScannerError = nil + + #if os(iOS) && !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, action: .openSettings) + 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, action: codeScannerError.action) + } + #if os(iOS) func handleQRCodeScan(_ result: Result) { switch result { case .success(let result): - handleScannedCode(result.string) + handleLoginCode(result.string) case .failure(.permissionDenied): - closesCodeScannerWithAlert = true - present(error: 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."), action: .openSettings) + present(error: Self.cameraAccessMessage, action: .openSettings) case .failure: - closesCodeScannerWithAlert = true - present(error: String(localized: "The camera is not available.", bundle: .module, comment: "Error message when the camera cannot be used to scan a login QR code.")) + present(error: Self.cameraUnavailableMessage) } } - #endif - /// - /// The scanner reports a code again and again while it is in view. - /// - func handleScannedCode(_ code: String) { - if let failedCode, failedCode.code == code, ContinuousClock.now - failedCode.lastSeen < failedCodeHoldTime { - self.failedCode = (code, .now) - return - } + 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.") + } - failedCode = nil - lastScannedCode = code - handleLoginCode(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.") } + #endif func handleLoginCode(_ code: String) { do { diff --git a/Sources/NextcloudKitUI/Views/Login/ServerAddressView.swift b/Sources/NextcloudKitUI/Views/Login/ServerAddressView.swift index d06a1f1c..8c189be0 100644 --- a/Sources/NextcloudKitUI/Views/Login/ServerAddressView.swift +++ b/Sources/NextcloudKitUI/Views/Login/ServerAddressView.swift @@ -142,12 +142,7 @@ public struct ServerAddressView: View { await model.presentLoginPage(loginAddress, using: webAuthenticationSession) } - // The QR code scanner shows its own errors while it is open. - .loginFlowAlert(model: model, isPresented: Binding { - model.isPresentingAlert && model.isPresentingCodeScanner == false - } set: { - model.isPresentingAlert = $0 - }) + .loginFlowAlert(model: model, isPresented: $model.isPresentingAlert) } private func scrollingForm(minHeight: CGFloat) -> some View { diff --git a/Tests/NextcloudKitUITests/LoginFlowModelTests.swift b/Tests/NextcloudKitUITests/LoginFlowModelTests.swift index 5b26ea98..b1c7cabf 100644 --- a/Tests/NextcloudKitUITests/LoginFlowModelTests.swift +++ b/Tests/NextcloudKitUITests/LoginFlowModelTests.swift @@ -229,23 +229,22 @@ struct LoginFlowModelTests { #expect(model.isPresentingAlert == false) } - @Test func invalidScannedCodeShowsErrorAndKeepsScanning() async throws { + @Test func invalidScannedCodeClosesScannerThenShowsError() async throws { let model = makeModel(recorder: Recorder()) model.presentCodeScanner() model.handleLoginCode("https://cloud.example.com") - #expect(model.isPresentingAlert) - #expect(model.isPresentingCodeScanner) + #expect(model.isPresentingCodeScanner == false) + #expect(model.isPresentingAlert == false) - model.dismissAlert() + model.codeScannerDidClose() - #expect(model.isPresentingAlert == false) - #expect(model.errorMessage == nil) - #expect(model.isPresentingCodeScanner) + #expect(model.isPresentingAlert) + #expect(model.errorMessage == QRCodeError.invalidPrefix.localizedDescription) } - @Test func failedLoginFromScannedCodeShowsErrorInScanner() async throws { + @Test func failedLoginFromScannedCodeClosesScannerThenShowsError() async throws { let recorder = Recorder() recorder.addAccountError = NKError(errorCode: 401) let model = makeModel(recorder: recorder) @@ -253,55 +252,24 @@ struct LoginFlowModelTests { model.presentCodeScanner() model.handleLoginCode("nc://login/user:jane&password:secret&server:https://cloud.example.com") - try await waitUntil { model.isPresentingAlert } + try await waitUntil { model.isPresentingCodeScanner == false && model.isActive == false } - #expect(model.isPresentingCodeScanner) - #expect(model.isActive == false) + #expect(recorder.isPresentingCodeScannerDuringAddAccount == true) - model.dismissAlert() + model.codeScannerDidClose() - #expect(model.isPresentingCodeScanner) + #expect(model.isPresentingAlert) } - @Test func failedScannedCodeCountsAgainOnceOutOfView() async throws { - let recorder = Recorder() - recorder.addAccountError = NKError(errorCode: 401) - let model = makeModel(recorder: recorder) - let code = "nc://login/user:jane&password:secret&server:https://cloud.example.com" - model.failedCodeHoldTime = .milliseconds(200) + @Test func reopenedScannerForgetsTheLastError() async throws { + let model = makeModel(recorder: Recorder()) model.presentCodeScanner() - model.handleScannedCode(code) - - try await waitUntil { model.isPresentingAlert } - - model.dismissAlert() - - // Still in front of the camera. - model.handleScannedCode(code) - - #expect(recorder.addedAccounts.count == 1) - #expect(model.isPresentingAlert == false) - - try await Task.sleep(for: .milliseconds(300)) - model.handleScannedCode(code) - - try await waitUntil { recorder.addedAccounts.count == 2 } - } - - @Test func otherCodeScansRightAfterAFailure() async throws { - let recorder = Recorder() - let model = makeModel(recorder: recorder) - + model.handleLoginCode("https://cloud.example.com") model.presentCodeScanner() - model.handleScannedCode("https://cloud.example.com") - - #expect(model.isPresentingAlert) - - model.dismissAlert() - model.handleScannedCode("nc://login/user:jane&password:secret&server:https://cloud.example.com") + model.codeScannerDidClose() - try await waitUntil { recorder.addedAccounts.count == 1 } + #expect(model.isPresentingAlert == false) } #if os(iOS) @@ -376,12 +344,12 @@ struct LoginFlowModelTests { model.presentCodeScanner() model.handleQRCodeScan(.failure(.permissionDenied)) - #expect(model.isPresentingAlert) - #expect(model.alertAction == .openSettings) + #expect(model.isPresentingCodeScanner == false) - model.dismissAlert() + model.codeScannerDidClose() - #expect(model.isPresentingCodeScanner == false) + #expect(model.isPresentingAlert) + #expect(model.alertAction == .openSettings) } #endif From fde9e71c79e7c7f165a6879485913596aef7d41f Mon Sep 17 00:00:00 2001 From: Milen Pivchev Date: Tue, 24 Nov 2026 17:38:02 +0100 Subject: [PATCH 18/33] fix(NextcloudKitUI): color the provider sign-up bar like the page As in Safari, the bar takes the page's theme color, or its background, with a title that stays readable on it. It no longer shows the window background above a page of another color. Assisted-by: Claude Code:claude-opus-5-5 Co-Authored-By: Claude Opus 5.5 Signed-off-by: Milen Pivchev --- .../Views/Login/ProviderSignUpModel.swift | 21 ++++-- .../Views/Login/ProviderSignUpView.swift | 69 +++++++++++-------- 2 files changed, 57 insertions(+), 33 deletions(-) diff --git a/Sources/NextcloudKitUI/Views/Login/ProviderSignUpModel.swift b/Sources/NextcloudKitUI/Views/Login/ProviderSignUpModel.swift index 7573c340..6213cbc5 100644 --- a/Sources/NextcloudKitUI/Views/Login/ProviderSignUpModel.swift +++ b/Sources/NextcloudKitUI/Views/Login/ProviderSignUpModel.swift @@ -48,9 +48,12 @@ final class ProviderSignUpModel: NSObject, Identifiable, WKNavigationDelegate { /// 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: UIColor? + @ObservationIgnored private let callbackScheme: String @ObservationIgnored private let onCallback: @MainActor (URL) -> Void - @ObservationIgnored private var loadingObservation: NSKeyValueObservation? + @ObservationIgnored private var observations: [NSKeyValueObservation] = [] @ObservationIgnored private var reissuedURLs: Set = [] @ObservationIgnored private var requestedURL: URL? @ObservationIgnored private var hasStarted = false @@ -81,11 +84,18 @@ final class ProviderSignUpModel: NSObject, Identifiable, WKNavigationDelegate { webView.navigationDelegate = self - loadingObservation = webView.observe(\.isLoading, options: [.initial, .new]) { [weak self] webView, _ in - MainActor.assumeIsolated { - self?.isLoading = webView.isLoading + 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 = webView.themeColor ?? webView.underPageBackgroundColor + } } - } + ] } // MARK: - Loading @@ -266,6 +276,7 @@ final class ProviderSignUpModel: NSObject, Identifiable, WKNavigationDelegate { } func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!) { + pageColor = webView.themeColor ?? webView.underPageBackgroundColor pageDidFinish() } diff --git a/Sources/NextcloudKitUI/Views/Login/ProviderSignUpView.swift b/Sources/NextcloudKitUI/Views/Login/ProviderSignUpView.swift index 47e9ed56..7c27e0ad 100644 --- a/Sources/NextcloudKitUI/Views/Login/ProviderSignUpView.swift +++ b/Sources/NextcloudKitUI/Views/Login/ProviderSignUpView.swift @@ -16,40 +16,53 @@ struct ProviderSignUpView: View { var body: some View { NavigationStack { - ZStack { - WebView(webView: model.webView) - - if let errorMessage = model.errorMessage { - ContentUnavailableView { - Label(errorMessage, systemImage: "exclamationmark.triangle") - } actions: { - Button(String(localized: "Retry", bundle: .module)) { - model.retry() - } - .accessibilityIdentifier("retryProviderSignUp") + page + // Colored like the page, as in Safari, since the bar does not track the web view's scrolling. + .toolbarBackground(pageColor ?? Color(uiColor: .systemBackground), for: .navigationBar) + .toolbarBackground(.visible, for: .navigationBar) + .toolbarColorScheme(pageColor.map { $0.readable == .white ? .dark : .light }, for: .navigationBar) + } + .onAppear { + model.start() + } + } + + private var pageColor: Color? { + model.pageColor.map { Color(uiColor: $0) } + } + + 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() } - .background(Color(uiColor: .systemBackground)) - } else if model.isLoading { - ProgressView() - .controlSize(.large) + .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") + } + .navigationTitle(model.url.host ?? "") + .navigationBarTitleDisplayMode(.inline) + .toolbar { + ToolbarItem(placement: .cancellationAction) { + Button { + dismiss() + } label: { + Text("Cancel", bundle: .module, comment: "Button label") } + .accessibilityIdentifier("cancelProviderSignUp") } } - .onAppear { - model.start() - } } } From 4309715f9c233db1f8cba5422b1450b11ea0688e Mon Sep 17 00:00:00 2001 From: Milen Pivchev Date: Tue, 24 Nov 2026 17:38:02 +0100 Subject: [PATCH 19/33] feat(NextcloudKitUI): list the other ways to log in below an or The QR code button now reads "Log in with QR code", and the buttons are smaller. Their labels wrap, and they stack at accessibility text sizes. Assisted-by: Claude Code:claude-opus-5-5 Co-Authored-By: Claude Opus 5.5 Signed-off-by: Milen Pivchev --- Sources/NextcloudKitUI/Localizable.xcstrings | 8 ++- .../Views/Login/ServerAddressView.swift | 62 ++++++++++++------- 2 files changed, 48 insertions(+), 22 deletions(-) diff --git a/Sources/NextcloudKitUI/Localizable.xcstrings b/Sources/NextcloudKitUI/Localizable.xcstrings index ad63eb54..f53fc6c3 100644 --- a/Sources/NextcloudKitUI/Localizable.xcstrings +++ b/Sources/NextcloudKitUI/Localizable.xcstrings @@ -7117,6 +7117,9 @@ "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." + }, "Login Failed" : { "comment" : "Alert title", "localizations" : { @@ -9493,7 +9496,7 @@ } }, "Scan QR Code" : { - "comment" : "Button label\nNavigation bar title", + "comment" : "Navigation bar title", "localizations" : { "da" : { "stringUnit" : { @@ -12293,6 +12296,9 @@ } } } + }, + "or" : { + "comment" : "Separator between the server address field and the other ways to log in." } }, "version" : "1.0" diff --git a/Sources/NextcloudKitUI/Views/Login/ServerAddressView.swift b/Sources/NextcloudKitUI/Views/Login/ServerAddressView.swift index 8c189be0..e2c45c7e 100644 --- a/Sources/NextcloudKitUI/Views/Login/ServerAddressView.swift +++ b/Sources/NextcloudKitUI/Views/Login/ServerAddressView.swift @@ -47,6 +47,7 @@ public struct ServerAddressView: View { @Environment(\.verticalSizeClass) var verticalSizeClass @Environment(\.webAuthenticationSession) private var webAuthenticationSession @Environment(\.openURL) private var openURL + @Environment(\.dynamicTypeSize) private var dynamicTypeSize // MARK: - Bindings @@ -245,31 +246,51 @@ public struct ServerAddressView: View { } /// - /// Scan QR Code and the links of the host app as prominent buttons, side by side when the height is compact. + /// The other ways to log in, below an "or", side by side when the height is compact. /// private var actions: some View { - let layout = verticalSizeClass == .compact ? AnyLayout(HStackLayout(spacing: 12)) : AnyLayout(VStackLayout(spacing: 12)) + let isSideBySide = verticalSizeClass == .compact && dynamicTypeSize.isAccessibilitySize == false + let layout = isSideBySide ? AnyLayout(HStackLayout(spacing: 10)) : AnyLayout(VStackLayout(spacing: 10)) - return layout { - #if os(iOS) // Camera usually is available on iOS devices only. - actionButton(String(localized: "Scan QR Code", bundle: .module, comment: "Button label"), systemImage: "qrcode.viewfinder", identifier: "scanQRCode") { - model.presentCodeScanner() - } + return VStack(spacing: 16) { + orSeparator - if let providerSignUp = configuration.providerSignUp { - actionButton(providerSignUp.title, systemImage: "person.crop.circle.badge.plus", identifier: "signUpWithProvider") { - model.presentProviderSignUp(providerSignUp.url) + layout { + #if os(iOS) // Camera usually is available on iOS devices only. + 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() } - } - #endif - if let hostingInformation = configuration.hostingInformation { - actionButton(hostingInformation.title, systemImage: "server.rack", identifier: "hostYourOwnServer") { - openURL(hostingInformation.url) + if let providerSignUp = configuration.providerSignUp { + actionButton(providerSignUp.title, systemImage: "person.crop.circle.badge.plus", identifier: "signUpWithProvider") { + model.presentProviderSignUp(providerSignUp.url) + } + } + #endif + + if let hostingInformation = configuration.hostingInformation { + actionButton(hostingInformation.title, systemImage: "server.rack", identifier: "hostYourOwnServer") { + openURL(hostingInformation.url) + } } } } - .frame(maxWidth: verticalSizeClass == .compact ? .infinity : 400) + .frame(maxWidth: isSideBySide ? .infinity : 320) + } + + 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) } /// @@ -280,17 +301,16 @@ public struct ServerAddressView: View { let button = Button(action: action) { Label { Text(verbatim: title) - .lineLimit(1) - .minimumScaleFactor(0.8) + .lineLimit(2) + .multilineTextAlignment(.center) } icon: { Image(systemName: systemImage) } - .font(.headline) + .font(.subheadline.weight(.semibold)) .foregroundStyle(backgroundColor) .frame(maxWidth: .infinity) - .padding(.vertical, 6) } - .controlSize(.large) + .controlSize(.regular) .accessibilityIdentifier(identifier) if #available(iOS 26.0, macOS 26.0, *) { From e66e309db08d38ddf55d1d874fc477c21406ce43 Mon Sep 17 00:00:00 2001 From: Milen Pivchev Date: Wed, 25 Nov 2026 10:35:02 +0100 Subject: [PATCH 20/33] feat(NextcloudKitUI): full-width login buttons, hosting link at the bottom The prominent glass buttons are as wide as the server address field and large. The hosting link sits apart at the bottom of the screen. Assisted-by: Claude Code:claude-opus-5-5 Co-Authored-By: Claude Opus 5.5 Signed-off-by: Milen Pivchev --- .../Views/Login/ServerAddressView.swift | 36 +++++++++++-------- 1 file changed, 22 insertions(+), 14 deletions(-) diff --git a/Sources/NextcloudKitUI/Views/Login/ServerAddressView.swift b/Sources/NextcloudKitUI/Views/Login/ServerAddressView.swift index e2c45c7e..ed6bc499 100644 --- a/Sources/NextcloudKitUI/Views/Login/ServerAddressView.swift +++ b/Sources/NextcloudKitUI/Views/Login/ServerAddressView.swift @@ -238,6 +238,13 @@ public struct ServerAddressView: View { actions Spacer() + + if let hostingInformation = configuration.hostingInformation { + actionButton(hostingInformation.title, systemImage: "server.rack", identifier: "hostYourOwnServer") { + openURL(hostingInformation.url) + } + .frame(maxWidth: actionsMaxWidth) + } } .disabled(model.isActive) .tint(foregroundColor) @@ -245,18 +252,24 @@ public struct ServerAddressView: View { .safeAreaPadding(.all) } + /// As wide as the server address field, up to a readable width on large screens. + private var actionsMaxWidth: CGFloat { + horizontalSizeClass == .regular ? 500 : .infinity + } + /// /// The other ways to log in, below an "or", side by side when the height is compact. /// + @ViewBuilder private var actions: some View { + #if os(iOS) // Camera usually is available on iOS devices only. let isSideBySide = verticalSizeClass == .compact && dynamicTypeSize.isAccessibilitySize == false - let layout = isSideBySide ? AnyLayout(HStackLayout(spacing: 10)) : AnyLayout(VStackLayout(spacing: 10)) + let layout = isSideBySide ? AnyLayout(HStackLayout(spacing: 12)) : AnyLayout(VStackLayout(spacing: 12)) - return VStack(spacing: 16) { + VStack(spacing: 16) { orSeparator layout { - #if os(iOS) // Camera usually is available on iOS devices only. 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() } @@ -266,16 +279,10 @@ public struct ServerAddressView: View { model.presentProviderSignUp(providerSignUp.url) } } - #endif - - if let hostingInformation = configuration.hostingInformation { - actionButton(hostingInformation.title, systemImage: "server.rack", identifier: "hostYourOwnServer") { - openURL(hostingInformation.url) - } - } } } - .frame(maxWidth: isSideBySide ? .infinity : 320) + .frame(maxWidth: actionsMaxWidth) + #endif } private var orSeparator: some View { @@ -294,7 +301,7 @@ public struct ServerAddressView: View { } /// - /// Filled with the foreground color, so the label takes the background color. + /// A prominent glass button filled with the foreground color, so the label takes the background color. /// @ViewBuilder private func actionButton(_ title: String, systemImage: String, identifier: String, action: @escaping () -> Void) -> some View { @@ -306,11 +313,12 @@ public struct ServerAddressView: View { } icon: { Image(systemName: systemImage) } - .font(.subheadline.weight(.semibold)) + .font(.headline) .foregroundStyle(backgroundColor) .frame(maxWidth: .infinity) + .padding(.vertical, 4) } - .controlSize(.regular) + .controlSize(.large) .accessibilityIdentifier(identifier) if #available(iOS 26.0, macOS 26.0, *) { From ebd2a0ab3e65370f5602c08d728dee472bb292a6 Mon Sep 17 00:00:00 2001 From: Milen Pivchev Date: Wed, 25 Nov 2026 11:15:08 +0100 Subject: [PATCH 21/33] feat(NextcloudKitUI): fade in the onboarding text The title and the features fade in one after another, sliding up slightly unless Reduce Motion is on. Assisted-by: Claude Code:claude-opus-5-5 Co-Authored-By: Claude Opus 5.5 Signed-off-by: Milen Pivchev --- .../Views/Onboarding/OnboardingView.swift | 22 ++++++++++++++++++- 1 file changed, 21 insertions(+), 1 deletion(-) diff --git a/Sources/NextcloudKitUI/Views/Onboarding/OnboardingView.swift b/Sources/NextcloudKitUI/Views/Onboarding/OnboardingView.swift index 47dd3b91..3b4072cd 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 { @@ -139,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.35).delay(Double(order) * 0.06), value: isShown) + } +} + #if DEBUG #Preview { From 388f5c01ff30d01f32a83a25f4f65c2e423a772c Mon Sep 17 00:00:00 2001 From: Milen Pivchev Date: Wed, 25 Nov 2026 11:17:53 +0100 Subject: [PATCH 22/33] feat(NextcloudKitUI): slow down the onboarding fade-in a little Assisted-by: Claude Code:claude-opus-5-5 Co-Authored-By: Claude Opus 5.5 Signed-off-by: Milen Pivchev --- Sources/NextcloudKitUI/Views/Onboarding/OnboardingView.swift | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Sources/NextcloudKitUI/Views/Onboarding/OnboardingView.swift b/Sources/NextcloudKitUI/Views/Onboarding/OnboardingView.swift index 3b4072cd..9ed5e021 100644 --- a/Sources/NextcloudKitUI/Views/Onboarding/OnboardingView.swift +++ b/Sources/NextcloudKitUI/Views/Onboarding/OnboardingView.swift @@ -155,7 +155,7 @@ private extension View { 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.35).delay(Double(order) * 0.06), value: isShown) + .animation(.easeOut(duration: 0.5).delay(Double(order) * 0.1), value: isShown) } } From 210d61fb885834c75307643742e83950a2bfbdde Mon Sep 17 00:00:00 2001 From: Milen Pivchev Date: Wed, 25 Nov 2026 12:01:59 +0100 Subject: [PATCH 23/33] refactor(NextcloudKitUI): drop the macOS conditionals The views only run on iOS today; macOS support can be added again when an app needs it. The desktop client uses NextcloudKit, not this module. Assisted-by: Claude Code:claude-opus-5-5 Co-Authored-By: Claude Opus 5.5 Signed-off-by: Milen Pivchev --- Sources/NextcloudKitUI/Color+readable.swift | 12 ------------ .../Documentation.docc/Documentation.md | 6 +++--- Sources/NextcloudKitUI/Image+appIcon.swift | 4 ---- .../Modifiers/CodeScannerSheet.swift | 4 ---- .../Modifiers/LoginFlowAlert.swift | 2 -- Sources/NextcloudKitUI/ViewRepresentable.swift | 14 -------------- .../Views/Login/LoginFlowModel.swift | 8 +------- .../Views/Login/ProviderSignUpModel.swift | 4 ---- .../Views/Login/ProviderSignUpView.swift | 4 ---- .../Views/Login/SharedAccountsView.swift | 2 -- .../NextcloudKitUI/Views/Login/WebView.swift | 18 +----------------- .../Edit/UnifiedShareEditView.swift | 4 ---- .../LoginFlowModelTests.swift | 4 ---- .../ProviderSignUpModelTests.swift | 4 ---- 14 files changed, 5 insertions(+), 85 deletions(-) delete mode 100644 Sources/NextcloudKitUI/ViewRepresentable.swift 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 0a7f6cd7..b3118849 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. 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/Modifiers/CodeScannerSheet.swift b/Sources/NextcloudKitUI/Modifiers/CodeScannerSheet.swift index 5bc4a474..f886d99b 100644 --- a/Sources/NextcloudKitUI/Modifiers/CodeScannerSheet.swift +++ b/Sources/NextcloudKitUI/Modifiers/CodeScannerSheet.swift @@ -5,8 +5,6 @@ import CodeScanner import SwiftUI -#if os(iOS) - /// /// A sheet with a camera view to scan QR codes for logging in. /// It stays open and busy while a scanned code logs in, and closes on an error, which the login view shows. @@ -85,5 +83,3 @@ extension View { modifier(CodeScannerSheet(model: model)) } } - -#endif diff --git a/Sources/NextcloudKitUI/Modifiers/LoginFlowAlert.swift b/Sources/NextcloudKitUI/Modifiers/LoginFlowAlert.swift index 6c57ab68..f0f8b060 100644 --- a/Sources/NextcloudKitUI/Modifiers/LoginFlowAlert.swift +++ b/Sources/NextcloudKitUI/Modifiers/LoginFlowAlert.swift @@ -15,7 +15,6 @@ struct LoginFlowAlert: ViewModifier { func body(content: Content) -> some View { content.alert(String(localized: "Login Failed", bundle: .module, comment: "Alert title"), isPresented: $isPresented) { - #if os(iOS) if model.alertAction == .openSettings { Button { model.dismissAlert() @@ -27,7 +26,6 @@ struct LoginFlowAlert: ViewModifier { Text("Open Settings", bundle: .module, comment: "Button label in the login error alert which opens the system settings of the app.") } } - #endif Button(role: .cancel) { model.dismissAlert() 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/LoginFlowModel.swift b/Sources/NextcloudKitUI/Views/Login/LoginFlowModel.swift index 888cb8b3..1ff79eb9 100644 --- a/Sources/NextcloudKitUI/Views/Login/LoginFlowModel.swift +++ b/Sources/NextcloudKitUI/Views/Login/LoginFlowModel.swift @@ -3,10 +3,8 @@ // SPDX-License-Identifier: GPL-3.0-or-later import AuthenticationServices -#if os(iOS) import AVFoundation import CodeScanner -#endif import NextcloudKit import SwiftUI @@ -313,7 +311,7 @@ final class LoginFlowModel: QRCodeParsing, URLSanitizing { func presentCodeScanner() { codeScannerError = nil - #if os(iOS) && !targetEnvironment(simulator) + #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: @@ -342,7 +340,6 @@ final class LoginFlowModel: QRCodeParsing, URLSanitizing { present(error: codeScannerError.message, action: codeScannerError.action) } - #if os(iOS) func handleQRCodeScan(_ result: Result) { switch result { case .success(let result): @@ -361,7 +358,6 @@ final class LoginFlowModel: QRCodeParsing, URLSanitizing { 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.") } - #endif func handleLoginCode(_ code: String) { do { @@ -398,7 +394,6 @@ final class LoginFlowModel: QRCodeParsing, URLSanitizing { // MARK: - Provider sign-up - #if os(iOS) /// The provider sign-up page while it is open. var providerSignUp: ProviderSignUpModel? @@ -434,7 +429,6 @@ final class LoginFlowModel: QRCodeParsing, URLSanitizing { present(error: error.localizedDescription) } } - #endif // MARK: - Shared accounts diff --git a/Sources/NextcloudKitUI/Views/Login/ProviderSignUpModel.swift b/Sources/NextcloudKitUI/Views/Login/ProviderSignUpModel.swift index 6213cbc5..fd5cb66f 100644 --- a/Sources/NextcloudKitUI/Views/Login/ProviderSignUpModel.swift +++ b/Sources/NextcloudKitUI/Views/Login/ProviderSignUpModel.swift @@ -2,8 +2,6 @@ // SPDX-FileCopyrightText: 2026 Milen Pivchev // SPDX-License-Identifier: GPL-3.0-or-later -#if os(iOS) - import NextcloudKit import SwiftUI import UIKit @@ -292,5 +290,3 @@ final class ProviderSignUpModel: NSObject, Identifiable, WKNavigationDelegate { webContentProcessDidTerminate() } } - -#endif diff --git a/Sources/NextcloudKitUI/Views/Login/ProviderSignUpView.swift b/Sources/NextcloudKitUI/Views/Login/ProviderSignUpView.swift index 7c27e0ad..aa4eef7d 100644 --- a/Sources/NextcloudKitUI/Views/Login/ProviderSignUpView.swift +++ b/Sources/NextcloudKitUI/Views/Login/ProviderSignUpView.swift @@ -2,8 +2,6 @@ // SPDX-FileCopyrightText: 2026 Milen Pivchev // SPDX-License-Identifier: GPL-3.0-or-later -#if os(iOS) - import SwiftUI /// @@ -65,5 +63,3 @@ struct ProviderSignUpView: View { } } } - -#endif diff --git a/Sources/NextcloudKitUI/Views/Login/SharedAccountsView.swift b/Sources/NextcloudKitUI/Views/Login/SharedAccountsView.swift index 0fb6e605..d86b5010 100644 --- a/Sources/NextcloudKitUI/Views/Login/SharedAccountsView.swift +++ b/Sources/NextcloudKitUI/Views/Login/SharedAccountsView.swift @@ -60,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 8fa9498d..33b2a40b 100644 --- a/Sources/NextcloudKitUI/Views/Login/WebView.swift +++ b/Sources/NextcloudKitUI/Views/Login/WebView.swift @@ -15,7 +15,7 @@ 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? @@ -58,27 +58,11 @@ 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/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 index b1c7cabf..d6623a34 100644 --- a/Tests/NextcloudKitUITests/LoginFlowModelTests.swift +++ b/Tests/NextcloudKitUITests/LoginFlowModelTests.swift @@ -2,9 +2,7 @@ // SPDX-FileCopyrightText: 2026 Milen Pivchev // SPDX-License-Identifier: GPL-3.0-or-later -#if os(iOS) import CodeScanner -#endif import Foundation import NextcloudKit @testable import NextcloudKitUI @@ -272,7 +270,6 @@ struct LoginFlowModelTests { #expect(model.isPresentingAlert == false) } - #if os(iOS) @Test func providerSignUpAddsAccountOnceItsPageClosed() async throws { let recorder = Recorder() let model = makeModel(recorder: recorder) @@ -351,7 +348,6 @@ struct LoginFlowModelTests { #expect(model.isPresentingAlert) #expect(model.alertAction == .openSettings) } - #endif @Test func cancelWhileRecoveringStopsTheLogin() async throws { let recorder = Recorder() diff --git a/Tests/NextcloudKitUITests/ProviderSignUpModelTests.swift b/Tests/NextcloudKitUITests/ProviderSignUpModelTests.swift index cbf62128..492e7f70 100644 --- a/Tests/NextcloudKitUITests/ProviderSignUpModelTests.swift +++ b/Tests/NextcloudKitUITests/ProviderSignUpModelTests.swift @@ -2,8 +2,6 @@ // SPDX-FileCopyrightText: 2026 Milen Pivchev // SPDX-License-Identifier: GPL-3.0-or-later -#if os(iOS) - import Foundation import NextcloudKit @testable import NextcloudKitUI @@ -138,5 +136,3 @@ struct ProviderSignUpModelTests { #expect(model.errorMessage == NKError(errorCode: NSURLErrorTimedOut).localizedGenericMessage) } } - -#endif From 3789191cc4f53902f0130ac0bbb6b339fe7ef855 Mon Sep 17 00:00:00 2001 From: Milen Pivchev Date: Wed, 25 Nov 2026 12:20:06 +0100 Subject: [PATCH 24/33] feat(NextcloudKitUI): move shared accounts into the login action buttons Replace the toolbar entry for accounts from other apps with a full-width action button next to the QR code and provider sign-up buttons, and stop auto-presenting the shared accounts sheet on appear. Also drop the remaining macOS conditionals from ServerAddressView and tweak the spacing around the brand image, the address field and the action buttons. Co-Authored-By: Claude Opus 5.5 Signed-off-by: Milen Pivchev --- Sources/NextcloudKitUI/Localizable.xcstrings | 13 +-- .../Views/Login/ServerAddressView.swift | 82 ++++--------------- 2 files changed, 25 insertions(+), 70 deletions(-) diff --git a/Sources/NextcloudKitUI/Localizable.xcstrings b/Sources/NextcloudKitUI/Localizable.xcstrings index f53fc6c3..2ff79e3b 100644 --- a/Sources/NextcloudKitUI/Localizable.xcstrings +++ b/Sources/NextcloudKitUI/Localizable.xcstrings @@ -1,6 +1,9 @@ { "sourceLanguage" : "en", "strings" : { + "" : { + + }, "%lld groups" : { "comment" : "Recipient summary for multiple groups.", "localizations" : { @@ -1792,7 +1795,7 @@ "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" : { @@ -7676,6 +7679,9 @@ "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" : { @@ -12296,10 +12302,7 @@ } } } - }, - "or" : { - "comment" : "Separator between the server address field and the other ways to log in." } }, "version" : "1.0" -} +} \ No newline at end of file diff --git a/Sources/NextcloudKitUI/Views/Login/ServerAddressView.swift b/Sources/NextcloudKitUI/Views/Login/ServerAddressView.swift index ed6bc499..a6e536ce 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 @@ -60,11 +61,6 @@ public struct ServerAddressView: View { /// @State private var model: LoginFlowModel - /// - /// State toggle whether the shared accounts have been suggested once during lifetime of this view. - /// - @State private var hasSuggestedSharedAccounts = false - /// /// State toggle for presenting the sheet to select accounts shared among apps of the same group. /// @@ -95,7 +91,7 @@ public struct ServerAddressView: View { // Scrolls only where the form does not fit, such as on small phones in landscape. GeometryReader { proxy in - if #available(iOS 26.0, macOS 26.0, *) { + if #available(iOS 26.0, *) { scrollingForm(minHeight: proxy.size.height) .scrollEdgeEffectHidden() } else { @@ -108,21 +104,9 @@ public struct ServerAddressView: View { if configuration.showsCancelButton { cancelToolbarItem } - - if sharedAccounts.isEmpty == false { - if #available(iOS 26.0, macOS 26.0, *) { - sharedAccountsToolbarItem - .sharedBackgroundVisibility(.hidden) - } else { - sharedAccountsToolbarItem - } - } } - #if os(iOS) .toolbarBackground(.hidden, for: .navigationBar) - #endif .sharedAccountsSheet(isPresented: $isPresentingSharedAccounts, sharedAccounts: sharedAccounts, selectionHandler: { model.selectSharedAccount($0) }) - #if os(iOS) // 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) { @@ -130,13 +114,6 @@ public struct ServerAddressView: View { } content: { providerSignUp in ProviderSignUpView(model: providerSignUp) } - #endif - .onAppear { - if sharedAccounts.isEmpty == false && hasSuggestedSharedAccounts == false { - isPresentingSharedAccounts = true - hasSuggestedSharedAccounts = true - } - } .task(id: model.isPresentingLoginPage) { // Clearing the flag cancels this task, which closes the browser sheet. guard model.isPresentingLoginPage, let loginAddress = model.loginAddress else { return } @@ -156,7 +133,7 @@ public struct ServerAddressView: View { private var form: some View { VStack { - Spacer(minLength: 40) + Spacer().frame(minHeight: 10, maxHeight: 50) brandImage .resizable() @@ -193,28 +170,17 @@ public struct ServerAddressView: View { 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 .accessibilityLabel(Text("Log in", bundle: .module, comment: "Accessibility label of the button which starts the login.")) .accessibilityIdentifier("submitServerAddress") } } - #if !os(macOS) .padding(EdgeInsets(top: 8, leading: 10, bottom: 8, trailing: 10)) .overlay( RoundedRectangle(cornerRadius: 8) .stroke(foregroundColor, lineWidth: 1) ) - #endif if horizontalSizeClass == .regular { Spacer(minLength: 100) @@ -233,7 +199,7 @@ public struct ServerAddressView: View { .multilineTextAlignment(.center) .padding(4) - Spacer() + Spacer().frame(height: 30) actions @@ -262,18 +228,25 @@ public struct ServerAddressView: View { /// @ViewBuilder private var actions: some View { - #if os(iOS) // Camera usually is available on iOS devices only. let isSideBySide = verticalSizeClass == .compact && dynamicTypeSize.isAccessibilitySize == false let layout = isSideBySide ? AnyLayout(HStackLayout(spacing: 12)) : AnyLayout(VStackLayout(spacing: 12)) VStack(spacing: 16) { orSeparator + Spacer().frame(height: 5) + 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) @@ -282,7 +255,6 @@ public struct ServerAddressView: View { } } .frame(maxWidth: actionsMaxWidth) - #endif } private var orSeparator: some View { @@ -316,12 +288,12 @@ public struct ServerAddressView: View { .font(.headline) .foregroundStyle(backgroundColor) .frame(maxWidth: .infinity) - .padding(.vertical, 4) + .padding(.vertical, -3) } .controlSize(.large) .accessibilityIdentifier(identifier) - if #available(iOS 26.0, macOS 26.0, *) { + if #available(iOS 26.0, *) { button.buttonStyle(.glassProminent) } else { button.buttonStyle(.borderedProminent) @@ -339,17 +311,16 @@ public struct ServerAddressView: View { } .textContentType(.URL) .autocorrectionDisabled() - #if os(iOS) .foregroundStyle(foregroundColor) .keyboardType(.URL) .textInputAutocapitalization(.never) .submitLabel(.done) - #endif .onSubmit { model.logIn() } .disabled(configuration.isServerAddressEditable == false) .opacity(configuration.isServerAddressEditable ? 1 : 0.5) + .padding(.vertical, 5) .accessibilityIdentifier("serverAddress") } @@ -380,6 +351,7 @@ public struct ServerAddressView: View { } .foregroundStyle(foregroundColor) } + .padding(.vertical, 5) .accessibilityIdentifier("enforcedServers") } @@ -400,26 +372,6 @@ public struct ServerAddressView: View { .accessibilityIdentifier("cancelLogin") } } - - /// - /// The toolbar entry point for accounts from other apps, as in the login view of the Files app. - /// - private var sharedAccountsToolbarItem: some ToolbarContent { - ToolbarItem(placement: .primaryAction) { - Button { - isPresentingSharedAccounts = true - } label: { - Label { - Text("Accounts from other Apps", bundle: .module, comment: "Button label") - } icon: { - Image(systemName: "person.badge.plus") - } - } - .tint(foregroundColor) - .disabled(model.isActive) - .accessibilityIdentifier("sharedAccounts") - } - } } #if DEBUG @@ -453,7 +405,7 @@ public struct ServerAddressView: View { 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: "cloud"), sharedAccounts: [], configuration: configuration) { _, _, _ in + return ServerAddressView(backgroundColor: .constant(.accentColor), brandImage: Image(systemName: "photo"), sharedAccounts: [], configuration: configuration) { _, _, _ in print("Add account!") } } From f3b5d0d623daa7077a26194f9d6f76bedff49de7 Mon Sep 17 00:00:00 2001 From: Milen Pivchev Date: Wed, 25 Nov 2026 15:22:51 +0100 Subject: [PATCH 25/33] feat(NextcloudKitUI): secondary login buttons and a plain hosting link The other ways to log in use bordered buttons tinted with the foreground color, so the server address stays the main action. The form follows the background's appearance, and "Host your own server" is a plain text button. Assisted-by: Claude Code:claude-opus-5-5 Co-Authored-By: Claude Opus 5.5 Signed-off-by: Milen Pivchev --- .../Views/Login/ServerAddressView.swift | 21 ++++++++----------- 1 file changed, 9 insertions(+), 12 deletions(-) diff --git a/Sources/NextcloudKitUI/Views/Login/ServerAddressView.swift b/Sources/NextcloudKitUI/Views/Login/ServerAddressView.swift index a6e536ce..5c06665f 100644 --- a/Sources/NextcloudKitUI/Views/Login/ServerAddressView.swift +++ b/Sources/NextcloudKitUI/Views/Login/ServerAddressView.swift @@ -206,14 +206,18 @@ public struct ServerAddressView: View { Spacer() if let hostingInformation = configuration.hostingInformation { - actionButton(hostingInformation.title, systemImage: "server.rack", identifier: "hostYourOwnServer") { + Button(hostingInformation.title) { openURL(hostingInformation.url) } - .frame(maxWidth: actionsMaxWidth) + .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) } @@ -273,11 +277,10 @@ public struct ServerAddressView: View { } /// - /// A prominent glass button filled with the foreground color, so the label takes the background color. + /// A secondary button tinted with the foreground color, so the server address stays the main way to log in. /// - @ViewBuilder private func actionButton(_ title: String, systemImage: String, identifier: String, action: @escaping () -> Void) -> some View { - let button = Button(action: action) { + Button(action: action) { Label { Text(verbatim: title) .lineLimit(2) @@ -286,18 +289,12 @@ public struct ServerAddressView: View { Image(systemName: systemImage) } .font(.headline) - .foregroundStyle(backgroundColor) .frame(maxWidth: .infinity) .padding(.vertical, -3) } + .buttonStyle(.bordered) .controlSize(.large) .accessibilityIdentifier(identifier) - - if #available(iOS 26.0, *) { - button.buttonStyle(.glassProminent) - } else { - button.buttonStyle(.borderedProminent) - } } private var serverAddressField: some View { From c4ba9570a0aeb145ac24fafcb581ab78ba64ed1b Mon Sep 17 00:00:00 2001 From: Milen Pivchev Date: Wed, 25 Nov 2026 15:22:52 +0100 Subject: [PATCH 26/33] feat(NextcloudKitUI): let the host replace the server address placeholder Assisted-by: Claude Code:claude-opus-5-5 Co-Authored-By: Claude Opus 5.5 Signed-off-by: Milen Pivchev --- .../NextcloudKitUI/Views/Login/LoginFlowConfiguration.swift | 5 +++++ Sources/NextcloudKitUI/Views/Login/ServerAddressView.swift | 2 +- 2 files changed, 6 insertions(+), 1 deletion(-) diff --git a/Sources/NextcloudKitUI/Views/Login/LoginFlowConfiguration.swift b/Sources/NextcloudKitUI/Views/Login/LoginFlowConfiguration.swift index e05a467b..728052b6 100644 --- a/Sources/NextcloudKitUI/Views/Login/LoginFlowConfiguration.swift +++ b/Sources/NextcloudKitUI/Views/Login/LoginFlowConfiguration.swift @@ -61,6 +61,11 @@ public struct LoginFlowConfiguration: Sendable { /// public var foregroundColor: Color? + /// + /// Replaces the placeholder of the server address field. + /// + public var serverAddressPrompt: String? + /// /// Replaces the hint below the server address field. /// diff --git a/Sources/NextcloudKitUI/Views/Login/ServerAddressView.swift b/Sources/NextcloudKitUI/Views/Login/ServerAddressView.swift index 5c06665f..3f089f21 100644 --- a/Sources/NextcloudKitUI/Views/Login/ServerAddressView.swift +++ b/Sources/NextcloudKitUI/Views/Login/ServerAddressView.swift @@ -302,7 +302,7 @@ public struct ServerAddressView: View { return TextField( text: $model.enteredServerAddress, - prompt: Text(verbatim: "https://example.org/").foregroundColor(foregroundColor.opacity(0.5)) + prompt: Text(verbatim: configuration.serverAddressPrompt ?? "https://example.org/").foregroundColor(foregroundColor.opacity(0.5)) ) { Text("Server Address", bundle: .module, comment: "Label for text field.") } From cd40cf3973456e2f0f01b281ac8869b3b6cc5f48 Mon Sep 17 00:00:00 2001 From: Milen Pivchev Date: Thu, 26 Nov 2026 12:14:26 +0100 Subject: [PATCH 27/33] refactor(NextcloudKitUI): trim login view leftovers Inline the error alert back into ServerAddressView and fold the content property into body. Replace the one-case AlertAction with a Bool and drop dismissAlert(), since the alert clears its binding itself. Collapse the host text overrides into single Text views, inline actionsMaxWidth, use the VStack spacing instead of a spacer, drop a stale "iOS only." remark, and remove the stray empty catalog key and restore its trailing newline. Assisted-by: Claude Code:claude-opus-5-5 Co-Authored-By: Claude Opus 5.5 Signed-off-by: Milen Pivchev --- Sources/NextcloudKitUI/Localizable.xcstrings | 5 +- .../Modifiers/LoginFlowAlert.swift | 45 ------- .../Views/Login/LoginFlowConfiguration.swift | 2 +- .../Views/Login/LoginFlowModel.swift | 31 ++--- .../Views/Login/ServerAddressView.swift | 121 ++++++++---------- .../LoginFlowModelTests.swift | 2 +- 6 files changed, 68 insertions(+), 138 deletions(-) delete mode 100644 Sources/NextcloudKitUI/Modifiers/LoginFlowAlert.swift diff --git a/Sources/NextcloudKitUI/Localizable.xcstrings b/Sources/NextcloudKitUI/Localizable.xcstrings index 117e26de..2be344ee 100644 --- a/Sources/NextcloudKitUI/Localizable.xcstrings +++ b/Sources/NextcloudKitUI/Localizable.xcstrings @@ -1,9 +1,6 @@ { "sourceLanguage" : "en", "strings" : { - "" : { - - }, "%lld groups" : { "comment" : "Recipient summary for multiple groups.", "localizations" : { @@ -12311,4 +12308,4 @@ } }, "version" : "1.0" -} \ No newline at end of file +} diff --git a/Sources/NextcloudKitUI/Modifiers/LoginFlowAlert.swift b/Sources/NextcloudKitUI/Modifiers/LoginFlowAlert.swift deleted file mode 100644 index f0f8b060..00000000 --- a/Sources/NextcloudKitUI/Modifiers/LoginFlowAlert.swift +++ /dev/null @@ -1,45 +0,0 @@ -// SPDX-FileCopyrightText: Nextcloud GmbH -// SPDX-FileCopyrightText: 2026 Milen Pivchev -// SPDX-License-Identifier: GPL-3.0-or-later - -import SwiftUI - -/// -/// The alert for errors of ``LoginFlowModel``, shown by the login view. -/// -struct LoginFlowAlert: ViewModifier { - @Environment(\.openURL) private var openURL - - let model: LoginFlowModel - @Binding var isPresented: Bool - - func body(content: Content) -> some View { - content.alert(String(localized: "Login Failed", bundle: .module, comment: "Alert title"), isPresented: $isPresented) { - if model.alertAction == .openSettings { - Button { - model.dismissAlert() - - 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) { - model.dismissAlert() - } label: { - Text("OK", bundle: .module, comment: "Button label for error alert dismissal.") - } - } message: { - Text(model.errorMessage ?? "?") - } - } -} - -extension View { - func loginFlowAlert(model: LoginFlowModel, isPresented: Binding) -> some View { - modifier(LoginFlowAlert(model: model, isPresented: isPresented)) - } -} diff --git a/Sources/NextcloudKitUI/Views/Login/LoginFlowConfiguration.swift b/Sources/NextcloudKitUI/Views/Login/LoginFlowConfiguration.swift index 728052b6..a4df1907 100644 --- a/Sources/NextcloudKitUI/Views/Login/LoginFlowConfiguration.swift +++ b/Sources/NextcloudKitUI/Views/Login/LoginFlowConfiguration.swift @@ -89,7 +89,7 @@ public struct LoginFlowConfiguration: Sendable { public var enforcedServers: [Server] = [] /// - /// A provider's sign-up page, which must end on the login callback URL with ``loginURLScheme``. iOS only. + /// A provider's sign-up page, which must end on the login callback URL with ``loginURLScheme``. /// public var providerSignUp: WebLink? diff --git a/Sources/NextcloudKitUI/Views/Login/LoginFlowModel.swift b/Sources/NextcloudKitUI/Views/Login/LoginFlowModel.swift index 1ff79eb9..d5688f86 100644 --- a/Sources/NextcloudKitUI/Views/Login/LoginFlowModel.swift +++ b/Sources/NextcloudKitUI/Views/Login/LoginFlowModel.swift @@ -18,13 +18,6 @@ import SwiftUI @MainActor @Observable final class LoginFlowModel: QRCodeParsing, URLSanitizing { - /// - /// An extra action offered by the error alert. - /// - enum AlertAction { - case openSettings - } - private let userAgent: String? private let configuration: LoginFlowConfiguration private let addAccount: AddAccountHandler @@ -44,8 +37,8 @@ final class LoginFlowModel: QRCodeParsing, URLSanitizing { /// Message to display in case of error. var errorMessage: String? - /// Extra action for the error alert. - var alertAction: AlertAction? + /// 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 @@ -63,7 +56,7 @@ final class LoginFlowModel: QRCodeParsing, URLSanitizing { 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?, action: AlertAction?)? + private var codeScannerError: (message: String?, offersSettings: Bool)? /// The login address acquired from the server through the login flow API. var loginAddress: URL? @@ -287,25 +280,19 @@ final class LoginFlowModel: QRCodeParsing, URLSanitizing { return error.localizedGenericMessage } - private func present(error: String?, action: AlertAction? = nil) { + 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, action) + codeScannerError = (error, offersSettings) isPresentingCodeScanner = false return } errorMessage = error - alertAction = action + alertOffersSettings = offersSettings isPresentingAlert = true } - func dismissAlert() { - errorMessage = nil - alertAction = nil - isPresentingAlert = false - } - // MARK: - QR code func presentCodeScanner() { @@ -315,7 +302,7 @@ final class LoginFlowModel: QRCodeParsing, URLSanitizing { // 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, action: .openSettings) + present(error: Self.cameraAccessMessage, offersSettings: true) return default: break @@ -337,7 +324,7 @@ final class LoginFlowModel: QRCodeParsing, URLSanitizing { guard let codeScannerError else { return } self.codeScannerError = nil - present(error: codeScannerError.message, action: codeScannerError.action) + present(error: codeScannerError.message, offersSettings: codeScannerError.offersSettings) } func handleQRCodeScan(_ result: Result) { @@ -345,7 +332,7 @@ final class LoginFlowModel: QRCodeParsing, URLSanitizing { case .success(let result): handleLoginCode(result.string) case .failure(.permissionDenied): - present(error: Self.cameraAccessMessage, action: .openSettings) + present(error: Self.cameraAccessMessage, offersSettings: true) case .failure: present(error: Self.cameraUnavailableMessage) } diff --git a/Sources/NextcloudKitUI/Views/Login/ServerAddressView.swift b/Sources/NextcloudKitUI/Views/Login/ServerAddressView.swift index 3f089f21..5fc5b14b 100644 --- a/Sources/NextcloudKitUI/Views/Login/ServerAddressView.swift +++ b/Sources/NextcloudKitUI/Views/Login/ServerAddressView.swift @@ -78,49 +78,61 @@ public struct ServerAddressView: View { // MARK: - Implementation public var body: some View { - NavigationStack { - content - } - } - - private var content: some View { @Bindable var model = model - return ZStack { - backgroundColor + return NavigationStack { + ZStack { + backgroundColor - // 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) + // 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) + } } } - } - .ignoresSafeArea() - .toolbar { - if configuration.showsCancelButton { - cancelToolbarItem + .ignoresSafeArea() + .toolbar { + if configuration.showsCancelButton { + cancelToolbarItem + } } - } - .toolbarBackground(.hidden, for: .navigationBar) - .sharedAccountsSheet(isPresented: $isPresentingSharedAccounts, sharedAccounts: sharedAccounts, selectionHandler: { model.selectSharedAccount($0) }) - // 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. - guard model.isPresentingLoginPage, let loginAddress = model.loginAddress else { return } + .toolbarBackground(.hidden, for: .navigationBar) + .sharedAccountsSheet(isPresented: $isPresentingSharedAccounts, sharedAccounts: sharedAccounts, selectionHandler: { model.selectSharedAccount($0) }) + // 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. + guard model.isPresentingLoginPage, let loginAddress = model.loginAddress else { return } + + await model.presentLoginPage(loginAddress, using: webAuthenticationSession) + } + .alert(String(localized: "Login Failed", bundle: .module, comment: "Alert title"), isPresented: $model.isPresentingAlert) { + 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.") + } + } - await model.presentLoginPage(loginAddress, using: webAuthenticationSession) + Button(role: .cancel) {} label: { + Text("OK", bundle: .module, comment: "Button label for error alert dismissal.") + } + } message: { + Text(model.errorMessage ?? "?") + } } - .loginFlowAlert(model: model, isPresented: $model.isPresentingAlert) } private func scrollingForm(minHeight: CGFloat) -> some View { @@ -187,17 +199,11 @@ public struct ServerAddressView: View { } } - Group { - if let serverAddressDescription = configuration.serverAddressDescription { - Text(verbatim: serverAddressDescription) - } else { - 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(foregroundColor) - .font(.footnote) - .multilineTextAlignment(.center) - .padding(4) + 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) @@ -222,11 +228,6 @@ public struct ServerAddressView: View { .safeAreaPadding(.all) } - /// As wide as the server address field, up to a readable width on large screens. - private var actionsMaxWidth: CGFloat { - horizontalSizeClass == .regular ? 500 : .infinity - } - /// /// The other ways to log in, below an "or", side by side when the height is compact. /// @@ -235,11 +236,9 @@ public struct ServerAddressView: View { let isSideBySide = verticalSizeClass == .compact && dynamicTypeSize.isAccessibilitySize == false let layout = isSideBySide ? AnyLayout(HStackLayout(spacing: 12)) : AnyLayout(VStackLayout(spacing: 12)) - VStack(spacing: 16) { + VStack(spacing: 37) { orSeparator - Spacer().frame(height: 5) - 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() @@ -258,7 +257,7 @@ public struct ServerAddressView: View { } } } - .frame(maxWidth: actionsMaxWidth) + .frame(maxWidth: horizontalSizeClass == .regular ? 500 : .infinity) } private var orSeparator: some View { @@ -331,16 +330,8 @@ public struct ServerAddressView: View { } } label: { HStack { - Group { - if let selectedServer { - Text(verbatim: selectedServer.name) - } else if let enforcedServersPrompt = configuration.enforcedServersPrompt { - Text(verbatim: enforcedServersPrompt) - } else { - Text("Select a server", bundle: .module, comment: "Label of the server picker in the login view before a server was picked.") - } - } - .lineLimit(1) + 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() diff --git a/Tests/NextcloudKitUITests/LoginFlowModelTests.swift b/Tests/NextcloudKitUITests/LoginFlowModelTests.swift index d6623a34..237bf54b 100644 --- a/Tests/NextcloudKitUITests/LoginFlowModelTests.swift +++ b/Tests/NextcloudKitUITests/LoginFlowModelTests.swift @@ -346,7 +346,7 @@ struct LoginFlowModelTests { model.codeScannerDidClose() #expect(model.isPresentingAlert) - #expect(model.alertAction == .openSettings) + #expect(model.alertOffersSettings) } @Test func cancelWhileRecoveringStopsTheLogin() async throws { From baab4186c02d7bbdae9383e42540a10b211b1c7c Mon Sep 17 00:00:00 2001 From: Milen Pivchev Date: Thu, 26 Nov 2026 12:16:07 +0100 Subject: [PATCH 28/33] refactor(NextcloudKitUI): drop the login options nobody sets Setting onCancel now shows the cancel button, replacing showsCancelButton. The polling timeout becomes a private constant, as it follows the server's token lifetime. LoginFlowModel keeps one task for the whole login, polling inline after the login page opens, and treats a missing server error handler as presentError. Assisted-by: Claude Code:claude-opus-5-5 Co-Authored-By: Claude Opus 5.5 Signed-off-by: Milen Pivchev --- .../Views/Login/LoginFlowConfiguration.swift | 9 +- .../Views/Login/LoginFlowModel.swift | 89 ++++++++----------- .../Views/Login/ServerAddressView.swift | 4 +- 3 files changed, 41 insertions(+), 61 deletions(-) diff --git a/Sources/NextcloudKitUI/Views/Login/LoginFlowConfiguration.swift b/Sources/NextcloudKitUI/Views/Login/LoginFlowConfiguration.swift index a4df1907..99823a1b 100644 --- a/Sources/NextcloudKitUI/Views/Login/LoginFlowConfiguration.swift +++ b/Sources/NextcloudKitUI/Views/Login/LoginFlowConfiguration.swift @@ -108,10 +108,8 @@ public struct LoginFlowConfiguration: Sendable { /// public var loginURLScheme = "nc" - public var showsCancelButton = false - /// - /// Called after the cancel button ended the login. The host dismisses the view. + /// Shows a cancel button, which ends the login and then calls this. The host dismisses the view. /// public var onCancel: CancelHandler? @@ -120,10 +118,5 @@ public struct LoginFlowConfiguration: Sendable { /// public var onServerError: ServerErrorHandler? - /// - /// Ends polling for the login result after this time. Matches the lifetime of a login flow token on the server. - /// - public var pollingTimeout: Duration = .seconds(20 * 60) - public init() {} } diff --git a/Sources/NextcloudKitUI/Views/Login/LoginFlowModel.swift b/Sources/NextcloudKitUI/Views/Login/LoginFlowModel.swift index d5688f86..0ac3be59 100644 --- a/Sources/NextcloudKitUI/Views/Login/LoginFlowModel.swift +++ b/Sources/NextcloudKitUI/Views/Login/LoginFlowModel.swift @@ -61,8 +61,10 @@ final class LoginFlowModel: QRCodeParsing, URLSanitizing { /// The login address acquired from the server through the login flow API. var loginAddress: URL? - private var startTask: Task? - 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 @@ -87,12 +89,10 @@ final class LoginFlowModel: QRCodeParsing, URLSanitizing { /// Check the server, request the login flow, present its web page and begin polling. /// func start(serverURL: URL) { - startTask?.cancel() - pollingTask?.cancel() - pollingTask = nil + loginTask?.cancel() isActive = true - startTask = Task { + loginTask = Task { let options = NKRequestOptions(customUserAgent: userAgent) let (_, statusResult) = await NextcloudKit.shared.getServerStatusAsync(serverUrl: serverURL.absoluteString, options: options) @@ -109,10 +109,10 @@ final class LoginFlowModel: QRCodeParsing, URLSanitizing { guard Task.isCancelled == false else { return } - startPolling(token: token, endpoint: endpoint) - loginAddress = login isPresentingLoginPage = true + + await poll(token: token, endpoint: endpoint, options: options) } catch { guard Task.isCancelled == false else { return } @@ -122,14 +122,9 @@ final class LoginFlowModel: QRCodeParsing, URLSanitizing { } private func recover(from error: NKError, serverURL: URL) async { - guard let onServerError = configuration.onServerError else { - endLogin(error) - return - } - nkLog(error: "Login server check failed: \(error.logDescription)") - let recovery = await onServerError(error, serverURL) + let recovery = await configuration.onServerError?(error, serverURL) ?? .presentError // The user may have cancelled while the host was asking how to recover. guard Task.isCancelled == false else { return } @@ -145,43 +140,37 @@ final class LoginFlowModel: QRCodeParsing, URLSanitizing { } } - private func startPolling(token: String, endpoint: URL) { - let deadline = ContinuousClock.now + configuration.pollingTimeout - - pollingTask = Task { [weak self] in - guard let self else { return } - - let options = NKRequestOptions(customUserAgent: self.userAgent) - - while Task.isCancelled == false { - guard ContinuousClock.now < deadline else { - self.cancel() - self.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 - } + private func poll(token: String, endpoint: URL, options: NKRequestOptions) async { + let deadline = ContinuousClock.now + Self.pollingTimeout - let poll = await NextcloudKit.shared.getLoginFlowV2PollAsync(token: token, endpoint: endpoint.absoluteString, options: options) + 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 + } - guard Task.isCancelled == false else { return } + let result = await NextcloudKit.shared.getLoginFlowV2PollAsync(token: token, endpoint: endpoint.absoluteString, options: options) - 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 - } + guard Task.isCancelled == false else { return } - // HTTP 404 means the flow is still pending, as do network blips while the user is in the browser. - let isPending = poll.error == .success || poll.responseData?.response?.statusCode == 404 || LoginPollingPolicy.isTransient(poll.error) + 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 + } - if isPending == false { - self.endLogin(poll.error) - 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) - try? await Task.sleep(for: .seconds(1)) + if isPending == false { + endLogin(result.error) + return } + + try? await Task.sleep(for: .seconds(1)) } } @@ -195,7 +184,7 @@ final class LoginFlowModel: QRCodeParsing, URLSanitizing { return } - pollingTask?.cancel() + loginTask?.cancel() complete(host: credentials.host, name: credentials.user, password: credentials.password) } catch { // Already handled when the login completed or was cancelled. @@ -215,12 +204,12 @@ final class LoginFlowModel: QRCodeParsing, URLSanitizing { /// - 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) { - pollingTask = nil + loginTask = nil isPresentingLoginPage = false isActive = true isAddingAccount = true - // Not a child of the polling or presentation task, which end when the login page closes. + // Not a child of the login or presentation task, which end when the login page closes. Task { do { try await addAccount(host, name, password) @@ -247,10 +236,8 @@ final class LoginFlowModel: QRCodeParsing, URLSanitizing { /// Stop the login. Called when the login page is closed, regardless of the reason. /// func cancel() { - startTask?.cancel() - startTask = nil - pollingTask?.cancel() - pollingTask = nil + loginTask?.cancel() + loginTask = nil isActive = false isPresentingLoginPage = false } diff --git a/Sources/NextcloudKitUI/Views/Login/ServerAddressView.swift b/Sources/NextcloudKitUI/Views/Login/ServerAddressView.swift index 5fc5b14b..1eaead3d 100644 --- a/Sources/NextcloudKitUI/Views/Login/ServerAddressView.swift +++ b/Sources/NextcloudKitUI/Views/Login/ServerAddressView.swift @@ -96,7 +96,7 @@ public struct ServerAddressView: View { } .ignoresSafeArea() .toolbar { - if configuration.showsCancelButton { + if configuration.onCancel != nil { cancelToolbarItem } } @@ -406,7 +406,7 @@ public struct ServerAddressView: View { 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.showsCancelButton = true + configuration.onCancel = {} return ServerAddressView(backgroundColor: .constant(.orange), brandImage: Image(systemName: "cloud"), sharedAccounts: [], configuration: configuration) { _, _, _ in print("Add account!") From fa48a8d041068423c88bcab92a36a5014c8138bc Mon Sep 17 00:00:00 2001 From: Milen Pivchev Date: Thu, 26 Nov 2026 12:16:07 +0100 Subject: [PATCH 29/33] test(NextcloudKitUI): merge overlapping login flow tests Assisted-by: Claude Code:claude-opus-5-5 Co-Authored-By: Claude Opus 5.5 Signed-off-by: Milen Pivchev --- .../LoginFlowModelTests.swift | 72 ++++++++----------- 1 file changed, 28 insertions(+), 44 deletions(-) diff --git a/Tests/NextcloudKitUITests/LoginFlowModelTests.swift b/Tests/NextcloudKitUITests/LoginFlowModelTests.swift index 237bf54b..cda78aa7 100644 --- a/Tests/NextcloudKitUITests/LoginFlowModelTests.swift +++ b/Tests/NextcloudKitUITests/LoginFlowModelTests.swift @@ -30,6 +30,8 @@ struct LoginFlowModelTests { 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 @@ -90,45 +92,18 @@ struct LoginFlowModelTests { #expect(model.errorMessage?.isEmpty == false) } - @Test func loginCodeAddsAccountWhileBusy() async throws { - let recorder = Recorder() - let model = makeModel(recorder: recorder) - - model.handleLoginCode("nc://login/user:jane&password:secret&server:https://cloud.example.com") - - 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(model.isAddingAccount == false) - #expect(model.isPresentingAlert == false) - } - - @Test func thrownAddAccountErrorIsPresented() async throws { - let recorder = Recorder() - let error = NKError(errorCode: 401) - recorder.addAccountError = error - let model = makeModel(recorder: recorder) - - model.handleLoginCode("nc://login/user:jane&password:secret&server:https://cloud.example.com") - - try await waitUntil { model.isPresentingAlert } - - #expect(model.errorMessage == error.localizedGenericMessage) - #expect(model.isActive == 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) @@ -139,10 +114,12 @@ struct LoginFlowModelTests { recorder.addAccountError = error let model = makeModel(recorder: recorder) - model.handleLoginCode("nc://login/user:jane&password:secret&server:https://cloud.example.com") + model.handleLoginCode(loginCode) try await waitUntil { model.isPresentingAlert } + #expect(model.isActive == false) + return model.errorMessage } @@ -152,7 +129,7 @@ struct LoginFlowModelTests { configuration.loginURLScheme = "abc" let model = makeModel(configuration: configuration, recorder: recorder) - model.handleLoginCode("nc://login/user:jane&password:secret&server:https://cloud.example.com") + model.handleLoginCode(loginCode) #expect(model.isPresentingAlert) #expect(model.errorMessage == QRCodeError.invalidPrefix.localizedDescription) @@ -196,7 +173,7 @@ struct LoginFlowModelTests { recorder.serverErrors.append((error, url)) if recorder.serverErrors.count == 1 { - return .retry(URL(string: "http://127.0.0.1:2/")!) // swiftlint:disable:this force_unwrapping + return .retry(URL(string: "http://127.0.0.1:2/")!) } return .cancel @@ -213,16 +190,23 @@ struct LoginFlowModelTests { #expect(model.isPresentingAlert == false) } - @Test func scannedCodeKeepsScannerOpenUntilAccountIsAdded() async throws { + @Test func scannedCodeAddsAccountWhileScannerStaysOpen() async throws { let recorder = Recorder() let model = makeModel(recorder: recorder) model.presentCodeScanner() - model.handleLoginCode("nc://login/user:jane&password:secret&server:https://cloud.example.com") + 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) } @@ -248,7 +232,7 @@ struct LoginFlowModelTests { let model = makeModel(recorder: recorder) model.presentCodeScanner() - model.handleLoginCode("nc://login/user:jane&password:secret&server:https://cloud.example.com") + model.handleLoginCode(loginCode) try await waitUntil { model.isPresentingCodeScanner == false && model.isActive == false } @@ -274,8 +258,8 @@ struct LoginFlowModelTests { let recorder = Recorder() let model = makeModel(recorder: recorder) - model.presentProviderSignUp(URL(string: "http://127.0.0.1:1/signup")!) // swiftlint:disable:this force_unwrapping - model.finishProviderSignUp(callbackURL: URL(string: "nc://login/server:https://cloud.example.com&user:jane&password:secret")!) // swiftlint:disable:this force_unwrapping + 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) @@ -296,7 +280,7 @@ struct LoginFlowModelTests { let recorder = Recorder() let model = makeModel(recorder: recorder) - model.presentProviderSignUp(URL(string: "http://127.0.0.1:1/signup")!) // swiftlint:disable:this force_unwrapping + model.presentProviderSignUp(URL(string: "http://127.0.0.1:1/signup")!) model.providerSignUp = nil model.providerSignUpDidClose() @@ -312,7 +296,7 @@ struct LoginFlowModelTests { 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")!) // swiftlint:disable:this force_unwrapping + 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 } @@ -328,7 +312,7 @@ struct LoginFlowModelTests { let recorder = Recorder() let model = makeModel(recorder: recorder) - model.finishProviderSignUp(callbackURL: URL(string: "nc://login/user:jane")!) // swiftlint:disable:this force_unwrapping + model.finishProviderSignUp(callbackURL: URL(string: "nc://login/user:jane")!) model.providerSignUpDidClose() #expect(model.isPresentingAlert) @@ -357,7 +341,7 @@ struct LoginFlowModelTests { recorder.serverErrors.append((error, url)) recorder.model?.cancel() - return .retry(URL(string: "http://127.0.0.1:2/")!) // swiftlint:disable:this force_unwrapping + return .retry(URL(string: "http://127.0.0.1:2/")!) } let model = makeModel(configuration: configuration, recorder: recorder) From c99187158c2ea60bb82c07dd370a95a31984b61f Mon Sep 17 00:00:00 2001 From: Milen Pivchev Date: Thu, 26 Nov 2026 12:17:01 +0100 Subject: [PATCH 30/33] refactor(NextcloudKitUI): simplify the provider sign-up page Drop the server-redirect callback check, which the navigation policy already covers, and the two forwarding seams pageDidFinish() and webContentProcessDidTerminate(); the tests now call the delegate methods. The model keeps the page color as a SwiftUI Color, WebView builds its web view directly in makeUIView(context:), and the optional user agent is assigned without an if let. Assisted-by: Claude Code:claude-opus-5-5 Co-Authored-By: Claude Opus 5.5 Signed-off-by: Milen Pivchev --- .../Views/Login/ProviderSignUpModel.swift | 44 ++++++------------- .../Views/Login/ProviderSignUpView.swift | 8 +--- .../NextcloudKitUI/Views/Login/WebView.swift | 10 +---- .../ProviderSignUpModelTests.swift | 11 ++--- 4 files changed, 24 insertions(+), 49 deletions(-) diff --git a/Sources/NextcloudKitUI/Views/Login/ProviderSignUpModel.swift b/Sources/NextcloudKitUI/Views/Login/ProviderSignUpModel.swift index fd5cb66f..16bed31a 100644 --- a/Sources/NextcloudKitUI/Views/Login/ProviderSignUpModel.swift +++ b/Sources/NextcloudKitUI/Views/Login/ProviderSignUpModel.swift @@ -47,7 +47,7 @@ final class ProviderSignUpModel: NSObject, Identifiable, WKNavigationDelegate { 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: UIColor? + private(set) var pageColor: Color? @ObservationIgnored private let callbackScheme: String @ObservationIgnored private let onCallback: @MainActor (URL) -> Void @@ -74,9 +74,7 @@ final class ProviderSignUpModel: NSObject, Identifiable, WKNavigationDelegate { configuration.websiteDataStore = .nonPersistent() webView = WKWebView(frame: .zero, configuration: configuration) - if let userAgent { - webView.customUserAgent = userAgent - } + webView.customUserAgent = userAgent super.init() @@ -90,7 +88,7 @@ final class ProviderSignUpModel: NSObject, Identifiable, WKNavigationDelegate { }, webView.observe(\.themeColor, options: [.new]) { [weak self] webView, _ in MainActor.assumeIsolated { - self?.pageColor = webView.themeColor ?? webView.underPageBackgroundColor + self?.pageColor = Color(uiColor: webView.themeColor ?? webView.underPageBackgroundColor) } } ] @@ -202,22 +200,6 @@ final class ProviderSignUpModel: NSObject, Identifiable, WKNavigationDelegate { return NKError(errorCode: statusCode, errorDescription: HTTPURLResponse.localizedString(forStatusCode: statusCode), kind: kind) } - func pageDidFinish() { - reissuedURLs.removeAll() - hasReloadedAfterTermination = false - } - - func webContentProcessDidTerminate() { - // 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)) - } - func showLoadError(_ error: Error) { // Page loads this model replaces end as interrupted or cancelled. let nsError = error as NSError @@ -267,15 +249,10 @@ final class ProviderSignUpModel: NSObject, Identifiable, WKNavigationDelegate { showLoadError(error) } - func webView(_ webView: WKWebView, didReceiveServerRedirectForProvisionalNavigation navigation: WKNavigation!) { - guard let url = webView.url, url.scheme?.lowercased() == callbackScheme else { return } - - finish(callbackURL: url) - } - func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!) { - pageColor = webView.themeColor ?? webView.underPageBackgroundColor - pageDidFinish() + pageColor = Color(uiColor: webView.themeColor ?? webView.underPageBackgroundColor) + reissuedURLs.removeAll() + hasReloadedAfterTermination = false } func webView(_ webView: WKWebView, didFailProvisionalNavigation navigation: WKNavigation!, withError error: Error) { @@ -287,6 +264,13 @@ final class ProviderSignUpModel: NSObject, Identifiable, WKNavigationDelegate { } func webViewWebContentProcessDidTerminate(_ webView: WKWebView) { - webContentProcessDidTerminate() + // 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 index aa4eef7d..b0fd3fe7 100644 --- a/Sources/NextcloudKitUI/Views/Login/ProviderSignUpView.swift +++ b/Sources/NextcloudKitUI/Views/Login/ProviderSignUpView.swift @@ -16,19 +16,15 @@ struct ProviderSignUpView: View { NavigationStack { page // Colored like the page, as in Safari, since the bar does not track the web view's scrolling. - .toolbarBackground(pageColor ?? Color(uiColor: .systemBackground), for: .navigationBar) + .toolbarBackground(model.pageColor ?? Color(uiColor: .systemBackground), for: .navigationBar) .toolbarBackground(.visible, for: .navigationBar) - .toolbarColorScheme(pageColor.map { $0.readable == .white ? .dark : .light }, for: .navigationBar) + .toolbarColorScheme(model.pageColor.map { $0.readable == .white ? .dark : .light }, for: .navigationBar) } .onAppear { model.start() } } - private var pageColor: Color? { - model.pageColor.map { Color(uiColor: $0) } - } - private var page: some View { ZStack { WebView(webView: model.webView) diff --git a/Sources/NextcloudKitUI/Views/Login/WebView.swift b/Sources/NextcloudKitUI/Views/Login/WebView.swift index 33b2a40b..4a20d785 100644 --- a/Sources/NextcloudKitUI/Views/Login/WebView.swift +++ b/Sources/NextcloudKitUI/Views/Login/WebView.swift @@ -36,7 +36,7 @@ public struct WebView: UIViewRepresentable { self.webView = webView } - func makeView() -> WKWebView { + public func makeUIView(context: Context) -> WKWebView { if let webView { return webView } @@ -47,9 +47,7 @@ public struct WebView: UIViewRepresentable { 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)) @@ -58,10 +56,6 @@ public struct WebView: UIViewRepresentable { return webView } - public func makeUIView(context: Context) -> WKWebView { - makeView() - } - public func updateUIView(_ webView: WKWebView, context: Context) {} } diff --git a/Tests/NextcloudKitUITests/ProviderSignUpModelTests.swift b/Tests/NextcloudKitUITests/ProviderSignUpModelTests.swift index 492e7f70..ec6b4ee5 100644 --- a/Tests/NextcloudKitUITests/ProviderSignUpModelTests.swift +++ b/Tests/NextcloudKitUITests/ProviderSignUpModelTests.swift @@ -6,6 +6,7 @@ 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. @@ -49,7 +50,7 @@ struct ProviderSignUpModelTests { #expect(model.policy(for: request, isMainFrame: true) == .reissue(ProviderSignUpModel.request(for: pageURL))) #expect(model.policy(for: request, isMainFrame: true) == .allow) - model.pageDidFinish() + model.webView(model.webView, didFinish: nil) #expect(model.policy(for: request, isMainFrame: true) == .reissue(ProviderSignUpModel.request(for: pageURL))) @@ -109,16 +110,16 @@ struct ProviderSignUpModelTests { @Test func webContentProcessEndReloadsOnceThenFails() { let model = makeModel() - model.webContentProcessDidTerminate() + model.webViewWebContentProcessDidTerminate(model.webView) #expect(model.errorMessage == nil) - model.webContentProcessDidTerminate() + model.webViewWebContentProcessDidTerminate(model.webView) #expect(model.errorMessage != nil) - model.pageDidFinish() - model.webContentProcessDidTerminate() + model.webView(model.webView, didFinish: nil) + model.webViewWebContentProcessDidTerminate(model.webView) #expect(model.errorMessage == nil) } From 17795c5a5f9c9ca1a33026e1463ed68bb8ff9887 Mon Sep 17 00:00:00 2001 From: Milen Pivchev Date: Thu, 26 Nov 2026 12:18:35 +0100 Subject: [PATCH 31/33] refactor(NextcloudKitUI): one login code parser Remove the public LoginCallbackParser and make LoginCredentials internal again, since no app uses them. The login callback is now parsed by parseLoginCallback in QRCodeParsing, next to parseLogin, and the test-only parse(_:) requirement is gone. Parser tests become one invalid-code table plus the callback cases. The always-true isEmpty checks on user and password are dropped. Assisted-by: Claude Code:claude-opus-5-5 Co-Authored-By: Claude Opus 5.5 Signed-off-by: Milen Pivchev --- .../Documentation.docc/Documentation.md | 2 - .../Features/LoginCallbackParser.swift | 20 ----- .../Features/QRCodeParsing.swift | 43 +++++----- .../Views/Login/LoginFlowModel.swift | 4 +- .../LoginCallbackParserTests.swift | 57 ------------- .../QRCodeParsingTests.swift | 79 +++++++++---------- 6 files changed, 58 insertions(+), 147 deletions(-) delete mode 100644 Sources/NextcloudKitUI/Features/LoginCallbackParser.swift delete mode 100644 Tests/NextcloudKitUITests/LoginCallbackParserTests.swift diff --git a/Sources/NextcloudKitUI/Documentation.docc/Documentation.md b/Sources/NextcloudKitUI/Documentation.docc/Documentation.md index b3118849..307f4a13 100644 --- a/Sources/NextcloudKitUI/Documentation.docc/Documentation.md +++ b/Sources/NextcloudKitUI/Documentation.docc/Documentation.md @@ -31,8 +31,6 @@ Apps with branding, managed configuration or their own certificate handling pass - ``ServerAddressView`` - ``AddAccountHandler`` - ``LoginFlowConfiguration`` -- ``LoginCallbackParser`` -- ``LoginCredentials`` ### Account Menu diff --git a/Sources/NextcloudKitUI/Features/LoginCallbackParser.swift b/Sources/NextcloudKitUI/Features/LoginCallbackParser.swift deleted file mode 100644 index f1afaa24..00000000 --- a/Sources/NextcloudKitUI/Features/LoginCallbackParser.swift +++ /dev/null @@ -1,20 +0,0 @@ -// SPDX-FileCopyrightText: Nextcloud GmbH -// SPDX-FileCopyrightText: 2026 Milen Pivchev -// SPDX-License-Identifier: GPL-3.0-or-later - -import Foundation - -/// -/// Parses the `://login/server:…&user:…&password:…` URL a server or sign-up provider redirects to after a successful login. -/// -public enum LoginCallbackParser { - public static func parse(_ url: URL, scheme: String = "nc") throws -> LoginCredentials { - try parse(url.absoluteString, scheme: scheme) - } - - public static func parse(_ string: String, scheme: String = "nc") throws -> LoginCredentials { - let (user, password, host) = try decomposeLoginCode(string, prefix: "\(scheme)://login/", decodingValues: true) - - return LoginCredentials(kind: .login, user: user, password: password, host: host) - } -} diff --git a/Sources/NextcloudKitUI/Features/QRCodeParsing.swift b/Sources/NextcloudKitUI/Features/QRCodeParsing.swift index 63a25b59..a1395371 100644 --- a/Sources/NextcloudKitUI/Features/QRCodeParsing.swift +++ b/Sources/NextcloudKitUI/Features/QRCodeParsing.swift @@ -31,46 +31,32 @@ enum QRCodeError: Error, LocalizedError { /// /// Credentials parsed from a login code, tagged with which login variant they represent. /// -public struct LoginCredentials: Sendable, Equatable { +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`). /// - public enum Kind: Sendable { + enum Kind { case login case onetimeLogin } - public let kind: Kind - public let user: String + let kind: Kind + let user: String /// /// The app password for ``Kind/login`` or the onetime token for ``Kind/onetimeLogin``. /// - public let password: String - public let host: URL + let password: String + let host: URL } /// /// 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 ``LoginCredentials``, distinguishing direct logins /// (`://login/…`) from onetime logins (`://onetime-login/…`). @@ -96,6 +82,15 @@ extension QRCodeParsing { 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) + } } /// @@ -104,7 +99,7 @@ extension QRCodeParsing { /// - 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. /// -func decomposeLoginCode(_ code: String, prefix loginCodePrefix: String, decodingValues: Bool = false) 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 } @@ -149,11 +144,11 @@ func decomposeLoginCode(_ code: String, prefix loginCodePrefix: String, decoding decomposedKeyValuePairs[key] = value } - guard let user = decomposedKeyValuePairs["user"], user.isEmpty == false else { + guard let user = decomposedKeyValuePairs["user"] else { throw QRCodeError.missingUser } - guard let password = decomposedKeyValuePairs["password"], password.isEmpty == false else { + guard let password = decomposedKeyValuePairs["password"] else { throw QRCodeError.missingPassword } diff --git a/Sources/NextcloudKitUI/Views/Login/LoginFlowModel.swift b/Sources/NextcloudKitUI/Views/Login/LoginFlowModel.swift index 0ac3be59..f1d41564 100644 --- a/Sources/NextcloudKitUI/Views/Login/LoginFlowModel.swift +++ b/Sources/NextcloudKitUI/Views/Login/LoginFlowModel.swift @@ -180,7 +180,7 @@ final class LoginFlowModel: QRCodeParsing, URLSanitizing { // A login page that redirects to the callback URL hands over the credentials directly. Otherwise polling continues. guard isPresentingLoginPage, - let credentials = try? LoginCallbackParser.parse(callbackURL, scheme: configuration.loginURLScheme) else { + let credentials = try? parseLoginCallback(callbackURL, scheme: configuration.loginURLScheme) else { return } @@ -395,7 +395,7 @@ final class LoginFlowModel: QRCodeParsing, URLSanitizing { providerSignUpCallbackURL = nil do { - let credentials = try LoginCallbackParser.parse(callbackURL, scheme: configuration.loginURLScheme) + let credentials = try parseLoginCallback(callbackURL, scheme: configuration.loginURLScheme) // 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) diff --git a/Tests/NextcloudKitUITests/LoginCallbackParserTests.swift b/Tests/NextcloudKitUITests/LoginCallbackParserTests.swift deleted file mode 100644 index 36b82daa..00000000 --- a/Tests/NextcloudKitUITests/LoginCallbackParserTests.swift +++ /dev/null @@ -1,57 +0,0 @@ -// SPDX-FileCopyrightText: Nextcloud GmbH -// SPDX-FileCopyrightText: 2026 Milen Pivchev -// SPDX-License-Identifier: GPL-3.0-or-later - -import Foundation -@testable import NextcloudKitUI -import Testing - -/// -/// Tests for ``LoginCallbackParser``. -/// -struct LoginCallbackParserTests { - @Test func validCallback() async throws { - let url = try #require(URL(string: "nc://login/server:https://cloud.example.com&user:jane&password:secret")) - let credentials = try LoginCallbackParser.parse(url) - - #expect(credentials.kind == .login) - #expect(credentials.user == "jane") - #expect(credentials.password == "secret") - #expect(credentials.host.absoluteString == "https://cloud.example.com") - } - - @Test func serverPathIsKept() async throws { - let credentials = try LoginCallbackParser.parse("nc://login/server:https://cloud.example.com/nextcloud&user:jane&password:secret") - - #expect(credentials.host.absoluteString == "https://cloud.example.com/nextcloud") - } - - @Test func plusInUserIsSpace() async throws { - let credentials = try LoginCallbackParser.parse("nc://login/server:https://cloud.example.com&user:jane+doe&password:secret") - - #expect(credentials.user == "jane doe") - } - - @Test func percentEncodedValues() async throws { - let credentials = try LoginCallbackParser.parse("nc://login/server:https://cloud.example.com&user:jane%40example.com&password:se%2Bcret") - - #expect(credentials.user == "jane@example.com") - #expect(credentials.password == "se+cret") - } - - @Test func customScheme() async throws { - let callback = "abc://login/server:https://cloud.example.com&user:jane&password:secret" - - #expect(try LoginCallbackParser.parse(callback, scheme: "abc").user == "jane") - - #expect(throws: QRCodeError.invalidPrefix) { - try LoginCallbackParser.parse(callback) - } - } - - @Test func missingPassword() async throws { - #expect(throws: QRCodeError.missingPassword) { - try LoginCallbackParser.parse("nc://login/server:https://cloud.example.com&user:jane") - } - } -} diff --git a/Tests/NextcloudKitUITests/QRCodeParsingTests.swift b/Tests/NextcloudKitUITests/QRCodeParsingTests.swift index d081c347..e569a5e0 100644 --- a/Tests/NextcloudKitUITests/QRCodeParsingTests.swift +++ b/Tests/NextcloudKitUITests/QRCodeParsingTests.swift @@ -21,39 +21,16 @@ struct QRCodeParsingTests { testSubject = QRCodeParsingTestSubject() } - @Test func emptyCode() async throws { - #expect(throws: QRCodeError.implausibleLength) { - try testSubject.parse("") - } - } - - @Test func invalidPrefix() async throws { - #expect(throws: QRCodeError.invalidPrefix) { - try testSubject.parse("nope://login/&user:test&password:secret&server:http://localhost:8080") - } - } - - @Test func missingUser() async throws { - #expect(throws: QRCodeError.missingUser) { - try testSubject.parse("nc://login/&password:secret&server:http://localhost:8080") - } - } - - @Test func missingPassword() async throws { - #expect(throws: QRCodeError.missingPassword) { - try testSubject.parse("nc://login/&user:test&server:http://localhost:8080") - } - } - - @Test func missingHost() async throws { - #expect(throws: QRCodeError.missingHost) { - try testSubject.parse("nc://login/&user:test&password:secret") - } - } - - @Test func validCode() async throws { - #expect(throws: Never.self) { - try testSubject.parse("nc://login/&user:test&password:secret&server:http://localhost:8080") + @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) } } @@ -73,19 +50,37 @@ struct QRCodeParsingTests { #expect(credentials.password == "token") } - @Test func customScheme() async throws { - let code = "abc://login/user:jane&password:secret&server:https://cloud.example.com" + @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(try testSubject.parseLogin(code, scheme: "abc").user == "jane") + #expect(credentials.kind == .login) + #expect(credentials.user == "jane") + #expect(credentials.password == "secret") + #expect(credentials.host.absoluteString == "https://cloud.example.com/nextcloud") + } - #expect(throws: QRCodeError.invalidPrefix) { - try testSubject.parseLogin(code) - } + @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 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 emptyValues() async throws { - #expect(throws: QRCodeError.missingUser) { - try testSubject.parseLogin("nc://login/user:&password:secret&server:https://cloud.example.com") + @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) } } From 033ecef25631e79747dea05dd49eb8c8a3803d4a Mon Sep 17 00:00:00 2001 From: Milen Pivchev Date: Thu, 26 Nov 2026 12:18:36 +0100 Subject: [PATCH 32/33] refactor(NextcloudKitUI): simplify URL sanitizing and trim its tests Drop the empty-input guard, which the host check already covers, and build the path with its trailing slash in one step. Remove the lowercasesScheme test, which repeats a mistypedSchemeSlashes row, and the swiftlint comments in ProviderSignUpModelTests, which have no effect because Tests is excluded from linting. Assisted-by: Claude Code:claude-opus-5-5 Co-Authored-By: Claude Opus 5.5 Signed-off-by: Milen Pivchev --- Sources/NextcloudKitUI/Features/URLSanitizing.swift | 12 ++---------- .../ProviderSignUpModelTests.swift | 12 ++++++------ Tests/NextcloudKitUITests/URLSanitizingTests.swift | 5 ----- 3 files changed, 8 insertions(+), 21 deletions(-) diff --git a/Sources/NextcloudKitUI/Features/URLSanitizing.swift b/Sources/NextcloudKitUI/Features/URLSanitizing.swift index 32944c0a..55f5262d 100644 --- a/Sources/NextcloudKitUI/Features/URLSanitizing.swift +++ b/Sources/NextcloudKitUI/Features/URLSanitizing.swift @@ -20,10 +20,6 @@ extension URLSanitizing { func sanitize(_ input: String, upgradingInsecureHTTP: Bool = false) -> URL? { var address = input.trimmingCharacters(in: .whitespacesAndNewlines) - guard address.isEmpty == false else { - return nil - } - // 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 != ":" } @@ -49,17 +45,13 @@ extension URLSanitizing { components.query = nil components.fragment = nil - var pathComponents = components.path.split(separator: "/").map(String.init) + var pathComponents = components.path.split(separator: "/") if pathComponents.last == "index.php" { pathComponents.removeLast() } - components.path = "/" + pathComponents.joined(separator: "/") - - if components.path.hasSuffix("/") == false { - components.path += "/" - } + components.path = "/" + pathComponents.map { "\($0)/" }.joined() return components.url } diff --git a/Tests/NextcloudKitUITests/ProviderSignUpModelTests.swift b/Tests/NextcloudKitUITests/ProviderSignUpModelTests.swift index ec6b4ee5..1f954d1d 100644 --- a/Tests/NextcloudKitUITests/ProviderSignUpModelTests.swift +++ b/Tests/NextcloudKitUITests/ProviderSignUpModelTests.swift @@ -15,8 +15,8 @@ import WebKit @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")! // swiftlint:disable:this force_unwrapping - private let pageURL = URL(string: "https://provider.example.com/register")! // swiftlint:disable:this force_unwrapping + 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 } @@ -30,7 +30,7 @@ struct ProviderSignUpModelTests { } @Test func uncachedURLAddsAQueryItem() { - let withQuery = URL(string: "https://nextcloud.com/signup-ios?lang=de")! // swiftlint:disable:this force_unwrapping + 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") @@ -38,7 +38,7 @@ struct ProviderSignUpModelTests { @Test func callbackURLFinishesInAnyLetterCase() { let model = makeModel() - let callbackURL = URL(string: "NC://login/server:https://cloud.example.com&user:jane&password:secret")! // swiftlint:disable:this force_unwrapping + 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)) } @@ -71,8 +71,8 @@ struct ProviderSignUpModelTests { @Test func linksTheWebViewCannotShowOpenInTheirApp() { let model = makeModel() - let mail = URL(string: "mailto:support@provider.example.com")! // swiftlint:disable:this force_unwrapping - let blank = URL(string: "about:blank")! // swiftlint:disable:this force_unwrapping + 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) diff --git a/Tests/NextcloudKitUITests/URLSanitizingTests.swift b/Tests/NextcloudKitUITests/URLSanitizingTests.swift index bab97aff..10454ef2 100644 --- a/Tests/NextcloudKitUITests/URLSanitizingTests.swift +++ b/Tests/NextcloudKitUITests/URLSanitizingTests.swift @@ -82,11 +82,6 @@ struct URLSanitizingTests { #expect(sanitized.absoluteString == "https://cloud.example.com/") } - @Test func lowercasesScheme() async throws { - let sanitized = try #require(testSubject.sanitize("HTTPS://cloud.example.com")) - #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/") From bc0aec8e3548406a32a74078d8cb57ffca82b68a Mon Sep 17 00:00:00 2001 From: Milen Pivchev Date: Thu, 26 Nov 2026 12:38:13 +0100 Subject: [PATCH 33/33] feat(NextcloudKitUI): limit QR code and sign-up logins to the enforced servers With enforcedServers set, a QR code, a one-time QR code or a provider sign-up for another host is refused, and accounts of other apps on other hosts are not offered. Hosts match without regard to letter case, as on Android. Assisted-by: Claude Code:claude-opus-5-5 Co-Authored-By: Claude Opus 5.5 Signed-off-by: Milen Pivchev --- Sources/NextcloudKitUI/Localizable.xcstrings | 3 ++ .../Views/Login/LoginFlowConfiguration.swift | 2 +- .../Views/Login/LoginFlowModel.swift | 25 ++++++++++++++++ .../Views/Login/ServerAddressView.swift | 6 ++-- .../LoginFlowModelTests.swift | 29 +++++++++++++++++++ 5 files changed, 62 insertions(+), 3 deletions(-) diff --git a/Sources/NextcloudKitUI/Localizable.xcstrings b/Sources/NextcloudKitUI/Localizable.xcstrings index 2be344ee..159a6562 100644 --- a/Sources/NextcloudKitUI/Localizable.xcstrings +++ b/Sources/NextcloudKitUI/Localizable.xcstrings @@ -7126,6 +7126,9 @@ "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" : { diff --git a/Sources/NextcloudKitUI/Views/Login/LoginFlowConfiguration.swift b/Sources/NextcloudKitUI/Views/Login/LoginFlowConfiguration.swift index 99823a1b..6c7a8be4 100644 --- a/Sources/NextcloudKitUI/Views/Login/LoginFlowConfiguration.swift +++ b/Sources/NextcloudKitUI/Views/Login/LoginFlowConfiguration.swift @@ -84,7 +84,7 @@ public struct LoginFlowConfiguration: Sendable { public var isServerAddressEditable = true /// - /// When not empty, a picker over these servers replaces the server address field. + /// 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] = [] diff --git a/Sources/NextcloudKitUI/Views/Login/LoginFlowModel.swift b/Sources/NextcloudKitUI/Views/Login/LoginFlowModel.swift index f1d41564..1d59fccb 100644 --- a/Sources/NextcloudKitUI/Views/Login/LoginFlowModel.swift +++ b/Sources/NextcloudKitUI/Views/Login/LoginFlowModel.swift @@ -337,6 +337,11 @@ final class LoginFlowModel: QRCodeParsing, URLSanitizing { do { let credentials = try parseLogin(code, scheme: configuration.loginURLScheme) + guard isAllowed(credentials.host) else { + present(error: Self.serverNotAllowedMessage) + return + } + switch credentials.kind { case .login: complete(host: credentials.host, name: credentials.user, password: credentials.password) @@ -397,6 +402,11 @@ final class LoginFlowModel: QRCodeParsing, URLSanitizing { 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 { @@ -404,6 +414,21 @@ final class LoginFlowModel: QRCodeParsing, URLSanitizing { } } + // 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/ServerAddressView.swift b/Sources/NextcloudKitUI/Views/Login/ServerAddressView.swift index 1eaead3d..a5c8a646 100644 --- a/Sources/NextcloudKitUI/Views/Login/ServerAddressView.swift +++ b/Sources/NextcloudKitUI/Views/Login/ServerAddressView.swift @@ -37,9 +37,11 @@ public struct ServerAddressView: View { 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 + let model = LoginFlowModel(userAgent: userAgent, configuration: configuration, addAccount: addAccount) + + self.sharedAccounts = sharedAccounts.filter { model.isAllowed($0.host) } self.configuration = configuration - self._model = State(initialValue: LoginFlowModel(userAgent: userAgent, configuration: configuration, addAccount: addAccount)) + self._model = State(initialValue: model) } // MARK: - Environment diff --git a/Tests/NextcloudKitUITests/LoginFlowModelTests.swift b/Tests/NextcloudKitUITests/LoginFlowModelTests.swift index cda78aa7..ba48ee34 100644 --- a/Tests/NextcloudKitUITests/LoginFlowModelTests.swift +++ b/Tests/NextcloudKitUITests/LoginFlowModelTests.swift @@ -139,6 +139,35 @@ struct LoginFlowModelTests { 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