import HydraulophoneCore import OSLog import SwiftUI import UIKit import WebKit struct LoginView: View { @Environment(\.dismiss) private var dismiss @EnvironmentObject private var model: AppModel private let isRequired: Bool @State private var status = "Sign in to YouTube Music below. Your session is stored only in this app's Keychain." @State private var isSaving = false init(isRequired: Bool = false) { self.isRequired = isRequired } var body: some View { NavigationStack { VStack(spacing: 0) { WebLoginView(session: model.session) { session in guard !isSaving else { return } isSaving = true status = "Saving your secure session…" Task { @MainActor in if let keychainStatus = await model.completeLogin(session: session) { isSaving = false status = "Secure session storage failed (Keychain \(keychainStatus)). Try again." } else { status = "Signed in securely." if !isRequired { dismiss() } } } } .frame(maxWidth: .infinity, maxHeight: .infinity) Text(status) .font(.footnote) .foregroundStyle(.secondary) .multilineTextAlignment(.center) .padding(.horizontal, 24) .padding(.vertical, 12) if let authErrorMessage = model.authErrorMessage { Label(authErrorMessage, systemImage: "exclamationmark.triangle") .font(.footnote) .foregroundStyle(.secondary) .multilineTextAlignment(.center) .padding(.horizontal, 24) .padding(.bottom, 12) if model.session == nil { Button("Retry secure sign-out") { _ = model.signOut() } .disabled(model.isSessionTransitioning) .padding(.bottom, 12) } } } .navigationTitle("Sign in") .navigationBarTitleDisplayMode(.inline) .toolbar { if !isRequired { ToolbarItem(placement: .topBarTrailing) { Button("Done") { dismiss() } } } } } } } private struct WebLoginView: UIViewRepresentable { let session: UserSession? let onAuthenticated: (UserSession) -> Void private static var loginUserAgent: String { #if targetEnvironment(macCatalyst) // YouTube Music rejects Catalyst WebKit's default browser identity. Use // the matching desktop Safari version for the embedded sign-in page. let systemVersion = ProcessInfo.processInfo.operatingSystemVersion let safariMajorVersion: Int switch systemVersion.majorVersion { case 14: safariMajorVersion = 17 case 15: safariMajorVersion = 18 default: safariMajorVersion = systemVersion.majorVersion } return [ "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7)", "AppleWebKit/605.1.15 (KHTML, like Gecko)", "Version/\(safariMajorVersion).0 Safari/605.1.15", ].joined(separator: " ") #else let version = UIDevice.current.systemVersion let majorVersion = Int(version.split(separator: ".").first ?? "") ?? 0 // Safari 26 and newer freezes the OS token at 18_6. Keep this login // browser identity separate from InnerTube's request profiles. let platformVersion = majorVersion >= 26 ? "18_6" : version.replacingOccurrences(of: ".", with: "_") return [ "Mozilla/5.0 (iPhone; CPU iPhone OS \(platformVersion) like Mac OS X)", "AppleWebKit/605.1.15 (KHTML, like Gecko)", "Version/\(version) Mobile/15E148 Safari/604.1", ].joined(separator: " ") #endif } func makeCoordinator() -> Coordinator { Coordinator(onAuthenticated: onAuthenticated) } func makeUIView(context: Context) -> WKWebView { let configuration = WKWebViewConfiguration() configuration.websiteDataStore = WebSessionStore.dataStore let webView = WKWebView(frame: .zero, configuration: configuration) webView.customUserAgent = Self.loginUserAgent webView.navigationDelegate = context.coordinator webView.allowsBackForwardNavigationGestures = true WebSessionStore.seed( session, in: configuration.websiteDataStore.httpCookieStore ) { guard let url = URL(string: "https://music.youtube.com") else { return } webView.load(URLRequest(url: url)) } return webView } func updateUIView(_ webView: WKWebView, context: Context) {} final class Coordinator: NSObject, WKNavigationDelegate { private let onAuthenticated: (UserSession) -> Void private let logger = Logger(subsystem: "com.hydraulophone", category: "auth") private var isCapturing = false init(onAuthenticated: @escaping (UserSession) -> Void) { self.onAuthenticated = onAuthenticated } func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!) { guard WebSessionStore.isMusicYouTubeHost(webView.url?.host), !isCapturing else { return } isCapturing = true webView.configuration.websiteDataStore.httpCookieStore.getAllCookies { [weak self, weak webView] cookies in guard let self, let webView, let cookieHeader = WebSessionStore.cookieHeader(from: cookies), WebSessionStore.hasNonEmptyCookieValue(named: "SAPISID", in: cookieHeader) else { self?.isCapturing = false self?.logger.info("Web login navigation finished without an SAPISID cookie") return } let script = """ (() => { if (typeof ytcfg === 'undefined' || !ytcfg.get) { return null; } return { dataSyncID: ytcfg.get('DATASYNC_ID') || null, visitorData: ytcfg.get('VISITOR_DATA') || null, delegatedSessionID: ytcfg.get('DELEGATED_SESSION_ID') || null }; })() """ webView.evaluateJavaScript(script) { [weak self] value, error in guard error == nil else { self?.isCapturing = false self?.logger.error("Web login could not read the session identity") return } let values = value as? [String: Any] let dataSyncID = values?["dataSyncID"] as? String let visitorData = values?["visitorData"] as? String let delegatedSessionID = values?["delegatedSessionID"] as? String let session = UserSession( cookieHeader: cookieHeader, dataSyncID: dataSyncID?.isEmpty == false ? dataSyncID : nil, delegatedSessionID: delegatedSessionID?.isEmpty == false ? delegatedSessionID : nil, visitorData: visitorData?.isEmpty == false ? visitorData : nil ) self?.logger.info("Web login captured an authenticated YouTube session") DispatchQueue.main.async { self?.isCapturing = false self?.onAuthenticated(session) } } } } func webView( _ webView: WKWebView, didFail navigation: WKNavigation!, withError _: Error ) { logger.error("Web login navigation failed") } func webView( _ webView: WKWebView, didFailProvisionalNavigation navigation: WKNavigation!, withError _: Error ) { logger.error("Web login provisional navigation failed") } } }