diff --git a/crates/coa-core/src/console.rs b/crates/coa-core/src/console.rs new file mode 100644 index 0000000..776244e --- /dev/null +++ b/crates/coa-core/src/console.rs @@ -0,0 +1,145 @@ +//! Console: read-only views of the server logs and a guarded way to send a command to the world server. + +use std::fs::File; +use std::io::{Read, Seek, SeekFrom}; +use std::path::{Path, PathBuf}; + +use serde::{Deserialize, Serialize}; + +use crate::error::{Error, Result}; + +#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "lowercase")] +pub enum Source { + World, + Auth, + Database, + Manager, +} + +pub fn log_path(root: &Path, manager_log: &Path, source: Source) -> PathBuf { + match source { + Source::World => root.join("Core/Logs/Server.log"), + Source::Auth => root.join("Core/Logs/Auth.log"), + Source::Database => root.join("mysql/logs/mysql-error.log"), + Source::Manager => manager_log.to_path_buf(), + } +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)] +#[serde(rename_all = "lowercase")] +pub enum Level { + Info, + Warn, + Error, +} + +#[derive(Debug, Clone, Serialize)] +pub struct Line { + pub text: String, + pub level: Level, +} + +fn classify(l: &str) -> Level { + let u = l.to_ascii_uppercase(); + if u.contains(" FATAL ") || u.contains(" ERROR ") || u.contains("[ERROR]") || u.contains("ERROR:") { + Level::Error + } else if u.contains(" WARN ") || u.contains("[WARNING]") || u.contains(" WARNING ") { + Level::Warn + } else { + Level::Info + } +} + +/// The last `max_lines` lines (after filtering) from the last ~512 KB of a log. Works on multi-gigabyte files. +pub fn tail(path: &Path, filter: Option<&str>, max_lines: usize) -> Result> { + const WINDOW: u64 = 512 * 1024; + let mut f = File::open(path).map_err(|_| Error::Invalid("This log does not exist yet.".into()))?; + let len = f.metadata()?.len(); + let start = len.saturating_sub(WINDOW); + f.seek(SeekFrom::Start(start))?; + let mut buf = Vec::new(); + f.take(WINDOW).read_to_end(&mut buf)?; + let text = String::from_utf8_lossy(&buf); + let mut lines: Vec<&str> = text.lines().collect(); + if start > 0 && !lines.is_empty() { + lines.remove(0); // a partial first line + } + let needle = filter.map(str::to_lowercase).filter(|n| !n.is_empty()); + let out: Vec = lines + .into_iter() + .filter(|l| needle.as_ref().map(|n| l.to_lowercase().contains(n)).unwrap_or(true)) + .map(|l| Line { level: classify(l), text: crate::diag::redact(l) }) + .collect(); + let skip = out.len().saturating_sub(max_lines); + Ok(out.into_iter().skip(skip).collect()) +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)] +#[serde(rename_all = "lowercase")] +pub enum Risk { + Normal, + /// Can shut things down, delete or change many records: needs an explicit confirmation. + Dangerous, +} + +/// Commands that must never run without confirmation. +pub fn risk(command: &str) -> Risk { + let c = command.trim().trim_start_matches('.').to_lowercase(); + const DANGEROUS: [&str; 14] = [ + "server shutdown", "server exit", "server restart", "account delete", "character delete", "character erase", "reset ", "ban ", "unban ", "deleted ", "server idlerestart", "server idleshutdown", "account set password", "reload ", + ]; + if DANGEROUS.iter().any(|d| c.starts_with(d)) { + Risk::Dangerous + } else { + Risk::Normal + } +} + +/// Validate a command before it goes to the console: one line, printable, bounded. +pub fn check_command(command: &str) -> Result<&str> { + let c = command.trim(); + if c.is_empty() || c.len() > 500 || c.contains(['\r', '\n', '\0']) { + return Err(Error::Invalid("Enter a single command.".into())); + } + Ok(c) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn tail_reads_the_end_of_a_big_file_filters_and_classifies() { + let d = tempfile::tempdir().unwrap(); + let p = d.path().join("Server.log"); + let mut s = String::new(); + for i in 0..40_000 { + s.push_str(&format!("2026-09-30 10:00:00 INFO [x] line {i}\n")); + } + s.push_str("2026-09-30 10:01:00 ERROR [sql] boom password=abc\n2026-09-30 10:01:01 WARN [x] careful\n"); + std::fs::write(&p, s).unwrap(); + let all = tail(&p, None, 5).unwrap(); + assert_eq!(all.len(), 5); + assert_eq!(all[3].level, Level::Error); + assert!(!all[3].text.contains("abc"), "secret-looking lines are redacted"); + assert_eq!(all[4].level, Level::Warn); + let f = tail(&p, Some("CAREFUL"), 100).unwrap(); + assert_eq!(f.len(), 1); + assert!(tail(&d.path().join("missing.log"), None, 5).is_err()); + } + + #[test] + fn dangerous_commands_are_recognised_and_input_is_validated() { + for c in ["server shutdown 10", ".account delete bob", "character delete x", "reset talents", "ban account x 1d y", "reload all"] { + assert_eq!(risk(c), Risk::Dangerous, "{c}"); + } + for c in ["server info", ".account onlinelist", "lookup item sword"] { + assert_eq!(risk(c), Risk::Normal, "{c}"); + } + assert!(check_command("server info").is_ok()); + for bad in ["", " ", "a\nb", "a\rb", &"x".repeat(501)] { + assert!(check_command(bad).is_err()); + } + } +} diff --git a/crates/coa-core/src/lib.rs b/crates/coa-core/src/lib.rs index eca7f0a..9b2a3be 100644 --- a/crates/coa-core/src/lib.rs +++ b/crates/coa-core/src/lib.rs @@ -2,6 +2,7 @@ pub mod backup; pub mod cleanbase; pub mod client; pub mod config; +pub mod console; pub mod db; pub mod diag; pub mod download; diff --git a/crates/coa-core/src/ra.rs b/crates/coa-core/src/ra.rs index 8dc289f..933b11e 100644 --- a/crates/coa-core/src/ra.rs +++ b/crates/coa-core/src/ra.rs @@ -64,6 +64,12 @@ impl Ra { Ok(Ra { stream }) } + /// Send one already-validated console command and return its output. + pub fn run(&mut self, cmd: &str) -> Result { + let c = crate::console::check_command(cmd)?; + self.command(c) + } + fn command(&mut self, cmd: &str) -> Result { debug_assert!(!cmd.contains(['\r', '\n'])); self.stream.write_all(format!("{cmd}\r\n").as_bytes())?; diff --git a/src-tauri/src/lib.rs b/src-tauri/src/lib.rs index df620be..e56bf4d 100644 --- a/src-tauri/src/lib.rs +++ b/src-tauri/src/lib.rs @@ -751,6 +751,42 @@ async fn export_diagnostics(state: State<'_, AppState>, id: String) -> std::resu } +#[tauri::command] +async fn console_tail( + state: State<'_, AppState>, + id: String, + source: coa_core::console::Source, + filter: Option, + lines: Option, +) -> std::result::Result, UiError> { + let root = path_of(&state, &id)?; + blocking(move || { + let path = coa_core::console::log_path(&root, &data_dir().join("logs").join("manager.log"), source); + coa_core::console::tail(&path, filter.as_deref(), lines.unwrap_or(300).min(2000)) + }) + .await +} + +#[tauri::command] +fn console_risk(command: String) -> coa_core::console::Risk { + coa_core::console::risk(&command) +} + +/// Send one command to the world server console. Risky commands need `confirmed`. +#[tauri::command] +async fn console_command(state: State<'_, AppState>, id: String, command: String, confirmed: bool) -> std::result::Result { + let root = path_of(&state, &id)?; + blocking(move || { + let c = coa_core::console::check_command(&command)?.to_string(); + if coa_core::console::risk(&c) == coa_core::console::Risk::Dangerous && !confirmed { + return Err(Error::Invalid("This command can shut things down or change many records. Confirm it first.".into())); + } + tracing::info!(command = %c, "console command"); + Ra::connect(&root)?.run(&c) + }) + .await +} + pub fn run() { let dir = data_dir(); let _ = coa_core::logging::init(&dir.join("logs").join("manager.log")); @@ -800,7 +836,10 @@ pub fn run() { friends_package, run_diagnostics, verify_files, - export_diagnostics + export_diagnostics, + console_tail, + console_risk, + console_command ]) .run(tauri::generate_context!()) .expect("error while running CoA Server Manager"); diff --git a/src/lib/api.ts b/src/lib/api.ts index a46483c..9a7423c 100644 --- a/src/lib/api.ts +++ b/src/lib/api.ts @@ -243,6 +243,12 @@ export interface DiagCheck { detail: string; } +export type ConsoleSource = "world" | "auth" | "database" | "manager"; +export interface ConsoleLine { + text: string; + level: "info" | "warn" | "error"; +} + export const api = { defaultInstallDir: () => invoke("default_install_dir"), scan: (path: string) => invoke("scan_server", { path }), @@ -287,6 +293,10 @@ export const api = { runDiagnostics: (id: string) => invoke<{ checks: DiagCheck[]; problems: number }>("run_diagnostics", { id }), verifyFiles: (id: string) => invoke<{ path: string; kind: "missing" | "changed" }[]>("verify_files", { id }), exportDiagnostics: (id: string) => invoke("export_diagnostics", { id }), + consoleTail: (id: string, source: ConsoleSource, filter?: string, lines = 300) => + invoke("console_tail", { id, source, filter: filter ?? null, lines }), + consoleRisk: (command: string) => invoke<"normal" | "dangerous">("console_risk", { command }), + consoleCommand: (id: string, command: string, confirmed: boolean) => invoke("console_command", { id, command, confirmed }), previewPreset: (id: string, scope: Scope, preset: string) => invoke("preview_preset", { id, scope, preset }), }; diff --git a/src/screens/ConsolePage.tsx b/src/screens/ConsolePage.tsx new file mode 100644 index 0000000..a7d32e1 --- /dev/null +++ b/src/screens/ConsolePage.tsx @@ -0,0 +1,125 @@ +import { useCallback, useEffect, useRef, useState } from "react"; +import { api, asUiError, type ConsoleLine, type ConsoleSource, type UiError } from "@/lib/api"; +import { cn } from "@/lib/utils"; +import { Button } from "@/components/ui/button"; +import { Card } from "@/components/ui/card"; + +const TABS: { id: ConsoleSource; label: string }[] = [ + { id: "world", label: "World" }, + { id: "auth", label: "Auth" }, + { id: "database", label: "Database" }, + { id: "manager", label: "Manager" }, +]; + +const TONE = { info: "text-ink/80", warn: "text-warn", error: "text-bad" } as const; + +export function ConsolePage({ serverId }: { serverId: string }) { + const [tab, setTab] = useState("world"); + const [filter, setFilter] = useState(""); + const [lines, setLines] = useState([]); + const [live, setLive] = useState(true); + const [missing, setMissing] = useState(null); + const [cmd, setCmd] = useState(""); + const [reply, setReply] = useState(null); + const [error, setError] = useState(null); + const [copied, setCopied] = useState(false); + const box = useRef(null); + + const load = useCallback(async () => { + try { + setLines(await api.consoleTail(serverId, tab, filter || undefined)); + setMissing(null); + } catch (e) { + setLines([]); + setMissing(asUiError(e).technical); + } + }, [serverId, tab, filter]); + + useEffect(() => { + void load(); + if (!live) return; + const t = setInterval(load, 2000); + return () => clearInterval(t); + }, [load, live]); + + useEffect(() => { + if (live && box.current) box.current.scrollTop = box.current.scrollHeight; + }, [lines, live]); + + async function send() { + setError(null); + setReply(null); + try { + const risk = await api.consoleRisk(cmd); + if (risk === "dangerous" && !window.confirm(`“${cmd}” can shut things down or change many records. Send it anyway?`)) return; + setReply((await api.consoleCommand(serverId, cmd, risk === "dangerous")) || "(no output)"); + setCmd(""); + } catch (e) { + setError(asUiError(e)); + } + } + + const errors = lines.filter((l) => l.level === "error").map((l) => l.text); + + return ( +
+

Console

+

What is the server doing?

+ +
+
+ {TABS.map((t) => ( + + ))} +
+ setFilter(e.target.value)} + className="ml-auto w-56 rounded-md border border-line bg-bg px-3 py-1.5 text-sm outline-none focus:border-gold" + /> + + +
+ +
+ {missing ?

{missing}

: lines.length === 0 ?

Nothing to show.

: lines.map((l, i) => ( +
+ {l.level !== "info" && {l.level}: } + {l.text} +
+ ))} +
+ + {tab === "world" && ( + +

Commands go straight to the running world server. Risky ones (shutdown, deleting or banning) ask for confirmation.

+
{ e.preventDefault(); void send(); }}> + setCmd(e.target.value)} placeholder="server info" className="selectable flex-1 rounded-md border border-line bg-bg px-3 py-2 font-mono text-sm outline-none focus:border-gold" /> + +
+ {reply &&
{reply}
} + {error &&

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

} +
+ )} +
+ ); +} diff --git a/src/screens/Shell.tsx b/src/screens/Shell.tsx index 007fac3..764f270 100644 --- a/src/screens/Shell.tsx +++ b/src/screens/Shell.tsx @@ -9,6 +9,7 @@ import { BackupsPage } from "@/screens/BackupsPage"; import { PlayersPage } from "@/screens/PlayersPage"; import { SettingsHome } from "@/screens/SettingsHome"; import { FriendsPage } from "@/screens/FriendsPage"; +import { ConsolePage } from "@/screens/ConsolePage"; import { Button } from "@/components/ui/button"; type Page = "overview" | "bots" | "server" | "players" | "friends" | "backups" | "console" | "settings"; @@ -83,6 +84,8 @@ export function Shell(props: { props.onForget(server.id)} /> ) : page === "bots" || page === "server" ? ( + ) : page === "console" ? ( + ) : page === "friends" ? ( ) : page === "settings" ? (