1 Commits
Author SHA1 Message Date
faumaray a6555d4c69 Enforce signed licenses and seamless track handoff
Independent component release / publish (push) Failing after 11s
2026-08-02 01:47:23 +03:00
15 changed files with 1367 additions and 98 deletions

No files matched your search

+40 -1
View File
@@ -7,6 +7,17 @@ if(NOT DEFINED ECHOION_COMPONENT_VERSION)
endif() endif()
project(EchoionCore VERSION "${ECHOION_COMPONENT_VERSION}" LANGUAGES CXX) project(EchoionCore VERSION "${ECHOION_COMPONENT_VERSION}" LANGUAGES CXX)
set(ECHOION_LICENSE_ROOT_KEY_ID "" CACHE STRING
"Pinned EchoionLicensing root key id")
set(ECHOION_LICENSE_ROOT_PUBLIC_KEY "" CACHE STRING
"Pinned base64url Ed25519 EchoionLicensing root public key")
set(ECHOION_PRODUCT_VERSION "${ECHOION_COMPONENT_VERSION}" CACHE STRING
"Echoion product version bound into licensing decisions")
set(ECHOION_BUILD_SIGNATURE "development:${ECHOION_COMPONENT_VERSION}" CACHE STRING
"Immutable signed-build identifier used by licensing revocation")
option(ECHOION_ALLOW_DEVELOPMENT_LICENSE_KEYS
"Allow opt-in trust keys from config (never enable for releases)" OFF)
if(PROJECT_IS_TOP_LEVEL) if(PROJECT_IS_TOP_LEVEL)
set(BUILD_SHARED_LIBS ON CACHE BOOL set(BUILD_SHARED_LIBS ON CACHE BOOL
"Build shared component dependencies" FORCE) "Build shared component dependencies" FORCE)
@@ -47,7 +58,15 @@ target_compile_definitions(EchoionCore PRIVATE
ECHOION_MODULE_BUILD ECHOION_MODULE_BUILD
ECHOION_COMPONENT_VERSION_MAJOR=${PROJECT_VERSION_MAJOR} ECHOION_COMPONENT_VERSION_MAJOR=${PROJECT_VERSION_MAJOR}
ECHOION_COMPONENT_VERSION_MINOR=${PROJECT_VERSION_MINOR} ECHOION_COMPONENT_VERSION_MINOR=${PROJECT_VERSION_MINOR}
ECHOION_COMPONENT_VERSION_PATCH=${PROJECT_VERSION_PATCH}) ECHOION_COMPONENT_VERSION_PATCH=${PROJECT_VERSION_PATCH}
ECHOION_LICENSE_ROOT_KEY_ID="${ECHOION_LICENSE_ROOT_KEY_ID}"
ECHOION_LICENSE_ROOT_PUBLIC_KEY="${ECHOION_LICENSE_ROOT_PUBLIC_KEY}"
ECHOION_PRODUCT_VERSION="${ECHOION_PRODUCT_VERSION}"
ECHOION_BUILD_SIGNATURE="${ECHOION_BUILD_SIGNATURE}")
if(ECHOION_ALLOW_DEVELOPMENT_LICENSE_KEYS)
target_compile_definitions(EchoionCore PRIVATE
ECHOION_ALLOW_DEVELOPMENT_LICENSE_KEYS)
endif()
add_library(Echoion::Core ALIAS EchoionCore) add_library(Echoion::Core ALIAS EchoionCore)
@@ -177,6 +196,9 @@ target_link_libraries(EchoionCore
Void::Service Void::Service
Void::ShortUrl Void::ShortUrl
Void::Plugin Void::Plugin
Void::Crypto
Void::Update
Void::Security
PRIVATE PRIVATE
Threads::Threads Threads::Threads
qjs qjs
@@ -291,6 +313,23 @@ if(BUILD_TESTS)
add_test(NAME echoion_core_config_loader_tests add_test(NAME echoion_core_config_loader_tests
COMMAND echoion_core_config_loader_tests) COMMAND echoion_core_config_loader_tests)
add_executable(echoion_core_gapless_handoff_tests
tests/test_gapless_handoff.cpp)
target_include_directories(echoion_core_gapless_handoff_tests PRIVATE
${CMAKE_CURRENT_SOURCE_DIR}/include)
target_compile_features(echoion_core_gapless_handoff_tests PRIVATE cxx_std_23)
add_test(NAME echoion_core_gapless_handoff_tests
COMMAND echoion_core_gapless_handoff_tests)
add_executable(echoion_core_license_verifier_tests
tests/test_license_verifier.cpp)
target_include_directories(echoion_core_license_verifier_tests PRIVATE
"${CMAKE_CURRENT_SOURCE_DIR}/include")
target_link_libraries(echoion_core_license_verifier_tests PRIVATE
EchoionCore OpenSSL::Crypto)
add_test(NAME echoion_core_license_verifier_tests
COMMAND echoion_core_license_verifier_tests)
add_executable(echoion_core_extension_state_tests add_executable(echoion_core_extension_state_tests
tests/test_extension_state.cpp) tests/test_extension_state.cpp)
target_include_directories(echoion_core_extension_state_tests PRIVATE target_include_directories(echoion_core_extension_state_tests PRIVATE
+4
View File
@@ -6,6 +6,7 @@
#include "MusicManager.hpp" #include "MusicManager.hpp"
#include "NetworkClient.hpp" #include "NetworkClient.hpp"
#include "RpcServer.hpp" #include "RpcServer.hpp"
#include "licensing/LicenseManager.hpp"
#ifdef ECHOION_WITH_WEB #ifdef ECHOION_WITH_WEB
#include "echoion/web/HttpServer.hpp" #include "echoion/web/HttpServer.hpp"
#endif #endif
@@ -192,9 +193,12 @@ namespace Echoion::Core
// Guard helper: ok if initialized, else a ServiceUnavailable error. // Guard helper: ok if initialized, else a ServiceUnavailable error.
[[nodiscard]] Api::Result<void> requireInitialized() const noexcept; [[nodiscard]] Api::Result<void> requireInitialized() const noexcept;
// Normal bot operations are denied while licensing is update-only.
[[nodiscard]] Api::Result<void> requireOperational() const noexcept;
// Components // Components
std::shared_ptr<NetworkClient> networkClient_; std::shared_ptr<NetworkClient> networkClient_;
std::unique_ptr<Licensing::LicenseManager> licenseManager_;
std::shared_ptr<LyricsService> lyricsService_; std::shared_ptr<LyricsService> lyricsService_;
std::shared_ptr<MusicManager> musicManager_; std::shared_ptr<MusicManager> musicManager_;
std::unique_ptr<CommandManager> commandManager_; std::unique_ptr<CommandManager> commandManager_;
+16 -10
View File
@@ -25,19 +25,25 @@ namespace Echoion::Core
NetworkClient(); NetworkClient();
~NetworkClient() override; ~NetworkClient() override;
Api::Result<void> initialize( Api::Result<void>
const std::optional<Void::Net::ProxyConfig>& proxy = initialize(const std::optional<Void::Net::ProxyConfig>& proxy =
std::nullopt) override; std::nullopt) override;
void shutdown() override; void shutdown() override;
// Synchronous requests // Synchronous requests
[[nodiscard]] Api::Result<Void::Net::Response> [[nodiscard]] Api::Result<Void::Net::Response> get(
get(std::string_view url, std::string_view url,
const std::vector<Void::Net::Header>& headers = {}) override; const std::vector<Void::Net::Header>& headers = {}) override;
[[nodiscard]] Api::Result<Void::Net::Response> [[nodiscard]] Api::Result<Void::Net::Response> post(
post(std::string_view url, std::string_view body, std::string_view url, std::string_view body,
const std::vector<Void::Net::Header>& headers = {}) const std::vector<Void::Net::Header>& headers = {}) override;
override; // Security-sensitive HTTPS request. Unlike legacy media scraping
// requests, this always verifies the peer certificate and follows
// no redirects so credentials cannot be forwarded to another
// origin.
[[nodiscard]] Api::Result<Void::Net::Response> postVerifiedTls(
std::string_view url, std::string_view body,
const std::vector<Void::Net::Header>& headers = {});
[[nodiscard]] Api::Result<Void::Net::Response> [[nodiscard]] Api::Result<Void::Net::Response>
request(const Void::Net::Request& req) override; request(const Void::Net::Request& req) override;
@@ -0,0 +1,64 @@
#pragma once
#include "echoion/core/NetworkClient.hpp"
#include "echoion/core/licensing/LicenseVerifier.hpp"
#include <ConfigTypes.hpp>
#include <atomic>
#include <cstdint>
#include <filesystem>
#include <mutex>
#include <string>
#include <thread>
namespace Echoion::Core::Licensing
{
class LicenseManager
{
public:
LicenseManager(Api::LicensingConfig config,
std::shared_ptr<NetworkClient>
network,
std::filesystem::path stateDirectory);
~LicenseManager();
LicenseManager(const LicenseManager&) = delete;
LicenseManager& operator=(const LicenseManager&) = delete;
/// Load a still-valid cached lease and then attempt an online
/// refresh. A failed refresh retains a valid cache; otherwise
/// operation remains update-only.
void initialize();
void shutdown();
void refreshNow();
[[nodiscard]] bool canOperate() const noexcept;
[[nodiscard]] LeaseStatus status() const;
[[nodiscard]] std::string deviceId() const;
private:
[[nodiscard]] Void::Result::Result<LeaseStatus>
verifyBundle(std::string_view bundle,
std::string_view expectedChallenge);
[[nodiscard]] std::string loadOrCreateDeviceId();
void installStatus(LeaseStatus status);
void installFailure(std::string reason,
bool retainValidLease = true);
void run(std::stop_token stopToken);
Api::LicensingConfig config_;
std::shared_ptr<NetworkClient> network_;
std::filesystem::path stateDirectory_;
Void::Update::Keyring rootKeys_;
std::string deviceId_;
std::atomic<bool> operational_{false};
std::atomic<std::int64_t> operationalUntilUnix_{0};
mutable std::mutex mutex_;
LeaseStatus status_;
std::jthread refreshThread_;
std::uint64_t minimumSequence_{0};
};
} // namespace Echoion::Core::Licensing
@@ -0,0 +1,60 @@
#pragma once
#include <Void/Functional/Result.hpp>
#include <Void/Update/Feed.hpp>
#include <chrono>
#include <cstdint>
#include <optional>
#include <string>
#include <string_view>
#include <vector>
namespace Echoion::Core::Licensing
{
enum class Mode { Active, UpdateOnly };
struct LeaseContext {
std::string productId;
std::string productVersion;
std::string deviceId;
std::string buildSignature;
std::string challenge;
std::chrono::system_clock::time_point now;
std::chrono::milliseconds maximumLeaseLifetime{
std::chrono::hours(24)};
std::uint64_t minimumSequence{0};
};
struct LeaseStatus {
Mode mode{Mode::UpdateOnly};
std::string reason;
std::string licenseId;
std::uint64_t sequence{0};
std::chrono::system_clock::time_point refreshAfter;
std::chrono::system_clock::time_point expiresAt;
std::vector<std::string> entitlements;
};
/// Decode a base64/base64url Ed25519 public key and add it to a keyring.
[[nodiscard]] Void::Result::Result<void>
addPublicKey(Void::Update::Keyring& keyring, std::string_view keyId,
std::string_view encodedKey);
/// Verify a root-signed keyset and append currently valid, non-revoked
/// lease signing keys. The pinned root itself remains in the returned
/// keyring so a direct emergency root-signed lease can still be accepted.
[[nodiscard]] Void::Result::Result<Void::Update::Keyring>
verifyKeyset(std::string_view envelopeJson,
const Void::Update::Keyring& rootKeys,
std::chrono::system_clock::time_point now);
/// Verify the signed lease and signed revocation snapshot as one decision.
/// Any malformed, expired, replayed, mismatched, or revoked input fails
/// closed into UpdateOnly through the returned error.
[[nodiscard]] Void::Result::Result<LeaseStatus>
verifyLease(std::string_view leaseEnvelopeJson,
std::string_view revocationEnvelopeJson,
const Void::Update::Keyring& leaseKeys,
const LeaseContext& context);
} // namespace Echoion::Core::Licensing
@@ -0,0 +1,18 @@
#pragma once
#include <cstddef>
namespace Echoion::Core::PlaybackDetail
{
/// A boundary can be emitted without padding when the outgoing tail and
/// already-decoded incoming PCM together fill one device frame.
[[nodiscard]] constexpr bool
canFillDeviceFrame(std::size_t outgoingSamples,
std::size_t incomingSamples,
std::size_t frameSamples) noexcept
{
return frameSamples > 0 && outgoingSamples > 0 &&
outgoingSamples < frameSamples &&
incomingSamples >= frameSamples - outgoingSamples;
}
} // namespace Echoion::Core::PlaybackDetail
+57
View File
@@ -38,6 +38,8 @@ namespace Echoion::Core
config.logging.maxFileSizeBytes, 64 * 1024, 1024ULL * 1024 * 1024); config.logging.maxFileSizeBytes, 64 * 1024, 1024ULL * 1024 * 1024);
config.logging.maxFiles = config.logging.maxFiles =
std::clamp<uint32_t>(config.logging.maxFiles, 1, 1000); std::clamp<uint32_t>(config.logging.maxFiles, 1, 1000);
config.logging.queueCapacity =
std::clamp<uint32_t>(config.logging.queueCapacity, 16, 1'000'000);
static constexpr std::array<std::string_view, 8> kLogLevels = { static constexpr std::array<std::string_view, 8> kLogLevels = {
"trace", "debug", "info", "warning", "trace", "debug", "info", "warning",
"warn", "error", "critical", "fatal"}; "warn", "error", "critical", "fatal"};
@@ -45,6 +47,61 @@ namespace Echoion::Core
kLogLevels.end()) { kLogLevels.end()) {
config.logging.level = "debug"; config.logging.level = "debug";
} }
static constexpr std::array<std::string_view, 3> kLogFormats = {
"pattern", "json", "logfmt"};
if (std::ranges::find(kLogFormats, config.logging.format) ==
kLogFormats.end()) {
config.logging.format = "pattern";
}
if (config.logging.pattern.empty() ||
config.logging.pattern.size() > 4096) {
config.logging.pattern =
"[{time}] [{level}] [{thread}] {file} - {message}";
}
static constexpr std::array<std::string_view, 3> kLogModes = {
"async", "immediate", "buffered"};
if (std::ranges::find(kLogModes, config.logging.mode) ==
kLogModes.end()) {
config.logging.mode = "async";
}
static constexpr std::array<std::string_view, 3> kOverflowPolicies = {
"block", "drop-newest", "drop-oldest"};
if (std::ranges::find(kOverflowPolicies,
config.logging.overflowPolicy) ==
kOverflowPolicies.end()) {
config.logging.overflowPolicy = "block";
}
config.licensing.refreshInterval =
std::clamp(config.licensing.refreshInterval,
std::chrono::duration_cast<std::chrono::milliseconds>(
std::chrono::minutes(15)),
std::chrono::duration_cast<std::chrono::milliseconds>(
std::chrono::hours(12)));
config.licensing.retryInterval =
std::clamp(config.licensing.retryInterval,
std::chrono::duration_cast<std::chrono::milliseconds>(
std::chrono::seconds(30)),
std::chrono::duration_cast<std::chrono::milliseconds>(
std::chrono::hours(1)));
config.licensing.maximumLeaseLifetime =
std::clamp(config.licensing.maximumLeaseLifetime,
std::chrono::duration_cast<std::chrono::milliseconds>(
std::chrono::hours(1)),
std::chrono::duration_cast<std::chrono::milliseconds>(
std::chrono::hours(24)));
if (config.licensing.productId.empty() ||
config.licensing.productId.size() > 128) {
config.licensing.productId = "echoion";
}
if (config.licensing.activationTokenEnv.empty() ||
config.licensing.activationTokenEnv.size() > 128) {
config.licensing.activationTokenEnv = "ECHOION_LICENSE_TOKEN";
}
if (!config.licensing.serviceUrl.empty() &&
!config.licensing.serviceUrl.starts_with("https://")) {
config.licensing.serviceUrl.clear();
}
// Keep partially specified updater sections usable. Security-sensitive // Keep partially specified updater sections usable. Security-sensitive
// URL/key validation happens in the host updater before the policy is // URL/key validation happens in the host updater before the policy is
+160 -32
View File
@@ -19,6 +19,7 @@
#include <Void/Log/LoggingAdapter.hpp> #include <Void/Log/LoggingAdapter.hpp>
#include <Void/Log/RotatingFileLogger.hpp> #include <Void/Log/RotatingFileLogger.hpp>
#include <Void/Log/Sinks.hpp> #include <Void/Log/Sinks.hpp>
#include <Void/Log/SplitFileLogger.hpp>
#include <Void/Text/Base64.hpp> #include <Void/Text/Base64.hpp>
#include <algorithm> #include <algorithm>
#include <cstdlib> #include <cstdlib>
@@ -92,34 +93,100 @@ namespace Echoion::Core
return "application/octet-stream"; return "application/octet-stream";
} }
// Build the configurable console + rolling-file logging stack. [[nodiscard]] Void::Logging::Mode logMode(std::string_view mode)
{
if (mode == "immediate") {
return Void::Logging::Mode::Immediate;
}
if (mode == "buffered") {
return Void::Logging::Mode::Buffered;
}
return Void::Logging::Mode::Async;
}
[[nodiscard]] Void::Logging::OverflowPolicy
logOverflowPolicy(std::string_view policy)
{
if (policy == "drop-newest") {
return Void::Logging::OverflowPolicy::DropNewest;
}
if (policy == "drop-oldest") {
return Void::Logging::OverflowPolicy::DropOldest;
}
return Void::Logging::OverflowPolicy::Block;
}
[[nodiscard]] std::shared_ptr<const Void::Logging::Formatter>
logFormatter(const Api::LoggingConfig& config)
{
namespace VL = Void::Logging;
if (config.format == "json") {
return std::make_shared<const VL::JsonLinesFormatter>();
}
if (config.format == "logfmt") {
return std::make_shared<const VL::LogfmtFormatter>();
}
return std::make_shared<const VL::PatternFormatter>(config.pattern);
}
// Build the configurable console + exact-level/combined logging stack.
[[nodiscard]] std::shared_ptr<Void::Logging::MultiLogger> [[nodiscard]] std::shared_ptr<Void::Logging::MultiLogger>
buildLogSink(const std::filesystem::path& logDirectory, buildLogSink(const std::filesystem::path& logDirectory,
const Api::LoggingConfig& config) const Api::LoggingConfig& config)
{ {
namespace VL = Void::Logging; namespace VL = Void::Logging;
auto multi = std::make_shared<VL::MultiLogger>(); auto multi = std::make_shared<VL::MultiLogger>();
auto formatter = std::make_shared<const VL::PatternFormatter>( const auto formatter = logFormatter(config);
"[{time}] [{level}] [{thread}] {file} - {message}"); const auto mode = logMode(config.mode);
const auto capacity =
static_cast<std::size_t>(config.queueCapacity);
const auto policy = logOverflowPolicy(config.overflowPolicy);
if (config.console) { if (config.console) {
auto console = std::make_shared<VL::ConsoleLogger>(std::cout); auto console = std::make_shared<VL::ConsoleLogger>(
std::cout, mode, capacity);
console->set_formatter(formatter); console->set_formatter(formatter);
multi->add(std::move(console)); multi->add(std::move(console));
} }
VL::RotatingFileOptions opts; if (config.splitByLevel) {
opts.max_bytes = static_cast<std::size_t>(config.maxFileSizeBytes); VL::SplitFileOptions options;
opts.max_files = config.maxFiles; options.combined = config.combined;
const auto logPath = logDirectory / config.fileName; options.max_bytes =
if (auto rotationError = static_cast<std::size_t>(config.maxFileSizeBytes);
rotateLogOnStartup(logPath, config.maxFiles)) { options.max_files = config.maxFiles;
std::cerr << "Echoion: cannot rotate startup log '" << logPath options.mode = mode;
<< "': " << rotationError.message() << '\n'; options.capacity = capacity;
} else if (auto fileSink = options.policy = policy;
VL::RotatingFileLogger::open(logPath, opts)) { if (auto sink =
(*fileSink)->set_formatter(formatter); VL::SplitFileLogger::open(logDirectory, options)) {
multi->add(std::shared_ptr<VL::Logger>(std::move(*fileSink))); (*sink)->set_formatter(formatter);
multi->add(std::shared_ptr<VL::Logger>(std::move(*sink)));
} else {
std::cerr << "Echoion: cannot open split log directory '"
<< logDirectory << "': " << sink.error().message()
<< '\n';
}
} else {
VL::RotatingFileOptions options;
options.max_bytes =
static_cast<std::size_t>(config.maxFileSizeBytes);
options.max_files = config.maxFiles;
options.mode = mode;
options.capacity = capacity;
options.policy = policy;
const auto logPath = logDirectory / config.fileName;
if (auto rotationError =
rotateLogOnStartup(logPath, config.maxFiles)) {
std::cerr << "Echoion: cannot rotate startup log '"
<< logPath << "': " << rotationError.message()
<< '\n';
} else if (auto fileSink =
VL::RotatingFileLogger::open(logPath, options)) {
(*fileSink)->set_formatter(formatter);
multi->add(
std::shared_ptr<VL::Logger>(std::move(*fileSink)));
}
} }
return multi; return multi;
} }
@@ -178,6 +245,19 @@ namespace Echoion::Core
return {}; return {};
} }
Api::Result<void> Core::requireOperational() const noexcept
{
if (auto initialized = requireInitialized(); !initialized) {
return initialized;
}
if (licenseManager_ && !licenseManager_->canOperate()) {
return Api::fail(Api::ErrorCode::PermissionDenied,
"Echoion is in update-only mode: " +
licenseManager_->status().reason);
}
return {};
}
Core::~Core() Core::~Core()
{ {
if (initialized_) { if (initialized_) {
@@ -254,6 +334,18 @@ namespace Echoion::Core
return std::unexpected(netResult.error()); return std::unexpected(netResult.error());
} }
licenseManager_ = std::make_unique<Licensing::LicenseManager>(
config_.licensing, networkClient_, stateDir);
licenseManager_->initialize();
if (!licenseManager_->canOperate()) {
Void::Log::warn(
"Core", "{}",
std::format(
"Licensing denied normal operation: {}. The process "
"remains available only for licensing and updates.",
licenseManager_->status().reason));
}
// Lyrics provider (lrclib) — shares the proxy-aware network client. // Lyrics provider (lrclib) — shares the proxy-aware network client.
lyricsService_ = std::make_shared<LyricsService>(networkClient_); lyricsService_ = std::make_shared<LyricsService>(networkClient_);
@@ -355,7 +447,8 @@ namespace Echoion::Core
static int callCount = 0; static int callCount = 0;
static auto lastLog = std::chrono::steady_clock::now(); static auto lastLog = std::chrono::steady_clock::now();
if (pluginInterface_ && !data.empty()) { if (pluginInterface_ && !data.empty() &&
(!licenseManager_ || licenseManager_->canOperate())) {
// Send int16 data directly to plugin (no conversion needed) // Send int16 data directly to plugin (no conversion needed)
auto result = pluginInterface_->sendAudioData(data); auto result = pluginInterface_->sendAudioData(data);
@@ -583,6 +676,23 @@ namespace Echoion::Core
} }
dashboard.as_object().emplace_back("playback", dashboard.as_object().emplace_back("playback",
std::move(playback)); std::move(playback));
if (licenseManager_) {
const auto status = licenseManager_->status();
const auto expiresAt =
status.expiresAt.time_since_epoch().count() == 0
? 0LL
: std::chrono::duration_cast<std::chrono::seconds>(
status.expiresAt.time_since_epoch())
.count();
dashboard.as_object().emplace_back(
"licensing",
Void::Json::object(
{{"mode", Value{licenseManager_->canOperate()
? "active"
: "update-only"}},
{"reason", Value{status.reason}},
{"expiresAt", Value{expiresAt}}}));
}
std::string body = Void::Json::serialize(dashboard); std::string body = Void::Json::serialize(dashboard);
return Web::HttpServer::DashboardSnapshot{ return Web::HttpServer::DashboardSnapshot{
.body = body, .body = body,
@@ -774,6 +884,11 @@ namespace Echoion::Core
musicManager_->shutdown(); musicManager_->shutdown();
} }
if (licenseManager_) {
licenseManager_->shutdown();
licenseManager_.reset();
}
#ifdef ECHOION_WITH_WEB #ifdef ECHOION_WITH_WEB
// Providers and the RPC bridge capture Core services, so drain all HTTP // Providers and the RPC bridge capture Core services, so drain all HTTP
// workers before destroying any of those dependencies. // workers before destroying any of those dependencies.
@@ -820,7 +935,7 @@ namespace Echoion::Core
Api::Result<void> Core::playTrack(const Api::TrackInfo& track) Api::Result<void> Core::playTrack(const Api::TrackInfo& track)
{ {
if (auto r = requireInitialized(); !r) { if (auto r = requireOperational(); !r) {
return std::unexpected(r.error()); return std::unexpected(r.error());
} }
@@ -852,7 +967,7 @@ namespace Echoion::Core
Api::Result<void> Core::play(const std::string& trackId) Api::Result<void> Core::play(const std::string& trackId)
{ {
if (auto r = requireInitialized(); !r) { if (auto r = requireOperational(); !r) {
return std::unexpected(r.error()); return std::unexpected(r.error());
} }
@@ -867,7 +982,7 @@ namespace Echoion::Core
Api::Result<void> Core::pause() Api::Result<void> Core::pause()
{ {
if (auto r = requireInitialized(); !r) { if (auto r = requireOperational(); !r) {
return std::unexpected(r.error()); return std::unexpected(r.error());
} }
@@ -883,7 +998,7 @@ namespace Echoion::Core
Api::Result<void> Core::resume() Api::Result<void> Core::resume()
{ {
if (auto r = requireInitialized(); !r) { if (auto r = requireOperational(); !r) {
return std::unexpected(r.error()); return std::unexpected(r.error());
} }
@@ -899,7 +1014,7 @@ namespace Echoion::Core
Api::Result<void> Core::stop() Api::Result<void> Core::stop()
{ {
if (auto r = requireInitialized(); !r) { if (auto r = requireOperational(); !r) {
return std::unexpected(r.error()); return std::unexpected(r.error());
} }
@@ -915,7 +1030,7 @@ namespace Echoion::Core
Api::Result<void> Core::skip(uint32_t count) Api::Result<void> Core::skip(uint32_t count)
{ {
if (auto r = requireInitialized(); !r) { if (auto r = requireOperational(); !r) {
return std::unexpected(r.error()); return std::unexpected(r.error());
} }
@@ -931,7 +1046,7 @@ namespace Echoion::Core
Api::Result<void> Core::seek(std::chrono::milliseconds position) Api::Result<void> Core::seek(std::chrono::milliseconds position)
{ {
if (auto r = requireInitialized(); !r) { if (auto r = requireOperational(); !r) {
return std::unexpected(r.error()); return std::unexpected(r.error());
} }
@@ -940,7 +1055,7 @@ namespace Echoion::Core
Api::Result<void> Core::setVolume(float volume) Api::Result<void> Core::setVolume(float volume)
{ {
if (auto r = requireInitialized(); !r) { if (auto r = requireOperational(); !r) {
return std::unexpected(r.error()); return std::unexpected(r.error());
} }
@@ -950,7 +1065,7 @@ namespace Echoion::Core
Api::Result<uint64_t> Core::queueTrackFull(const Api::TrackInfo& track, Api::Result<uint64_t> Core::queueTrackFull(const Api::TrackInfo& track,
uint64_t clientId) uint64_t clientId)
{ {
if (auto r = requireInitialized(); !r) { if (auto r = requireOperational(); !r) {
return std::unexpected(r.error()); return std::unexpected(r.error());
} }
@@ -971,7 +1086,7 @@ namespace Echoion::Core
Api::Result<uint64_t> Core::queueTrack(const std::string& trackId, Api::Result<uint64_t> Core::queueTrack(const std::string& trackId,
uint64_t clientId) uint64_t clientId)
{ {
if (auto r = requireInitialized(); !r) { if (auto r = requireOperational(); !r) {
return std::unexpected(r.error()); return std::unexpected(r.error());
} }
@@ -990,7 +1105,7 @@ namespace Echoion::Core
Api::Result<void> Core::removeFromQueue(uint64_t queueId) Api::Result<void> Core::removeFromQueue(uint64_t queueId)
{ {
if (auto r = requireInitialized(); !r) { if (auto r = requireOperational(); !r) {
return std::unexpected(r.error()); return std::unexpected(r.error());
} }
@@ -1011,7 +1126,7 @@ namespace Echoion::Core
Api::Result<void> Core::clearQueue() Api::Result<void> Core::clearQueue()
{ {
if (auto r = requireInitialized(); !r) { if (auto r = requireOperational(); !r) {
return std::unexpected(r.error()); return std::unexpected(r.error());
} }
@@ -1036,7 +1151,7 @@ namespace Echoion::Core
Api::Result<void> Core::moveInQueue(uint64_t queueId, uint32_t newPosition) Api::Result<void> Core::moveInQueue(uint64_t queueId, uint32_t newPosition)
{ {
if (auto r = requireInitialized(); !r) { if (auto r = requireOperational(); !r) {
return std::unexpected(r.error()); return std::unexpected(r.error());
} }
@@ -1138,7 +1253,7 @@ namespace Echoion::Core
Api::Result<void> Core::loadPlaylist(const std::string& playlistId, Api::Result<void> Core::loadPlaylist(const std::string& playlistId,
uint64_t clientId) uint64_t clientId)
{ {
if (auto r = requireInitialized(); !r) { if (auto r = requireOperational(); !r) {
return std::unexpected(r.error()); return std::unexpected(r.error());
} }
@@ -1236,6 +1351,7 @@ namespace Echoion::Core
// Publish the candidate only after provider and live web validation. // Publish the candidate only after provider and live web validation.
config_ = std::move(candidate); config_ = std::move(candidate);
installLogging(stateDirectory(configPath_) / "logs", config_.logging);
if (commandManager_) { if (commandManager_) {
commandManager_->setPrefix(config_.bot.commandPrefix); commandManager_->setPrefix(config_.bot.commandPrefix);
commandManager_->setServerConfig(config_); commandManager_->setServerConfig(config_);
@@ -1763,6 +1879,10 @@ namespace Echoion::Core
return Api::fail(Api::ErrorCode::ServiceUnavailable, return Api::fail(Api::ErrorCode::ServiceUnavailable,
"Core not initialized"); "Core not initialized");
} }
if (licenseManager_ && !licenseManager_->canOperate()) {
return Api::fail(Api::ErrorCode::PermissionDenied,
"Echoion is in update-only mode");
}
if (extensionPlugins_) { if (extensionPlugins_) {
extensionPlugins_->dispatch(event); extensionPlugins_->dispatch(event);
} }
@@ -1911,7 +2031,8 @@ namespace Echoion::Core
// Subscribers can only be resolved to online clients once the plugin // Subscribers can only be resolved to online clients once the plugin
// interface is set, so this is the earliest point a restored session // interface is set, so this is the earliest point a restored session
// (queue / radio) can actually begin playing after a load or reload. // (queue / radio) can actually begin playing after a load or reload.
if (musicManager_) { if (musicManager_ &&
(!licenseManager_ || licenseManager_->canOperate())) {
// Now that we have the plugin interface, update the whisper list // Now that we have the plugin interface, update the whisper list
// This is needed because subscriptions may have been loaded from // This is needed because subscriptions may have been loaded from
// database before the plugin interface was available // database before the plugin interface was available
@@ -1935,6 +2056,13 @@ namespace Echoion::Core
return; return;
} }
if (licenseManager_ && !licenseManager_->canOperate()) {
Void::Log::warn(
"Core", "{}",
"Auto-connect denied while licensing is update-only");
return;
}
if (config_.teamspeak.address.empty()) { if (config_.teamspeak.address.empty()) {
Void::Log::info( Void::Log::info(
"Core", "{}", "Core", "{}",
+46 -7
View File
@@ -1,6 +1,6 @@
#include <Void/Log/Log.hpp>
#include "echoion/core/NetworkClient.hpp" #include "echoion/core/NetworkClient.hpp"
#include <Void/Functional/Retry.hpp> #include <Void/Functional/Retry.hpp>
#include <Void/Log/Log.hpp>
#include <Void/Net/Http.hpp> #include <Void/Net/Http.hpp>
#include <algorithm> #include <algorithm>
#include <format> #include <format>
@@ -18,8 +18,10 @@ namespace Echoion::Core
proxy_ = proxy; proxy_ = proxy;
} }
initialized_ = true; initialized_ = true;
Void::Log::info("NetworkClient", "{}", std::format("NetworkClient initialized (proxy: {})", Void::Log::info(
proxy.has_value() ? "enabled" : "disabled")); "NetworkClient", "{}",
std::format("NetworkClient initialized (proxy: {})",
proxy.has_value() ? "enabled" : "disabled"));
return {}; return {};
} }
@@ -32,7 +34,8 @@ namespace Echoion::Core
// Snapshot the proxy under the lock. setProxy()/initialize() can run on // Snapshot the proxy under the lock. setProxy()/initialize() can run on
// other threads (config reload, init), and a torn read of the // other threads (config reload, init), and a torn read of the
// optional<ProxyConfig> (it holds std::string host/user/pass) could // optional<ProxyConfig> (it holds std::string host/user/pass) could
// yield an empty host -> enabled()==false -> a silent direct connection. // yield an empty host -> enabled()==false -> a silent direct
// connection.
std::optional<Void::Net::ProxyConfig> active; std::optional<Void::Net::ProxyConfig> active;
{ {
std::lock_guard<std::mutex> lock(mutex_); std::lock_guard<std::mutex> lock(mutex_);
@@ -57,15 +60,17 @@ namespace Echoion::Core
retryPolicy_, [&] { return executeRequest(req); }, retryPolicy_, [&] { return executeRequest(req); },
[this](const Api::Result<Void::Net::Response>& result) { [this](const Api::Result<Void::Net::Response>& result) {
if (!result) { if (!result) {
Void::Log::warn("NetworkClient", "{}", std::format( Void::Log::warn("NetworkClient", "{}",
"Request error: {}, retrying", result.error().message)); std::format("Request error: {}, retrying",
result.error().message));
return true; return true;
} }
// Retry only on the configured retryable HTTP statuses. // Retry only on the configured retryable HTTP statuses.
const auto& codes = retryableStatusCodes_; const auto& codes = retryableStatusCodes_;
if (std::find(codes.begin(), codes.end(), result->status) != if (std::find(codes.begin(), codes.end(), result->status) !=
codes.end()) { codes.end()) {
Void::Log::warn("NetworkClient", "{}", Void::Log::warn(
"NetworkClient", "{}",
std::format("Request failed with status {}, retrying", std::format("Request failed with status {}, retrying",
result->status)); result->status));
return true; return true;
@@ -122,6 +127,40 @@ namespace Echoion::Core
return request(req); return request(req);
} }
Api::Result<Void::Net::Response> NetworkClient::postVerifiedTls(
std::string_view url, std::string_view body,
const std::vector<Void::Net::Header>& headers)
{
if (!url.starts_with("https://")) {
return Api::fail(Api::ErrorCode::InvalidArgument,
"Verified request requires an HTTPS URL");
}
std::optional<Void::Net::ProxyConfig> active;
{
std::lock_guard<std::mutex> lock(mutex_);
active = proxy_;
}
Void::Net::HttpClient client;
client.set_verify_tls(true);
client.set_max_redirects(0);
client.set_max_body_size(1024 * 1024);
if (active && active->enabled()) {
client.set_proxy(*active);
}
Void::Net::Request request;
request.url = std::string{url};
request.method = Void::Net::Method::Post;
request.headers = headers;
request.body = std::string{body};
request.timeout = std::chrono::seconds{15};
auto result = client.send(request);
if (!result) {
return Api::fail(Api::ErrorCode::NetworkError,
result.error().message());
}
return std::move(*result);
}
void NetworkClient::setProxy( void NetworkClient::setProxy(
const std::optional<Void::Net::ProxyConfig>& proxy) const std::optional<Void::Net::ProxyConfig>& proxy)
{ {
+361
View File
@@ -0,0 +1,361 @@
#include "echoion/core/licensing/LicenseManager.hpp"
#include <Void/Data/Json.hpp>
#include <Void/Log/Log.hpp>
#include <Void/Security/Security.hpp>
#include <algorithm>
#include <cstdlib>
#include <format>
#include <fstream>
#include <limits>
#include <optional>
#include <thread>
#ifndef ECHOION_LICENSE_ROOT_KEY_ID
#define ECHOION_LICENSE_ROOT_KEY_ID ""
#endif
#ifndef ECHOION_LICENSE_ROOT_PUBLIC_KEY
#define ECHOION_LICENSE_ROOT_PUBLIC_KEY ""
#endif
#ifndef ECHOION_BUILD_SIGNATURE
#define ECHOION_BUILD_SIGNATURE "development"
#endif
#ifndef ECHOION_PRODUCT_VERSION
#define ECHOION_PRODUCT_VERSION "0.0.0"
#endif
namespace Echoion::Core::Licensing
{
namespace
{
[[nodiscard]] std::optional<std::string>
readFile(const std::filesystem::path& path)
{
std::ifstream input(path, std::ios::binary);
if (!input) {
return std::nullopt;
}
return std::string{std::istreambuf_iterator<char>{input},
std::istreambuf_iterator<char>{}};
}
[[nodiscard]] bool writePrivateFile(const std::filesystem::path& path,
std::string_view contents)
{
std::error_code error;
std::filesystem::create_directories(path.parent_path(), error);
if (error) {
return false;
}
const auto temporary = path.string() + ".tmp";
{
std::ofstream output(temporary,
std::ios::binary | std::ios::trunc);
if (!output) {
return false;
}
output.write(contents.data(),
static_cast<std::streamsize>(contents.size()));
output.flush();
if (!output) {
return false;
}
}
std::filesystem::permissions(
temporary,
std::filesystem::perms::owner_read |
std::filesystem::perms::owner_write,
std::filesystem::perm_options::replace, error);
if (error) {
std::filesystem::remove(temporary, error);
return false;
}
std::filesystem::rename(temporary, path, error);
return !error;
}
[[nodiscard]] std::string endpoint(std::string url)
{
while (url.ends_with('/')) {
url.pop_back();
}
return url + "/api/v1/licenses/refresh";
}
[[nodiscard]] bool isAuthoritativeDenial(long status) noexcept
{
return status == 401 || status == 402 || status == 403 ||
status == 410 || status == 423 || status == 451;
}
} // namespace
LicenseManager::LicenseManager(Api::LicensingConfig config,
std::shared_ptr<NetworkClient>
network,
std::filesystem::path stateDirectory)
: config_(std::move(config)), network_(std::move(network)),
stateDirectory_(std::move(stateDirectory))
{
}
LicenseManager::~LicenseManager() { shutdown(); }
void LicenseManager::initialize()
{
if (!config_.required) {
installStatus(LeaseStatus{.mode = Mode::Active,
.reason = "licensing-not-required"});
return;
}
deviceId_ = loadOrCreateDeviceId();
if (deviceId_.empty()) {
installFailure("cannot create protected device identity");
return;
}
if (std::string_view{ECHOION_LICENSE_ROOT_KEY_ID}.empty() ||
std::string_view{ECHOION_LICENSE_ROOT_PUBLIC_KEY}.empty()) {
installFailure("release has no pinned licensing root key");
} else if (auto added =
addPublicKey(rootKeys_, ECHOION_LICENSE_ROOT_KEY_ID,
ECHOION_LICENSE_ROOT_PUBLIC_KEY);
!added) {
installFailure(added.error().message());
}
#ifdef ECHOION_ALLOW_DEVELOPMENT_LICENSE_KEYS
if (config_.developmentMode) {
for (const auto& key : config_.developmentKeys) {
if (auto added = addPublicKey(rootKeys_, key.id, key.ed25519);
!added) {
Void::Log::warn("Licensing", "{}", added.error().message());
}
}
}
#endif
if (rootKeys_.empty()) {
return;
}
const auto cachedPath =
stateDirectory_ / "licensing" / "lease-bundle.json";
if (auto cached = readFile(cachedPath)) {
auto parsed = Void::Json::parse(*cached);
const auto cachedChallenge = parsed && parsed->is_object()
? parsed->get_str("challenge")
: std::string{};
if (auto verified = verifyBundle(*cached, cachedChallenge);
verified) {
installStatus(std::move(*verified));
} else {
installFailure("cached lease rejected: " +
verified.error().message());
}
}
refreshNow();
refreshThread_ =
std::jthread([this](std::stop_token stopToken) { run(stopToken); });
}
void LicenseManager::shutdown()
{
if (refreshThread_.joinable()) {
refreshThread_.request_stop();
refreshThread_.join();
}
}
void LicenseManager::refreshNow()
{
if (!config_.required || rootKeys_.empty() || network_ == nullptr ||
config_.serviceUrl.empty()) {
return;
}
auto challenge = Void::Security::random_token();
if (!challenge) {
installFailure(challenge.error().message());
return;
}
const char* token = std::getenv(config_.activationTokenEnv.c_str());
if (token == nullptr || std::string_view{token}.empty()) {
installFailure("activation token environment variable is missing");
return;
}
const auto request = Void::Json::object(
{{"schemaVersion", 1},
{"productId", config_.productId},
{"productVersion", ECHOION_PRODUCT_VERSION},
{"deviceId", deviceId_},
{"buildSignature", ECHOION_BUILD_SIGNATURE},
{"challenge", *challenge},
{"minimumSequence", static_cast<double>(minimumSequence_)}});
const auto body = Void::Json::serialize(request);
const std::vector<Void::Net::Header> headers = {
{"Content-Type", "application/json"},
{"Accept", "application/json"},
{"Authorization", std::string{"Bearer "} + token}};
auto response = network_->postVerifiedTls(endpoint(config_.serviceUrl),
body, headers);
if (!response || !response->ok()) {
const auto reason =
response ? std::format("license server returned HTTP {}",
response->status)
: "license server request failed";
const bool authoritative =
response && isAuthoritativeDenial(response->status);
if (authoritative) {
std::error_code ignored;
std::filesystem::remove(stateDirectory_ / "licensing" /
"lease-bundle.json",
ignored);
}
installFailure(reason, !authoritative);
return;
}
auto verified = verifyBundle(response->body, *challenge);
if (!verified) {
installFailure(verified.error().message());
return;
}
if (!writePrivateFile(stateDirectory_ / "licensing" /
"lease-bundle.json",
response->body)) {
Void::Log::warn("Licensing", "{}",
"could not persist refreshed license bundle");
}
installStatus(std::move(*verified));
}
bool LicenseManager::canOperate() const noexcept
{
if (!operational_.load(std::memory_order_acquire)) {
return false;
}
const auto until =
operationalUntilUnix_.load(std::memory_order_acquire);
const auto now =
std::chrono::duration_cast<std::chrono::seconds>(
std::chrono::system_clock::now().time_since_epoch())
.count();
return now <= until;
}
LeaseStatus LicenseManager::status() const
{
std::lock_guard lock(mutex_);
return status_;
}
std::string LicenseManager::deviceId() const
{
std::lock_guard lock(mutex_);
return deviceId_;
}
Void::Result::Result<LeaseStatus>
LicenseManager::verifyBundle(std::string_view bundle,
std::string_view expectedChallenge)
{
auto root = Void::Json::parse(bundle);
if (!root || !root->is_object() ||
root->get_num("schemaVersion") != 1 ||
root->get_str("challenge") != expectedChallenge) {
return Void::Result::fail("Licensing: invalid response binding");
}
const auto* keysetValue = root->find("keyset");
const auto* leaseValue = root->find("lease");
const auto* revocationsValue = root->find("revocations");
if (keysetValue == nullptr || leaseValue == nullptr ||
revocationsValue == nullptr || !keysetValue->is_object() ||
!leaseValue->is_object() || !revocationsValue->is_object()) {
return Void::Result::fail("Licensing: incomplete server response");
}
const auto now = std::chrono::system_clock::now();
auto keys =
verifyKeyset(Void::Json::serialize(*keysetValue), rootKeys_, now);
if (!keys) {
return std::unexpected{keys.error()};
}
return verifyLease(
Void::Json::serialize(*leaseValue),
Void::Json::serialize(*revocationsValue), *keys,
LeaseContext{.productId = config_.productId,
.productVersion = ECHOION_PRODUCT_VERSION,
.deviceId = deviceId_,
.buildSignature = ECHOION_BUILD_SIGNATURE,
.challenge = std::string{expectedChallenge},
.now = now,
.maximumLeaseLifetime = config_.maximumLeaseLifetime,
.minimumSequence = minimumSequence_});
}
std::string LicenseManager::loadOrCreateDeviceId()
{
const auto path = stateDirectory_ / "licensing" / "device.id";
if (auto existing = readFile(path);
existing && !existing->empty() && existing->size() <= 128) {
return *existing;
}
auto created = Void::Security::random_token();
if (!created || !writePrivateFile(path, *created)) {
return {};
}
return *created;
}
void LicenseManager::installStatus(LeaseStatus status)
{
const bool active = status.mode == Mode::Active;
std::int64_t operationalUntil = 0;
if (active) {
operationalUntil =
!config_.required
? std::numeric_limits<std::int64_t>::max()
: std::chrono::duration_cast<std::chrono::seconds>(
status.expiresAt.time_since_epoch())
.count();
}
{
std::lock_guard lock(mutex_);
minimumSequence_ = std::max(minimumSequence_, status.sequence);
status_ = std::move(status);
}
operationalUntilUnix_.store(operationalUntil,
std::memory_order_release);
operational_.store(active, std::memory_order_release);
Void::Log::info("Licensing", "{}",
active ? "license active" : "update-only mode");
}
void LicenseManager::installFailure(std::string reason,
bool retainValidLease)
{
const auto current = status();
if (retainValidLease && current.mode == Mode::Active &&
current.expiresAt > std::chrono::system_clock::now()) {
Void::Log::warn("Licensing", "{}", std::move(reason));
return;
}
installStatus(
LeaseStatus{.mode = Mode::UpdateOnly, .reason = std::move(reason)});
}
void LicenseManager::run(std::stop_token stopToken)
{
while (!stopToken.stop_requested()) {
const auto delay =
canOperate() ? config_.refreshInterval : config_.retryInterval;
for (auto waited = std::chrono::milliseconds{0};
waited < delay && !stopToken.stop_requested();
waited += std::chrono::seconds{1}) {
std::this_thread::sleep_for(
std::min(std::chrono::milliseconds{1000}, delay - waited));
}
if (!stopToken.stop_requested()) {
refreshNow();
}
}
}
} // namespace Echoion::Core::Licensing
+277
View File
@@ -0,0 +1,277 @@
#include "echoion/core/licensing/LicenseVerifier.hpp"
#include <Void/Data/Json.hpp>
#include <Void/Text/Base64.hpp>
#include <algorithm>
#include <array>
#include <cctype>
#include <cmath>
#include <cstring>
#include <limits>
#include <ranges>
namespace Echoion::Core::Licensing
{
namespace
{
using Clock = std::chrono::system_clock;
using Result = Void::Result::Result<void>;
[[nodiscard]] bool validKeyId(std::string_view value)
{
return !value.empty() && value.size() <= 128 &&
std::ranges::all_of(value, [](unsigned char character) {
return std::isalnum(character) != 0 ||
character == '.' || character == '_' ||
character == '-';
});
}
[[nodiscard]] Void::Result::Result<Void::Json::Value>
parseObject(std::string_view json, std::string_view name)
{
auto parsed = Void::Json::parse(json);
if (!parsed || !parsed->is_object()) {
return Void::Result::fail(std::string{name} +
" payload is not a JSON object");
}
return std::move(*parsed);
}
[[nodiscard]] Void::Result::Result<std::string>
requiredString(const Void::Json::Value& value, std::string_view key,
std::size_t maximum = 512)
{
const auto* field = value.find(key);
if (field == nullptr || !field->is_string() ||
field->as_string().empty() ||
field->as_string().size() > maximum) {
return Void::Result::fail("Licensing: invalid field " +
std::string{key});
}
return field->as_string();
}
[[nodiscard]] Void::Result::Result<std::uint64_t>
requiredUnsigned(const Void::Json::Value& value,
std::string_view key)
{
const auto* field = value.find(key);
if (field == nullptr || !field->is_number()) {
return Void::Result::fail("Licensing: invalid field " +
std::string{key});
}
const double number = field->as_number();
if (!std::isfinite(number) || number < 0.0 ||
std::trunc(number) != number ||
number > static_cast<double>(
std::numeric_limits<std::uint64_t>::max())) {
return Void::Result::fail("Licensing: invalid field " +
std::string{key});
}
return static_cast<std::uint64_t>(number);
}
[[nodiscard]] Clock::time_point unixTime(std::uint64_t seconds)
{
return Clock::time_point{std::chrono::seconds{seconds}};
}
[[nodiscard]] bool stringArrayContains(const Void::Json::Value& object,
std::string_view key,
std::string_view needle)
{
const auto* value = object.find(key);
if (value == nullptr || !value->is_array()) {
return false;
}
return std::ranges::any_of(
value->as_array(), [&](const auto& item) {
return item.is_string() && item.as_string() == needle;
});
}
[[nodiscard]] std::vector<std::string>
stringArray(const Void::Json::Value& object, std::string_view key)
{
std::vector<std::string> output;
const auto* value = object.find(key);
if (value == nullptr || !value->is_array()) {
return output;
}
for (const auto& item : value->as_array()) {
if (item.is_string() && item.as_string().size() <= 256) {
output.push_back(item.as_string());
}
}
return output;
}
} // namespace
Void::Result::Result<void> addPublicKey(Void::Update::Keyring& keyring,
std::string_view keyId,
std::string_view encodedKey)
{
if (!validKeyId(keyId)) {
return Void::Result::fail("Licensing: invalid public key id");
}
auto decoded = Void::Encoding::Base64::decode_url(encodedKey);
if (!decoded) {
decoded = Void::Encoding::Base64::decode(encodedKey);
}
if (!decoded || decoded->size() != Void::Crypto::Ed25519PublicKeySize) {
return Void::Result::fail("Licensing: invalid Ed25519 public key");
}
Void::Update::Ed25519PublicKey key{};
std::memcpy(key.data(), decoded->data(), decoded->size());
keyring.insert_or_assign(std::string{keyId}, key);
return {};
}
Void::Result::Result<Void::Update::Keyring>
verifyKeyset(std::string_view envelopeJson,
const Void::Update::Keyring& rootKeys,
Clock::time_point now)
{
Void::Update::VerificationPolicy policy;
policy.now = now;
policy.maxEnvelopeBytes = 256 * 1024;
policy.maxPayloadBytes = 192 * 1024;
auto verified =
Void::Update::verifyEnvelope(envelopeJson, rootKeys, policy);
if (!verified) {
return std::unexpected{verified.error()};
}
auto document = parseObject(verified->signedPayload, "Keyset");
if (!document) {
return std::unexpected{document.error()};
}
if (auto name = requiredString(*document, "document");
!name || *name != "echoion-license-keyset") {
return Void::Result::fail("Licensing: wrong keyset document");
}
auto generatedAt = requiredUnsigned(*document, "generatedAt");
auto expiresAt = requiredUnsigned(*document, "expiresAt");
const auto* keys = document->find("keys");
if (!generatedAt || !expiresAt || keys == nullptr ||
!keys->is_array() || keys->as_array().size() > 64 ||
unixTime(*generatedAt) > now + std::chrono::minutes(5) ||
unixTime(*expiresAt) <= now) {
return Void::Result::fail("Licensing: invalid or expired keyset");
}
auto output = rootKeys;
for (const auto& item : keys->as_array()) {
if (!item.is_object() || item.get_bool("revoked", false)) {
continue;
}
auto id = requiredString(item, "id", 256);
auto key = requiredString(item, "ed25519", 256);
auto notBefore = requiredUnsigned(item, "notBefore");
auto notAfter = requiredUnsigned(item, "notAfter");
if (!id || !key || !notBefore || !notAfter ||
unixTime(*notBefore) > now || unixTime(*notAfter) <= now) {
continue;
}
if (auto added = addPublicKey(output, *id, *key); !added) {
return std::unexpected{added.error()};
}
}
return output;
}
Void::Result::Result<LeaseStatus>
verifyLease(std::string_view leaseEnvelopeJson,
std::string_view revocationEnvelopeJson,
const Void::Update::Keyring& leaseKeys,
const LeaseContext& context)
{
Void::Update::VerificationPolicy policy;
policy.now = context.now;
policy.maxEnvelopeBytes = 512 * 1024;
policy.maxPayloadBytes = 384 * 1024;
auto leaseEnvelope =
Void::Update::verifyEnvelope(leaseEnvelopeJson, leaseKeys, policy);
if (!leaseEnvelope) {
return std::unexpected{leaseEnvelope.error()};
}
auto revocationEnvelope = Void::Update::verifyEnvelope(
revocationEnvelopeJson, leaseKeys, policy);
if (!revocationEnvelope) {
return std::unexpected{revocationEnvelope.error()};
}
auto lease = parseObject(leaseEnvelope->signedPayload, "Lease");
auto revocations =
parseObject(revocationEnvelope->signedPayload, "Revocation");
if (!lease || !revocations) {
return Void::Result::fail("Licensing: malformed signed payload");
}
auto leaseDocument = requiredString(*lease, "document");
auto revocationDocument = requiredString(*revocations, "document");
auto licenseId = requiredString(*lease, "licenseId");
auto accountId = requiredString(*lease, "accountId");
auto deviceId = requiredString(*lease, "deviceId");
auto productId = requiredString(*lease, "productId");
auto productVersion = requiredString(*lease, "productVersion");
auto buildSignature = requiredString(*lease, "buildSignature");
auto challenge = requiredString(*lease, "challenge");
auto status = requiredString(*lease, "status");
auto issuedAt = requiredUnsigned(*lease, "issuedAt");
auto refreshAfter = requiredUnsigned(*lease, "refreshAfter");
auto expiresAt = requiredUnsigned(*lease, "expiresAt");
auto sequence = requiredUnsigned(*lease, "sequence");
auto revocationSequence =
requiredUnsigned(*lease, "revocationSequence");
auto snapshotSequence = requiredUnsigned(*revocations, "sequence");
auto snapshotExpiresAt = requiredUnsigned(*revocations, "expiresAt");
if (!leaseDocument || *leaseDocument != "echoion-license-lease" ||
!revocationDocument ||
*revocationDocument != "echoion-license-revocations" ||
!licenseId || !accountId || !deviceId || !productId ||
!productVersion || !buildSignature || !challenge || !status ||
!issuedAt || !refreshAfter || !expiresAt || !sequence ||
!revocationSequence || !snapshotSequence || !snapshotExpiresAt) {
return Void::Result::fail("Licensing: incomplete signed decision");
}
const auto issued = unixTime(*issuedAt);
const auto refresh = unixTime(*refreshAfter);
const auto expiry = unixTime(*expiresAt);
if (*status != "active" || *productId != context.productId ||
*productVersion != context.productVersion ||
*deviceId != context.deviceId ||
*buildSignature != context.buildSignature ||
*challenge != context.challenge ||
*sequence < context.minimumSequence ||
*snapshotSequence < *revocationSequence ||
issued > context.now + std::chrono::minutes(5) ||
expiry <= context.now || expiry <= issued ||
expiry - issued > context.maximumLeaseLifetime ||
refresh < issued || refresh > expiry ||
unixTime(*snapshotExpiresAt) <= context.now) {
return Void::Result::fail("Licensing: lease is inactive, "
"mismatched, expired, or replayed");
}
if (stringArrayContains(*revocations, "licenseIds", *licenseId) ||
stringArrayContains(*revocations, "accountIds", *accountId) ||
stringArrayContains(*revocations, "deviceIds", *deviceId) ||
stringArrayContains(*revocations, "buildSignatures",
*buildSignature) ||
stringArrayContains(*revocations, "productVersions",
*productVersion) ||
stringArrayContains(*revocations, "keyIds", leaseEnvelope->keyId)) {
return Void::Result::fail("Licensing: entitlement was revoked");
}
return LeaseStatus{.mode = Mode::Active,
.reason = "active",
.licenseId = std::move(*licenseId),
.sequence = *sequence,
.refreshAfter = refresh,
.expiresAt = expiry,
.entitlements = stringArray(*lease, "entitlements")};
}
} // namespace Echoion::Core::Licensing
+57 -47
View File
@@ -1,3 +1,4 @@
#include "echoion/core/playback/GaplessHandoff.hpp"
#include "echoion/core/playback/PlaybackEngine.hpp" #include "echoion/core/playback/PlaybackEngine.hpp"
#include <Void/Log/Log.hpp> #include <Void/Log/Log.hpp>
@@ -198,8 +199,8 @@ namespace Echoion::Core
} }
while (ring_.size() < MAX_BUFFER_SHORTS && while (ring_.size() < MAX_BUFFER_SHORTS &&
current_.decoder->getNextChunk(incomingChunk_)) { current_.decoder->getNextChunk(incomingChunk_)) {
ring_.append(std::span<const short>( ring_.append(std::span<const short>(incomingChunk_.data(),
incomingChunk_.data(), incomingChunk_.size())); incomingChunk_.size()));
} }
} }
@@ -215,8 +216,8 @@ namespace Echoion::Core
current_.state == DecoderSlot::State::Active && current_.state == DecoderSlot::State::Active &&
next_.state == DecoderSlot::State::Warming && next_.state == DecoderSlot::State::Warming &&
!host_.repeatEnabled()) { !host_.repeatEnabled()) {
const auto duration = std::chrono::milliseconds( const auto duration =
currentDurationMs_.load()); std::chrono::milliseconds(currentDurationMs_.load());
const auto position = clock_.position(); const auto position = clock_.position();
if (duration.count() > 0 && if (duration.count() > 0 &&
duration - position <= duration - position <=
@@ -256,8 +257,26 @@ namespace Echoion::Core
emitChunk(true); emitChunk(true);
} else if (current_.state == DecoderSlot::State::Active && } else if (current_.state == DecoderSlot::State::Active &&
current_.decoder->isFinished()) { current_.decoder->isFinished()) {
// Flush the tail (shorter than one chunk), zero-padded. // When the warmed decoder already has enough PCM, concatenate
// the outgoing tail and incoming head in this same 20ms device
// frame. This avoids the zero-padding discontinuity that used
// to sound like a short "psst" between tracks.
if (!ring_.empty()) { if (!ring_.empty()) {
const auto incomingReady =
next_.state == DecoderSlot::State::Warming &&
next_.decoder &&
PlaybackDetail::canFillDeviceFrame(
ring_.size(), next_.decoder->queuedSamples(),
SHORTS_PER_CHUNK);
if (incomingReady) {
handleTrackEnd();
while (ring_.size() < SHORTS_PER_CHUNK &&
current_.state == DecoderSlot::State::Active &&
current_.decoder->getNextChunk(incomingChunk_)) {
ring_.append(std::span<const short>(
incomingChunk_.data(), incomingChunk_.size()));
}
}
emitChunk(true); emitChunk(true);
} else { } else {
handleTrackEnd(); handleTrackEnd();
@@ -465,8 +484,7 @@ namespace Echoion::Core
void PlaybackEngine::handle(CmdSeek&& cmd) void PlaybackEngine::handle(CmdSeek&& cmd)
{ {
if (current_.state != DecoderSlot::State::Active || if (current_.state != DecoderSlot::State::Active || !current_.decoder) {
!current_.decoder) {
return; return;
} }
ring_.clear(); ring_.clear();
@@ -478,9 +496,9 @@ namespace Echoion::Core
if (result) { if (result) {
clock_.seekTo(cmd.position); clock_.seekTo(cmd.position);
} else { } else {
Void::Log::error("PlaybackEngine", "{}", Void::Log::error(
std::format("Seek failed: {}", "PlaybackEngine", "{}",
result.error().message)); std::format("Seek failed: {}", result.error().message));
} }
} }
@@ -548,10 +566,9 @@ namespace Echoion::Core
return; return;
} }
const auto position = clock_.position(); const auto position = clock_.position();
const bool nearEnd = const bool nearEnd = duration <= PREFETCH_THRESHOLD
duration <= PREFETCH_THRESHOLD ? position >= std::chrono::seconds(2)
? position >= std::chrono::seconds(2) : (duration - position) <= PREFETCH_THRESHOLD;
: (duration - position) <= PREFETCH_THRESHOLD;
if (!nearEnd) { if (!nearEnd) {
return; return;
} }
@@ -571,10 +588,10 @@ namespace Echoion::Core
std::async(std::launch::async, [this, entryCopy]() { std::async(std::launch::async, [this, entryCopy]() {
return host_.resolveStream(entryCopy, false); return host_.resolveStream(entryCopy, false);
}); });
Void::Log::info( Void::Log::info("PlaybackEngine", "{}",
"PlaybackEngine", "{}", std::format("Prefetching next track: {} - {}",
std::format("Prefetching next track: {} - {}", entryCopy.track.title,
entryCopy.track.title, entryCopy.track.artist)); entryCopy.track.artist));
} }
void PlaybackEngine::pollNextResolve() void PlaybackEngine::pollNextResolve()
@@ -591,10 +608,9 @@ namespace Echoion::Core
auto result = slot->resolveFuture.get(); auto result = slot->resolveFuture.get();
if (!result) { if (!result) {
Void::Log::warn( Void::Log::warn("PlaybackEngine", "{}",
"PlaybackEngine", "{}", std::format("Stream resolve failed: {}",
std::format("Stream resolve failed: {}", result.error().message));
result.error().message));
host_.onPlaybackError(result.error(), slot->entry); host_.onPlaybackError(result.error(), slot->entry);
const bool wasCurrent = (slot == &current_); const bool wasCurrent = (slot == &current_);
slot->closeAndReset(); slot->closeAndReset();
@@ -683,15 +699,14 @@ namespace Echoion::Core
// handoff). // handoff).
current_.closeAndReset(); current_.closeAndReset();
std::swap(current_, next_); std::swap(current_, next_);
if (!current_.entry || if (!current_.entry || !host_.takeNextTrack(current_.entry->queueId)) {
!host_.takeNextTrack(current_.entry->queueId)) {
// Queue changed under the peek: put the tail back as normal // Queue changed under the peek: put the tail back as normal
// output and advance conventionally later. // output and advance conventionally later.
Void::Log::info("PlaybackEngine", "{}", Void::Log::info("PlaybackEngine", "{}",
"Queue changed during crossfade; aborting fade"); "Queue changed during crossfade; aborting fade");
current_.closeAndReset(); current_.closeAndReset();
ring_.append(std::span<const short>(fadeTail_.data(), ring_.append(
fadeTail_.size())); std::span<const short>(fadeTail_.data(), fadeTail_.size()));
clearFade(); clearFade();
if (!beginNextFromQueue()) { if (!beginNextFromQueue()) {
playing_ = false; playing_ = false;
@@ -892,9 +907,8 @@ namespace Echoion::Core
if (hasIncoming) { if (hasIncoming) {
incoming = static_cast<float>(ring_[i]); incoming = static_cast<float>(ring_[i]);
if (rampOut > 0) { if (rampOut > 0) {
incoming *= 1.0f - incoming *= 1.0f - static_cast<float>(i) /
static_cast<float>(i) / static_cast<float>(rampOut);
static_cast<float>(rampOut);
} else if (i < rampIn) { } else if (i < rampIn) {
incoming *= static_cast<float>(i) / incoming *= static_cast<float>(i) /
static_cast<float>(rampIn); static_cast<float>(rampIn);
@@ -910,8 +924,8 @@ namespace Echoion::Core
fadeTailPos_ < fadeTail_.size() fadeTailPos_ < fadeTail_.size()
? static_cast<float>(fadeTail_[fadeTailPos_]) ? static_cast<float>(fadeTail_[fadeTailPos_])
: 0.0f; : 0.0f;
mixed = incoming * std::sin(theta) + mixed =
tail * std::cos(theta); incoming * std::sin(theta) + tail * std::cos(theta);
if (fadeTailPos_ < fadeTail_.size()) { if (fadeTailPos_ < fadeTail_.size()) {
++fadeTailPos_; ++fadeTailPos_;
} }
@@ -921,13 +935,12 @@ namespace Echoion::Core
// complete so the incoming finishes its rise (or, // complete so the incoming finishes its rise (or,
// with both sources dry, the fade ends and normal // with both sources dry, the fade ends and normal
// starvation handling resumes). // starvation handling resumes).
if (hasIncoming || if (hasIncoming || fadeTailPos_ >= fadeTail_.size()) {
fadeTailPos_ >= fadeTail_.size()) {
++fadeEnvPos_; ++fadeEnvPos_;
} }
} }
outChunk_[i] = static_cast<short>(std::clamp( outChunk_[i] = static_cast<short>(
static_cast<int>(mixed), -32768, 32767)); std::clamp(static_cast<int>(mixed), -32768, 32767));
} }
fadeIncomingStarved_ = starved; fadeIncomingStarved_ = starved;
if (fadeEnvPos_ >= fadeTail_.size()) { if (fadeEnvPos_ >= fadeTail_.size()) {
@@ -948,14 +961,13 @@ namespace Echoion::Core
for (size_t i = 0; i < filled; ++i) { for (size_t i = 0; i < filled; ++i) {
const int sample = static_cast<int>( const int sample = static_cast<int>(
static_cast<float>(outChunk_[i]) * gain); static_cast<float>(outChunk_[i]) * gain);
outChunk_[i] = static_cast<short>( outChunk_[i] =
std::clamp(sample, -32768, 32767)); static_cast<short>(std::clamp(sample, -32768, 32767));
} }
} }
// Zero-pad the remainder of a short chunk. // Zero-pad the remainder of a short chunk.
std::fill(outChunk_.begin() + std::fill(outChunk_.begin() + static_cast<std::ptrdiff_t>(filled),
static_cast<std::ptrdiff_t>(filled),
outChunk_.end(), 0); outChunk_.end(), 0);
ring_.popFront(consumed); ring_.popFront(consumed);
} else { } else {
@@ -990,12 +1002,11 @@ namespace Echoion::Core
: agcMeanSquare_ + alpha * (chunkMs - agcMeanSquare_); : agcMeanSquare_ + alpha * (chunkMs - agcMeanSquare_);
const float rmsDb = static_cast<float>( const float rmsDb = static_cast<float>(
10.0 * std::log10(agcMeanSquare_ / 10.0 * std::log10(agcMeanSquare_ / (32768.0 * 32768.0)));
(32768.0 * 32768.0)));
const float wantedDb = normalizeTargetDb_.load() - rmsDb; const float wantedDb = normalizeTargetDb_.load() - rmsDb;
// Slew: fast attack (turn down), slow release (turn up). // Slew: fast attack (turn down), slow release (turn up).
constexpr float kAttackPerChunk = 0.4f; // 20 dB/s constexpr float kAttackPerChunk = 0.4f; // 20 dB/s
constexpr float kReleasePerChunk = 0.06f; // 3 dB/s constexpr float kReleasePerChunk = 0.06f; // 3 dB/s
const float delta = wantedDb - agcGainDb_; const float delta = wantedDb - agcGainDb_;
if (delta < 0.0f) { if (delta < 0.0f) {
@@ -1011,8 +1022,7 @@ namespace Echoion::Core
void PlaybackEngine::positionTick() void PlaybackEngine::positionTick()
{ {
if (current_.state != DecoderSlot::State::Active || if (current_.state != DecoderSlot::State::Active || !current_.entry) {
!current_.entry) {
return; return;
} }
const auto now = std::chrono::steady_clock::now(); const auto now = std::chrono::steady_clock::now();
@@ -1020,9 +1030,9 @@ namespace Echoion::Core
return; return;
} }
lastPositionTick_ = now; lastPositionTick_ = now;
host_.onPositionTick(*current_.entry, clock_.position(), host_.onPositionTick(
std::chrono::milliseconds( *current_.entry, clock_.position(),
currentDurationMs_.load())); std::chrono::milliseconds(currentDurationMs_.load()));
} }
} // namespace Echoion::Core } // namespace Echoion::Core
+43 -1
View File
@@ -50,7 +50,12 @@ int main()
"level": "verbose", "level": "verbose",
"fileName": "../outside.log", "fileName": "../outside.log",
"maxFileSizeBytes": 1, "maxFileSizeBytes": 1,
"maxFiles": 0 "maxFiles": 0,
"format": "xml",
"pattern": "",
"mode": "parallel",
"queueCapacity": 1,
"overflowPolicy": "discard"
} }
})"); })");
expect(logging.has_value(), "logging configuration parses"); expect(logging.has_value(), "logging configuration parses");
@@ -63,12 +68,49 @@ int main()
"log size is clamped to a safe minimum"); "log size is clamped to a safe minimum");
expect(logging->logging.maxFiles == 1, expect(logging->logging.maxFiles == 1,
"at least one rolled log is retained"); "at least one rolled log is retained");
expect(logging->logging.format == "pattern" &&
!logging->logging.pattern.empty(),
"invalid formatter configuration is normalized");
expect(logging->logging.mode == "async" &&
logging->logging.queueCapacity == 16 &&
logging->logging.overflowPolicy == "block",
"invalid dispatch configuration is normalized");
} }
const auto parentLog = const auto parentLog =
ConfigLoader::loadFromJson(R"({"logging":{"fileName":".."}})"); ConfigLoader::loadFromJson(R"({"logging":{"fileName":".."}})");
expect(parentLog && parentLog->logging.fileName == "echoion.log", expect(parentLog && parentLog->logging.fileName == "echoion.log",
"parent-directory logging filename is normalized"); "parent-directory logging filename is normalized");
const auto licensing = ConfigLoader::loadFromJson(R"({
"licensing": {
"required": true,
"serviceUrl": "http://downgrade.example",
"productId": "",
"activationTokenEnv": "",
"refreshInterval": "1m",
"retryInterval": "1s",
"maximumLeaseLifetime": "72h"
}
})");
expect(licensing.has_value(), "licensing configuration parses");
if (licensing) {
expect(licensing->licensing.required,
"licensing required flag is preserved");
expect(licensing->licensing.serviceUrl.empty(),
"licensing service cannot downgrade from HTTPS");
expect(licensing->licensing.productId == "echoion" &&
licensing->licensing.activationTokenEnv ==
"ECHOION_LICENSE_TOKEN",
"licensing identifiers receive safe defaults");
expect(licensing->licensing.refreshInterval ==
std::chrono::minutes(15) &&
licensing->licensing.retryInterval ==
std::chrono::seconds(30) &&
licensing->licensing.maximumLeaseLifetime ==
std::chrono::hours(24),
"licensing cadence and offline lease are bounded");
}
expectShortening("legacy disabled", expectShortening("legacy disabled",
R"({ R"({
"youtube": {"enableUrlShortening": false}, "youtube": {"enableUrlShortening": false},
+34
View File
@@ -0,0 +1,34 @@
#include "echoion/core/playback/GaplessHandoff.hpp"
#include <iostream>
namespace
{
int failures = 0;
void expect(bool condition, const char* message)
{
if (!condition) {
std::cerr << "FAILED: " << message << '\n';
++failures;
}
}
} // namespace
int main()
{
using Echoion::Core::PlaybackDetail::canFillDeviceFrame;
expect(canFillDeviceFrame(300, 700, 1000),
"outgoing tail and incoming head can exactly fill a frame");
expect(canFillDeviceFrame(300, 900, 1000),
"extra incoming PCM is retained for the next frame");
expect(!canFillDeviceFrame(300, 699, 1000),
"handoff waits rather than padding when incoming PCM is short");
expect(!canFillDeviceFrame(0, 1000, 1000),
"an empty outgoing tail is a normal track-end path");
expect(!canFillDeviceFrame(1000, 1000, 1000),
"a complete outgoing frame does not need a boundary join");
return failures == 0 ? 0 : 1;
}
+130
View File
@@ -0,0 +1,130 @@
#include "echoion/core/licensing/LicenseVerifier.hpp"
#include <Void/Text/Base64.hpp>
#include <openssl/evp.h>
#include <cstring>
#include <format>
#include <iostream>
#include <memory>
#include <string>
#include <string_view>
namespace
{
constexpr std::string_view seedHex =
"9d61b19deffd5a60ba844af492ec2cc44449c5697b326919703bac031cae7f60";
constexpr std::string_view publicHex =
"d75a980182b10ab7d54bfed3c964073a0ee172f3daa62325af021a68f707511a";
std::string hex(std::string_view value)
{
std::string output;
output.reserve(value.size() / 2);
for (std::size_t index = 0; index < value.size(); index += 2) {
output.push_back(static_cast<char>(
std::stoi(std::string{value.substr(index, 2)}, nullptr, 16)));
}
return output;
}
std::string sign(std::string_view message)
{
using Key = std::unique_ptr<EVP_PKEY, decltype(&EVP_PKEY_free)>;
using Context = std::unique_ptr<EVP_MD_CTX, decltype(&EVP_MD_CTX_free)>;
const auto seed = hex(seedHex);
Key key{EVP_PKEY_new_raw_private_key(
EVP_PKEY_ED25519, nullptr,
reinterpret_cast<const unsigned char*>(seed.data()),
seed.size()),
&EVP_PKEY_free};
Context context{EVP_MD_CTX_new(), &EVP_MD_CTX_free};
if (!key || !context ||
EVP_DigestSignInit(context.get(), nullptr, nullptr, nullptr,
key.get()) != 1) {
return {};
}
std::string signature(Void::Crypto::Ed25519SignatureSize, '\0');
std::size_t size = signature.size();
if (EVP_DigestSign(
context.get(),
reinterpret_cast<unsigned char*>(signature.data()), &size,
reinterpret_cast<const unsigned char*>(message.data()),
message.size()) != 1) {
return {};
}
signature.resize(size);
return signature;
}
std::string envelope(std::string_view payload)
{
return std::format(
"{{\n \"schemaVersion\": 3,\n \"keyId\": \"test-key\",\n"
" \"document\": {},\n \"signedPayload\": \"{}\",\n"
" \"signature\": \"{}\"\n}}",
payload, Void::Encoding::Base64::encode_url(payload),
Void::Encoding::Base64::encode_url(sign(payload)));
}
int failures = 0;
void expect(bool condition, std::string_view message)
{
if (!condition) {
std::cerr << "FAILED: " << message << '\n';
++failures;
}
}
} // namespace
int main()
{
using namespace Echoion::Core::Licensing;
const auto publicKey = hex(publicHex);
const auto encodedKey = Void::Encoding::Base64::encode_url(publicKey);
Void::Update::Keyring keys;
expect(addPublicKey(keys, "test-key", encodedKey).has_value(),
"base64url public key is accepted");
expect(!addPublicKey(keys, "broken\nkey", encodedKey),
"public key ids reject whitespace and control characters");
constexpr std::uint64_t now = 1'800'000'000;
const auto lease = std::format(
R"({{"document":"echoion-license-lease","licenseId":"lic-1","accountId":"account-1","deviceId":"device-1","productId":"echoion","productVersion":"2.0.0","buildSignature":"build-1","challenge":"challenge-1","status":"active","issuedAt":{},"refreshAfter":{},"expiresAt":{},"sequence":42,"revocationSequence":8,"entitlements":["runtime","updates"]}})",
now - 10, now + 3600, now + 7200);
const auto revocations = std::format(
R"({{"document":"echoion-license-revocations","sequence":8,"generatedAt":{},"expiresAt":{},"licenseIds":[],"accountIds":[],"deviceIds":[],"buildSignatures":[],"keyIds":[]}})",
now - 10, now + 7200);
LeaseContext context{
.productId = "echoion",
.productVersion = "2.0.0",
.deviceId = "device-1",
.buildSignature = "build-1",
.challenge = "challenge-1",
.now = std::chrono::system_clock::time_point{std::chrono::seconds{now}},
.maximumLeaseLifetime = std::chrono::hours(24),
.minimumSequence = 41};
auto active =
verifyLease(envelope(lease), envelope(revocations), keys, context);
expect(active && active->mode == Mode::Active && active->sequence == 42,
"matching signed lease enables normal operation");
context.buildSignature = "pirated-build";
expect(!verifyLease(envelope(lease), envelope(revocations), keys, context),
"build signature mismatch fails closed");
context.buildSignature = "build-1";
const auto revoked = std::format(
R"({{"document":"echoion-license-revocations","sequence":9,"generatedAt":{},"expiresAt":{},"licenseIds":["lic-1"],"accountIds":[],"deviceIds":[],"buildSignatures":[],"keyIds":[]}})",
now - 10, now + 7200);
expect(!verifyLease(envelope(lease), envelope(revoked), keys, context),
"specific license revocation fails closed");
context.minimumSequence = 43;
expect(!verifyLease(envelope(lease), envelope(revocations), keys, context),
"older lease sequence cannot be replayed");
return failures == 0 ? 0 : 1;
}