Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
35 commits
Select commit Hold shift + click to select a range
89960a3
fix(NextcloudKitUI): sanitize bare hosts and parse login callbacks
mpivchev Nov 19, 2026
e5cce44
feat(NextcloudKitUI): configurable login flow for host apps
mpivchev Nov 19, 2026
6519d63
fix(NextcloudKitUI): only hand server status failures to the host
mpivchev Nov 19, 2026
058a785
fix(NextcloudKitUI): repair server addresses with a mistyped scheme
mpivchev Nov 19, 2026
b25f9b1
fix(NextcloudKitUI): allow cancelling the login until the account is …
mpivchev Nov 19, 2026
0d142bd
feat(NextcloudKitUI): keep the QR code scanner busy while its code lo…
mpivchev Nov 23, 2026
0a52286
fix(NextcloudKitUI): keep the QR code scanner bar readable over the c…
mpivchev Nov 23, 2026
b9392b1
fix(NextcloudKitUI): say no server was found when adding the account …
mpivchev Nov 24, 2026
db33986
feat(NextcloudKitUI): let the host start the login when the view appears
mpivchev Nov 24, 2026
d8480d0
feat(NextcloudKitUI): identify the onboarding button for UI tests
mpivchev Nov 24, 2026
179bd65
feat(NextcloudKitUI): add the provider sign-up page
mpivchev Nov 24, 2026
cc11e00
feat(NextcloudKitUI): offer provider sign-up and hosting information …
mpivchev Nov 24, 2026
546163a
refactor(NextcloudKitUI): drop the login options only the pushed logi…
mpivchev Nov 24, 2026
4c62c1c
fix(NextcloudKitUI): let the QR code scanner read a code again after …
mpivchev Nov 24, 2026
a070188
fix(NextcloudKitUI): keep the login bars transparent on iOS 26
mpivchev Nov 24, 2026
39638c0
feat(NextcloudKitUI): show the login actions as prominent glass buttons
mpivchev Nov 24, 2026
d6c8055
fix(NextcloudKitUI): close the QR code scanner on an error
mpivchev Nov 24, 2026
fde9e71
fix(NextcloudKitUI): color the provider sign-up bar like the page
mpivchev Nov 24, 2026
4309715
feat(NextcloudKitUI): list the other ways to log in below an or
mpivchev Nov 24, 2026
e66e309
feat(NextcloudKitUI): full-width login buttons, hosting link at the b…
mpivchev Nov 25, 2026
ebd2a0a
feat(NextcloudKitUI): fade in the onboarding text
mpivchev Nov 25, 2026
388f5c0
feat(NextcloudKitUI): slow down the onboarding fade-in a little
mpivchev Nov 25, 2026
210d61f
refactor(NextcloudKitUI): drop the macOS conditionals
mpivchev Nov 25, 2026
3789191
feat(NextcloudKitUI): move shared accounts into the login action buttons
mpivchev Nov 25, 2026
f3b5d0d
feat(NextcloudKitUI): secondary login buttons and a plain hosting link
mpivchev Nov 25, 2026
c4ba957
feat(NextcloudKitUI): let the host replace the server address placeho…
mpivchev Nov 25, 2026
476bab4
Merge branch 'main' of https://github.com/nextcloud/NextcloudKit into…
mpivchev Nov 25, 2026
cd40cf3
refactor(NextcloudKitUI): trim login view leftovers
mpivchev Nov 26, 2026
baab418
refactor(NextcloudKitUI): drop the login options nobody sets
mpivchev Nov 26, 2026
fa48a8d
test(NextcloudKitUI): merge overlapping login flow tests
mpivchev Nov 26, 2026
c991871
refactor(NextcloudKitUI): simplify the provider sign-up page
mpivchev Nov 26, 2026
17795c5
refactor(NextcloudKitUI): one login code parser
mpivchev Nov 26, 2026
033ecef
refactor(NextcloudKitUI): simplify URL sanitizing and trim its tests
mpivchev Nov 26, 2026
bc0aec8
feat(NextcloudKitUI): limit QR code and sign-up logins to the enforce…
mpivchev Nov 26, 2026
f870bc9
Merge branch 'main' into shared-login-swiftui
mpivchev Nov 26, 2026
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion Package.swift
Original file line number Diff line number Diff line change
Expand Up @@ -50,6 +50,6 @@ let package = Package(
dependencies: ["NextcloudKit", "Mocker"]),
.testTarget(
name: "NextcloudKitUITests",
dependencies: ["NextcloudKit", "NextcloudKitUI", "Mocker"]),
dependencies: ["NextcloudKit", "NextcloudKitUI", "CodeScanner", "Mocker"]),
]
)
12 changes: 0 additions & 12 deletions Sources/NextcloudKitUI/Color+readable.swift
Original file line number Diff line number Diff line change
Expand Up @@ -21,25 +21,13 @@ extension Color {
}
}

#if os(iOS)
let uiColor = UIColor(self)

var red: CGFloat = 0, green: CGFloat = 0, blue: CGFloat = 0, alpha: CGFloat = 0

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)

Expand Down
9 changes: 6 additions & 3 deletions Sources/NextcloudKitUI/Documentation.docc/Documentation.md
Original file line number Diff line number Diff line change
@@ -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.
Expand All @@ -26,8 +26,11 @@ Key traits of this package:

### Login

Apps with branding, managed configuration or their own certificate handling pass a ``LoginFlowConfiguration`` to ``ServerAddressView``. The view stays busy until the ``AddAccountHandler`` returns and shows the error it throws. With ``LoginFlowConfiguration/providerSignUp`` and ``LoginFlowConfiguration/hostingInformation`` it also offers to sign up with a provider and to read about hosting a server.

- ``ServerAddressView``
- ``AddAccountHandler``
- ``LoginFlowConfiguration``

### Account Menu

Expand Down
22 changes: 22 additions & 0 deletions Sources/NextcloudKitUI/Features/LoginPollingPolicy.swift
Original file line number Diff line number Diff line change
@@ -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
}
}
}
89 changes: 54 additions & 35 deletions Sources/NextcloudKitUI/Features/QRCodeParsing.swift
Original file line number Diff line number Diff line change
Expand Up @@ -5,20 +5,33 @@
import Foundation

///
/// Errors specific to the parsing of Nextcloud login QR codes.
/// Errors specific to the parsing of Nextcloud login codes, as in QR codes or login callback URLs.
///
enum QRCodeError: Error {
enum QRCodeError: Error, LocalizedError {
case implausibleLength
case invalidPrefix
case missingHost
case missingPassword
case missingUser

var errorDescription: String? {
switch self {
case .implausibleLength, .invalidPrefix:
String(localized: "This is not a valid login code.", bundle: .module, comment: "Error message when a scanned QR code is not a Nextcloud login code.")
case .missingHost:
String(localized: "The login code is missing the server address.", bundle: .module, comment: "Error message when a login QR code has no server address.")
case .missingPassword:
String(localized: "The login code is missing the password.", bundle: .module, comment: "Error message when a login QR code has no password.")
case .missingUser:
String(localized: "The login code is missing the user name.", bundle: .module, comment: "Error message when a login QR code has no user name.")
}
}
}

///
/// Credentials parsed from a login QR code, tagged with which login variant they represent.
/// Credentials parsed from a login code, tagged with which login variant they represent.
///
struct ParsedLoginCredentials {
struct LoginCredentials {
///
/// Whether the password is a ready-to-use app password (`login`) or a onetime token that
/// still has to be exchanged for an app password (`onetimeLogin`).
Expand All @@ -41,32 +54,18 @@ struct ParsedLoginCredentials {
///
/// Logic for parsing the atomic data values from a composite string as provided through a QR code for logging in.
///
protocol QRCodeParsing {
///
/// Extract individual bits from a composite string as in an QR code for logging in.
///
/// - Parameters:
/// - code: The raw string which is attained from a scanned QR code.
///
/// - Returns: A tuple consisting of the user name, app password and server address in this exact order.
///
func parse(_ code: String) throws -> (user: String, password: String, host: URL)
}
protocol QRCodeParsing {}

extension QRCodeParsing {
func parse(_ code: String) throws -> (user: String, password: String, host: URL) {
try decomposeLoginCode(code, prefix: "nc://login/")
}

///
/// Parse a login QR code into ``ParsedLoginCredentials``, distinguishing direct logins
/// (`nc://login/…`) from onetime logins (`nc://onetime-login/…`).
/// Parse a login QR code into ``LoginCredentials``, distinguishing direct logins
/// (`<scheme>://login/…`) from onetime logins (`<scheme>://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) {
Expand All @@ -80,14 +79,27 @@ extension QRCodeParsing {
}

let (user, password, host) = try decomposeLoginCode(code, prefix: prefix)
return ParsedLoginCredentials(kind: kind, user: user, password: password, host: host)

return LoginCredentials(kind: kind, user: user, password: password, host: host)
}

///
/// Parse the `<scheme>://login/…` URL a server or sign-up provider redirects to after a successful login.
///
func parseLoginCallback(_ url: URL, scheme: String = "nc") throws -> LoginCredentials {
let (user, password, host) = try decomposeLoginCode(url.absoluteString, prefix: "\(scheme)://login/", decodingValues: true)

return LoginCredentials(kind: .login, user: user, password: password, host: host)
}
}

///
/// Decompose a `<prefix>user:…&password:…&server:…` login code into its values.
/// Decompose a `<prefix>user:…&password:…&server:…` login code into its values, in any order.
///
/// - Parameters:
/// - decodingValues: Whether values are percent-decoded and `+` in the user name means a space, as in the URL the server redirects to after a login.
///
private func decomposeLoginCode(_ code: String, prefix loginCodePrefix: String) throws -> (user: String, password: String, host: URL) {
private func decomposeLoginCode(_ code: String, prefix loginCodePrefix: String, decodingValues: Bool = false) throws -> (user: String, password: String, host: URL) {
guard code.count > loginCodePrefix.count else {
throw QRCodeError.implausibleLength
}
Expand All @@ -108,11 +120,7 @@ private func decomposeLoginCode(_ code: String, prefix loginCodePrefix: String)
throw QRCodeError.missingHost
}

guard let prefixRange = code.range(of: loginCodePrefix) else {
throw QRCodeError.invalidPrefix
}

let compositeKeyValuePairs = code[prefixRange.upperBound...].components(separatedBy: "&")
let compositeKeyValuePairs = code.dropFirst(loginCodePrefix.count).components(separatedBy: "&")
var decomposedKeyValuePairs = [String: String]()

compositeKeyValuePairs.forEach { compositeKeyValuePair in
Expand All @@ -122,7 +130,18 @@ private func decomposeLoginCode(_ code: String, prefix loginCodePrefix: String)
return
}

decomposedKeyValuePairs[String(parts[0])] = String(parts[1])
let key = String(parts[0])
var value = String(parts[1])

if decodingValues {
if key == "user" {
value = value.replacingOccurrences(of: "+", with: " ")
}

value = value.removingPercentEncoding ?? value
}

decomposedKeyValuePairs[key] = value
}

guard let user = decomposedKeyValuePairs["user"] else {
Expand All @@ -133,7 +152,7 @@ private func decomposeLoginCode(_ code: String, prefix loginCodePrefix: String)
throw QRCodeError.missingPassword
}

guard let hostString = decomposedKeyValuePairs["server"], let host = URL(string: hostString) else {
guard let hostString = decomposedKeyValuePairs["server"], let host = URL(string: hostString), host.host != nil else {
throw QRCodeError.missingHost
}

Expand Down
67 changes: 34 additions & 33 deletions Sources/NextcloudKitUI/Features/URLSanitizing.swift
Original file line number Diff line number Diff line change
Expand Up @@ -7,51 +7,52 @@ import Foundation
///
/// Turn user input of a server address into a sanitized URL.
///
/// - Returns: If `input` is a valid URL, then the sanitized `URL` and otherwise `nil`.
///
protocol URLSanitizing {
func sanitize(_ input: String) -> URL?
}
protocol URLSanitizing {}

extension URLSanitizing {
func sanitize(_ input: String) -> URL? {
guard input.isEmpty == false else {
return nil
///
/// - Parameters:
/// - input: The server address as typed, with or without scheme, port, path or a trailing `index.php`.
/// - upgradingInsecureHTTP: Whether an explicit `http` scheme is replaced with `https`.
///
/// - Returns: If `input` is a valid HTTP(S) address, then the sanitized `URL` ending in `/` and otherwise `nil`.
///
func sanitize(_ input: String, upgradingInsecureHTTP: Bool = false) -> URL? {
var address = input.trimmingCharacters(in: .whitespacesAndNewlines)

// Repair a scheme typed with fewer than two slashes, such as "https:/host".
if let range = address.range(of: #"^https?:/?(?!/)"#, options: [.regularExpression, .caseInsensitive]) {
let scheme = address[range].prefix { $0 != ":" }
address.replaceSubrange(range, with: "\(scheme)://")
}

guard var components = URLComponents(string: input) else {
return nil
// Without a scheme, URLComponents reads "host" as a path and "host:8080" as a scheme.
if address.hasPrefix("//") {
address = "https:\(address)"
} else if address.contains("://") == false {
address = "https://\(address)"
}

// Ensure HTTP(S) is used.
if let givenScheme = components.scheme {
if ["http", "https"].contains(givenScheme) == false {
return nil
}
} else {
components.scheme = "https"
guard var components = URLComponents(string: address),
let scheme = components.scheme?.lowercased(),
["http", "https"].contains(scheme),
let host = components.host,
host.isEmpty == false else {
return nil
}

if components.path.isEmpty {
components.path = "/"
} else {
// Drop last path component, if it is a PHP script.
let pathComponents = components.path.split(separator: "/")
components.scheme = upgradingInsecureHTTP ? "https" : scheme
components.query = nil
components.fragment = nil

if let lastPathComponent = pathComponents.last, lastPathComponent == "index.php" {
components.path = pathComponents.dropLast().joined(separator: "/")
}
var pathComponents = components.path.split(separator: "/")

// Add trailing slash, if missing.
if components.path.hasSuffix("/") == false {
components.path = "\(components.path)/"
}
if pathComponents.last == "index.php" {
pathComponents.removeLast()
}

guard let url = components.url else {
return nil
}
components.path = "/" + pathComponents.map { "\($0)/" }.joined()

return url
return components.url
}
}
4 changes: 0 additions & 4 deletions Sources/NextcloudKitUI/Image+appIcon.swift
Original file line number Diff line number Diff line change
Expand Up @@ -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
}
}
Loading
Loading