diff --git a/.codacy.yml b/.codacy.yml index 26bb940c..1d9f03f9 100644 --- a/.codacy.yml +++ b/.codacy.yml @@ -7,3 +7,12 @@ exclude_paths: - "target/**" - "Cargo.lock" - "skills-lock.json" +engines: + duplication: + exclude_paths: + - "crates/**/tests/**" + - "**/tests.rs" + metrics: + exclude_paths: + - "crates/**/tests/**" + - "**/tests.rs" diff --git a/.gitignore b/.gitignore index 6c3335c7..c389c330 100644 --- a/.gitignore +++ b/.gitignore @@ -5,4 +5,6 @@ !.idea/icon.svg **/.elemental -/.codex-target \ No newline at end of file +/.codex-target + +/.archify \ No newline at end of file diff --git a/Cargo.lock b/Cargo.lock index 51603c7d..33160b53 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -589,6 +589,26 @@ version = "1.0.20" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "d0881ea181b1df73ff77ffaaf9c7544ecc11e82fba9b5f27b262a3c73a332555" +[[package]] +name = "elemental-addon" +version = "0.3.0" +dependencies = [ + "async-trait", + "elemental-core", + "elemental-driver", + "elemental-infra", + "elemental-schema", + "elemental-shared", + "hex", + "nidhogg", + "reqwest", + "serde", + "serde_json", + "sha2 0.11.2", + "thiserror 2.0.21", + "tokio", +] + [[package]] name = "elemental-core" version = "0.3.0" @@ -653,6 +673,7 @@ dependencies = [ name = "elemental-kit" version = "0.3.0" dependencies = [ + "elemental-addon", "elemental-core", "elemental-driver", "elemental-infra", @@ -667,13 +688,13 @@ name = "elemental-launcher" version = "0.3.0" dependencies = [ "async-trait", + "elemental-addon", "elemental-core", "elemental-driver", "elemental-infra", "elemental-shared", "erased-serde", "hex", - "nidhogg", "serde", "serde_json", "sha2 0.11.2", diff --git a/Cargo.toml b/Cargo.toml index d595a38d..327ccf10 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -1,6 +1,7 @@ [workspace] resolver = "3" members = [ + "crates/addon", "crates/core", "crates/driver", "crates/elemental", diff --git a/crates/addon/Cargo.toml b/crates/addon/Cargo.toml new file mode 100644 index 00000000..eae61ce8 --- /dev/null +++ b/crates/addon/Cargo.toml @@ -0,0 +1,59 @@ +[package] +name = "elemental-addon" +documentation = "https://docs.rs/elemental-addon" +description = "Composable, host-aware addon system for Elemental Minecraft instances." + +version.workspace = true +edition.workspace = true +repository.workspace = true +license.workspace = true + +[features] +default = ["liteloader", "tls-aws-lc"] +tls-aws-lc = [ + "elemental-core/tls-aws-lc", + "elemental-driver/tls-aws-lc", + "elemental-infra/tls-aws-lc", + "nidhogg?/tls-aws-lc", + "reqwest?/rustls", +] +tls-rustls-no-provider = [ + "elemental-core/tls-rustls-no-provider", + "elemental-driver/tls-rustls-no-provider", + "elemental-infra/tls-rustls-no-provider", + "nidhogg?/tls-rustls-no-provider", + "reqwest?/rustls-no-provider", +] +tls-native = [ + "elemental-core/tls-native", + "elemental-driver/tls-native", + "elemental-infra/tls-native", + "nidhogg?/tls-native", + "reqwest?/native-tls", +] +tls-native-vendored = [ + "elemental-core/tls-native-vendored", + "elemental-driver/tls-native-vendored", + "elemental-infra/tls-native-vendored", + "nidhogg?/tls-native-vendored", + "reqwest?/native-tls-vendored", +] +liteloader = ["elemental-driver/maven-xml", "dep:reqwest"] +authlib-injector = ["elemental-core/yggdrasil-auth", "dep:hex", "dep:nidhogg", "dep:sha2", "nidhogg/authlib-injector"] +authlib-injector-embed = ["authlib-injector", "nidhogg/authlib-injector-embed"] + +[dependencies] +async-trait = { workspace = true } +elemental-core = { path = "../core", version = "0.3.0", default-features = false, features = ["http"] } +elemental-driver = { path = "../driver", version = "0.3.0", default-features = false } +elemental-infra = { path = "../infra", version = "0.3.0", default-features = false } +elemental-schema = { path = "../schema", version = "0.3.0" } +elemental-shared = { path = "../shared", version = "0.3.0" } +hex = { workspace = true, optional = true } +nidhogg = { workspace = true, optional = true } +reqwest = { workspace = true, optional = true } +serde = { workspace = true } +serde_json = { workspace = true } +sha2 = { workspace = true, optional = true } +thiserror = { workspace = true } +tokio = { workspace = true } diff --git a/crates/addon/src/addon.rs b/crates/addon/src/addon.rs new file mode 100644 index 00000000..25164d47 --- /dev/null +++ b/crates/addon/src/addon.rs @@ -0,0 +1,436 @@ +use std::{borrow::Cow, path::PathBuf, sync::Arc}; + +use async_trait::async_trait; +use elemental_core::{ + auth::credential::Credential, minecraft::MinecraftVersionId, runtime::RuntimeResolver, +}; +use elemental_driver::{ + catalog::GameVersion, + driver::{DriverDescriptor, InstanceProbe}, + families::version_json::{InstanceStorage, MetadataPatch, PatchMode}, + launch::RuntimeOptions, +}; +use elemental_infra::downloader::DownloadSession; +use serde::{Deserialize, Serialize}; + +use crate::error::{Error, Result}; + +/// Identifies an addon type by stable machine ID and human-readable display name. +#[derive(Debug, Clone, PartialEq, Eq, Hash)] +pub struct AddonDescriptor { + /// Stable machine-readable identifier (for example, `"liteloader"`). + pub id: Cow<'static, str>, + /// Human-readable display name. + pub name: Cow<'static, str>, +} + +impl AddonDescriptor { + /// Creates a new addon descriptor from a machine ID and display name. + pub fn new(id: impl Into>, name: impl Into>) -> Self { + Self { + id: id.into(), + name: name.into(), + } + } +} + +/// Which patch modes an [`Addon`] is capable of supporting. +#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Serialize, Deserialize)] +#[serde(rename_all = "snake_case")] +pub enum PatchModeSupport { + /// Only supports launch-time virtual overlays (`vpatch`) and/or runtime hooks. + VirtualOnly, + /// Requires physical writes into the instance's `version.json`. + PhysicalOnly, + /// Supports both virtual overlays (`vpatch`) and physical `version.json` patching. + #[default] + Both, +} + +/// Per-addon patch mode preference, monotonically constrained by the instance-level [`PatchMode`]. +#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Serialize, Deserialize)] +#[serde(rename_all = "lowercase")] +pub enum AddonPatchMode { + /// Follow the instance's [`PatchMode`] policy (default). + #[default] + Inherit, + /// Force virtual patching (`vpatch`) regardless of a `Physical` instance policy. + Virtual, + /// Request physical patching into `version.json` (rejected if instance policy is `Virtual`). + Physical, +} + +/// Resolves the effective [`PatchMode`] for an addon given the instance-level policy, +/// the addon's per-addon preference, and the addon's declared capability. +/// +/// Enforces monotonic tightening: an addon can tighten a `Physical` instance policy down +/// to `Virtual`, but can never elevate a `Virtual` instance policy to `Physical`. +pub fn resolve_effective_patch_mode( + addon_id: &str, + instance_policy: PatchMode, + addon_mode: AddonPatchMode, + support: PatchModeSupport, +) -> Result { + if instance_policy == PatchMode::Virtual + && (addon_mode == AddonPatchMode::Physical || support == PatchModeSupport::PhysicalOnly) + { + return Err(Error::PatchModeDisallowedByInstance { + id: addon_id.to_owned(), + instance_policy, + }); + } + + match (addon_mode, support) { + (AddonPatchMode::Physical, PatchModeSupport::VirtualOnly) => { + Err(Error::PatchModeUnsupported { + id: addon_id.to_owned(), + requested: PatchMode::Physical, + supported: "VirtualOnly".to_owned(), + }) + } + (AddonPatchMode::Virtual, PatchModeSupport::PhysicalOnly) => { + Err(Error::PatchModeUnsupported { + id: addon_id.to_owned(), + requested: PatchMode::Virtual, + supported: "PhysicalOnly".to_owned(), + }) + } + (AddonPatchMode::Virtual, _) => Ok(PatchMode::Virtual), + (AddonPatchMode::Physical, _) => Ok(PatchMode::Physical), + (AddonPatchMode::Inherit, PatchModeSupport::VirtualOnly) => Ok(PatchMode::Virtual), + (AddonPatchMode::Inherit, PatchModeSupport::PhysicalOnly) => Ok(PatchMode::Physical), + (AddonPatchMode::Inherit, PatchModeSupport::Both) => Ok(instance_policy), + } +} + +/// Whether an installed addon is managed by Elemental or detected from an external launcher. +#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "lowercase")] +pub enum AddonOrigin { + /// Installed and tracked by Elemental in `.elemental/addons.json`. + Elemental, + /// Detected from an existing instance's metadata or files without an Elemental state record. + External, +} + +/// Result of checking whether an addon can be applied to a host driver and game version. +#[derive(Debug, Clone, PartialEq, Eq)] +pub enum AddonCompatibility { + /// The addon can be applied to the target host instance. + Compatible, + /// The addon cannot be applied to the target host instance. + Incompatible { + /// Human-readable explanation of why the addon is incompatible. + reason: String, + }, +} + +/// Read-only context passed to [`Addon::check_compatibility`]. +pub struct AddonContext<'a> { + /// Host driver installed on the target instance. + pub driver: DriverDescriptor, + /// Target Minecraft version, when known. + pub game_version: Option<&'a MinecraftVersionId>, + /// Storage handle for the target instance directory. + pub instance: &'a InstanceStorage, +} + +/// Inputs passed to [`Addon::prepare`]. +pub struct AddonPrepareRequest<'a> { + /// Active download session used to download addon artifacts. + pub session: &'a DownloadSession, + /// Storage handle for the target instance directory. + pub instance: &'a InstanceStorage, + /// Host driver installed on the target instance. + pub driver: DriverDescriptor, + /// Minecraft version of the target instance. + pub game_version: &'a MinecraftVersionId, + /// Requested addon version, if specified by the caller. + pub addon_version: Option<&'a str>, + /// Runtime options configured for installation/launch preparation. + pub runtime_options: &'a RuntimeOptions, + /// Runtime resolver for locating Java installations when needed. + pub runtime_resolver: &'a RuntimeResolver, +} + +/// Output produced by [`Addon::prepare`]. +#[derive(Debug, Clone, Default)] +pub struct AddonPrepareOutput { + /// Resolved addon version string to persist in instance state. + pub version: Option, + /// Declarative metadata patch layered onto the instance's `PistonMetaData`. + pub metadata_patch: Option, + /// Additional files created/managed by this addon (tracked for cleanup on removal). + pub managed_files: Vec, +} + +/// Launch-time argument injections produced by [`Addon::augment_launch`]. +#[derive(Debug, Clone, Default, PartialEq, Eq)] +pub struct AddonLaunchArgs { + /// Additional JVM flags appended before the main class. + pub extra_jvm_arguments: Vec, + /// Additional game arguments appended after the host driver's game arguments. + pub extra_game_arguments: Vec, +} + +/// Context passed to [`Addon::augment_launch`]. +pub struct AddonLaunchContext<'a> { + /// Storage handle for the instance being launched. + pub instance: &'a InstanceStorage, + /// Host driver of the instance being launched. + pub driver: DriverDescriptor, + /// Authenticated player credential for this launch. + pub credential: &'a Credential, + /// Persisted state record for this addon on the instance. + pub record: &'a InstalledAddonRecord, +} + +/// Summary of an addon installed or detected on an instance. +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +pub struct InstalledAddon { + /// Machine-readable addon identifier. + pub id: String, + /// Human-readable addon display name. + pub name: String, + /// Installed addon version, when known. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub version: Option, + /// Whether this addon is Elemental-managed or externally detected. + pub origin: AddonOrigin, + /// Effective patch mode resolved from instance policy and per-addon preference. + #[serde(default)] + pub effective_patch_mode: PatchMode, + /// Whether launching requires executing [`Addon::augment_launch`] in code. + #[serde(default)] + pub requires_runtime_hook: bool, +} + +/// Persisted state record for a single addon installed on an instance. +#[derive(Debug, Clone, Serialize, Deserialize)] +pub struct InstalledAddonRecord { + /// Machine-readable addon identifier. + pub id: String, + /// Human-readable addon display name. + pub name: String, + /// Installed addon version, when recorded. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub version: Option, + /// Origin indicating whether Elemental or an external launcher installed the addon. + pub origin: AddonOrigin, + /// Per-addon patch mode preference. + #[serde(default)] + pub patch_mode: AddonPatchMode, + /// Patch mode capabilities declared by the addon when installed. + #[serde(default)] + pub patch_mode_support: PatchModeSupport, + /// Whether this addon requires a launch-time hook via [`Addon::augment_launch`]. + #[serde(default)] + pub requires_runtime_hook: bool, + /// Instance-relative paths of files managed by this addon. + #[serde(default, skip_serializing_if = "Vec::is_empty")] + pub managed_files: Vec, + /// Stored metadata patch applied in [`PatchMode::Virtual`] or [`PatchMode::Physical`]. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub metadata_patch: Option, +} + +impl InstalledAddonRecord { + /// Computes the effective [`PatchMode`] constrained by `instance_policy`. + pub fn effective_patch_mode(&self, instance_policy: PatchMode) -> Result { + resolve_effective_patch_mode( + &self.id, + instance_policy, + self.patch_mode, + self.patch_mode_support, + ) + } + + /// Converts this persisted record into a public [`InstalledAddon`] summary. + pub fn to_installed(&self, instance_policy: PatchMode) -> InstalledAddon { + let effective_patch_mode = self + .effective_patch_mode(instance_policy) + .unwrap_or(PatchMode::Virtual); + InstalledAddon { + id: self.id.clone(), + name: self.name.clone(), + version: self.version.clone(), + origin: self.origin, + effective_patch_mode, + requires_runtime_hook: self.requires_runtime_hook, + } + } +} + +/// A catalog entry describing an available version of an [`Addon`]. +#[derive(Clone, Debug, PartialEq, Eq, Hash)] +pub struct AddonRelease { + /// Addon release version string. + pub version: String, + /// Optional release channel (for example, `"release"` or `"snapshot"`). + pub channel: Option, + /// Optional publication timestamp string from the upstream source. + pub published_at: Option, + /// Whether the upstream catalog marks this release as a prerelease. + pub prerelease: Option, +} + +impl AddonRelease { + /// Creates a release entry for the given addon `version`. + pub fn new(version: impl Into) -> Self { + Self { + version: version.into(), + channel: None, + published_at: None, + prerelease: None, + } + } + + /// Sets the release channel label. + pub fn with_channel(mut self, channel: Option) -> Self { + self.channel = channel; + self + } + + /// Sets the publication timestamp string. + pub fn with_published_at(mut self, published_at: Option) -> Self { + self.published_at = published_at; + self + } + + /// Sets whether this release is a prerelease. + pub fn with_prerelease(mut self, prerelease: Option) -> Self { + self.prerelease = prerelease; + self + } +} + +/// Optional host driver and game version filters for querying an addon's version catalog. +#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)] +pub struct AddonCatalogQuery<'a> { + /// Optional host driver filter to query compatible addon releases for. + pub driver: Option, + /// Optional Minecraft version filter to query compatible addon releases for. + pub game_version: Option<&'a MinecraftVersionId>, +} + +impl<'a> AddonCatalogQuery<'a> { + /// Creates an unfiltered catalog query. + pub fn new() -> Self { + Self::default() + } + + /// Filters releases by host `driver`. + pub fn with_driver(mut self, driver: DriverDescriptor) -> Self { + self.driver = Some(driver); + self + } + + /// Filters releases by Minecraft `game_version`. + pub fn with_game_version(mut self, game_version: &'a MinecraftVersionId) -> Self { + self.game_version = Some(game_version); + self + } +} + +/// Composable, host-aware extension layered onto a Minecraft instance. +#[async_trait] +pub trait Addon: Send + Sync { + /// Returns the addon's unique identifier and display name. + fn descriptor(&self) -> AddonDescriptor; + + /// Declares which patch modes this addon supports. + fn patch_mode_support(&self) -> PatchModeSupport { + PatchModeSupport::Both + } + + /// Returns `true` when this addon requires code execution during launch + /// command construction (`augment_launch`) and cannot degrade to data-only. + fn requires_runtime_hook(&self) -> bool { + false + } + + /// Returns supported game versions when this addon exposes a remote catalog. + async fn supported_game_versions(&self) -> Result>> { + Ok(None) + } + + /// Returns available addon releases for a host driver and game version, or + /// `None` when this addon does not provide a version catalog. + async fn available_versions( + &self, + _query: &AddonCatalogQuery<'_>, + ) -> Result>> { + Ok(None) + } + + /// Checks whether this addon is compatible with the host driver and game version. + fn check_compatibility(&self, _ctx: &AddonContext<'_>) -> AddonCompatibility { + AddonCompatibility::Compatible + } + + /// Detects whether an unmanaged/external copy of this addon is already present in `probe`. + async fn inspect(&self, _probe: &InstanceProbe) -> Result> { + Ok(None) + } + + /// Downloads any required artifacts and produces the metadata patch and managed files + /// to persist for this addon. + async fn prepare(&self, _request: &AddonPrepareRequest<'_>) -> Result { + Ok(AddonPrepareOutput::default()) + } + + /// Augments the launch command with dynamic JVM or game arguments before spawning. + async fn augment_launch( + &self, + _args: &mut AddonLaunchArgs, + _ctx: &AddonLaunchContext<'_>, + ) -> Result<()> { + Ok(()) + } +} + +#[async_trait] +impl Addon for Arc { + fn descriptor(&self) -> AddonDescriptor { + (**self).descriptor() + } + + fn patch_mode_support(&self) -> PatchModeSupport { + (**self).patch_mode_support() + } + + fn requires_runtime_hook(&self) -> bool { + (**self).requires_runtime_hook() + } + + async fn supported_game_versions(&self) -> Result>> { + (**self).supported_game_versions().await + } + + async fn available_versions( + &self, + query: &AddonCatalogQuery<'_>, + ) -> Result>> { + (**self).available_versions(query).await + } + + fn check_compatibility(&self, ctx: &AddonContext<'_>) -> AddonCompatibility { + (**self).check_compatibility(ctx) + } + + async fn inspect(&self, probe: &InstanceProbe) -> Result> { + (**self).inspect(probe).await + } + + async fn prepare(&self, request: &AddonPrepareRequest<'_>) -> Result { + (**self).prepare(request).await + } + + async fn augment_launch( + &self, + args: &mut AddonLaunchArgs, + ctx: &AddonLaunchContext<'_>, + ) -> Result<()> { + (**self).augment_launch(args, ctx).await + } +} diff --git a/crates/addon/src/builtins/authlib_injector/endpoints.rs b/crates/addon/src/builtins/authlib_injector/endpoints.rs new file mode 100644 index 00000000..7af9053d --- /dev/null +++ b/crates/addon/src/builtins/authlib_injector/endpoints.rs @@ -0,0 +1,129 @@ +use std::path::{Path, PathBuf}; + +use elemental_core::url::{OriginEndpoints, OriginPolicy}; + +use crate::error::Result; + +/// Machine-readable identifier for the built-in authlib-injector addon. +pub const AUTHLIB_INJECTOR_ADDON_ID: &str = "authlib-injector"; + +/// Canonical upstream base URL for authlib-injector builds. +pub const AUTHLIB_INJECTOR_OFFICIAL_URL: &str = nidhogg::authlib_injector::OFFICIAL_URL; + +const KNOWN_ORIGINS: &[&str] = &[AUTHLIB_INJECTOR_OFFICIAL_URL]; + +/// Endpoint resolver for authlib-injector metadata and artifact downloads. +#[derive(Debug, Clone)] +pub struct AuthlibInjectorEndpoints { + endpoints: OriginEndpoints, +} + +impl Default for AuthlibInjectorEndpoints { + fn default() -> Self { + Self::official() + } +} + +impl AuthlibInjectorEndpoints { + /// Creates endpoints applying the given `origin_policy`. + pub fn new(origin_policy: OriginPolicy) -> Self { + Self { + endpoints: OriginEndpoints::new(KNOWN_ORIGINS, origin_policy), + } + } + + /// Creates endpoints targeting the official authlib-injector origin. + pub fn official() -> Self { + Self::new(OriginPolicy::default()) + } + + /// Resolves the `artifacts.json` manifest URL listing all releases. + pub fn artifacts_url(&self) -> Result { + Ok(self + .endpoints + .resolve(AUTHLIB_INJECTOR_OFFICIAL_URL, "artifacts.json")?) + } + + /// Resolves the `artifact/latest.json` URL describing the newest release. + pub fn latest_artifact_url(&self) -> Result { + Ok(self + .endpoints + .resolve(AUTHLIB_INJECTOR_OFFICIAL_URL, "artifact/latest.json")?) + } + + /// Resolves the `artifact/{build_number}.json` URL for a specific build. + pub fn artifact_url(&self, build_number: u64) -> Result { + Ok(self.endpoints.resolve( + AUTHLIB_INJECTOR_OFFICIAL_URL, + &format!("artifact/{build_number}.json"), + )?) + } + + /// Rewrites an upstream download URL according to the configured mirror policy. + pub fn rewrite_download_url(&self, raw_url: &str) -> Result { + Ok(self.endpoints.rewrite_known_or_keep(raw_url)?) + } +} + +/// Origin from which a prepared authlib-injector JAR was obtained. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum AuthlibInjectorSource { + /// Downloaded or matched from the remote distribution API. + Remote, + /// Materialized from the compile-time embedded snapshot. + #[cfg(feature = "authlib-injector-embed")] + Embedded, +} + +/// Prepared authlib-injector artifact metadata and resolved JAR path. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct AuthlibInjector { + path: PathBuf, + version: String, + source: AuthlibInjectorSource, + fallback_reason: Option, +} + +impl AuthlibInjector { + pub(super) fn new( + path: PathBuf, + version: String, + source: AuthlibInjectorSource, + fallback_reason: Option, + ) -> Self { + Self { + path, + version, + source, + fallback_reason, + } + } + + /// Absolute path to the prepared `authlib-injector` JAR on disk. + pub fn path(&self) -> &Path { + &self.path + } + + /// Resolved `authlib-injector` version string. + pub fn version(&self) -> &str { + &self.version + } + + /// Where this artifact was obtained from. + pub fn source(&self) -> AuthlibInjectorSource { + self.source + } + + /// Fallback reason if an embedded snapshot replaced a failed remote fetch. + pub fn fallback_reason(&self) -> Option<&str> { + self.fallback_reason.as_deref() + } + + /// Returns the JVM arguments required to attach authlib-injector for `auth_server`. + pub fn jvm_arguments(&self, auth_server: &str) -> [String; 2] { + [ + format!("-javaagent:{}={auth_server}", self.path.display()), + "-Dauthlibinjector.side=client".to_owned(), + ] + } +} diff --git a/crates/addon/src/builtins/authlib_injector/install.rs b/crates/addon/src/builtins/authlib_injector/install.rs new file mode 100644 index 00000000..10cc579d --- /dev/null +++ b/crates/addon/src/builtins/authlib_injector/install.rs @@ -0,0 +1,179 @@ +use std::{ + io::ErrorKind, + path::{Path, PathBuf}, +}; + +use elemental_core::storage::layout::Layoutable; +use elemental_driver::families::version_json::{ + GameStorage, InstanceStorage, VersionJsonRootResource, +}; +use elemental_infra::{ + SafeRelativePath, + downloader::{DownloadSession, DownloadTask}, +}; +use nidhogg::authlib_injector::Artifact; +#[cfg(feature = "authlib-injector-embed")] +use nidhogg::authlib_injector::{EmbeddedArtifact, embedded}; +use sha2::{Digest, Sha256}; + +use crate::error::{Error, Result}; + +use super::endpoints::{AuthlibInjector, AuthlibInjectorEndpoints, AuthlibInjectorSource}; + +const ARTIFACT_DIRECTORY: &str = "authlib-injector"; + +pub(super) fn artifact_relative_path(version: &str) -> Result { + Ok(SafeRelativePath::parse(format!( + "{ARTIFACT_DIRECTORY}/authlib-injector-{version}.jar" + ))?) +} + +pub(super) fn jar_path_for_storage(storage: &GameStorage, version: &str) -> Result { + let relative = artifact_relative_path(version)?; + let path = storage.try_get_resource(VersionJsonRootResource::Elemental(Some(relative)))?; + Ok(std::path::absolute(path)?) +} + +pub(super) fn jar_path_for_instance(instance: &InstanceStorage, version: &str) -> Result { + let relative = artifact_relative_path(version)?; + let path = + instance.try_get_parent_resource(VersionJsonRootResource::Elemental(Some(relative)))?; + Ok(std::path::absolute(path)?) +} + +pub(super) async fn ensure_remote( + endpoints: &AuthlibInjectorEndpoints, + session: &DownloadSession, + artifact: Artifact, + resolve_path: &(dyn Fn(&str) -> Result + Sync), +) -> Result { + let path = resolve_path(&artifact.version)?; + if existing_artifact_matches(&path, &artifact.checksums.sha256).await? { + return Ok(AuthlibInjector::new( + path, + artifact.version, + AuthlibInjectorSource::Remote, + None, + )); + } + + let download_url = endpoints.rewrite_download_url(&artifact.download_url)?; + match install_remote(&path, session, &download_url, &artifact.checksums.sha256).await { + Ok(()) => Ok(AuthlibInjector::new( + path, + artifact.version, + AuthlibInjectorSource::Remote, + None, + )), + Err(error) => install_embedded_fallback(resolve_path, &artifact.version, error).await, + } +} + +async fn install_remote( + path: &Path, + session: &DownloadSession, + download_url: &str, + expected_sha256: &str, +) -> Result<()> { + ensure_parent(path).await?; + remove_if_present(path).await?; + session + .submit(DownloadTask::new(download_url, path)) + .await?; + verify_file(path, expected_sha256).await +} + +async fn verify_file(path: &Path, expected: &str) -> Result<()> { + let Some(actual) = file_sha256(path).await? else { + return Err(Error::AuthlibInjectorMissing { + path: path.to_owned(), + }); + }; + if actual == expected { + return Ok(()); + } + + remove_if_present(path).await?; + Err(Error::AuthlibInjectorChecksum { + path: path.to_owned(), + expected: expected.to_owned(), + actual, + }) +} + +#[cfg(feature = "authlib-injector-embed")] +async fn install_embedded_fallback( + resolve_path: &(dyn Fn(&str) -> Result + Sync), + requested_version: &str, + error: Error, +) -> Result { + let embedded_artifact = embedded()?; + if embedded_artifact.artifact().version != requested_version { + return Err(error); + } + let path = resolve_path(&embedded_artifact.artifact().version)?; + install_embedded_with_reason(&path, embedded_artifact, Some(error.to_string())).await +} + +#[cfg(not(feature = "authlib-injector-embed"))] +async fn install_embedded_fallback( + _resolve_path: &(dyn Fn(&str) -> Result + Sync), + _requested_version: &str, + error: Error, +) -> Result { + Err(error) +} + +#[cfg(feature = "authlib-injector-embed")] +pub(super) async fn install_embedded_with_reason( + path: &Path, + embedded: EmbeddedArtifact, + fallback_reason: Option, +) -> Result { + ensure_parent(path).await?; + remove_if_present(path).await?; + tokio::fs::write(path, embedded.jar()).await?; + let artifact = embedded.artifact(); + verify_file(path, &artifact.checksums.sha256).await?; + + Ok(AuthlibInjector::new( + path.to_owned(), + artifact.version.clone(), + AuthlibInjectorSource::Embedded, + fallback_reason, + )) +} + +pub(super) fn matches_requested_version(version: &str, build_number: u64, requested: &str) -> bool { + version == requested || build_number.to_string() == requested +} + +async fn ensure_parent(path: &Path) -> Result<()> { + if let Some(parent) = path.parent() { + tokio::fs::create_dir_all(parent).await?; + } + Ok(()) +} + +async fn existing_artifact_matches(path: &Path, expected: &str) -> Result { + let Some(actual) = file_sha256(path).await? else { + return Ok(false); + }; + Ok(actual == expected) +} + +async fn file_sha256(path: &Path) -> Result> { + match tokio::fs::read(path).await { + Ok(bytes) => Ok(Some(hex::encode(Sha256::digest(bytes)))), + Err(source) if source.kind() == ErrorKind::NotFound => Ok(None), + Err(source) => Err(source.into()), + } +} + +async fn remove_if_present(path: &Path) -> Result<()> { + match tokio::fs::remove_file(path).await { + Ok(()) => Ok(()), + Err(source) if source.kind() == ErrorKind::NotFound => Ok(()), + Err(source) => Err(source.into()), + } +} diff --git a/crates/addon/src/builtins/authlib_injector/mod.rs b/crates/addon/src/builtins/authlib_injector/mod.rs new file mode 100644 index 00000000..6032a4a3 --- /dev/null +++ b/crates/addon/src/builtins/authlib_injector/mod.rs @@ -0,0 +1,251 @@ +mod endpoints; +mod install; + +use std::path::PathBuf; + +use async_trait::async_trait; +use elemental_core::http::{RequestBuilderExt, SwappableClient}; +use elemental_driver::families::version_json::GameStorage; +use elemental_infra::downloader::DownloadSession; +use nidhogg::authlib_injector::Artifact; +#[cfg(feature = "authlib-injector-embed")] +use nidhogg::authlib_injector::{EmbeddedArtifact, embedded}; +use serde::Deserialize; + +use crate::{ + addon::{ + Addon, AddonCatalogQuery, AddonDescriptor, AddonLaunchArgs, AddonLaunchContext, + AddonPrepareOutput, AddonPrepareRequest, AddonRelease, PatchModeSupport, + }, + error::{Error, Result}, +}; + +pub use endpoints::{ + AUTHLIB_INJECTOR_ADDON_ID, AUTHLIB_INJECTOR_OFFICIAL_URL, AuthlibInjector, + AuthlibInjectorEndpoints, AuthlibInjectorSource, +}; + +#[cfg(feature = "authlib-injector-embed")] +use install::install_embedded_with_reason; +use install::{ + ensure_remote, jar_path_for_instance, jar_path_for_storage, matches_requested_version, +}; + +#[derive(Debug, Deserialize)] +struct ArtifactsManifest { + artifacts: Vec, +} + +#[derive(Debug, Deserialize)] +struct ArtifactSummary { + build_number: u64, + version: String, + #[serde(default)] + release_time: Option, +} + +enum ResolvedArtifact { + Remote(Artifact), + #[cfg(feature = "authlib-injector-embed")] + Embedded { + embedded: EmbeddedArtifact, + fallback_reason: Option, + }, +} + +/// Built-in addon that manages versioned authlib-injector artifacts and attaches +/// `-javaagent` when launching with an external Yggdrasil `auth_server`. +#[derive(Debug, Clone, Default)] +pub struct AuthlibInjectorAddon { + endpoints: AuthlibInjectorEndpoints, + client: SwappableClient, +} + +impl AuthlibInjectorAddon { + /// Creates an `AuthlibInjectorAddon` using official endpoints and default HTTP client. + pub fn new() -> Self { + Self::default() + } + + /// Replaces the endpoint policy used to fetch manifests and rewrite download URLs. + pub fn with_endpoints(mut self, endpoints: AuthlibInjectorEndpoints) -> Self { + self.endpoints = endpoints; + self + } + + /// Replaces the [`SwappableClient`] used to query authlib-injector metadata. + pub fn with_http_client(mut self, client: SwappableClient) -> Self { + self.client = client; + self + } + + /// Resolves the absolute cache path for a specific authlib-injector `version`. + pub fn jar_path_for_version(&self, storage: &GameStorage, version: &str) -> Result { + jar_path_for_storage(storage, version) + } + + /// Prepares the requested `version` (or latest when `None`) via `session` and + /// returns the verified [`AuthlibInjector`] descriptor. + pub async fn install( + &self, + storage: &GameStorage, + session: &DownloadSession, + version: Option<&str>, + ) -> Result { + self.install_with_resolver(session, version, &|resolved_version| { + self.jar_path_for_version(storage, resolved_version) + }) + .await + } + + async fn install_with_resolver( + &self, + session: &DownloadSession, + version: Option<&str>, + resolve_path: &(dyn Fn(&str) -> Result + Sync), + ) -> Result { + match self.resolve_artifact(version).await? { + ResolvedArtifact::Remote(artifact) => { + ensure_remote(&self.endpoints, session, artifact, resolve_path).await + } + #[cfg(feature = "authlib-injector-embed")] + ResolvedArtifact::Embedded { + embedded, + fallback_reason, + } => { + let path = resolve_path(&embedded.artifact().version)?; + install_embedded_with_reason(&path, embedded, fallback_reason).await + } + } + } + + async fn fetch_artifacts(&self) -> Result> { + let url = self.endpoints.artifacts_url()?; + let manifest: ArtifactsManifest = self.client.get(url).send_json().await?; + Ok(manifest.artifacts) + } + + async fn resolve_artifact(&self, version: Option<&str>) -> Result { + match version { + None => self.resolve_latest_artifact().await, + Some(requested) => self.resolve_pinned_artifact(requested).await, + } + } + + async fn resolve_latest_artifact(&self) -> Result { + let url = self.endpoints.latest_artifact_url()?; + match self.client.get(url).send_json::().await { + Ok(artifact) => Ok(ResolvedArtifact::Remote(artifact)), + #[cfg(feature = "authlib-injector-embed")] + Err(error) => Ok(ResolvedArtifact::Embedded { + embedded: embedded()?, + fallback_reason: Some(error.to_string()), + }), + #[cfg(not(feature = "authlib-injector-embed"))] + Err(error) => Err(error.into()), + } + } + + async fn resolve_pinned_artifact(&self, requested: &str) -> Result { + match self.fetch_pinned_artifact(requested).await { + Ok(artifact) => Ok(ResolvedArtifact::Remote(artifact)), + #[cfg(feature = "authlib-injector-embed")] + Err(Error::HttpRequest(http_error)) => { + let embedded_artifact = embedded()?; + let artifact = embedded_artifact.artifact(); + if matches_requested_version(&artifact.version, artifact.build_number, requested) { + Ok(ResolvedArtifact::Embedded { + embedded: embedded_artifact, + fallback_reason: Some(http_error.to_string()), + }) + } else { + Err(Error::HttpRequest(http_error)) + } + } + Err(error) => Err(error), + } + } + + async fn fetch_pinned_artifact(&self, requested: &str) -> Result { + let artifacts = self.fetch_artifacts().await?; + let summary = artifacts + .into_iter() + .find(|item| matches_requested_version(&item.version, item.build_number, requested)) + .ok_or_else(|| Error::AuthlibInjectorVersionNotFound { + version: requested.to_owned(), + })?; + let url = self.endpoints.artifact_url(summary.build_number)?; + Ok(self.client.get(url).send_json::().await?) + } +} + +#[async_trait] +impl Addon for AuthlibInjectorAddon { + fn descriptor(&self) -> AddonDescriptor { + AddonDescriptor::new(AUTHLIB_INJECTOR_ADDON_ID, "authlib-injector") + } + + fn patch_mode_support(&self) -> PatchModeSupport { + PatchModeSupport::VirtualOnly + } + + fn requires_runtime_hook(&self) -> bool { + true + } + + async fn available_versions( + &self, + _query: &AddonCatalogQuery<'_>, + ) -> Result>> { + let artifacts = self.fetch_artifacts().await?; + Ok(Some( + artifacts + .into_iter() + .map(|entry| AddonRelease::new(entry.version).with_published_at(entry.release_time)) + .collect(), + )) + } + + async fn prepare(&self, request: &AddonPrepareRequest<'_>) -> Result { + let injector = self + .install_with_resolver(request.session, request.addon_version, &|version| { + jar_path_for_instance(request.instance, version) + }) + .await?; + Ok(AddonPrepareOutput { + version: Some(injector.version().to_owned()), + metadata_patch: None, + managed_files: Vec::new(), + }) + } + + async fn augment_launch( + &self, + args: &mut AddonLaunchArgs, + ctx: &AddonLaunchContext<'_>, + ) -> Result<()> { + let Some(auth_server) = &ctx.credential.auth_server else { + return Ok(()); + }; + let version = ctx + .record + .version + .as_deref() + .ok_or_else(|| Error::VersionRequired { + id: AUTHLIB_INJECTOR_ADDON_ID.to_owned(), + })?; + let path = jar_path_for_instance(ctx.instance, version)?; + if !path.is_file() { + return Err(Error::AuthlibInjectorMissing { path }); + } + let injector = AuthlibInjector::new( + path, + version.to_owned(), + AuthlibInjectorSource::Remote, + None, + ); + args.extra_jvm_arguments + .extend(injector.jvm_arguments(auth_server)); + Ok(()) + } +} diff --git a/crates/addon/src/builtins/custom_patch.rs b/crates/addon/src/builtins/custom_patch.rs new file mode 100644 index 00000000..e73087a1 --- /dev/null +++ b/crates/addon/src/builtins/custom_patch.rs @@ -0,0 +1,79 @@ +use async_trait::async_trait; +use elemental_driver::families::version_json::MetadataPatch; + +use crate::{ + addon::{ + Addon, AddonCompatibility, AddonContext, AddonDescriptor, AddonPrepareOutput, + AddonPrepareRequest, + }, + error::Result, +}; + +/// Addon wrapping a user-provided declarative [`MetadataPatch`]. +#[derive(Debug, Clone)] +pub struct CustomPatchAddon { + descriptor: AddonDescriptor, + version: Option, + patch: MetadataPatch, + allowed_drivers: Option>, +} + +impl CustomPatchAddon { + /// Creates an addon that applies `patch` under the given `id` and `name`. + pub fn new( + id: impl Into>, + name: impl Into>, + patch: MetadataPatch, + ) -> Self { + Self { + descriptor: AddonDescriptor::new(id, name), + version: None, + patch, + allowed_drivers: None, + } + } + + /// Sets the default version string recorded when the caller omits one. + pub fn with_version(mut self, version: impl Into) -> Self { + self.version = Some(version.into()); + self + } + + /// Restricts compatibility to instances using one of the specified driver IDs. + pub fn with_allowed_drivers(mut self, drivers: Vec<&'static str>) -> Self { + self.allowed_drivers = Some(drivers); + self + } +} + +#[async_trait] +impl Addon for CustomPatchAddon { + fn descriptor(&self) -> AddonDescriptor { + self.descriptor.clone() + } + + fn check_compatibility(&self, ctx: &AddonContext<'_>) -> AddonCompatibility { + if let Some(allowed) = &self.allowed_drivers + && !allowed.contains(&ctx.driver.id) + { + return AddonCompatibility::Incompatible { + reason: format!( + "driver '{}' is not in allowed drivers {:?}", + ctx.driver.id, allowed + ), + }; + } + AddonCompatibility::Compatible + } + + async fn prepare(&self, request: &AddonPrepareRequest<'_>) -> Result { + Ok(AddonPrepareOutput { + version: request + .addon_version + .map(str::to_owned) + .or_else(|| self.version.clone()), + metadata_patch: Some(self.patch.clone()), + managed_files: Vec::new(), + }) + } +} diff --git a/crates/addon/src/builtins/jvm_agent.rs b/crates/addon/src/builtins/jvm_agent.rs new file mode 100644 index 00000000..70d4942f --- /dev/null +++ b/crates/addon/src/builtins/jvm_agent.rs @@ -0,0 +1,102 @@ +use std::path::PathBuf; + +use async_trait::async_trait; + +use crate::{ + addon::{ + Addon, AddonDescriptor, AddonLaunchArgs, AddonLaunchContext, AddonPrepareOutput, + AddonPrepareRequest, PatchModeSupport, + }, + error::Result, +}; + +/// Addon that injects a `-javaagent` and optional JVM arguments at launch time. +#[derive(Debug, Clone)] +pub struct JvmAgentAddon { + descriptor: AddonDescriptor, + version: Option, + jar_path: PathBuf, + agent_option: Option, + extra_jvm_arguments: Vec, +} + +impl JvmAgentAddon { + /// Creates a JVM agent addon injecting `-javaagent:` at launch time. + pub fn new( + id: impl Into>, + name: impl Into>, + jar_path: impl Into, + ) -> Self { + Self { + descriptor: AddonDescriptor::new(id, name), + version: None, + jar_path: jar_path.into(), + agent_option: None, + extra_jvm_arguments: Vec::new(), + } + } + + /// Sets the default version string recorded when the caller omits one. + pub fn with_version(mut self, version: impl Into) -> Self { + self.version = Some(version.into()); + self + } + + /// Attaches an agent option string formatted as `-javaagent:=