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

geesawra.industries/hydraulophone

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

0
0
main
1362 lines · 40.3 KB Raw History
import Foundation
import HydraulophoneCore
import OSLog
import UIKit
import WebKit

enum ProofOriginCachePolicy {
  static let videoTokenLifetime: TimeInterval = 10 * 60

  static func generatorExpiresAt(now: Date, integrityLifetime: TimeInterval) -> Date {
    now.addingTimeInterval(integrityLifetime - videoTokenLifetime)
  }

  static func tokenExpiresAt(now: Date) -> Date {
    now.addingTimeInterval(videoTokenLifetime)
  }

  static func canReuseGenerator(
    isDead: Bool,
    requestedVisitorData: String,
    cachedVisitorData: String?,
    expiresAt: Date?,
    now: Date
  ) -> Bool {
    !isDead && cachedVisitorData == requestedVisitorData
      && (expiresAt.map { $0 > now } ?? false)
  }

  static func tokenIsValid(expiresAt: Date, now: Date) -> Bool {
    expiresAt > now
  }
}

/// The app-layer BotGuard proof provider.
///
/// This provider is intentionally independent from `WebSessionStore`: it never
/// reads, seeds, or writes the login web session. It is intended for the
/// explicitly opt-in high-quality/debug player probe, not for the normal HLS
/// playback path.
public actor WebViewProofOfOriginProvider: PlayerProofOfOriginProviding {
  private let logger = Logger(subsystem: "com.hydraulophone", category: "proof")
  private static let generationTimeout: Duration = .seconds(12)
  private static let maximumSessionTokens = 1
  private static let maximumVideoTokens = 8

  private let httpClient: ProofOriginHTTPClient
  private var generationCounter: UInt64 = 0
  private var activeGeneration: PendingGeneration?

  private var webViewGenerator: ProofOriginWebView?
  private var webViewGeneratorExpiresAt: Date?
  private var webViewGeneratorVisitorData: String?

  private var sessionTokens: [String: CachedProofToken] = [:]
  private var videoTokens: [String: CachedProofToken] = [:]

  public init() {
    httpClient = ProofOriginHTTPClient(apiKey: nil)
  }

  /// Internal probe initializer. The caller supplies the public JNN key from
  /// its approved runtime configuration; it is never persisted by this actor.
  init(apiKey: String?) {
    httpClient = ProofOriginHTTPClient(apiKey: apiKey)
  }

  public func tokens(
    visitorData: String,
    videoID: String
  ) async throws -> PlayerProofTokens {
    guard !visitorData.isEmpty, !videoID.isEmpty else {
      throw ProofOfOriginError.invalidInput
    }
    try Task.checkCancellation()

    let now = Date()
    pruneExpiredTokens(now: now)

    if let activeGeneration {
      guard activeGeneration.visitorData == visitorData else {
        throw ProofOfOriginError.busy
      }
      let tokens = try await waitForExistingGeneration(activeGeneration)
      if activeGeneration.videoID == videoID { return tokens }
      // Foreground playback may arrive during prewarm or successor minting.
      // Join that generator, then mint the requested video's own token.
      try Task.checkCancellation()
      return try await self.tokens(visitorData: visitorData, videoID: videoID)
    }

    generationCounter &+= 1
    let generationID = generationCounter

    return try await withTaskCancellationHandler(
      operation: {
        try await withCheckedThrowingContinuation {
          (continuation: CheckedContinuation<PlayerProofTokens, Error>) in
          if Task.isCancelled {
            continuation.resume(throwing: CancellationError())
            return
          }

          let pending = PendingGeneration(
            id: generationID,
            visitorData: visitorData,
            videoID: videoID,
            continuation: continuation
          )
          activeGeneration = pending
          start(pending)
        }
      },
      onCancel: {
        Task { [weak self] in
          await self?.cancelPrimaryWaiter(generationID)
        }
      })
  }

  public func invalidate() async {
    sessionTokens.removeAll(keepingCapacity: false)
    videoTokens.removeAll(keepingCapacity: false)
    httpClient.cancelAll()

    if let activeGeneration {
      activeGeneration.workTask?.cancel()
      activeGeneration.timeoutTask?.cancel()
      finish(activeGeneration, result: .failure(ProofOfOriginError.cancelled))
    }

    await discardGenerator()
  }

  private func waitForExistingGeneration(
    _ generation: PendingGeneration
  ) async throws -> PlayerProofTokens {
    let waiterID = UUID()
    return try await withTaskCancellationHandler(
      operation: {
        try await withCheckedThrowingContinuation {
          (continuation: CheckedContinuation<PlayerProofTokens, Error>) in
          guard !Task.isCancelled, activeGeneration?.id == generation.id else {
            continuation.resume(throwing: CancellationError())
            return
          }
          generation.waiters[waiterID] = continuation
        }
      },
      onCancel: {
        Task { [weak self] in
          await self?.cancelWaiter(waiterID, generationID: generation.id)
        }
      })
  }

  private func start(_ generation: PendingGeneration) {
    let id = generation.id
    generation.timeoutTask = Task { [weak self] in
      do {
        try await Task.sleep(for: Self.generationTimeout)
        guard !Task.isCancelled else { return }
        await self?.timeoutGeneration(id)
      } catch {
        // Cancellation of the timeout task is the normal completion path.
      }
    }

    generation.workTask = Task { [weak self] in
      guard let self else { return }
      do {
        let result = try await self.generate(
          visitorData: generation.visitorData,
          videoID: generation.videoID
        )
        await self.finishGeneration(id, result: .success(result))
      } catch is CancellationError {
        await self.finishGeneration(id, result: .failure(CancellationError()))
      } catch {
        await self.finishGeneration(id, result: .failure(error))
      }
    }
  }

  private func generate(
    visitorData: String,
    videoID: String
  ) async throws -> PlayerProofTokens {
    let generator = try await ensureGenerator(for: visitorData)
    guard let generatorExpiresAt = webViewGeneratorExpiresAt else {
      throw ProofOfOriginError.invalidIntegrityToken
    }
    try requireActiveGenerator(
      generator,
      visitorData: visitorData,
      expiresAt: generatorExpiresAt
    )
    pruneExpiredTokens(now: Date())

    let playerToken: String
    if let cached = validToken(sessionTokens[visitorData], now: Date()) {
      playerToken = cached
    } else {
      let bytes = try await generator.mint(identifier: visitorData)
      try requireActiveGenerator(
        generator,
        visitorData: visitorData,
        expiresAt: generatorExpiresAt
      )
      playerToken = ProofOriginEncoding.base64URL(bytes)
      let tokenCreatedAt = Date()
      storeSessionToken(
        playerToken,
        for: visitorData,
        expiresAt: generatorExpiresAt,
        now: tokenCreatedAt
      )
    }

    let cacheKey = videoCacheKey(visitorData: visitorData, videoID: videoID)
    let streamingToken: String
    if let cached = validToken(videoTokens[cacheKey], now: Date()) {
      streamingToken = cached
    } else {
      let bytes = try await generator.mint(identifier: videoID)
      try requireActiveGenerator(
        generator,
        visitorData: visitorData,
        expiresAt: generatorExpiresAt
      )
      streamingToken = ProofOriginEncoding.base64URL(bytes)
      storeVideoToken(streamingToken, for: cacheKey, now: Date())
    }

    try requireActiveGenerator(
      generator,
      visitorData: visitorData,
      expiresAt: generatorExpiresAt
    )
    return PlayerProofTokens(player: playerToken, streaming: streamingToken)
  }

  private func ensureGenerator(for visitorData: String) async throws -> ProofOriginWebView {
    if let webViewGenerator,
      ProofOriginCachePolicy.canReuseGenerator(
        isDead: await webViewGenerator.isDead,
        requestedVisitorData: visitorData,
        cachedVisitorData: webViewGeneratorVisitorData,
        expiresAt: webViewGeneratorExpiresAt,
        now: Date()
      )
    {
      return webViewGenerator
    }

    await discardGenerator()

    logger.notice("proof stage=create")
    let challengeResponse = try await httpClient.post(
      endpoint: .create,
      body: ProofOriginRequest.createBody()
    )
    logger.notice("proof stage=challenge")
    let challenge = try ProofOriginChallenge(responseBody: challengeResponse)
    let html = try ProofOriginResources.helperHTML()
    logger.notice("proof stage=webview")
    let generator = try await ProofOriginWebView.make(helperHTML: html)
    // Publish the generator before any fallible BotGuard/GenerateIT work so a
    // timeout or cancellation can release it even while a JS call is pending.
    webViewGenerator = generator
    webViewGeneratorExpiresAt = nil
    webViewGeneratorVisitorData = visitorData

    do {
      logger.notice("proof stage=botguard")
      let botGuardResponse = try await generator.run(challenge: challenge)
      guard botGuardResponse.utf8.count <= 2 * 1024 * 1024 else {
        throw ProofOfOriginError.bodyTooLarge
      }
      logger.notice("proof stage=integrity")
      let integrityResponse = try await httpClient.post(
        endpoint: .generateIntegrityToken,
        body: ProofOriginRequest.generateIntegrityBody(
          botGuardResponse: botGuardResponse
        )
      )
      let integrity = try ProofOriginIntegrity(responseBody: integrityResponse)
      guard integrity.expiresAt > Date() else {
        throw ProofOfOriginError.invalidIntegrityToken
      }
      try await generator.installMinter(integrityBytes: integrity.bytes)
      guard integrity.expiresAt > Date() else {
        throw ProofOfOriginError.invalidIntegrityToken
      }
      logger.notice("proof stage=minter_ready")

      webViewGenerator = generator
      webViewGeneratorExpiresAt = integrity.expiresAt
      webViewGeneratorVisitorData = visitorData
      return generator
    } catch {
      webViewGenerator = nil
      webViewGeneratorExpiresAt = nil
      webViewGeneratorVisitorData = nil
      await generator.invalidate()
      throw error
    }
  }

  private func requireActiveGenerator(
    _ generator: ProofOriginWebView,
    visitorData: String,
    expiresAt: Date
  ) throws {
    guard let currentGenerator = webViewGenerator,
      currentGenerator === generator,
      webViewGeneratorVisitorData == visitorData,
      expiresAt > Date()
    else {
      throw ProofOfOriginError.invalidIntegrityToken
    }
  }

  private func timeoutGeneration(_ id: UInt64) async {
    guard let activeGeneration, activeGeneration.id == id else { return }
    activeGeneration.workTask?.cancel()
    httpClient.cancelAll()
    finish(activeGeneration, result: .failure(ProofOfOriginError.timedOut))
    await discardGenerator()
  }

  private func cancelGeneration(_ id: UInt64) async {
    guard let activeGeneration, activeGeneration.id == id else { return }
    activeGeneration.workTask?.cancel()
    activeGeneration.timeoutTask?.cancel()
    httpClient.cancelAll()
    finish(activeGeneration, result: .failure(CancellationError()))
    await discardGenerator()
  }

  private func cancelPrimaryWaiter(_ id: UInt64) async {
    guard let activeGeneration, activeGeneration.id == id else { return }
    activeGeneration.continuation?.resume(throwing: CancellationError())
    activeGeneration.continuation = nil
    if activeGeneration.waiters.isEmpty {
      await cancelGeneration(id)
    }
  }

  private func cancelWaiter(_ waiterID: UUID, generationID: UInt64) async {
    guard let activeGeneration, activeGeneration.id == generationID else { return }
    activeGeneration.waiters.removeValue(forKey: waiterID)?.resume(throwing: CancellationError())
    if activeGeneration.continuation == nil, activeGeneration.waiters.isEmpty {
      await cancelGeneration(generationID)
    }
  }

  private func finishGeneration(
    _ id: UInt64,
    result: Result<PlayerProofTokens, Error>
  ) async {
    guard let activeGeneration, activeGeneration.id == id else { return }
    finish(activeGeneration, result: result)
    if case .failure = result {
      await discardGenerator()
    }
  }

  private func finish(
    _ generation: PendingGeneration,
    result: Result<PlayerProofTokens, Error>
  ) {
    guard activeGeneration?.id == generation.id else { return }
    activeGeneration = nil
    generation.timeoutTask?.cancel()
    generation.workTask?.cancel()

    switch result {
    case .success(let tokens):
      logger.notice("proof outcome=success")
      generation.continuation?.resume(returning: tokens)
      generation.continuation = nil
      for waiter in generation.waiters.values {
        waiter.resume(returning: tokens)
      }
    case .failure(let error):
      let category = (error as? ProofOfOriginError)?.rawValue ?? "other"
      logger.notice("proof outcome=failure category=\(category, privacy: .public)")
      generation.continuation?.resume(throwing: error)
      generation.continuation = nil
      for waiter in generation.waiters.values {
        waiter.resume(throwing: error)
      }
    }
    generation.waiters.removeAll(keepingCapacity: false)
  }

  private func discardGenerator() async {
    let generator = webViewGenerator
    webViewGenerator = nil
    webViewGeneratorExpiresAt = nil
    webViewGeneratorVisitorData = nil
    // AuraMusic keeps one visitor-bound token per live generator. No cached
    // session token remains usable after replacing or releasing that generator.
    sessionTokens.removeAll(keepingCapacity: false)
    await generator?.invalidate()
  }

  private func storeSessionToken(
    _ token: String,
    for visitorData: String,
    expiresAt: Date,
    now: Date
  ) {
    sessionTokens[visitorData] = CachedProofToken(
      value: token,
      expiresAt: expiresAt,
      lastUsedAt: now
    )
    trim(&sessionTokens, maximumCount: Self.maximumSessionTokens)
  }

  private func storeVideoToken(
    _ token: String,
    for cacheKey: String,
    now: Date
  ) {
    videoTokens[cacheKey] = CachedProofToken(
      value: token,
      expiresAt: ProofOriginCachePolicy.tokenExpiresAt(now: now),
      lastUsedAt: now
    )
    trim(&videoTokens, maximumCount: Self.maximumVideoTokens)
  }

  private func validToken(
    _ token: CachedProofToken?,
    now: Date
  ) -> String? {
    guard let token, ProofOriginCachePolicy.tokenIsValid(expiresAt: token.expiresAt, now: now)
    else { return nil }
    return token.value
  }

  private func pruneExpiredTokens(now: Date) {
    sessionTokens = sessionTokens.filter { $0.value.expiresAt > now }
    videoTokens = videoTokens.filter { $0.value.expiresAt > now }
  }

  private func trim(
    _ tokens: inout [String: CachedProofToken],
    maximumCount: Int
  ) {
    guard tokens.count > maximumCount else { return }
    let removals = tokens.count - maximumCount
    for key
      in tokens
      .sorted(by: { $0.value.lastUsedAt < $1.value.lastUsedAt })
      .prefix(removals)
      .map(\.key)
    {
      tokens.removeValue(forKey: key)
    }
  }

  private func videoCacheKey(visitorData: String, videoID: String) -> String {
    visitorData + "\u{001F}" + videoID
  }
}

private final class PendingGeneration: @unchecked Sendable {
  let id: UInt64
  let visitorData: String
  let videoID: String
  var continuation: CheckedContinuation<PlayerProofTokens, Error>?
  var waiters: [UUID: CheckedContinuation<PlayerProofTokens, Error>] = [:]
  var workTask: Task<Void, Never>?
  var timeoutTask: Task<Void, Never>?

  init(
    id: UInt64,
    visitorData: String,
    videoID: String,
    continuation: CheckedContinuation<PlayerProofTokens, Error>
  ) {
    self.id = id
    self.visitorData = visitorData
    self.videoID = videoID
    self.continuation = continuation
  }
}

private struct CachedProofToken: Sendable {
  let value: String
  let expiresAt: Date
  let lastUsedAt: Date
}

private enum ProofOfOriginError: String, Error, Sendable {
  case invalidInput
  case missingConfiguration
  case busy
  case cancelled
  case timedOut
  case resourceUnavailable
  case transport
  case redirected
  case bodyTooLarge
  case unexpectedStatus
  case invalidChallenge
  case invalidIntegrityToken
  case javascript
  case webViewUnavailable
}

private enum ProofOriginEndpoint {
  case create
  case generateIntegrityToken

  var url: URL? {
    switch self {
    case .create:
      return URL(string: "https://www.youtube.com/api/jnn/v1/Create")
    case .generateIntegrityToken:
      return URL(string: "https://www.youtube.com/api/jnn/v1/GenerateIT")
    }
  }
}

private enum ProofOriginRequest {
  static let requestKey = "O43z0dpjhgX20SCx4KAo"

  static func createBody() -> Data {
    jsonData([requestKey])
  }

  static func generateIntegrityBody(botGuardResponse: String) -> Data {
    jsonData([requestKey, botGuardResponse])
  }

  private static func jsonData(_ value: [String]) -> Data {
    // These arrays contain only public protocol values and the current
    // challenge response. No cookie, authorization, visitor header, or account
    // value is added to either request.
    (try? JSONSerialization.data(withJSONObject: value, options: [])) ?? Data()
  }
}

private enum ProofOriginEncoding {
  static let userAgent =
    "Mozilla/5.0 (Windows NT 10.0; Win64; x64) "
    + "AppleWebKit/537.36 (KHTML, like Gecko) Chrome/131.0.0.0 Safari/537.3"

  static func base64URL(_ bytes: [UInt8]) -> String {
    Data(bytes).base64EncodedString()
      .replacingOccurrences(of: "+", with: "-")
      .replacingOccurrences(of: "/", with: "_")
  }

  static func decodeYouTubeBase64(_ value: String) -> Data? {
    var normalized =
      value
      .replacingOccurrences(of: "-", with: "+")
      .replacingOccurrences(of: "_", with: "/")
      .replacingOccurrences(of: ".", with: "=")
    let remainder = normalized.count % 4
    if remainder != 0 {
      normalized += String(repeating: "=", count: 4 - remainder)
    }
    return Data(base64Encoded: normalized)
  }
}

private struct ProofOriginChallenge: Sendable {
  let interpreterJavascript: String
  let program: String
  let globalName: String

  init(responseBody: Data) throws {
    guard
      let root = try? JSONSerialization.jsonObject(with: responseBody),
      let outer = root as? [Any],
      !outer.isEmpty
    else {
      throw ProofOfOriginError.invalidChallenge
    }

    let challenge: [Any]
    if outer.count > 1,
      let scrambled = outer[1] as? String
    {
      guard
        let decoded = ProofOriginEncoding.decodeYouTubeBase64(scrambled),
        let descrambled = String(
          bytes: decoded.map { $0 &+ 97 },
          encoding: .utf8
        ),
        let parsed = try? JSONSerialization.jsonObject(
          with: Data(descrambled.utf8)
        ),
        let parsedArray = parsed as? [Any]
      else {
        throw ProofOfOriginError.invalidChallenge
      }
      challenge = parsedArray
    } else {
      guard let plain = outer[0] as? [Any] else {
        throw ProofOfOriginError.invalidChallenge
      }
      challenge = plain
    }

    guard
      challenge.count > 5,
      let interpreterJavascript = Self.firstString(in: challenge[1]),
      let program = challenge[4] as? String,
      let globalName = challenge[5] as? String,
      !interpreterJavascript.isEmpty,
      !program.isEmpty,
      !globalName.isEmpty,
      interpreterJavascript.utf8.count <= 1_500_000,
      program.utf8.count <= 1_500_000,
      globalName.utf8.count <= 256
    else {
      throw ProofOfOriginError.invalidChallenge
    }

    // Challenge index 2 may contain a remote interpreter URL. It is
    // deliberately ignored: the app never fetches challenge-provided scripts.
    self.interpreterJavascript = interpreterJavascript
    self.program = program
    self.globalName = globalName
  }

  private static func firstString(in value: Any) -> String? {
    if let string = value as? String {
      return string
    }
    guard let array = value as? [Any] else { return nil }
    return array.compactMap { $0 as? String }.first
  }
}

private struct ProofOriginIntegrity: Sendable {
  let bytes: [UInt8]
  let expiresAt: Date

  init(responseBody: Data, now: Date = Date()) throws {
    guard
      let root = try? JSONSerialization.jsonObject(with: responseBody),
      let values = root as? [Any],
      values.count > 1,
      let encoded = values[0] as? String,
      let ttl = values[1] as? NSNumber,
      ttl.doubleValue > 0,
      let decoded = ProofOriginEncoding.decodeYouTubeBase64(encoded),
      !decoded.isEmpty,
      decoded.count <= 4 * 1024
    else {
      throw ProofOfOriginError.invalidIntegrityToken
    }

    bytes = Array(decoded)
    // AuraMusic's pinned provider expires the generator ten minutes before the
    // GenerateIT TTL. A short TTL can therefore make it immediately unusable;
    // preserving that margin is safer than extending a generator's lifetime.
    expiresAt = ProofOriginCachePolicy.generatorExpiresAt(
      now: now, integrityLifetime: ttl.doubleValue)
  }
}

private final class ProofOriginHTTPClient: NSObject, URLSessionDataDelegate,
  URLSessionTaskDelegate, @unchecked Sendable
{
  private static let maximumBodyBytes = 2 * 1024 * 1024

  private let apiKey: String?
  private var session: URLSession!
  private let lock = NSLock()
  private var states: [Int: HTTPRequestState] = [:]

  init(apiKey: String?) {
    self.apiKey = apiKey
    let configuration = URLSessionConfiguration.ephemeral
    configuration.httpShouldSetCookies = false
    configuration.httpCookieAcceptPolicy = .never
    configuration.httpCookieStorage = nil
    configuration.urlCredentialStorage = nil
    configuration.requestCachePolicy = .reloadIgnoringLocalCacheData
    configuration.timeoutIntervalForRequest = 8
    configuration.timeoutIntervalForResource = 12

    let delegateQueue = OperationQueue()
    delegateQueue.maxConcurrentOperationCount = 1
    super.init()
    self.session = URLSession(
      configuration: configuration,
      delegate: self,
      delegateQueue: delegateQueue
    )
  }

  deinit {
    session.invalidateAndCancel()
  }

  func post(endpoint: ProofOriginEndpoint, body: Data) async throws -> Data {
    guard let apiKey, !apiKey.isEmpty, apiKey.utf8.count <= 256,
      apiKey.utf8.allSatisfy({
        (48...57).contains($0) || (65...90).contains($0) || (97...122).contains($0)
          || $0 == 45 || $0 == 95
      })
    else {
      throw ProofOfOriginError.missingConfiguration
    }
    guard let url = endpoint.url else {
      throw ProofOfOriginError.transport
    }
    var request = URLRequest(url: url)
    request.httpMethod = "POST"
    request.httpBody = body
    request.setValue(ProofOriginEncoding.userAgent, forHTTPHeaderField: "User-Agent")
    request.setValue("application/json", forHTTPHeaderField: "Accept")
    request.setValue("application/json+protobuf", forHTTPHeaderField: "Content-Type")
    request.setValue(
      "grpc-web-javascript/0.1",
      forHTTPHeaderField: "x-user-agent"
    )
    request.setValue(
      apiKey,
      forHTTPHeaderField: "x-goog-api-key"
    )
    let state = HTTPRequestState()
    return try await withTaskCancellationHandler(
      operation: {
        try await withCheckedThrowingContinuation {
          (continuation: CheckedContinuation<Data, Error>) in
          guard state.install(continuation: continuation) else {
            return
          }
          let task = session.dataTask(with: request)
          state.install(task: task)
          lock.lock()
          states[task.taskIdentifier] = state
          lock.unlock()
          task.resume()
        }
      },
      onCancel: {
        state.cancel()
        self.remove(state)
      })
  }

  func cancelAll() {
    let pending: [HTTPRequestState]
    lock.lock()
    pending = Array(states.values)
    lock.unlock()
    for state in pending {
      state.cancel()
      remove(state)
    }
  }

  func urlSession(
    _ session: URLSession,
    dataTask: URLSessionDataTask,
    didReceive response: URLResponse,
    completionHandler: @escaping (URLSession.ResponseDisposition) -> Void
  ) {
    guard let state = state(for: dataTask.taskIdentifier) else {
      completionHandler(.cancel)
      return
    }
    guard let response = response as? HTTPURLResponse else {
      state.finish(.failure(ProofOfOriginError.unexpectedStatus))
      remove(state)
      dataTask.cancel()
      completionHandler(.cancel)
      return
    }

    Logger(subsystem: "com.hydraulophone", category: "proof").notice(
      "proof_http status=\(response.statusCode)"
    )
    guard response.statusCode == 200 else {
      state.finish(.failure(ProofOfOriginError.unexpectedStatus))
      remove(state)
      dataTask.cancel()
      completionHandler(.cancel)
      return
    }
    state.accept(response: response)
    completionHandler(.allow)
  }

  func urlSession(
    _ session: URLSession,
    dataTask: URLSessionDataTask,
    didReceive data: Data
  ) {
    guard let state = state(for: dataTask.taskIdentifier) else { return }
    guard state.append(data: data, maximumBytes: Self.maximumBodyBytes) else {
      state.finish(.failure(ProofOfOriginError.bodyTooLarge))
      remove(state)
      dataTask.cancel()
      return
    }
  }

  func urlSession(
    _ session: URLSession,
    task: URLSessionTask,
    willPerformHTTPRedirection response: HTTPURLResponse,
    newRequest request: URLRequest,
    completionHandler: @escaping (URLRequest?) -> Void
  ) {
    if let state = state(for: task.taskIdentifier) {
      state.finish(.failure(ProofOfOriginError.redirected))
      remove(state)
      task.cancel()
    }
    completionHandler(nil)
  }

  func urlSession(
    _ session: URLSession,
    task: URLSessionTask,
    didCompleteWithError error: Error?
  ) {
    guard let state = state(for: task.taskIdentifier) else { return }
    if error != nil {
      state.finish(
        .failure(state.wasCancelled ? CancellationError() : ProofOfOriginError.transport))
    } else {
      state.finish(.success(state.data))
    }
    remove(state)
  }

  private func state(for taskIdentifier: Int) -> HTTPRequestState? {
    lock.lock()
    defer { lock.unlock() }
    return states[taskIdentifier]
  }

  private func remove(_ state: HTTPRequestState) {
    guard let taskIdentifier = state.taskIdentifier else { return }
    lock.lock()
    states.removeValue(forKey: taskIdentifier)
    lock.unlock()
  }
}

private final class HTTPRequestState: @unchecked Sendable {
  private let lock = NSLock()
  private var continuation: CheckedContinuation<Data, Error>?
  private var completed = false
  private(set) var data = Data()
  private(set) var response: HTTPURLResponse?
  private(set) var task: URLSessionDataTask?
  private(set) var wasCancelled = false
  private(set) var taskIdentifier: Int?

  func install(continuation: CheckedContinuation<Data, Error>) -> Bool {
    lock.lock()
    guard !completed else {
      lock.unlock()
      continuation.resume(
        throwing: wasCancelled ? CancellationError() : ProofOfOriginError.transport
      )
      return false
    }
    self.continuation = continuation
    lock.unlock()
    return true
  }

  func install(task: URLSessionDataTask) {
    lock.lock()
    self.task = task
    taskIdentifier = task.taskIdentifier
    let wasCancelled = self.wasCancelled
    lock.unlock()
    if wasCancelled {
      task.cancel()
    }
  }

  func accept(response: HTTPURLResponse) {
    lock.lock()
    self.response = response
    lock.unlock()
  }

  func append(data: Data, maximumBytes: Int) -> Bool {
    lock.lock()
    defer { lock.unlock() }
    guard !completed, self.data.count <= maximumBytes - data.count else {
      return false
    }
    self.data.append(data)
    return true
  }

  func cancel() {
    lock.lock()
    wasCancelled = true
    let task = task
    lock.unlock()
    task?.cancel()
    finish(.failure(CancellationError()))
  }

  func finish(_ result: Result<Data, Error>) {
    lock.lock()
    guard !completed else {
      lock.unlock()
      return
    }
    completed = true
    let continuation = self.continuation
    self.continuation = nil
    lock.unlock()

    guard let continuation else { return }
    switch result {
    case .success(let data):
      continuation.resume(returning: data)
    case .failure(let error):
      continuation.resume(throwing: error)
    }
  }
}

@MainActor
private final class ProofOriginWebView: NSObject, WKNavigationDelegate, WKUIDelegate {
  private var webView: WKWebView?
  private var loadContinuation: CheckedContinuation<Void, Error>?
  private var contentRuleContinuation: CheckedContinuation<Void, Error>?
  private var javascriptContinuations: [UInt64: CheckedContinuation<Any, Error>] = [:]
  private var nextJavascriptID: UInt64 = 0
  private let contentRuleIdentifier = "HydraulophoneProofOriginNetworkBlocker-\(UUID().uuidString)"
  private var acceptingInitialNavigation = false
  private var didLoad = false
  private(set) var isDead = false

  private override init() {
    super.init()

    let configuration = WKWebViewConfiguration()
    configuration.websiteDataStore = WKWebsiteDataStore.nonPersistent()
    configuration.defaultWebpagePreferences.allowsContentJavaScript = true

    let view = WKWebView(frame: .zero, configuration: configuration)
    view.customUserAgent = ProofOriginEncoding.userAgent
    view.navigationDelegate = self
    view.uiDelegate = self
    webView = view

    NotificationCenter.default.addObserver(
      self,
      selector: #selector(applicationDidEnterBackground),
      name: UIApplication.didEnterBackgroundNotification,
      object: nil
    )
    NotificationCenter.default.addObserver(
      self,
      selector: #selector(applicationWillTerminate),
      name: UIApplication.willTerminateNotification,
      object: nil
    )
  }

  static func make(helperHTML: String) async throws -> ProofOriginWebView {
    let generator = ProofOriginWebView()
    do {
      try await generator.installNetworkBlocker()
      try await generator.load(helperHTML: helperHTML)
      _ = try await generator.call(
        """
        if (typeof window.__hydraulophonePreflight !== "function") {
          throw new Error("preflight");
        }
        return window.__hydraulophonePreflight();
        """
      )
      return generator
    } catch {
      generator.invalidate()
      throw ProofOfOriginError.webViewUnavailable
    }
  }

  func run(challenge: ProofOriginChallenge) async throws -> String {
    let value = try await call(
      """
      return await window.__hydraulophoneRunBotGuard(
        interpreterJavascript,
        globalName,
        program
      );
      """,
      arguments: [
        "interpreterJavascript": challenge.interpreterJavascript,
        "globalName": challenge.globalName,
        "program": challenge.program,
      ]
    )

    guard
      let payload = value as? [String: Any],
      let response = payload["botguardResponse"] as? String,
      payload["signalOutputReady"] as? Bool == true,
      !response.isEmpty
    else {
      throw ProofOfOriginError.javascript
    }
    return response
  }

  func installMinter(integrityBytes: [UInt8]) async throws {
    let value = try await call(
      """
      return await window.__hydraulophoneInstallMinter(integrityBytes);
      """,
      arguments: ["integrityBytes": integrityBytes.map(Int.init)]
    )
    guard value as? Bool == true else {
      throw ProofOfOriginError.javascript
    }
  }

  func mint(identifier: String) async throws -> [UInt8] {
    let value = try await call(
      """
      return await window.__hydraulophoneMint(identifierBytes);
      """,
      arguments: [
        "identifierBytes": Array(identifier.utf8).map(Int.init)
      ]
    )
    guard let values = value as? [Any], !values.isEmpty else {
      throw ProofOfOriginError.javascript
    }

    let bytes = values.compactMap { value -> UInt8? in
      guard let number = value as? NSNumber else { return nil }
      let integer = number.intValue
      guard (0...255).contains(integer) else { return nil }
      return UInt8(integer)
    }
    guard bytes.count == values.count, !bytes.isEmpty, bytes.count <= 4 * 1024 else {
      throw ProofOfOriginError.javascript
    }
    return bytes
  }

  func invalidate() {
    guard !isDead else { return }
    isDead = true
    failPending(with: ProofOfOriginError.cancelled)
    NotificationCenter.default.removeObserver(self)
    WKContentRuleListStore.default().removeContentRuleList(
      forIdentifier: contentRuleIdentifier
    ) { _ in }

    guard let webView else { return }
    webView.stopLoading()
    webView.navigationDelegate = nil
    webView.uiDelegate = nil
    webView.configuration.userContentController.removeAllUserScripts()
    webView.loadHTMLString("", baseURL: nil)
    self.webView = nil
  }

  private func installNetworkBlocker() async throws {
    guard let webView else { throw ProofOfOriginError.webViewUnavailable }
    let source = """
      [{"trigger":{"url-filter":".*"},"action":{"type":"block"}}]
      """
    try await withTaskCancellationHandler(
      operation: {
        try await withCheckedThrowingContinuation {
          (continuation: CheckedContinuation<Void, Error>) in
          contentRuleContinuation = continuation
          WKContentRuleListStore.default().compileContentRuleList(
            forIdentifier: contentRuleIdentifier,
            encodedContentRuleList: source
          ) { [weak self] list, _ in
            Task { @MainActor in
              guard let self else { return }
              guard let list else {
                self.finishContentRule(
                  result: .failure(ProofOfOriginError.webViewUnavailable)
                )
                return
              }
              webView.configuration.userContentController.add(list)
              self.finishContentRule(result: .success(()))
            }
          }
        }
      },
      onCancel: {
        Task { @MainActor [weak self] in
          self?.finishContentRule(result: .failure(CancellationError()))
        }
      })
  }

  private func load(helperHTML: String) async throws {
    guard let webView else { throw ProofOfOriginError.webViewUnavailable }
    try await withTaskCancellationHandler(
      operation: {
        try await withCheckedThrowingContinuation {
          (continuation: CheckedContinuation<Void, Error>) in
          loadContinuation = continuation
          acceptingInitialNavigation = true
          webView.loadHTMLString(
            helperHTML,
            baseURL: URL(string: "https://www.youtube.com")
          )
        }
      },
      onCancel: {
        Task { @MainActor [weak self] in
          self?.failLoad(with: CancellationError())
        }
      })
    didLoad = true
  }

  private func call(
    _ functionBody: String,
    arguments: [String: Any] = [:]
  ) async throws -> Any {
    guard !isDead, let webView else {
      throw ProofOfOriginError.webViewUnavailable
    }
    try Task.checkCancellation()

    nextJavascriptID &+= 1
    let requestID = nextJavascriptID
    return try await withTaskCancellationHandler(
      operation: {
        try await withCheckedThrowingContinuation {
          (continuation: CheckedContinuation<Any, Error>) in
          javascriptContinuations[requestID] = continuation
          webView.callAsyncJavaScript(
            functionBody,
            arguments: arguments,
            in: nil,
            in: .page
          ) { [weak self] result in
            Task { @MainActor in
              switch result {
              case .success(let value):
                self?.finishJavascript(requestID, result: .success(value))
              case .failure:
                self?.finishJavascript(
                  requestID,
                  result: .failure(ProofOfOriginError.javascript)
                )
              }
            }
          }
        }
      },
      onCancel: {
        Task { @MainActor [weak self] in
          self?.finishJavascript(
            requestID,
            result: .failure(CancellationError())
          )
        }
      })
  }

  private func finishJavascript(
    _ id: UInt64,
    result: Result<Any, Error>
  ) {
    guard let continuation = javascriptContinuations.removeValue(forKey: id) else {
      return
    }
    switch result {
    case .success(let value):
      continuation.resume(returning: value)
    case .failure(let error):
      continuation.resume(throwing: error)
    }
  }

  private func failPending(with error: Error) {
    if let contentRuleContinuation {
      self.contentRuleContinuation = nil
      contentRuleContinuation.resume(throwing: error)
    }
    if let loadContinuation {
      self.loadContinuation = nil
      loadContinuation.resume(throwing: error)
    }
    let continuations = javascriptContinuations
    javascriptContinuations.removeAll(keepingCapacity: false)
    for continuation in continuations.values {
      continuation.resume(throwing: error)
    }
  }

  private func finishContentRule(result: Result<Void, Error>) {
    guard let continuation = contentRuleContinuation else { return }
    contentRuleContinuation = nil
    switch result {
    case .success:
      continuation.resume()
    case .failure(let error):
      continuation.resume(throwing: error)
    }
  }

  private func failLoad(with error: Error) {
    guard let continuation = loadContinuation else { return }
    loadContinuation = nil
    continuation.resume(throwing: error)
  }

  @objc private func applicationDidEnterBackground() {
    invalidate()
  }

  @objc private func applicationWillTerminate() {
    invalidate()
  }

  func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!) {
    acceptingInitialNavigation = false
    guard let continuation = loadContinuation else { return }
    loadContinuation = nil
    continuation.resume()
  }

  func webView(
    _ webView: WKWebView,
    didFail navigation: WKNavigation!,
    withError error: Error
  ) {
    acceptingInitialNavigation = false
    failLoad(with: ProofOfOriginError.webViewUnavailable)
  }

  func webView(
    _ webView: WKWebView,
    didFailProvisionalNavigation navigation: WKNavigation!,
    withError error: Error
  ) {
    acceptingInitialNavigation = false
    failLoad(with: ProofOfOriginError.webViewUnavailable)
  }

  func webViewWebContentProcessDidTerminate(_ webView: WKWebView) {
    isDead = true
    NotificationCenter.default.removeObserver(self)
    failPending(with: ProofOfOriginError.webViewUnavailable)
    self.webView = nil
  }

  func webView(
    _ webView: WKWebView,
    decidePolicyFor navigationAction: WKNavigationAction,
    decisionHandler: @escaping (WKNavigationActionPolicy) -> Void
  ) {
    guard
      acceptingInitialNavigation,
      navigationAction.targetFrame?.isMainFrame == true
    else {
      decisionHandler(.cancel)
      return
    }
    guard
      let url = navigationAction.request.url,
      url.scheme == "https",
      url.host?.caseInsensitiveCompare("www.youtube.com") == .orderedSame
    else {
      decisionHandler(.cancel)
      return
    }
    decisionHandler(.allow)
  }

  func webView(
    _ webView: WKWebView,
    decidePolicyFor navigationResponse: WKNavigationResponse,
    decisionHandler: @escaping (WKNavigationResponsePolicy) -> Void
  ) {
    guard acceptingInitialNavigation, navigationResponse.isForMainFrame else {
      decisionHandler(.cancel)
      return
    }
    guard
      let url = navigationResponse.response.url,
      url.scheme == "https",
      url.host?.caseInsensitiveCompare("www.youtube.com") == .orderedSame
    else {
      decisionHandler(.cancel)
      return
    }
    decisionHandler(.allow)
  }

  func webView(
    _ webView: WKWebView,
    createWebViewWith configuration: WKWebViewConfiguration,
    for navigationAction: WKNavigationAction,
    windowFeatures: WKWindowFeatures
  ) -> WKWebView? {
    nil
  }

  func webView(
    _ webView: WKWebView,
    requestMediaCapturePermissionFor origin: WKSecurityOrigin,
    initiatedByFrame frame: WKFrameInfo,
    type: WKMediaCaptureType,
    decisionHandler: @escaping (WKPermissionDecision) -> Void
  ) {
    decisionHandler(.deny)
  }

  func webView(
    _ webView: WKWebView,
    requestDeviceOrientationAndMotionPermissionFor origin: WKSecurityOrigin,
    initiatedByFrame frame: WKFrameInfo,
    decisionHandler: @escaping (WKPermissionDecision) -> Void
  ) {
    decisionHandler(.deny)
  }
}

private enum ProofOriginResources {
  static func helperHTML() throws -> String {
    let bundles = [Bundle.main, Bundle(for: ResourceAnchor.self)]
    for bundle in bundles {
      let urls = [
        bundle.url(
          forResource: "proof_of_origin",
          withExtension: "html",
          subdirectory: "ProofOfOrigin"
        ),
        bundle.url(forResource: "proof_of_origin", withExtension: "html"),
      ]
      for url in urls.compactMap({ $0 }) {
        if let html = try? String(contentsOf: url, encoding: .utf8), !html.isEmpty {
          return html
        }
      }
    }
    throw ProofOfOriginError.resourceUnavailable
  }

  private final class ResourceAnchor: NSObject {}
}