Anmeldung über die Plex-Seite statt über einen Code
Kein Code mehr zum Abtippen. Die Anmeldemaske kommt von Plex und öffnet sich über ASWebAuthenticationSession in einem Fenster innerhalb der App; nach dem Anmelden schickt Plex über forwardUrl auf ein eigenes Schema zurück, das Fenster schließt sich von selbst. Der PIN steckt weiterhin darunter — er ist der einzige Weg, auf dem Plex einen Token herausgibt. Sichtbar ist er nicht mehr. Was das bringt: - Kein Fernseher-Gefühl mehr. - Zwei-Faktor läuft mit, weil Plex die Seite selbst ausliefert. - Das Passwort erreicht Flixy nie. Steht auch so unter dem Knopf. - prefersEphemeralWebBrowserSession = false: wer in Safari schon bei Plex angemeldet ist, braucht nur zu bestätigen. Zwei Details, die sonst still scheitern: - Die Rückadresse wird strenger kodiert als die übrigen Werte. `:` und `/` lässt urlQueryAllowed durch, und für Plex endete der Wert dann beim ersten Schrägstrich — der Rücksprung käme nie. - Das Schema muss in CFBundleURLTypes stehen, sonst kennt iOS es nicht und das Fenster bliebe offen stehen. Als Schema die Bundle-Kennung statt eines kurzen Worts wie „flixy": ein kurzes könnte eine andere App beanspruchen und die Anmeldung abfangen. 132 Tests. Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
This commit is contained in:
@@ -28,6 +28,20 @@ enum Branding {
|
||||
Bundle.main.bundleIdentifier ?? "com.scarriffleservices.flixy"
|
||||
}
|
||||
|
||||
/// Das eigene URL-Schema, über das Plex nach der Anmeldung zurückschickt.
|
||||
///
|
||||
/// Die Bundle-Kennung statt eines kurzen Wortes wie „flixy": sie ist
|
||||
/// garantiert eindeutig. Bei einem kurzen Schema könnte eine andere App
|
||||
/// denselben Namen beanspruchen und die Anmeldung abfangen.
|
||||
static var urlScheme: String {
|
||||
Bundle.main.bundleIdentifier ?? "com.scarriffleservices.flixy"
|
||||
}
|
||||
|
||||
/// Wohin Plex nach der Anmeldung zurückschickt.
|
||||
static var authCallbackURL: URL {
|
||||
URL(string: "\(urlScheme)://auth")!
|
||||
}
|
||||
|
||||
/// Die Version aus dem Bundle, für die Kopfzeile `X-Plex-Version`.
|
||||
static var version: String {
|
||||
Bundle.main.object(forInfoDictionaryKey: "CFBundleShortVersionString") as? String ?? "0"
|
||||
|
||||
@@ -18,6 +18,17 @@
|
||||
<string>APPL</string>
|
||||
<key>CFBundleShortVersionString</key>
|
||||
<string>1.0</string>
|
||||
<key>CFBundleURLTypes</key>
|
||||
<array>
|
||||
<dict>
|
||||
<key>CFBundleURLName</key>
|
||||
<string>com.scarriffleservices.flixy.auth</string>
|
||||
<key>CFBundleURLSchemes</key>
|
||||
<array>
|
||||
<string>com.scarriffleservices.flixy</string>
|
||||
</array>
|
||||
</dict>
|
||||
</array>
|
||||
<key>CFBundleVersion</key>
|
||||
<string>1</string>
|
||||
<key>NSAppTransportSecurity</key>
|
||||
|
||||
+2035
-2036
File diff suppressed because it is too large
Load Diff
@@ -14,8 +14,8 @@ final class FlixySession {
|
||||
/// Beim Start: liegt ein Token im Schlüsselbund?
|
||||
case launching
|
||||
case signedOut
|
||||
/// Der Code steht bereit, der Nutzer bestätigt ihn im Browser.
|
||||
case awaitingAuthorization(PlexPin)
|
||||
/// Das Anmeldefenster von Plex ist offen.
|
||||
case authenticating
|
||||
/// Mehrere Server am Konto — einer muss gewählt werden.
|
||||
case choosingServer([PlexResource])
|
||||
/// Ein Weg zum Server wird gesucht.
|
||||
@@ -27,8 +27,8 @@ final class FlixySession {
|
||||
switch (lhs, rhs) {
|
||||
case (.launching, .launching), (.signedOut, .signedOut), (.ready, .ready):
|
||||
true
|
||||
case (.awaitingAuthorization(let l), .awaitingAuthorization(let r)):
|
||||
l.id == r.id
|
||||
case (.authenticating, .authenticating):
|
||||
true
|
||||
case (.choosingServer(let l), .choosingServer(let r)):
|
||||
l.map(\.clientIdentifier) == r.map(\.clientIdentifier)
|
||||
case (.connecting(let l), .connecting(let r)):
|
||||
@@ -58,6 +58,7 @@ final class FlixySession {
|
||||
private let identity: PlexClientIdentity
|
||||
private let tokenStore: any TokenStoring
|
||||
private let authenticator: PlexAuthenticator
|
||||
private let webAuthenticator = PlexWebAuthenticator()
|
||||
private let defaults: UserDefaults
|
||||
private var authorizationTask: Task<Void, Never>?
|
||||
|
||||
@@ -85,11 +86,47 @@ final class FlixySession {
|
||||
|
||||
// MARK: - Anmeldung
|
||||
|
||||
/// Öffnet die Anmeldeseite von Plex.
|
||||
///
|
||||
/// Der PIN steckt weiterhin darunter — er ist der einzige Weg, auf dem
|
||||
/// Plex einen Token herausgibt. Sichtbar ist er nicht mehr: Plex liefert
|
||||
/// seine eigene Anmeldemaske aus und schickt die App danach über
|
||||
/// `forwardUrl` zurück.
|
||||
func beginSignIn() async {
|
||||
phase = .authenticating
|
||||
|
||||
do {
|
||||
let pin = try await authenticator.requestPin()
|
||||
phase = .awaitingAuthorization(pin)
|
||||
waitForAuthorization(of: pin)
|
||||
|
||||
guard let url = pin.authorizationURL(
|
||||
clientIdentifier: identity.clientIdentifier,
|
||||
product: Branding.plexProduct,
|
||||
forwardURL: Branding.authCallbackURL
|
||||
) else {
|
||||
phase = .failed(message: String(localized: "signIn.windowFailed"))
|
||||
return
|
||||
}
|
||||
|
||||
try await webAuthenticator.authenticate(
|
||||
url: url,
|
||||
callbackScheme: Branding.urlScheme
|
||||
)
|
||||
|
||||
// Das Fenster ist zu, jetzt liegt der Token bereit. Kurz
|
||||
// nachgefragt statt sofort erwartet: zwischen dem Rücksprung und
|
||||
// dem Eintrag bei Plex liegen manchmal ein, zwei Sekunden.
|
||||
let token = try await authenticator.waitForAuthorization(
|
||||
pin: pin,
|
||||
pollInterval: .milliseconds(500),
|
||||
timeout: .seconds(20)
|
||||
)
|
||||
await connect(accountToken: token)
|
||||
|
||||
} catch PlexWebAuthenticator.Failure.cancelled {
|
||||
// Fenster geschlossen. Kein Fehler — kommentarlos zurück.
|
||||
phase = .signedOut
|
||||
} catch let error as PlexWebAuthenticator.Failure {
|
||||
phase = .failed(message: webAuthenticationMessage(for: error))
|
||||
} catch {
|
||||
phase = .failed(message: message(for: error))
|
||||
}
|
||||
@@ -101,17 +138,10 @@ final class FlixySession {
|
||||
phase = .signedOut
|
||||
}
|
||||
|
||||
private func waitForAuthorization(of pin: PlexPin) {
|
||||
authorizationTask?.cancel()
|
||||
authorizationTask = Task { [authenticator] in
|
||||
do {
|
||||
let token = try await authenticator.waitForAuthorization(pin: pin)
|
||||
guard !Task.isCancelled else { return }
|
||||
await connect(accountToken: token)
|
||||
} catch {
|
||||
guard !Task.isCancelled else { return }
|
||||
phase = .failed(message: message(for: error))
|
||||
}
|
||||
private func webAuthenticationMessage(for failure: PlexWebAuthenticator.Failure) -> String {
|
||||
switch failure {
|
||||
case .cancelled: String(localized: "signIn.cancelled")
|
||||
case .presentationFailed(let description): description
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,74 @@
|
||||
import AuthenticationServices
|
||||
import Foundation
|
||||
import UIKit
|
||||
|
||||
/// Öffnet die Anmeldeseite von Plex in einem Fenster innerhalb der App.
|
||||
///
|
||||
/// `ASWebAuthenticationSession` ist dafür der vorgesehene Weg: die Seite kommt
|
||||
/// von Plex, das Passwort wird dort eingegeben und erreicht die App nie. Nach
|
||||
/// dem Anmelden schickt Plex den Browser auf eine Adresse mit unserem eigenen
|
||||
/// Schema, das Fenster schließt sich von selbst, und die App weiß, dass sie
|
||||
/// den Token abholen kann.
|
||||
///
|
||||
/// Ein einfacher `SFSafariViewController` täte es nicht: er meldet nicht, wann
|
||||
/// die Rückadresse erreicht wurde, und müsste von Hand geschlossen werden.
|
||||
@MainActor
|
||||
final class PlexWebAuthenticator: NSObject {
|
||||
enum Failure: Error, Equatable {
|
||||
/// Der Nutzer hat das Fenster geschlossen. Kein Fehler im eigentlichen
|
||||
/// Sinn — die Oberfläche soll darauf kommentarlos zurückgehen.
|
||||
case cancelled
|
||||
case presentationFailed(String)
|
||||
}
|
||||
|
||||
/// Führt die Anmeldung durch und kehrt zurück, sobald Plex die App
|
||||
/// zurückgeschickt hat.
|
||||
func authenticate(url: URL, callbackScheme: String) async throws(Failure) {
|
||||
do {
|
||||
try await withCheckedThrowingContinuation { (continuation: CheckedContinuation<Void, any Error>) in
|
||||
let session = ASWebAuthenticationSession(
|
||||
url: url,
|
||||
callbackURLScheme: callbackScheme
|
||||
) { _, error in
|
||||
if let error {
|
||||
continuation.resume(throwing: error)
|
||||
} else {
|
||||
continuation.resume()
|
||||
}
|
||||
}
|
||||
|
||||
session.presentationContextProvider = self
|
||||
// `false`, damit eine bestehende Plex-Anmeldung in Safari
|
||||
// mitgenutzt wird: wer dort schon angemeldet ist, braucht nur
|
||||
// zu bestätigen statt das Passwort erneut einzugeben.
|
||||
session.prefersEphemeralWebBrowserSession = false
|
||||
|
||||
guard session.start() else {
|
||||
continuation.resume(throwing: Failure.presentationFailed(
|
||||
String(localized: "signIn.windowFailed")
|
||||
))
|
||||
return
|
||||
}
|
||||
}
|
||||
} catch let error as ASWebAuthenticationSessionError where error.code == .canceledLogin {
|
||||
throw .cancelled
|
||||
} catch let error as Failure {
|
||||
throw error
|
||||
} catch {
|
||||
throw .presentationFailed(error.localizedDescription)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
extension PlexWebAuthenticator: ASWebAuthenticationPresentationContextProviding {
|
||||
func presentationAnchor(for session: ASWebAuthenticationSession) -> ASPresentationAnchor {
|
||||
// Das Fenster der App. Über die verbundenen Szenen gesucht, weil eine
|
||||
// SwiftUI-App keinen festen Verweis darauf hat — und ein frisch
|
||||
// erzeugtes Fenster erschiene hinter dem sichtbaren.
|
||||
let scene = UIApplication.shared.connectedScenes
|
||||
.compactMap { $0 as? UIWindowScene }
|
||||
.first { $0.activationState == .foregroundActive }
|
||||
|
||||
return scene?.keyWindow ?? ASPresentationAnchor()
|
||||
}
|
||||
}
|
||||
@@ -24,12 +24,10 @@ struct RootView: View {
|
||||
.frame(maxWidth: .infinity, maxHeight: .infinity)
|
||||
.background(Color.flixyCanvas)
|
||||
|
||||
case .signedOut, .awaitingAuthorization:
|
||||
case .signedOut, .authenticating:
|
||||
SignInView(
|
||||
phase: session.phase,
|
||||
clientIdentifier: session.clientIdentifier,
|
||||
onSignIn: { Task { await session.beginSignIn() } },
|
||||
onCancel: { session.cancelSignIn() }
|
||||
onSignIn: { Task { await session.beginSignIn() } }
|
||||
)
|
||||
|
||||
case .choosingServer(let servers):
|
||||
|
||||
@@ -4,18 +4,20 @@ import PlexKit
|
||||
|
||||
/// Der Anmeldebildschirm.
|
||||
///
|
||||
/// Zeigt den Code, den Plex vergeben hat, und schickt in den Browser. Die App
|
||||
/// bekommt Benutzername und Passwort nie zu sehen — sie fragt nur regelmäßig
|
||||
/// nach, ob der Code bestätigt wurde.
|
||||
/// Ein Knopf, mehr nicht. Die Anmeldemaske kommt von Plex und öffnet sich in
|
||||
/// einem Fenster innerhalb der App; das Passwort wird dort eingegeben und
|
||||
/// erreicht Flixy nie. Nach dem Anmelden schließt sich das Fenster von selbst.
|
||||
struct SignInView: View {
|
||||
let phase: FlixySession.Phase
|
||||
let clientIdentifier: String
|
||||
let onSignIn: () -> Void
|
||||
let onCancel: () -> Void
|
||||
|
||||
@Environment(\.openURL) private var openURL
|
||||
@Environment(\.flixyAccent) private var accent
|
||||
|
||||
private var isAuthenticating: Bool {
|
||||
if case .authenticating = phase { return true }
|
||||
return false
|
||||
}
|
||||
|
||||
var body: some View {
|
||||
VStack(spacing: FlixySpacing.section) {
|
||||
Spacer()
|
||||
@@ -37,17 +39,26 @@ struct SignInView: View {
|
||||
|
||||
Spacer()
|
||||
|
||||
if case .awaitingAuthorization(let pin) = phase {
|
||||
awaitingAuthorization(pin: pin)
|
||||
} else {
|
||||
VStack(spacing: FlixySpacing.regular) {
|
||||
Button(action: onSignIn) {
|
||||
Text("signIn.action")
|
||||
.font(.flixyRowHeader)
|
||||
.frame(maxWidth: .infinity)
|
||||
.padding(.vertical, FlixySpacing.regular)
|
||||
Group {
|
||||
if isAuthenticating {
|
||||
ProgressView().tint(Color.flixyCanvas)
|
||||
} else {
|
||||
Text("signIn.action").font(.flixyRowHeader)
|
||||
}
|
||||
}
|
||||
.frame(maxWidth: .infinity)
|
||||
.padding(.vertical, FlixySpacing.regular)
|
||||
}
|
||||
.buttonStyle(.borderedProminent)
|
||||
.tint(accent)
|
||||
.disabled(isAuthenticating)
|
||||
|
||||
Text("signIn.privacy")
|
||||
.font(.flixyCaption)
|
||||
.foregroundStyle(Color.flixyTextMuted)
|
||||
.multilineTextAlignment(.center)
|
||||
}
|
||||
|
||||
Spacer().frame(height: FlixySpacing.section)
|
||||
@@ -57,51 +68,4 @@ struct SignInView: View {
|
||||
.frame(maxWidth: .infinity, maxHeight: .infinity)
|
||||
.background(Color.flixyCanvas)
|
||||
}
|
||||
|
||||
@ViewBuilder
|
||||
private func awaitingAuthorization(pin: PlexPin) -> some View {
|
||||
VStack(spacing: FlixySpacing.loose) {
|
||||
Text("signIn.codeHint")
|
||||
.font(.flixyCaption)
|
||||
.foregroundStyle(Color.flixyTextSecondary)
|
||||
.multilineTextAlignment(.center)
|
||||
|
||||
Text(pin.code)
|
||||
// Feste Zeichenbreite, damit der Code beim Abtippen nicht
|
||||
// springt und Ziffern nicht mit Buchstaben verschwimmen.
|
||||
.font(.system(.largeTitle, design: .monospaced, weight: .semibold))
|
||||
.tracking(6)
|
||||
.foregroundStyle(Color.flixyTextPrimary)
|
||||
.textSelection(.enabled)
|
||||
.padding(.vertical, FlixySpacing.regular)
|
||||
.frame(maxWidth: .infinity)
|
||||
.background(Color.flixyElevated, in: .rect(cornerRadius: FlixyRadius.sheet))
|
||||
|
||||
Button {
|
||||
if let url = pin.authorizationURL(
|
||||
clientIdentifier: clientIdentifier,
|
||||
product: Branding.plexProduct
|
||||
) {
|
||||
openURL(url)
|
||||
}
|
||||
} label: {
|
||||
Label("signIn.openBrowser", systemImage: "safari")
|
||||
.frame(maxWidth: .infinity)
|
||||
.padding(.vertical, FlixySpacing.regular)
|
||||
}
|
||||
.buttonStyle(.borderedProminent)
|
||||
.tint(accent)
|
||||
|
||||
HStack(spacing: FlixySpacing.snug) {
|
||||
ProgressView().controlSize(.small)
|
||||
Text("signIn.waiting")
|
||||
.font(.flixyCaption)
|
||||
.foregroundStyle(Color.flixyTextMuted)
|
||||
}
|
||||
|
||||
Button("action.cancel", action: onCancel)
|
||||
.font(.flixyCaption)
|
||||
.foregroundStyle(Color.flixyTextSecondary)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -52,10 +52,17 @@ public struct PlexPin: Sendable, Equatable, Decodable {
|
||||
/// antwortet mit „Diese Anfrage konnte nicht abgeschlossen werden".
|
||||
/// Festgehalten in `AuthorizationURLTests`.
|
||||
///
|
||||
/// `forwardUrl` fehlt bewusst: der Rücksprung in die App wäre bequemer,
|
||||
/// verlangt aber ein eigenes URL-Schema. Solange die App den Code ohnehin
|
||||
/// im Hintergrund abfragt, merkt niemand einen Unterschied.
|
||||
public func authorizationURL(clientIdentifier: String, product: String) -> URL? {
|
||||
/// `forwardUrl` schickt den Browser nach der Anmeldung auf eine Adresse
|
||||
/// mit eigenem Schema zurück. Genau darauf wartet
|
||||
/// `ASWebAuthenticationSession`: das Anmeldefenster schließt sich von
|
||||
/// selbst, und die App weiß, dass sie den Token abholen kann. Ohne diese
|
||||
/// Rückadresse bliebe die Seite offen und der Nutzer müsste raten, wann er
|
||||
/// fertig ist.
|
||||
public func authorizationURL(
|
||||
clientIdentifier: String,
|
||||
product: String,
|
||||
forwardURL: URL? = nil
|
||||
) -> URL? {
|
||||
// `&`, `=` und `+` müssen raus: sie trennen Parameter bzw. stehen für
|
||||
// ein Leerzeichen. In einem Wert würden sie die Adresse zerreißen.
|
||||
let allowed = CharacterSet.urlQueryAllowed.subtracting(CharacterSet(charactersIn: "&=+"))
|
||||
@@ -68,9 +75,22 @@ public struct PlexPin: Sendable, Equatable, Decodable {
|
||||
let product = encode(product)
|
||||
else { return nil }
|
||||
|
||||
return URL(string: """
|
||||
var text = """
|
||||
https://app.plex.tv/auth#?clientID=\(client)&code=\(code)\
|
||||
&context%5Bdevice%5D%5Bproduct%5D=\(product)
|
||||
""")
|
||||
"""
|
||||
|
||||
// Strenger kodiert als die übrigen Werte: die Rückadresse enthält
|
||||
// `:` und `/`, und die lässt `urlQueryAllowed` durch. Als Wert
|
||||
// innerhalb einer Adresse, die Plex selbst noch einmal zerlegt, müssen
|
||||
// sie kodiert sein — sonst endet der Wert für Plex beim ersten
|
||||
// Schrägstrich.
|
||||
let unreserved = CharacterSet.alphanumerics.union(CharacterSet(charactersIn: "-._~"))
|
||||
if let forwardURL,
|
||||
let forward = forwardURL.absoluteString.addingPercentEncoding(withAllowedCharacters: unreserved) {
|
||||
text += "&forwardUrl=\(forward)"
|
||||
}
|
||||
|
||||
return URL(string: text)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -39,3 +39,43 @@ struct AuthorizationURLTests {
|
||||
#expect(!url.absoluteString.contains("Flixy Player"))
|
||||
}
|
||||
}
|
||||
|
||||
@Suite("Anmelde-Adresse mit Rücksprung")
|
||||
struct AuthorizationForwardURLTests {
|
||||
private let pin = PlexPin(id: 42, code: "5474")
|
||||
|
||||
@Test("Ohne Rückadresse bleibt die Adresse wie bisher")
|
||||
func withoutForwardURL() throws {
|
||||
let url = try #require(pin.authorizationURL(clientIdentifier: "abc", product: "Flixy"))
|
||||
#expect(!url.absoluteString.contains("forwardUrl"))
|
||||
}
|
||||
|
||||
@Test("Die Rückadresse wird angehängt und kodiert")
|
||||
func forwardURLIsAppendedAndEncoded() throws {
|
||||
// Das Schema enthält Doppelpunkte und Schrägstriche. Unkodiert
|
||||
// zerrissen sie die Adresse, und Plex führte den Rücksprung nie aus —
|
||||
// das Anmeldefenster bliebe offen stehen.
|
||||
let url = try #require(pin.authorizationURL(
|
||||
clientIdentifier: "abc",
|
||||
product: "Flixy",
|
||||
forwardURL: URL(string: "com.scarriffleservices.flixy://auth")!
|
||||
))
|
||||
|
||||
let text = url.absoluteString
|
||||
#expect(text.contains("forwardUrl=com.scarriffleservices.flixy%3A%2F%2Fauth"))
|
||||
#expect(!text.contains("%25"))
|
||||
}
|
||||
|
||||
@Test("Die übrigen Parameter bleiben unversehrt")
|
||||
func otherParametersSurvive() throws {
|
||||
let url = try #require(pin.authorizationURL(
|
||||
clientIdentifier: "abc",
|
||||
product: "Flixy",
|
||||
forwardURL: URL(string: "flixy://auth")!
|
||||
))
|
||||
let text = url.absoluteString
|
||||
#expect(text.contains("clientID=abc"))
|
||||
#expect(text.contains("code=5474"))
|
||||
#expect(text.contains("context%5Bdevice%5D%5Bproduct%5D=Flixy"))
|
||||
}
|
||||
}
|
||||
|
||||
@@ -76,6 +76,14 @@ targets:
|
||||
UIBackgroundModes:
|
||||
- audio
|
||||
|
||||
# Das Schema, über das Plex nach der Anmeldung zurückschickt. Ohne
|
||||
# diesen Eintrag kennt iOS es nicht, und ASWebAuthenticationSession
|
||||
# käme nie zurück — das Anmeldefenster bliebe offen stehen.
|
||||
CFBundleURLTypes:
|
||||
- CFBundleURLName: com.scarriffleservices.flixy.auth
|
||||
CFBundleURLSchemes:
|
||||
- com.scarriffleservices.flixy
|
||||
|
||||
# Ohne diesen Schlüssel lehnt ActivityKit jede Anfrage ab — und
|
||||
# zwar wortlos, was die Suche nach dem Grund unangenehm macht.
|
||||
NSSupportsLiveActivities: true
|
||||
|
||||
Reference in New Issue
Block a user