import Foundation import OSLog /// A separate anonymous session prevents authenticated API traffic from /// entering this disk cache. URLSession owns HTTP freshness and validation. /// Its Foundation references are immutable and individually thread-safe. final class PlayerScriptHTTPCache: @unchecked Sendable { private let cache: URLCache private let delegate: PlayerScriptCacheDelegate private let session: URLSession init() { let directory = FileManager.default.urls(for: .cachesDirectory, in: .userDomainMask)[0] .appendingPathComponent("HydraulophonePlayerScripts/v1", isDirectory: true) try? FileManager.default.createDirectory(at: directory, withIntermediateDirectories: true) var root = directory var values = URLResourceValues() values.isExcludedFromBackup = true try? root.setResourceValues(values) // Leave room for Foundation's per-response size limits: a player is ~3 MB. cache = URLCache( memoryCapacity: 8 * 1024 * 1024, diskCapacity: 64 * 1024 * 1024, directory: directory) delegate = PlayerScriptCacheDelegate() let configuration = URLSessionConfiguration.default configuration.httpCookieStorage = nil configuration.httpShouldSetCookies = false configuration.urlCredentialStorage = nil configuration.urlCache = cache configuration.requestCachePolicy = .useProtocolCachePolicy configuration.timeoutIntervalForRequest = 15 configuration.timeoutIntervalForResource = 30 session = URLSession(configuration: configuration, delegate: delegate, delegateQueue: nil) } deinit { session.invalidateAndCancel() } func invalidate() { cache.removeAllCachedResponses() } func data(for request: URLRequest, maximumBytes: Int) async throws -> (Data, URLResponse) { guard let url = request.url, InnerTubeMediaURLPolicy.isAllowedPlayerJavaScriptURL(url), request.value(forHTTPHeaderField: "Cookie") == nil, request.value(forHTTPHeaderField: "Authorization") == nil else { throw PlayerStreamCipherError.invalidScript } let (bytes, response) = try await session.bytes(for: request) defer { bytes.task.cancel() } guard let http = response as? HTTPURLResponse, (200..<300).contains(http.statusCode), let finalURL = response.url, InnerTubeMediaURLPolicy.isAllowedPlayerJavaScriptURL(finalURL), response.expectedContentLength <= maximumBytes else { throw PlayerStreamCipherError.invalidScript } var data = Data() for try await byte in bytes { guard data.count < maximumBytes else { throw PlayerStreamCipherError.invalidScript } if data.count.isMultiple(of: 16_384) { try Task.checkCancellation() } data.append(byte) } return (data, response) } /// The small prepared-script shortcut must not outlive the HTTP response's /// freshness. When uncertain, delegate every reuse to URLSession instead. static func preparedReuseDeadline(response: HTTPURLResponse, now: Date = Date()) -> Date { let directives = (response.value(forHTTPHeaderField: "Cache-Control") ?? "") .lowercased().split(separator: ",").map { $0.trimmingCharacters(in: .whitespaces) } guard !directives.contains(where: { let name = $0.split(separator: "=", maxSplits: 1).first ?? "" return name == "no-cache" || name == "no-store" }), response.value(forHTTPHeaderField: "Set-Cookie") == nil, response.value(forHTTPHeaderField: "Vary")?.trimmingCharacters(in: .whitespaces) != "*" else { return now } let formatter = DateFormatter() formatter.locale = Locale(identifier: "en_US_POSIX") formatter.timeZone = TimeZone(secondsFromGMT: 0) formatter.dateFormat = "EEE, dd MMM yyyy HH:mm:ss zzz" let serverDate = response.value(forHTTPHeaderField: "Date").flatMap(formatter.date(from:)) let age = max(0, Double(response.value(forHTTPHeaderField: "Age") ?? "") ?? 0) let apparentAge = max(age, serverDate.map { max(0, now.timeIntervalSince($0)) } ?? 0) let maxAges = directives.filter { $0.hasPrefix("max-age=") } let freshness: Double if maxAges.count == 1, let raw = maxAges[0].split(separator: "=", maxSplits: 1).last, let seconds = Double(raw.trimmingCharacters(in: CharacterSet(charactersIn: "\" "))), seconds.isFinite, seconds >= 0 { freshness = seconds } else if maxAges.isEmpty, let serverDate, let expiry = response.value(forHTTPHeaderField: "Expires").flatMap(formatter.date(from:)) { freshness = max(0, expiry.timeIntervalSince(serverDate)) } else { return now } // Version discovery has its own conservative 30-minute upper bound. return now.addingTimeInterval(min(1_800, max(0, freshness - apparentAge))) } } private final class PlayerScriptCacheDelegate: NSObject, URLSessionDataDelegate { func urlSession( _ session: URLSession, task: URLSessionTask, willPerformHTTPRedirection response: HTTPURLResponse, newRequest request: URLRequest, completionHandler: @escaping (URLRequest?) -> Void ) { completionHandler( request.url.flatMap { InnerTubeMediaURLPolicy.isAllowedPlayerJavaScriptURL($0) ? request : nil }) } func urlSession( _ session: URLSession, dataTask: URLSessionDataTask, willCacheResponse proposedResponse: CachedURLResponse, completionHandler: @escaping (CachedURLResponse?) -> Void ) { guard let response = proposedResponse.response as? HTTPURLResponse, response.statusCode == 200, let url = response.url, InnerTubeMediaURLPolicy.isAllowedPlayerJavaScriptURL(url), response.value(forHTTPHeaderField: "Set-Cookie") == nil else { completionHandler(nil) return } completionHandler(proposedResponse) } #if DEBUG func urlSession( _ session: URLSession, task: URLSessionTask, didFinishCollecting metrics: URLSessionTaskMetrics ) { let cached = metrics.transactionMetrics.last?.resourceFetchType == .localCache Logger(subsystem: "com.hydraulophone", category: "startup").notice( "player_script http_cache_hit=\(cached)") } #endif }