~ knotless Search/
↑↓ move↵ open⇧↵ all results

geesawra.industries/hydraulophone

An unofficial YouTube Music app for iPhone, iPad, and Mac.

0
0
main
272 lines · 8.2 KB Raw History
import Foundation
import HydraulophoneCore
import WebKit

/// Owns the short-lived web view data used for the reviewed sign-in flow.
///
/// The web view is deliberately non-persistent. Once authenticated, the
/// cookie header is copied into the Keychain-backed `UserSession`; it is never
/// written to defaults, a fixture, or a diagnostic log. The legacy store is
/// read only to migrate sessions created by earlier builds.
enum WebSessionStore {
  static let dataStore = WKWebsiteDataStore.nonPersistent()
  private static let legacyDataStore = WKWebsiteDataStore.default()

  @MainActor
  static func legacySession() async -> UserSession? {
    await withCheckedContinuation { continuation in
      legacyDataStore.httpCookieStore.getAllCookies { cookies in
        guard
          let header = cookieHeader(from: cookies),
          hasNonEmptyCookieValue(named: "SAPISID", in: header)
        else {
          continuation.resume(returning: nil)
          return
        }
        continuation.resume(returning: UserSession(cookieHeader: header))
      }
    }
  }

  /// Seeds an ephemeral web view from the Keychain-backed session before the
  /// login page is loaded. This keeps the convenience of an existing web
  /// session without making WebKit's persistent store another credential
  /// database.
  @MainActor
  static func seed(
    _ session: UserSession?,
    in cookieStore: WKHTTPCookieStore,
    completion: @escaping () -> Void
  ) {
    let cookies = session.flatMap(cookies(from:)) ?? []
    guard !cookies.isEmpty else {
      completion()
      return
    }

    let group = DispatchGroup()
    for cookie in cookies {
      group.enter()
      cookieStore.setCookie(cookie) {
        group.leave()
      }
    }
    group.notify(queue: .main, execute: completion)
  }

  @MainActor
  static func clear() {
    clearSharedLegacyCookies()
    clear(store: dataStore)
    clear(store: legacyDataStore)
  }

  /// Completes only after legacy cookies and website records have both been
  /// removed. Restore uses this after installing a valid Keychain session so
  /// credentials from versions that used the persistent WebKit store do not
  /// remain on disk.
  @MainActor
  static func clearLegacyData() async {
    clearSharedLegacyCookies()
    await withCheckedContinuation { (continuation: CheckedContinuation<Void, Never>) in
      clear(store: legacyDataStore) {
        continuation.resume()
      }
    }
  }

  static func isMusicYouTubeHost(_ host: String?) -> Bool {
    host?.caseInsensitiveCompare("music.youtube.com") == .orderedSame
  }

  /// Only cookies that can actually be sent to the Music web origin are
  /// extracted. In particular, `notyoutube.com` and `youtube.com.evil.test`
  /// do not pass this boundary check.
  static func isCookieScopedToMusicYouTube(_ domain: String) -> Bool {
    let normalized = normalizedDomain(domain)
    return normalized == "youtube.com" || normalized == "music.youtube.com"
  }

  static func cookieHeader(
    from cookies: [HTTPCookie],
    now: Date = Date()
  ) -> String? {
    let relevantCookies = cookies.filter {
      isApplicableToMusicRoot($0, now: now)
    }
    guard !relevantCookies.isEmpty else {
      return nil
    }

    var cookiesByName: [String: HTTPCookie] = [:]
    for cookie in relevantCookies {
      if let existing = cookiesByName[cookie.name] {
        if outranks(cookie, over: existing) {
          cookiesByName[cookie.name] = cookie
        }
      } else {
        cookiesByName[cookie.name] = cookie
      }
    }

    let header = cookiesByName.values
      .sorted { $0.name < $1.name }
      .map { "\($0.name)=\($0.value)" }
      .joined(separator: "; ")
    return header.isEmpty ? nil : header
  }

  private static func isApplicableToMusicRoot(
    _ cookie: HTTPCookie,
    now: Date
  ) -> Bool {
    guard isCookieScopedToMusicYouTube(cookie.domain), cookie.path == "/" else {
      return false
    }
    guard !cookie.isSecure || musicRootUsesHTTPS else {
      return false
    }
    if let expiresDate = cookie.expiresDate, expiresDate <= now {
      return false
    }
    return true
  }

  private static func outranks(
    _ candidate: HTTPCookie,
    over existing: HTTPCookie
  ) -> Bool {
    let candidateDomain = normalizedDomain(candidate.domain)
    let existingDomain = normalizedDomain(existing.domain)
    let candidateIsExact = candidateDomain == "music.youtube.com"
    let existingIsExact = existingDomain == "music.youtube.com"
    if candidateIsExact != existingIsExact {
      return candidateIsExact
    }
    if candidate.path.count != existing.path.count {
      return candidate.path.count > existing.path.count
    }
    if candidateDomain != existingDomain {
      return candidateDomain < existingDomain
    }
    return candidate.domain < existing.domain
  }

  private static let musicRootUsesHTTPS = true

  static func cookieValue(named name: String, in header: String) -> String? {
    header
      .split(separator: ";")
      .compactMap { part -> (String, String)? in
        let trimmed = part.trimmingCharacters(in: .whitespaces)
        guard let separator = trimmed.firstIndex(of: "=") else {
          return nil
        }
        let cookieName = String(trimmed[..<separator])
        let cookieValue = String(trimmed[trimmed.index(after: separator)...])
        return (cookieName, cookieValue)
      }
      .first(where: { $0.0 == name })
      .map(\.1)
  }

  static func hasNonEmptyCookieValue(named name: String, in header: String) -> Bool {
    guard let value = cookieValue(named: name, in: header) else {
      return false
    }
    return !value.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty
  }

  private static func cookies(from session: UserSession) -> [HTTPCookie] {
    session.cookieHeader
      .split(separator: ";")
      .compactMap { pair in
        guard let separator = pair.firstIndex(of: "=") else {
          return nil
        }
        let name = pair[..<separator].trimmingCharacters(in: .whitespaces)
        let value = pair[pair.index(after: separator)...]
          .trimmingCharacters(in: .whitespaces)
        guard !name.isEmpty, !value.isEmpty else {
          return nil
        }
        return HTTPCookie(
          properties: [
            .domain: "music.youtube.com",
            .path: "/",
            .name: String(name),
            .value: String(value),
            .secure: "TRUE",
          ]
        )
      }
  }

  private static func clear(
    store: WKWebsiteDataStore,
    completion: @escaping () -> Void = {}
  ) {
    let group = DispatchGroup()

    group.enter()
    store.httpCookieStore.getAllCookies { cookies in
      let cookieGroup = DispatchGroup()
      for cookie in cookies where isRelevantAccountDomain(cookie.domain) {
        cookieGroup.enter()
        store.httpCookieStore.delete(cookie) {
          cookieGroup.leave()
        }
      }
      cookieGroup.notify(queue: .main) {
        group.leave()
      }
    }

    let websiteDataTypes = WKWebsiteDataStore.allWebsiteDataTypes()
    group.enter()
    store.fetchDataRecords(ofTypes: websiteDataTypes) { records in
      let relevantRecords = records.filter {
        isRelevantAccountDomain($0.displayName)
      }
      guard !relevantRecords.isEmpty else {
        group.leave()
        return
      }
      store.removeData(
        ofTypes: websiteDataTypes,
        for: relevantRecords,
        completionHandler: {
          group.leave()
        }
      )
    }

    group.notify(queue: .main, execute: completion)
  }

  private static func clearSharedLegacyCookies() {
    let storage = HTTPCookieStorage.shared
    for cookie in storage.cookies ?? [] where isRelevantAccountDomain(cookie.domain) {
      storage.deleteCookie(cookie)
    }
  }

  static func isRelevantAccountDomain(_ domain: String) -> Bool {
    let normalized = normalizedDomain(domain)
    return normalized == "youtube.com"
      || normalized.hasSuffix(".youtube.com")
      || normalized == "google.com"
      || normalized.hasSuffix(".google.com")
  }

  private static func normalizedDomain(_ domain: String) -> String {
    var normalized =
      domain
      .trimmingCharacters(in: .whitespacesAndNewlines)
      .lowercased()
    while normalized.hasPrefix(".") {
      normalized.removeFirst()
    }
    return normalized
  }
}