diff --git a/crates/coa-core/examples/mkpkg.rs b/crates/coa-core/examples/mkpkg.rs new file mode 100644 index 0000000..6aef704 --- /dev/null +++ b/crates/coa-core/examples/mkpkg.rs @@ -0,0 +1,25 @@ +//! Build and sign a small update package. usage: mkpkg ... +use base64::{engine::general_purpose::STANDARD, Engine}; +use coa_core::manifest::Kind; +use coa_core::package::{build, BuildOptions}; +use ed25519_dalek::{Signer, SigningKey}; + +fn main() { + let a: Vec = std::env::args().skip(1).collect(); + let out = std::path::PathBuf::from(&a[0]); + let src = out.with_file_name(format!("{}-src", out.file_name().unwrap().to_string_lossy())); + let _ = std::fs::remove_dir_all(&src); + let _ = std::fs::remove_dir_all(&out); + for spec in &a[2..] { + let (p, c) = spec.split_once('=').expect("path=content"); + let f = src.join(p); + std::fs::create_dir_all(f.parent().unwrap()).unwrap(); + std::fs::write(f, c.replace("\n", "\n")).unwrap(); + } + build(&src, &out, &BuildOptions { kind: Kind::Update, version: a[1].clone(), core_commit: None, built_at: chrono::Utc::now().to_rfc3339(), part_size: 1 << 20 }, &|_| {}).unwrap(); + let key = format!("{}/.coa-manager/signing/manifest-signing.key", std::env::var("USERPROFILE").unwrap()); + let seed: [u8; 32] = STANDARD.decode(std::fs::read_to_string(key).unwrap().trim()).unwrap().try_into().unwrap(); + let sig = SigningKey::from_bytes(&seed).sign(&std::fs::read(out.join("manifest.json")).unwrap()); + std::fs::write(out.join("manifest.json.sig"), STANDARD.encode(sig.to_bytes())).unwrap(); + println!("package {} at {}", a[1], out.display()); +} diff --git a/src-tauri/src/lib.rs b/src-tauri/src/lib.rs index 13dfef4..0ab7b59 100644 --- a/src-tauri/src/lib.rs +++ b/src-tauri/src/lib.rs @@ -11,6 +11,7 @@ use coa_core::download::Cancel; use coa_core::driver::{self, DriverOutcome, Verb}; use coa_core::install::{self, Preflight, Source}; use coa_core::ra::Ra; +use coa_core::update::{self, Resolution}; use coa_core::error::UiError; use coa_core::layout::{self, Classification, ScanReport}; use coa_core::process::{self, Observed}; @@ -30,6 +31,18 @@ struct AppState { } /// Where official server packages are published (created by the release pipeline, Phase 6). +/// Where signed update packages are published; override with COA_UPDATE_SOURCE (URL or local package folder). +const DEFAULT_UPDATE_URL: &str = "https://github.com/Corfirean/coa-server-build/releases/latest/download"; + +fn update_source(custom: Option) -> Source { + let pick = custom.filter(|s| !s.trim().is_empty()).or_else(|| std::env::var("COA_UPDATE_SOURCE").ok()); + match pick { + Some(p) if p.to_ascii_lowercase().starts_with("http") => Source::Url(p), + Some(p) => Source::Dir(PathBuf::from(p)), + None => Source::Url(DEFAULT_UPDATE_URL.into()), + } +} + const DEFAULT_PACKAGE_URL: &str = "https://github.com/Corfirean/coa-server-build/releases/latest/download"; fn package_source(custom: Option) -> Source { @@ -383,6 +396,73 @@ async fn create_account(state: State<'_, AppState>, id: String, username: String .await } +fn install_meta(root: &std::path::Path) -> Result<(PathBuf, InstallMeta)> { + let dir = meta_dir(root)?; + let (_, meta) = MetaDir::open(&dir)?; + Ok((dir, meta)) +} + +#[tauri::command] +async fn check_update(state: State<'_, AppState>, id: String, source: Option) -> std::result::Result { + let root = path_of(&state, &id)?; + let src = update_source(source); + blocking(move || { + let (_, meta) = install_meta(&root)?; + update::preview(&root, &meta, &src, coa_core::signing::EMBEDDED_PUBLIC_KEY, &Default::default()) + }) + .await +} + +#[tauri::command] +fn pending_update(state: State<'_, AppState>, id: String) -> std::result::Result, UiError> { + let root = path_of(&state, &id)?; + Ok(update::unfinished(&meta_dir(&root)?)) +} + +#[tauri::command] +async fn apply_update( + app: AppHandle, + state: State<'_, AppState>, + id: String, + source: Option, + resolutions: BTreeMap, +) -> std::result::Result { + let root = path_of(&state, &id)?; + let src = update_source(source); + let _guard = BusyGuard::acquire(&state, &id)?; + blocking(move || { + let (dir, _) = install_meta(&root)?; + // Files cannot be replaced while the server runs: stop it first (gracefully), like the Stop button. + let observed = coa_core::process::observe(&root, &layout::read_ports(&root)); + if observed.world.state != coa_core::process::ServiceState::Stopped || observed.auth.state != coa_core::process::ServiceState::Stopped { + let out = driver::run(&root, Verb::StopAll)?; + if !out.ok { + return Err(Error::Invalid("The server could not be stopped, so the update was not started.".into())); + } + } + let env = update::RepackEnv { root: &root, meta_dir: &dir }; + update::apply( + &update::Params { root: &root, meta_dir: &dir, source: src, trusted_key: coa_core::signing::EMBEDDED_PUBLIC_KEY, cancel: Cancel::default(), resolutions, env: &env, fail_after_ops: None }, + &|step, percent| { + let _ = app.emit("update-progress", serde_json::json!({ "step": step, "percent": percent })); + }, + ) + }) + .await +} + +#[tauri::command] +async fn rollback_update(state: State<'_, AppState>, id: String, txn: String) -> std::result::Result { + let root = path_of(&state, &id)?; + let _guard = BusyGuard::acquire(&state, &id)?; + blocking(move || { + let dir = meta_dir(&root)?; + let env = update::RepackEnv { root: &root, meta_dir: &dir }; + update::rollback(&root, &dir, &txn, &env) + }) + .await +} + pub fn run() { let dir = data_dir(); let _ = coa_core::logging::init(&dir.join("logs").join("manager.log")); @@ -413,7 +493,11 @@ pub fn run() { install_preflight, install_new, cancel_install, - create_account + create_account, + check_update, + pending_update, + apply_update, + rollback_update ]) .run(tauri::generate_context!()) .expect("error while running CoA Server Manager"); diff --git a/src/lib/api.ts b/src/lib/api.ts index c99bd9f..9a0053f 100644 --- a/src/lib/api.ts +++ b/src/lib/api.ts @@ -173,6 +173,30 @@ export interface InstallStep { detail: string | null; } +export interface UpdatePlanItem { + path: string; + action: "create" | "replace" | "merge-config" | "skip" | "conflict"; + reason: string | null; +} + +export interface UpdatePreview { + from_version: string | null; + to_version: string; + items: UpdatePlanItem[]; + conflicts: string[]; + migrations: number; + download_bytes: number; +} + +export interface UpdateTxn { + id: string; + state: "prepared" | "applying" | "applied" | "needs-decision" | "committed" | "rolled-back" | "failed"; + from_version: string | null; + to_version: string; + recovery_point: string | null; + message: string | null; +} + export const api = { defaultInstallDir: () => invoke("default_install_dir"), scan: (path: string) => invoke("scan_server", { path }), @@ -196,6 +220,11 @@ export const api = { cancelInstall: () => invoke("cancel_install"), createAccount: (id: string, username: string, password: string, administrator: boolean) => invoke("create_account", { id, username, password, administrator }), + checkUpdate: (id: string, source?: string) => invoke("check_update", { id, source: source ?? null }), + pendingUpdate: (id: string) => invoke("pending_update", { id }), + applyUpdate: (id: string, resolutions: Record, source?: string) => + invoke<{ txn: UpdateTxn }>("apply_update", { id, source: source ?? null, resolutions }), + rollbackUpdate: (id: string, txn: string) => invoke("rollback_update", { id, txn }), previewPreset: (id: string, scope: Scope, preset: string) => invoke("preview_preset", { id, scope, preset }), }; diff --git a/src/screens/SettingsHome.tsx b/src/screens/SettingsHome.tsx new file mode 100644 index 0000000..c3ef4b4 --- /dev/null +++ b/src/screens/SettingsHome.tsx @@ -0,0 +1,194 @@ +import { useEffect, useState } from "react"; +import { listen } from "@tauri-apps/api/event"; +import { open } from "@tauri-apps/plugin-dialog"; +import { ChevronDown, ChevronRight, Loader2 } from "lucide-react"; +import { api, asUiError, type UiError, type UpdatePreview, type UpdateTxn } from "@/lib/api"; +import { Button } from "@/components/ui/button"; +import { Card } from "@/components/ui/card"; + +const ACTION_TEXT: Record = { + create: "New file", + replace: "Updated", + "merge-config": "New settings added", + skip: "Unchanged", + conflict: "Needs your decision", +}; + +function mb(bytes: number) { + return bytes >= 1 << 20 ? `${(bytes / (1 << 20)).toFixed(1)} MB` : `${Math.max(1, Math.round(bytes / 1024))} KB`; +} + +export function SettingsHome({ serverId }: { serverId: string }) { + const [preview, setPreview] = useState(null); + const [pending, setPending] = useState(null); + const [busy, setBusy] = useState<"check" | "update" | "rollback" | null>(null); + const [progress, setProgress] = useState<{ step: string; percent: number } | null>(null); + const [error, setError] = useState(null); + const [done, setDone] = useState(null); + const [choices, setChoices] = useState>({}); + const [advanced, setAdvanced] = useState(false); + const [source, setSource] = useState(""); + + useEffect(() => { + void api.pendingUpdate(serverId).then(setPending).catch(() => {}); + const un = listen<{ step: string; percent: number }>("update-progress", (e) => setProgress(e.payload)); + return () => { + void un.then((f) => f()); + }; + }, [serverId]); + + async function check() { + setBusy("check"); + setError(null); + setDone(null); + setPreview(null); + try { + const p = await api.checkUpdate(serverId, source.trim() || undefined); + setPreview(p); + setChoices(Object.fromEntries(p.conflicts.map((c) => [c, "keep" as const]))); + } catch (e) { + setError(asUiError(e)); + } finally { + setBusy(null); + } + } + + async function update() { + setBusy("update"); + setError(null); + setProgress({ step: "Starting", percent: 0 }); + try { + const out = await api.applyUpdate(serverId, choices, source.trim() || undefined); + setPreview(null); + if (out.txn.state === "committed") setDone(`Updated to version ${out.txn.to_version}.`); + else setPending(out.txn); + } catch (e) { + setError(asUiError(e)); + } finally { + setBusy(null); + setProgress(null); + void api.pendingUpdate(serverId).then(setPending).catch(() => {}); + } + } + + async function rollback(t: UpdateTxn) { + if (!window.confirm("Go back to the previous version? Your characters and accounts are not changed.")) return; + setBusy("rollback"); + setError(null); + try { + await api.rollbackUpdate(serverId, t.id); + setPending(null); + setDone("Went back to the previous version. Your data was not touched."); + } catch (e) { + setError(asUiError(e)); + } finally { + setBusy(null); + } + } + + async function browse() { + const p = await open({ directory: true, multiple: false, title: "Choose an update package folder" }); + if (typeof p === "string") setSource(p); + } + + return ( +
+

Settings

+

How does Manager behave?

+ + {pending && ( + +

+ {pending.state === "needs-decision" ? "The updated server did not start correctly" : "An earlier update did not finish"} +

+

{pending.message ?? "You can safely go back to the previous version."}

+

Going back restores program files and settings. Characters and accounts are never rolled back automatically.

+ +
+ )} + + +

Server updates

+

Updates are checked for authenticity, backed up first, and can be undone.

+ +
+ + +
+ {advanced && ( +
+ setSource(e.target.value)} placeholder="Update package folder (leave empty to use the official source)" className="selectable flex-1 rounded-md border border-line bg-bg px-3 py-2 text-sm outline-none focus:border-gold" /> + +
+ )} + + {done &&

{done}

} + {error && ( +

+ {error.human.code === "unknown" ? error.technical : error.human.message} +

+ )} + + {preview && ( +
+

+ Version {preview.to_version} is available{preview.from_version ? ` (you have ${preview.from_version})` : ""} +

+

+ Download {mb(preview.download_bytes)} · {preview.items.filter((i) => i.action !== "skip").length} file(s) change + {preview.migrations > 0 ? ` · ${preview.migrations} database update(s)` : ""} +

+
    + {preview.items.filter((i) => i.action !== "skip").map((i) => ( +
  • +
    + {i.path} + {ACTION_TEXT[i.action]} +
    + {i.action === "conflict" && ( +
    + This file was modified outside CoA Server Manager + This file was modified outside CoA Server Manager. + {(["keep", "replace"] as const).map((c) => ( + + ))} +
    + )} +
  • + ))} +
+ +

The server is stopped during the update and started again to check that it works.

+
+ )} + + {busy === "update" && progress && ( +
+
+ {progress.step} + {progress.percent}% +
+
+
+
+
+ )} + +
+ ); +} diff --git a/src/screens/Shell.tsx b/src/screens/Shell.tsx index 970bf1c..dd51b13 100644 --- a/src/screens/Shell.tsx +++ b/src/screens/Shell.tsx @@ -7,6 +7,7 @@ import { Placeholder } from "@/screens/Placeholder"; import { SettingsPage } from "@/screens/SettingsPage"; import { BackupsPage } from "@/screens/BackupsPage"; import { PlayersPage } from "@/screens/PlayersPage"; +import { SettingsHome } from "@/screens/SettingsHome"; import { Button } from "@/components/ui/button"; type Page = "overview" | "bots" | "server" | "players" | "friends" | "backups" | "console" | "settings"; @@ -81,6 +82,8 @@ export function Shell(props: { props.onForget(server.id)} /> ) : page === "bots" || page === "server" ? ( + ) : page === "settings" ? ( + ) : page === "players" ? ( ) : page === "backups" ? (