Files
EchoionCore/src/SignatureCipher.cpp
T

805 lines
23 KiB
C++

#include "echoion/core/Logger.hpp"
#include "echoion/core/SignatureCipher.hpp"
#include <Void/Data/Json.hpp>
#include <algorithm>
#include <cctype>
#include <filesystem>
#include <format>
#include <fstream>
#include <regex>
// Minimal embedded fallback - a stub that logs errors
// The real solver is downloaded from GitHub releases
namespace
{
constexpr std::string_view FALLBACK_CORE_JS = R"(
var globalThis = globalThis || this;
var jsc = function(input) {
return JSON.stringify({
error: "Solver libraries not available. Please check internet connection.",
responses: []
});
};
)";
}
namespace Echoion::Core
{
SignatureCipher::SignatureCipher() = default;
SignatureCipher::~SignatureCipher() { clear(); }
SignatureCipher::SignatureCipher(SignatureCipher&& other) noexcept
: runtime_(other.runtime_), context_(other.context_),
playerJsCode_(std::move(other.playerJsCode_)),
preprocessedPlayer_(std::move(other.preprocessedPlayer_)),
initialized_(other.initialized_),
solverInitialized_(other.solverInitialized_),
hasPlayerJs_(other.hasPlayerJs_)
{
other.runtime_ = nullptr;
other.context_ = nullptr;
other.initialized_ = false;
other.solverInitialized_ = false;
other.hasPlayerJs_ = false;
}
SignatureCipher&
SignatureCipher::operator=(SignatureCipher&& other) noexcept
{
if (this != &other) {
clear();
runtime_ = other.runtime_;
context_ = other.context_;
playerJsCode_ = std::move(other.playerJsCode_);
preprocessedPlayer_ = std::move(other.preprocessedPlayer_);
initialized_ = other.initialized_;
solverInitialized_ = other.solverInitialized_;
hasPlayerJs_ = other.hasPlayerJs_;
other.runtime_ = nullptr;
other.context_ = nullptr;
other.initialized_ = false;
other.solverInitialized_ = false;
other.hasPlayerJs_ = false;
}
return *this;
}
void SignatureCipher::initialize()
{
std::lock_guard<std::mutex> lock(mutex_);
if (initialized_) {
return;
}
initSolver();
initialized_ = true;
}
bool SignatureCipher::setPlayerJs(std::string_view playerJsCode)
{
std::lock_guard<std::mutex> lock(mutex_);
if (!initialized_) {
ECHOION_LOG_ERROR(
"Cipher not initialized. Call initialize() first.");
return false;
}
if (!solverInitialized_) {
ECHOION_LOG_WARNING(
"Solver not initialized - cannot process player JS");
return false;
}
playerJsCode_ = std::string(playerJsCode);
hasPlayerJs_ = false;
preprocessedPlayer_.clear();
if (playerJsCode_.empty()) {
ECHOION_LOG_WARNING("Empty player JS code provided");
return false;
}
if (!context_) {
ECHOION_LOG_ERROR("QuickJS context not available");
return false;
}
// Create input for the solver
Void::Json::Value input = Void::Json::object();
input.as_object().emplace_back("type", Void::Json::Value{"player"});
input.as_object().emplace_back(
"player", Void::Json::Value{playerJsCode_});
input.as_object().emplace_back("output_preprocessed",
Void::Json::Value{true});
input.as_object().emplace_back("requests", Void::Json::array());
std::string inputStr = Void::Json::serialize(input);
// Log input for debugging (truncate if too large)
std::string_view inputPreview(inputStr);
if (inputPreview.size() > 500) {
inputPreview = inputPreview.substr(0, 500);
ECHOION_LOG_DEBUG(
std::format("Solver input (truncated): {}...", inputPreview));
} else {
ECHOION_LOG_DEBUG(std::format("Solver input: {}", inputPreview));
}
// Get global object and jsc function
JSValue global = JS_GetGlobalObject(context_);
JSValue jsc = JS_GetPropertyStr(context_, global, "jsc");
if (JS_IsUndefined(jsc)) {
ECHOION_LOG_ERROR("jsc function not found in QuickJS context");
JS_FreeValue(context_, global);
return false;
}
// Parse input JSON
JSValue inputVal =
JS_ParseJSON(context_, inputStr.c_str(), inputStr.size(), "input");
if (JS_IsException(inputVal)) {
ECHOION_LOG_ERROR("Failed to parse input JSON");
JS_FreeValue(context_, jsc);
JS_FreeValue(context_, global);
return false;
}
// Call jsc function with error handling wrapper
// The solver can throw on malformed player JS, so we wrap in try/catch
// Also JSON.stringify the result since jsc returns a JS object, not a
// string
const char* wrapperJS = R"(
(function(jscFunc, input) {
try {
var result = jscFunc(input);
return JSON.stringify(result);
} catch (e) {
return JSON.stringify({
error: e.message || String(e),
stack: e.stack || '',
responses: []
});
}
})
)";
JSValue wrapper = JS_Eval(context_, wrapperJS, strlen(wrapperJS),
"<wrapper>", JS_EVAL_TYPE_GLOBAL);
if (JS_IsException(wrapper)) {
ECHOION_LOG_ERROR("Failed to compile error handling wrapper");
JS_FreeValue(context_, inputVal);
JS_FreeValue(context_, jsc);
JS_FreeValue(context_, global);
return false;
}
// Call the wrapper with jsc and input as arguments
JSValue args[] = {jsc, inputVal};
JSValue result = JS_Call(context_, wrapper, global, 2, args);
JS_FreeValue(context_, wrapper);
if (!JS_IsException(result)) {
// Check if result is null or undefined
if (JS_IsNull(result) || JS_IsUndefined(result)) {
ECHOION_LOG_ERROR("jsc returned null/undefined - solver may "
"have failed silently");
} else {
const char* resultStr = JS_ToCString(context_, result);
if (resultStr) {
// Log first 500 chars of result for debugging
std::string_view resultView(resultStr);
if (resultView.size() > 500) {
resultView = resultView.substr(0, 500);
}
ECHOION_LOG_DEBUG(
std::format("jsc result: {}", resultView));
try {
auto parsed = Void::Json::parse(resultStr);
if (parsed) {
const Void::Json::Value& output = *parsed;
const Void::Json::Value* pp =
output.find("preprocessed_player");
const Void::Json::Value* err = output.find("error");
if (pp && pp->is_string()) {
preprocessedPlayer_ = pp->as_string();
hasPlayerJs_ = true;
ECHOION_LOG_INFO(
"Player JS preprocessed successfully");
} else if (err && err->is_string()) {
ECHOION_LOG_ERROR(std::format(
"Solver error: {}", err->as_string()));
} else {
ECHOION_LOG_ERROR(std::format(
"Unexpected solver output: {}", resultStr));
}
} else {
ECHOION_LOG_ERROR(std::format(
"Failed to parse solver JSON output: {}",
resultStr));
}
} catch (const std::exception& e) {
ECHOION_LOG_ERROR(std::format(
"Failed to parse solver output: {}", e.what()));
}
JS_FreeCString(context_, resultStr);
} else {
ECHOION_LOG_ERROR("jsc returned non-convertible value");
}
}
} else {
JSValue error = JS_GetException(context_);
const char* errorStr = JS_ToCString(context_, error);
if (errorStr) {
ECHOION_LOG_ERROR(
std::format("QuickJS execution error: {}", errorStr));
} else {
// Try to get exception details differently
ECHOION_LOG_ERROR("QuickJS execution failed (exception value "
"not convertible to string)");
}
JS_FreeCString(context_, errorStr);
JS_FreeValue(context_, error);
}
return hasPlayerJs_;
}
bool SignatureCipher::isReady() const
{
std::lock_guard<std::mutex> lock(mutex_);
return initialized_ && solverInitialized_ && hasPlayerJs_;
}
bool SignatureCipher::isInitialized() const
{
std::lock_guard<std::mutex> lock(mutex_);
return initialized_;
}
std::string SignatureCipher::decipher(std::string_view signatureCipher)
{
if (!isReady() || signatureCipher.empty()) {
return std::string(signatureCipher);
}
// Parse the signature cipher parameters
// Format: s=ENCODED_SIG&sp=SIG_PARAM&url=ENCODED_URL
std::string url, signature, sigParam = "signature";
// Parse query string
auto parseQuery = [](std::string_view query) {
std::map<std::string, std::string> result;
std::regex re("([^&=]+)=([^&]*)");
std::string queryStr(query);
for (std::sregex_iterator it(queryStr.begin(), queryStr.end(), re),
end;
it != end;
++it) {
std::string key = (*it)[1].str();
std::string value = (*it)[2].str();
// URL decode
auto decodeUrl = [](std::string_view input) -> std::string {
std::string out;
for (size_t i = 0; i < input.size(); ++i) {
if (input[i] == '%' && i + 2 < input.size()) {
int hex =
std::stoi(std::string(input.substr(i + 1, 2)),
nullptr, 16);
out += static_cast<char>(hex);
i += 2;
} else if (input[i] == '+') {
out += ' ';
} else {
out += input[i];
}
}
return out;
};
result[key] = decodeUrl(value);
}
return result;
};
auto params = parseQuery(signatureCipher);
if (params.count("s")) {
signature = params["s"];
}
if (params.count("sp")) {
sigParam = params["sp"];
}
if (params.count("url")) {
url = params["url"];
}
if (signature.empty()) {
return std::string(signatureCipher);
}
// Solve the signature challenge
std::string deciphered = solveChallenge(signature, "sig");
if (deciphered.empty()) {
return std::string(signatureCipher);
}
// Build final URL
if (!url.empty()) {
url += "&" + sigParam + "=" + deciphered;
return url;
}
return deciphered;
}
std::string SignatureCipher::solveChallenge(const std::string& challenge,
const std::string& type)
{
std::lock_guard<std::mutex> lock(mutex_);
if (!solverInitialized_ || preprocessedPlayer_.empty()) {
return "";
}
if (!context_) {
return "";
}
// Create input for challenge solving
using Void::Json::Value;
Value input = Void::Json::object();
input.as_object().emplace_back("type", Value{"preprocessed"});
input.as_object().emplace_back("preprocessed_player",
Value{preprocessedPlayer_});
Value request = Void::Json::object();
request.as_object().emplace_back("type", Value{type});
Value challenges = Void::Json::array();
challenges.as_array().push_back(Value{challenge});
request.as_object().emplace_back("challenges", std::move(challenges));
Value requests = Void::Json::array();
requests.as_array().push_back(std::move(request));
input.as_object().emplace_back("requests", std::move(requests));
std::string inputStr = Void::Json::serialize(input);
// Get global object and jsc function
JSValue global = JS_GetGlobalObject(context_);
JSValue jsc = JS_GetPropertyStr(context_, global, "jsc");
if (JS_IsUndefined(jsc)) {
JS_FreeValue(context_, global);
return "";
}
// Parse input JSON
JSValue inputVal =
JS_ParseJSON(context_, inputStr.c_str(), inputStr.size(), "input");
if (JS_IsException(inputVal)) {
JS_FreeValue(context_, jsc);
JS_FreeValue(context_, global);
return "";
}
// Call jsc function
JSValue args[] = {inputVal};
JSValue result = JS_Call(context_, jsc, global, 1, args);
std::string output;
if (!JS_IsException(result)) {
const char* resultStr = JS_ToCString(context_, result);
if (resultStr) {
try {
auto parsed = Void::Json::parse(resultStr);
const Void::Json::Value* responses =
parsed ? parsed->find("responses") : nullptr;
if (responses && responses->is_array() &&
!responses->as_array().empty()) {
const Void::Json::Value& firstResponse =
responses->as_array()[0];
const Void::Json::Value* respType =
firstResponse.find("type");
const Void::Json::Value* data =
firstResponse.find("data");
if (respType && respType->is_string() &&
respType->as_string() == "result" && data &&
data->is_object()) {
const Void::Json::Value* dc = data->find(challenge);
if (dc && dc->is_string()) {
output = dc->as_string();
}
}
}
} catch (const std::exception& e) {
ECHOION_LOG_ERROR(std::format(
"Failed to parse challenge response: {}", e.what()));
}
JS_FreeCString(context_, resultStr);
}
} else {
JSValue error = JS_GetException(context_);
const char* errorStr = JS_ToCString(context_, error);
ECHOION_LOG_ERROR(std::format("Challenge solving error: {}",
errorStr ? errorStr : "unknown"));
JS_FreeCString(context_, errorStr);
JS_FreeValue(context_, error);
}
JS_FreeValue(context_, result);
JS_FreeValue(context_, inputVal);
JS_FreeValue(context_, jsc);
JS_FreeValue(context_, global);
return output;
}
std::string SignatureCipher::decipherNParam(std::string_view nParam)
{
if (!isReady() || nParam.empty()) {
return std::string(nParam);
}
return solveChallenge(std::string(nParam), "n");
}
void SignatureCipher::clear()
{
std::lock_guard<std::mutex> lock(mutex_);
cleanupQuickJS();
playerJsCode_.clear();
preprocessedPlayer_.clear();
initialized_ = false;
solverInitialized_ = false;
hasPlayerJs_ = false;
}
std::filesystem::path SignatureCipher::getCacheDir()
{
std::filesystem::path cacheDir;
// Use XDG_CACHE_HOME or fallback to ~/.cache
const char* xdgCache = std::getenv("XDG_CACHE_HOME");
if (xdgCache && *xdgCache) {
cacheDir = std::filesystem::path(xdgCache) / "echoion";
} else {
const char* home = std::getenv("HOME");
if (home && *home) {
cacheDir = std::filesystem::path(home) / ".cache" / "echoion";
} else {
// Fallback to current directory
cacheDir = std::filesystem::path(".echoion_cache");
}
}
std::error_code ec;
std::filesystem::create_directories(cacheDir, ec);
return cacheDir;
}
std::optional<std::string>
SignatureCipher::downloadSolverLibrary(std::string_view url)
{
// Simple curl-based download with redirect following
// -s: silent, -L: follow redirects, -f: fail on HTTP error, -m 30:
// timeout 30s
std::string cmd =
std::format("curl -sLf -m 30 '{}' 2>&1", std::string(url));
ECHOION_LOG_DEBUG(std::format("Downloading: {}", url));
FILE* pipe = popen(cmd.c_str(), "r");
if (!pipe) {
ECHOION_LOG_WARNING(std::format("Failed to run curl for {}", url));
return std::nullopt;
}
std::string result;
char buffer[4096];
while (fgets(buffer, sizeof(buffer), pipe) != nullptr) {
result += buffer;
}
int status = pclose(pipe);
if (status != 0) {
ECHOION_LOG_WARNING(
std::format("curl failed with status {} for {}", status, url));
return std::nullopt;
}
if (result.empty()) {
ECHOION_LOG_WARNING(
std::format("Downloaded empty file from {}", url));
return std::nullopt;
}
return result;
}
void SignatureCipher::initSolver()
{
if (runtime_ && context_) {
return; // Already initialized
}
// Create QuickJS runtime
runtime_ = JS_NewRuntime();
if (!runtime_) {
ECHOION_LOG_ERROR("Failed to create QuickJS runtime");
return;
}
// Set memory limit (256 MB - player JS processing needs more memory)
JS_SetMemoryLimit(runtime_, 256 * 1024 * 1024);
// Set max stack size (8 MB to handle deep AST recursion)
JS_SetMaxStackSize(runtime_, 8 * 1024 * 1024);
// Create context
context_ = JS_NewContext(runtime_);
if (!context_) {
ECHOION_LOG_ERROR("Failed to create QuickJS context");
JS_FreeRuntime(runtime_);
runtime_ = nullptr;
return;
}
// Get cache directory for storing solver libraries
auto cacheDir = getCacheDir();
auto corePath = cacheDir / "yt.solver.core.js";
auto libPath = cacheDir / "yt.solver.lib.js";
std::string coreCode;
std::string libCode;
// Try to load from cache first
std::error_code ec;
if (std::filesystem::exists(corePath, ec) &&
std::filesystem::exists(libPath, ec)) {
// Load from cache
std::ifstream coreFile(corePath);
std::ifstream libFile(libPath);
if (coreFile && libFile) {
coreCode =
std::string((std::istreambuf_iterator<char>(coreFile)),
std::istreambuf_iterator<char>());
libCode = std::string((std::istreambuf_iterator<char>(libFile)),
std::istreambuf_iterator<char>());
ECHOION_LOG_INFO(
std::format("Loaded solver libraries from cache (core: {} "
"bytes, lib: {} bytes)",
coreCode.size(), libCode.size()));
// Validate content
if (coreCode.empty() || libCode.empty()) {
ECHOION_LOG_WARNING("Cached solver files are empty");
coreCode.clear();
libCode.clear();
}
}
}
// Download if not in cache or empty
if (coreCode.empty() || libCode.empty()) {
ECHOION_LOG_INFO(
"Downloading solver libraries from GitHub releases...");
// Download core
auto coreOpt =
downloadSolverLibrary("https://github.com/yt-dlp/ejs/releases/"
"latest/download/yt.solver.core.js");
// Download lib
auto libOpt =
downloadSolverLibrary("https://github.com/yt-dlp/ejs/releases/"
"latest/download/yt.solver.lib.js");
if (coreOpt && libOpt && !coreOpt->empty() && !libOpt->empty()) {
coreCode = *coreOpt;
libCode = *libOpt;
ECHOION_LOG_DEBUG(
std::format("Downloaded core: {} bytes, lib: {} bytes",
coreCode.size(), libCode.size()));
// Log first 200 chars of core to verify it's valid
if (!coreCode.empty()) {
std::string_view preview(
coreCode.c_str(),
std::min(size_t(200), coreCode.size()));
ECHOION_LOG_DEBUG(std::format("Core preview: {}", preview));
}
// Validate downloaded content looks like JS
if (coreCode.find("function") == std::string::npos &&
coreCode.find("var") == std::string::npos) {
ECHOION_LOG_WARNING("Downloaded core.js doesn't look like "
"valid JavaScript");
coreCode.clear();
}
if (libCode.find("function") == std::string::npos &&
libCode.find("var") == std::string::npos) {
ECHOION_LOG_WARNING(
"Downloaded lib.js doesn't look like valid JavaScript");
libCode.clear();
}
// Save to cache
if (!coreCode.empty() && !libCode.empty()) {
std::ofstream coreOut(corePath);
std::ofstream libOut(libPath);
if (coreOut && libOut) {
coreOut << coreCode;
libOut << libCode;
coreOut.close();
libOut.close();
ECHOION_LOG_INFO(
"Solver libraries cached successfully");
}
}
} else {
ECHOION_LOG_WARNING("Failed to download solver libraries");
}
}
// Load libraries into QuickJS
// Order matters: lib.js creates 'lib' object, then bridge, then core.js
// uses meriyah/astring
bool coreLoaded = false;
bool libLoaded = false;
bool bridgeLoaded = false;
// Step 1: Load lib.js (contains meriyah and astring)
if (!libCode.empty()) {
JSValue libResult =
JS_Eval(context_, libCode.c_str(), libCode.size(), "lib.js",
JS_EVAL_TYPE_GLOBAL);
if (!JS_IsException(libResult)) {
libLoaded = true;
ECHOION_LOG_DEBUG("Solver lib.js loaded successfully");
} else {
JSValue error = JS_GetException(context_);
const char* errorStr = JS_ToCString(context_, error);
ECHOION_LOG_WARNING(
std::format("Failed to load lib solver: {}",
errorStr ? errorStr : "unknown"));
JS_FreeCString(context_, errorStr);
JS_FreeValue(context_, error);
}
JS_FreeValue(context_, libResult);
}
// Step 2: Create bridge to expose meriyah and astring as global
// variables
if (libLoaded) {
const char* bridge =
"var meriyah=lib.meriyah; var astring=lib.astring;";
JSValue bridgeResult = JS_Eval(context_, bridge, strlen(bridge),
"bridge", JS_EVAL_TYPE_GLOBAL);
if (!JS_IsException(bridgeResult)) {
bridgeLoaded = true;
ECHOION_LOG_DEBUG("Solver bridge created successfully");
} else {
JSValue error = JS_GetException(context_);
const char* errorStr = JS_ToCString(context_, error);
ECHOION_LOG_ERROR(std::format("Failed to load bridge: {}",
errorStr ? errorStr : "unknown"));
JS_FreeCString(context_, errorStr);
JS_FreeValue(context_, error);
}
JS_FreeValue(context_, bridgeResult);
}
// Step 3: Load core.js (uses meriyah and astring, creates jsc global
// function)
if (!coreCode.empty() && bridgeLoaded && libLoaded) {
JSValue coreResult =
JS_Eval(context_, coreCode.c_str(), coreCode.size(), "core.js",
JS_EVAL_TYPE_GLOBAL);
if (!JS_IsException(coreResult)) {
coreLoaded = true;
ECHOION_LOG_DEBUG("Solver core.js loaded successfully");
} else {
JSValue error = JS_GetException(context_);
const char* errorStr = JS_ToCString(context_, error);
ECHOION_LOG_ERROR(std::format("Failed to load core solver: {}",
errorStr ? errorStr : "unknown"));
JS_FreeCString(context_, errorStr);
JS_FreeValue(context_, error);
}
JS_FreeValue(context_, coreResult);
}
// If core failed to load, we can't solve cipher signatures
if (!coreLoaded) {
ECHOION_LOG_WARNING(
"Loading fallback solver stub - ciphered videos won't work");
JSValue fallbackResult = JS_Eval(
context_, FALLBACK_CORE_JS.data(), FALLBACK_CORE_JS.size(),
"fallback.js", JS_EVAL_TYPE_GLOBAL);
JS_FreeValue(context_, fallbackResult);
cleanupQuickJS();
return;
}
// Verify jsc function exists in global scope
JSValue global = JS_GetGlobalObject(context_);
JSValue jsc = JS_GetPropertyStr(context_, global, "jsc");
bool hasJsc = !JS_IsUndefined(jsc);
JS_FreeValue(context_, jsc);
JS_FreeValue(context_, global);
if (!hasJsc) {
ECHOION_LOG_ERROR("jsc function not found after loading solver - "
"ciphered videos won't work");
cleanupQuickJS();
return;
}
solverInitialized_ = true;
ECHOION_LOG_INFO(
"QuickJS solver initialized successfully (jsc function verified)");
}
std::optional<std::string>
SignatureCipher::executeJS(std::string_view code,
std::string_view filename)
{
if (!context_) {
return std::nullopt;
}
JSValue result = JS_Eval(context_, code.data(), code.size(),
filename.data(), JS_EVAL_TYPE_GLOBAL);
if (JS_IsException(result)) {
JSValue error = JS_GetException(context_);
const char* errorStr = JS_ToCString(context_, error);
ECHOION_LOG_ERROR(std::format("JS execution error: {}",
errorStr ? errorStr : "unknown"));
JS_FreeCString(context_, errorStr);
JS_FreeValue(context_, error);
JS_FreeValue(context_, result);
return std::nullopt;
}
std::string output;
const char* resultStr = JS_ToCString(context_, result);
if (resultStr) {
output = resultStr;
JS_FreeCString(context_, resultStr);
}
JS_FreeValue(context_, result);
return output;
}
void SignatureCipher::cleanupQuickJS()
{
if (context_) {
JS_FreeContext(context_);
context_ = nullptr;
}
if (runtime_) {
JS_FreeRuntime(runtime_);
runtime_ = nullptr;
}
solverInitialized_ = false;
}
} // namespace Echoion::Core