geesawra.industries/hydraulophone
An unofficial YouTube Music app for iPhone, iPad, and Mac.
0
0
// Local adaptation of YouTubeKit SignatureSolver.swift.
// Copyright (c) 2022 Alexander Eichhorn. MIT; see NOTICE and the vendored licenses.
// Source: alexeichhorn/YouTubeKit, e5b7d0396ce12bf3444f0d209e8436c83373b7af.
import Foundation
#if canImport(JavaScriptCore)
import JavaScriptCore
#endif
/// Executes the pinned parser-based solver locally, never a remote extractor.
/// One script and bounded challenge results are cached in memory. Synchronous
/// JavaScript execution stays on this actor, not the UI actor; cancellation is
/// checked before and after evaluation (JavaScriptCore has no public Swift
/// interruption API). No native network or filesystem bridge is installed.
public actor JavaScriptCorePlayerStreamCipher: PlayerStreamCipher, PlayerStreamCipherPreparing {
#if canImport(JavaScriptCore)
private var evaluator: PlayerScriptEvaluator?
#endif
public init() {}
public func prepare(playerScript: String) async throws {
try Task.checkCancellation()
#if canImport(JavaScriptCore)
if evaluator?.playerScript != playerScript {
evaluator = try PlayerScriptEvaluator(script: playerScript)
}
// Exercise the parser/preprocessor with a non-secret synthetic challenge,
// as InnerTubeX does. Real playback still solves its own URL challenges.
_ = try evaluator?.solve(signature: "prewarm", n: nil)
try Task.checkCancellation()
#endif
}
public func decipher(_ request: PlayerStreamCipherRequest) async throws -> URL {
try Task.checkCancellation()
guard InnerTubeMediaURLPolicy.isAllowedMediaURL(request.url),
request.signature != nil || request.n != nil,
request.signature.map({ !$0.isEmpty && $0.utf8.count <= 16_384 }) ?? true,
request.n.map({ !$0.isEmpty && $0.utf8.count <= 16_384 }) ?? true,
!request.signatureParameter.isEmpty,
request.signatureParameter.utf8.count <= 100
else {
throw PlayerStreamCipherError.invalidCipher
}
#if canImport(JavaScriptCore)
if evaluator?.playerScript != request.playerScript {
evaluator = try PlayerScriptEvaluator(script: request.playerScript)
}
guard let evaluator else { throw PlayerStreamCipherError.invalidScript }
let output = try evaluator.solve(signature: request.signature, n: request.n)
try Task.checkCancellation()
var replacements: [(name: String, value: String)] = []
for (key, value) in [(request.signatureParameter, output.signature), ("n", output.n)] {
guard let value else { continue }
replacements.append((key, value))
}
guard
let result = Self.replacingQueryParameters(replacements, in: request.url),
InnerTubeMediaURLPolicy.isAllowedMediaURL(result)
else {
throw PlayerStreamCipherError.invalidResult
}
return result
#else
throw PlayerStreamCipherError.unsupported
#endif
}
/// Replaces only the transformed challenge parameters. QueryItems round-trip
/// the entire media URL through decoded name/value pairs, which can change
/// percent-escaped bytes in unrelated signed parameters.
private static func replacingQueryParameters(
_ replacements: [(name: String, value: String)],
in url: URL
) -> URL? {
guard !replacements.isEmpty else { return url }
let absoluteString = url.absoluteString
let fragmentStart = absoluteString.firstIndex(of: "#") ?? absoluteString.endIndex
let beforeFragment = absoluteString[..<fragmentStart]
let fragment = absoluteString[fragmentStart...]
let queryStart = beforeFragment.firstIndex(of: "?")
let base = queryStart.map { beforeFragment[..<$0] } ?? beforeFragment
let originalQuery: String
if let queryStart {
originalQuery = String(beforeFragment[beforeFragment.index(after: queryStart)...])
} else {
originalQuery = ""
}
let replacementByName = Dictionary(
replacements.map { ($0.name, $0.value) },
uniquingKeysWith: { _, latest in latest }
)
let orderedNames = replacements.map(\.name).reduce(into: [String]()) { names, name in
if !names.contains(name) { names.append(name) }
}
let fields =
originalQuery.isEmpty
? []
: originalQuery.split(separator: "&", omittingEmptySubsequences: false).map(String.init)
var output: [String] = []
var replacedNames = Set<String>()
for field in fields {
let rawName = String(field.prefix(while: { $0 != "=" }))
let decodedName = rawName.removingPercentEncoding ?? rawName
guard let value = replacementByName[decodedName] else {
output.append(field)
continue
}
if replacedNames.insert(decodedName).inserted {
guard let encodedValue = Self.percentEncodeQueryParameter(value) else {
return nil
}
output.append("\(rawName)=\(encodedValue)")
}
}
for name in orderedNames where !replacedNames.contains(name) {
guard
let encodedName = Self.percentEncodeQueryParameter(name),
let value = replacementByName[name],
let encodedValue = Self.percentEncodeQueryParameter(value)
else {
return nil
}
output.append("\(encodedName)=\(encodedValue)")
}
let query = output.joined(separator: "&")
let updatedString = String(base) + (query.isEmpty ? "" : "?\(query)") + String(fragment)
return URL(string: updatedString)
}
private static func percentEncodeQueryParameter(_ value: String) -> String? {
let unreserved = CharacterSet(
charactersIn: "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-._~"
)
return value.addingPercentEncoding(withAllowedCharacters: unreserved)
}
}
#if canImport(JavaScriptCore)
/// All JS values are confined to the owning solver actor.
private final class PlayerScriptEvaluator {
let playerScript: String
private let context: JSContext
private var preparedPlayer: String?
private var cache: [Challenge: Output] = [:]
struct Challenge: Hashable {
let signature: String?
let n: String?
}
struct Output {
let signature: String?
let n: String?
}
private struct Request: Encodable {
let type: String
let challenges: [String]
}
private struct Input: Encodable {
let type: String
let player: String?
let preprocessedPlayer: String?
let requests: [Request]
let outputPreprocessed: Bool
enum CodingKeys: String, CodingKey {
case type, player, requests
case preprocessedPlayer = "preprocessed_player"
case outputPreprocessed = "output_preprocessed"
}
}
private struct Response: Decodable {
struct Item: Decodable {
let type: String
let data: [String: String]?
}
let type: String
let responses: [Item]
let preprocessedPlayer: String?
enum CodingKeys: String, CodingKey {
case type, responses
case preprocessedPlayer = "preprocessed_player"
}
}
init(script: String) throws {
guard !script.isEmpty, script.utf8.count <= 4 * 1024 * 1024,
let context = JSContext(virtualMachine: JSVirtualMachine())
else {
throw PlayerStreamCipherError.invalidScript
}
playerScript = script
self.context = context
// Exception text may contain player source/challenges; never expose it.
context.exceptionHandler = { context, exception in context?.exception = exception }
context.evaluateScript(Self.environment)
guard context.exception == nil else { throw PlayerStreamCipherError.invalidScript }
for file in ["meriyah.umd.js", "astring.umd.js", "yt_ejs_helper.js"] {
guard
let url = Self.resourceBundle.url(
forResource: file, withExtension: nil, subdirectory: "YouTubeKit"
),
let source = try? String(contentsOf: url, encoding: .utf8)
else {
throw PlayerStreamCipherError.invalidScript
}
context.exception = nil
context.evaluateScript(source)
guard context.exception == nil else { throw PlayerStreamCipherError.invalidScript }
}
}
func solve(signature: String?, n: String?) throws -> Output {
let challenge = Challenge(signature: signature, n: n)
if let output = cache[challenge] { return output }
try Task.checkCancellation()
var requests: [Request] = []
if let n { requests.append(Request(type: "n", challenges: [n])) }
if let signature { requests.append(Request(type: "sig", challenges: [signature])) }
let input = Input(
type: preparedPlayer == nil ? "player" : "preprocessed_player",
player: preparedPlayer == nil ? playerScript : nil,
preprocessedPlayer: preparedPlayer,
requests: requests,
outputPreprocessed: preparedPlayer == nil
)
guard let json = String(data: try JSONEncoder().encode(input), encoding: .utf8) else {
throw PlayerStreamCipherError.invalidCipher
}
context.exception = nil
context.setObject(json, forKeyedSubscript: "hydraulophoneInput" as NSString)
defer { context.setObject(nil, forKeyedSubscript: "hydraulophoneInput" as NSString) }
let result = context.evaluateScript("JSON.stringify(jsc(JSON.parse(hydraulophoneInput)))")
try Task.checkCancellation()
guard context.exception == nil, let result, result.isString,
let outputJSON = result.toString(), outputJSON.utf8.count <= 8 * 1024 * 1024,
let data = outputJSON.data(using: .utf8),
let response = try? JSONDecoder().decode(Response.self, from: data),
response.type == "result",
response.responses.count == requests.count
else {
throw PlayerStreamCipherError.invalidScript
}
var transformed: [String: String] = [:]
for (request, item) in zip(requests, response.responses) {
guard item.type == "result", let input = request.challenges.first,
let value = item.data?[input], !value.isEmpty, value.utf8.count <= 16_384
else {
throw PlayerStreamCipherError.invalidResult
}
transformed[request.type] = value
}
let output = Output(signature: transformed["sig"], n: transformed["n"])
if let prepared = response.preprocessedPlayer {
guard prepared.utf8.count <= 8 * 1024 * 1024 else {
throw PlayerStreamCipherError.invalidScript
}
preparedPlayer = prepared
}
if cache.count >= 32 { cache.removeAll(keepingCapacity: true) }
cache[challenge] = output
return output
}
private static var resourceBundle: Bundle {
#if SWIFT_PACKAGE
.module
#else
Bundle(for: SolverResourceBundle.self)
#endif
}
// Minimal environment from the pinned YouTubeKit SignatureSolver. These
// objects provide values for player code, not actual DOM/network services.
private static let environment = #"""
globalThis.XMLHttpRequest = { prototype: {} };
globalThis.URL = class URL {
constructor(url) {
this.href = url;
const match = url.match(/^(https?:)\/\/([^/:]+)(:(\d+))?(\/[^?#]*)?(\?[^#]*)?(#.*)?$/);
this.protocol = match ? match[1] : '';
this.hostname = match ? match[2] : '';
this.port = match && match[4] ? match[4] : '';
this.pathname = match && match[5] ? match[5] : '/';
this.search = match && match[6] ? match[6] : '';
this.hash = match && match[7] ? match[7] : '';
}
};
globalThis.navigator = {
userAgent: 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36'
};
const window = Object.assign(Object.create(null), globalThis);
window.location = new URL("https://www.youtube.com/watch?v=hydraulophone");
const document = {};
let self = globalThis;
"""#
}
private final class SolverResourceBundle: NSObject {}
#endif