centralcore 1.0.2

Open-source Rust library for building Minecraft Java Edition launchers
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
//! # CentralCore
//!
//! CentralCore is an open-source Rust library for building Minecraft Java
//! Edition launchers. It provides an asynchronous, UI-independent engine behind
//! the [`CentralCore`] facade.
//!
//! ## Features
//!
//! - Vanilla, Fabric, and Forge installation and launch planning.
//! - Managed Java discovery, installation, verification, and selection.
//! - Extensible authentication and secure native credential storage.
//! - Inspectable Install / Verify / Repair / Update workflows.
//! - Provider-defined optional components and dependency resolution.
//! - Verified offline cache reuse and recovery.
//! - Signed providers with explicit local trust and anti-rollback checks.
//! - Structured events for desktop, CLI, IPC, and automation hosts.
//!
//! ## Quick start
//!
//! This example follows the public API used by the packaged `vanilla` example:
//!
//! ```no_run
//! use centralcore::{CentralCore, InstanceSpec};
//!
//! #[tokio::main]
//! async fn main() -> centralcore::Result<()> {
//!     let core = CentralCore::builder()
//!         .data_dir("./centralcore-data")
//!         .build()
//!         .await?;
//!
//!     let instance = core
//!         .instances()
//!         .create(InstanceSpec::vanilla("demo", "Demo", "1.21.1")?)
//!         .await?;
//!     let cancellation = core.downloads().cancellation_token();
//!     let plan = core
//!         .minecraft()
//!         .resolve_install_plan(&instance, &cancellation)
//!         .await?;
//!
//!     println!("{} files are required", plan.downloads().len());
//!     Ok(())
//! }
//! ```
//!
//! ## Architecture / UI independence
//!
//! CentralCore contains no frontend framework and does not own an application
//! event loop. A desktop UI, command-line tool, server, or IPC adapter owns
//! presentation and calls the same service API. Long-running operations expose
//! typed, inspectable plans and emit UI-agnostic events through [`events`].
//!
//! ## Main services
//!
//! [`CentralCore`] provides access to focused managers:
//!
//! - [`CentralCore::instances`] stores isolated instance specifications.
//! - [`CentralCore::minecraft`] plans installation, verification, repair,
//!   update, and launch operations.
//! - [`CentralCore::loaders`] handles Fabric, Forge, and custom loader support.
//! - [`CentralCore::java`] discovers and manages compatible Java runtimes.
//! - [`CentralCore::auth`] coordinates authentication providers and sessions.
//! - [`CentralCore::providers`] resolves static providers and optional
//!   components.
//! - [`CentralCore::downloads`] supplies download, integrity, and cancellation
//!   primitives.
//! - [`CentralCore::cache`] verifies and prunes shared cached content.
//! - [`CentralCore::processes`] manages concurrent Minecraft processes.
//! - [`CentralCore::events`] exposes structured core events.
//!
//! ## Security / signed providers
//!
//! Remote providers can require detached Ed25519 signatures. Trust is local:
//! provider documents cannot approve their own keys. The [`trust`] and
//! [`providers`] modules implement explicit key approval, rotation, revocation,
//! verified snapshots, and rollback protection. Applications should require
//! signatures for production remote providers and protect their publisher-side
//! private keys outside CentralCore.
//!
//! ## Further documentation
//!
//! - [Project README](https://github.com/vexato/CentralCore)
//! - [Examples](https://github.com/vexato/CentralCore/tree/main/crates/centralcore/examples)
//! - [Architecture guide](https://github.com/vexato/CentralCore/blob/main/docs/architecture.md)
//! - [UI integration guide](https://github.com/vexato/CentralCore/blob/main/docs/integrating-a-ui.md)
//! - [Authentication guide](https://github.com/vexato/CentralCore/blob/main/docs/auth.md)
//! - [Provider security model](https://github.com/vexato/CentralCore/blob/main/docs/security/signatures.md)

#![forbid(unsafe_code)]
#![deny(rustdoc::broken_intra_doc_links)]

use std::path::{Path, PathBuf};
use std::sync::Arc;

pub mod auth;
pub mod cache;
pub mod config;
pub mod download;
pub mod errors;
pub mod events;
pub mod files;
pub mod instance;
pub mod java;
pub mod loaders;
mod lock;
pub mod minecraft;
pub mod mods;
pub mod platform;
pub mod process;
pub mod providers;
pub mod trust;

pub use cache::{CacheManager, CachePolicy};
pub use config::CoreConfig;
pub use errors::{Error, Result};
pub use events::{CoreEvent, EventBus, EventEnvelope, EventId};
pub use instance::{Instance, InstanceId, InstanceService, InstanceSpec, InstanceStatus};
pub use process::{
    DetachedInstance, ProcessExit, ProcessManager, ProcessRecoveryReport, RunningInstance,
};
pub use trust::TrustStore;

use auth::{AuthManager, CredentialStore, OfflineAuthProvider, SystemCredentialStore};
use download::DownloadManager;
use java::JavaManager;
use loaders::LoaderManager;
use minecraft::{MinecraftManager, MinecraftServices};
use providers::ProviderManager;

/// Main entry point for applications embedding CentralCore.
#[derive(Debug, Clone)]
pub struct CentralCore {
    config: CoreConfig,
    events: EventBus,
    instances: InstanceService,
    downloads: DownloadManager,
    java: JavaManager,
    loaders: LoaderManager,
    auth: AuthManager,
    minecraft: MinecraftManager,
    processes: ProcessManager,
    cache: CacheManager,
    providers: ProviderManager,
    trust: TrustStore,
}

impl CentralCore {
    /// Starts construction with safe local defaults.
    #[must_use]
    pub fn builder() -> CentralCoreBuilder {
        CentralCoreBuilder::default()
    }

    /// Returns the validated active configuration.
    #[must_use]
    pub fn config(&self) -> &CoreConfig {
        &self.config
    }

    /// Accesses isolated instance storage.
    #[must_use]
    pub fn instances(&self) -> &InstanceService {
        &self.instances
    }

    /// Accesses Java runtime discovery and selection.
    #[must_use]
    pub fn java(&self) -> &JavaManager {
        &self.java
    }

    /// Accesses loader discovery and the generic loader registry.
    #[must_use]
    pub fn loaders(&self) -> &LoaderManager {
        &self.loaders
    }

    /// Accesses download policy, validation, and cancellation primitives.
    #[must_use]
    pub fn downloads(&self) -> &DownloadManager {
        &self.downloads
    }

    /// Accesses the authentication provider registry.
    #[must_use]
    pub fn auth(&self) -> &AuthManager {
        &self.auth
    }

    /// Accesses official Minecraft metadata, installation, and launch.
    #[must_use]
    pub fn minecraft(&self) -> &MinecraftManager {
        &self.minecraft
    }

    /// Accesses the multi-instance process registry.
    #[must_use]
    pub fn processes(&self) -> &ProcessManager {
        &self.processes
    }

    /// Accesses shared-cache status, verification, and pruning.
    #[must_use]
    pub fn cache(&self) -> &CacheManager {
        &self.cache
    }

    /// Accesses the persistent provider registry and static-provider pipeline.
    #[must_use]
    pub fn providers(&self) -> &ProviderManager {
        &self.providers
    }

    /// Accesses locally approved provider-signing public keys.
    #[must_use]
    pub fn trust(&self) -> &TrustStore {
        &self.trust
    }

    /// Accesses the shared event bus.
    #[must_use]
    pub fn events(&self) -> &EventBus {
        &self.events
    }

    /// Removes a managed Java runtime after proving no tracked Minecraft process uses it.
    pub async fn remove_java_runtime(&self, runtime_id: &str) -> Result<()> {
        let runtime = self.java.managed().verify(runtime_id).await?;
        if self
            .processes
            .is_executable_running(&runtime.runtime.executable)
            .await?
        {
            return Err(Error::Java("Java runtime is currently in use".into()));
        }
        self.java.managed().remove(runtime_id).await
    }
}

/// Builder for [`CentralCore`].
#[derive(Clone)]
pub struct CentralCoreBuilder {
    data_directory: PathBuf,
    config: Option<CoreConfig>,
    credential_store: Option<Arc<dyn CredentialStore>>,
}

impl std::fmt::Debug for CentralCoreBuilder {
    fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        formatter
            .debug_struct("CentralCoreBuilder")
            .field("data_directory", &self.data_directory)
            .field("config", &self.config)
            .field("custom_credential_store", &self.credential_store.is_some())
            .finish()
    }
}

impl Default for CentralCoreBuilder {
    fn default() -> Self {
        Self {
            data_directory: PathBuf::from(".centralcore"),
            config: None,
            credential_store: None,
        }
    }
}

impl CentralCoreBuilder {
    /// Selects the root used for config, instances, caches, and runtimes.
    #[must_use]
    pub fn data_dir(mut self, path: impl Into<PathBuf>) -> Self {
        self.data_directory = path.into();
        self.config = None;
        self
    }

    /// Uses an explicit already-constructed configuration.
    #[must_use]
    pub fn config(mut self, config: CoreConfig) -> Self {
        self.data_directory = config.data_directory.clone();
        self.config = Some(config);
        self
    }

    /// Overrides the native credential vault, primarily for tests or host integration.
    #[must_use]
    pub fn credential_store(mut self, store: Arc<dyn CredentialStore>) -> Self {
        self.credential_store = Some(store);
        self
    }

    /// Validates configuration, prepares the data layout, and wires services.
    pub async fn build(self) -> Result<CentralCore> {
        let config_path = self.data_directory.join("centralcore.json");
        let config = match self.config {
            Some(config) => config,
            None if tokio::fs::try_exists(&config_path).await? => {
                CoreConfig::load(&config_path).await?
            }
            None => CoreConfig::new(&self.data_directory),
        };
        config.validate()?;

        for directory in [
            config.data_directory.as_path(),
            &config.data_directory.join("instances"),
            &config.data_directory.join("cache"),
            &config.data_directory.join("runtimes"),
            &config.data_directory.join("minecraft"),
            &config.data_directory.join("processes"),
            &config.data_directory.join("locks"),
            &config.data_directory.join("providers"),
            &config.data_directory.join("auth"),
            &config.data_directory.join("trust"),
        ] {
            tokio::fs::create_dir_all(directory).await?;
        }
        if !tokio::fs::try_exists(&config_path).await? {
            config.save(&config_path).await?;
        }

        let events = EventBus::new(config.event_capacity);
        let trust = TrustStore::new(&config.data_directory, events.clone());
        let locks = lock::LockManager::new(config.data_directory.join("locks"));
        let instances = InstanceService::new(
            config.data_directory.join("instances"),
            events.clone(),
            locks.clone(),
        );
        let downloads = DownloadManager::new(config.download.clone(), events.clone())?
            .with_locks(locks.clone());
        let java = JavaManager::new(
            config.java.clone(),
            config.data_directory.join("runtimes").join("java"),
            config.data_directory.join("cache").join("java"),
            downloads.clone(),
            locks.clone(),
            events.clone(),
        );
        let loaders = LoaderManager::new(
            config.data_directory.join("minecraft"),
            downloads.clone(),
            java.clone(),
            events.clone(),
        );
        let processes =
            ProcessManager::new(config.data_directory.join("processes"), events.clone());
        let cache = CacheManager::new(
            config.data_directory.join("minecraft"),
            instances.clone(),
            locks.clone(),
            events.clone(),
            config.reliability.verify_concurrency,
        );
        let minecraft = MinecraftManager::new(
            &config.data_directory,
            config.minecraft.clone(),
            MinecraftServices {
                downloads: downloads.clone(),
                java: java.clone(),
                instances: instances.clone(),
                processes: processes.clone(),
                cache: cache.clone(),
                locks: locks.clone(),
                events: events.clone(),
                loaders: loaders.clone(),
            },
        );
        let providers = ProviderManager::new(
            &config.data_directory,
            config.providers.clone(),
            downloads.clone(),
            instances.clone(),
            minecraft.clone(),
            cache.clone(),
            locks,
            events.clone(),
            trust.clone(),
        );
        processes.recover().await?;
        minecraft.recover().await?;
        java.managed().recover().await?;
        let credential_store = self.credential_store.unwrap_or_else(|| {
            Arc::new(SystemCredentialStore::new("centralcore")) as Arc<dyn CredentialStore>
        });
        let auth = AuthManager::new(&config.data_directory, credential_store, events.clone());
        auth.register(Arc::new(OfflineAuthProvider)).await?;
        auth.load_configured().await?;
        auth.load_sessions().await?;

        Ok(CentralCore {
            config,
            events,
            instances,
            downloads,
            java,
            loaders,
            auth,
            minecraft,
            processes,
            cache,
            providers,
            trust,
        })
    }
}

/// Returns the conventional config file below a data directory.
#[must_use]
pub fn config_path(data_directory: impl AsRef<Path>) -> PathBuf {
    data_directory.as_ref().join("centralcore.json")
}

#[cfg(test)]
mod tests {
    use super::*;

    #[tokio::test]
    async fn builder_prepares_a_versioned_layout() {
        let temporary = tempfile::tempdir().expect("tempdir");
        let core = CentralCore::builder()
            .data_dir(temporary.path())
            .build()
            .await
            .expect("core");

        assert!(core.instances().root().is_dir());
        assert!(temporary.path().join("centralcore.json").is_file());
        assert_eq!(core.config().format_version, config::CONFIG_FORMAT_VERSION);
    }

    #[test]
    fn facade_is_clone_send_and_sync() {
        fn assert_traits<T: Clone + Send + Sync>() {}
        assert_traits::<CentralCore>();
        assert_traits::<CentralCoreBuilder>();
    }

    #[tokio::test]
    async fn two_cores_share_one_data_directory_without_duplicate_creation() {
        let temporary = tempfile::tempdir().expect("tempdir");
        let first = CentralCore::builder()
            .data_dir(temporary.path())
            .build()
            .await
            .expect("first core");
        let second = CentralCore::builder()
            .data_dir(temporary.path())
            .build()
            .await
            .expect("second core");
        let left = first
            .instances()
            .create(InstanceSpec::vanilla("shared", "Shared", "1.21.1").expect("left spec"));
        let right = second
            .instances()
            .create(InstanceSpec::vanilla("shared", "Shared", "1.21.1").expect("right spec"));
        let (left, right) = tokio::join!(left, right);
        assert_ne!(left.is_ok(), right.is_ok());
        assert_eq!(first.instances().list().await.expect("list").len(), 1);
    }
}