horizon-server: the web panel
One page embedded in the binary (crates/horizon-server/panel: HTML, CSS and JS, no framework or CDN): status, live TPS, MSPT, RAM and CPU graphs over the last 10 minutes, players with op and kick, the console, and backups with restore, plus restart and stop. It listens on [panel] bind, 127.0.0.1:8130 by default; a tailnet address reaches it from the owner's devices, and any other address is refused unless allow_public is set. `horizon-server panel` prints a one-time login link (10 minutes) that becomes an HttpOnly, SameSite=Strict session cookie. The Host header must name the panel, every POST needs X-Horizon: 1, failed logins are rate-limited, and the page is served with a strict Content-Security-Policy. The control API gains GET /api/v1/metrics and, with the token only, POST /api/v1/panel/login. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
@@ -0,0 +1,78 @@
|
||||
<!doctype html>
|
||||
<html lang="en">
|
||||
<head>
|
||||
<meta charset="utf-8">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1">
|
||||
<meta name="referrer" content="no-referrer">
|
||||
<title>Horizon server</title>
|
||||
<link rel="stylesheet" href="/panel.css">
|
||||
<script src="/panel.js" defer></script>
|
||||
</head>
|
||||
<body>
|
||||
<header>
|
||||
<div class="title">
|
||||
<h1>Horizon server</h1>
|
||||
<span id="phase" class="pill">…</span>
|
||||
<span id="summary" class="muted"></span>
|
||||
</div>
|
||||
<div class="actions">
|
||||
<button id="restart" type="button">Restart</button>
|
||||
<button id="stop" type="button" class="danger">Stop</button>
|
||||
</div>
|
||||
</header>
|
||||
|
||||
<main id="app" hidden>
|
||||
<section class="charts" aria-label="Last 10 minutes">
|
||||
<figure><figcaption>TPS <b id="tps-now">–</b></figcaption><canvas id="tps" width="320" height="96"></canvas></figure>
|
||||
<figure><figcaption>MSPT <b id="mspt-now">–</b></figcaption><canvas id="mspt" width="320" height="96"></canvas></figure>
|
||||
<figure><figcaption>RAM <b id="ram-now">–</b></figcaption><canvas id="ram" width="320" height="96"></canvas></figure>
|
||||
<figure><figcaption>CPU <b id="cpu-now">–</b></figcaption><canvas id="cpu" width="320" height="96"></canvas></figure>
|
||||
</section>
|
||||
|
||||
<div class="columns">
|
||||
<section>
|
||||
<h2>Players <span id="player-count" class="muted"></span></h2>
|
||||
<table>
|
||||
<thead><tr><th>Name</th><th>Ping</th><th></th></tr></thead>
|
||||
<tbody id="players"></tbody>
|
||||
</table>
|
||||
<p id="no-players" class="muted">Nobody is online.</p>
|
||||
</section>
|
||||
|
||||
<section>
|
||||
<h2>Backups</h2>
|
||||
<form id="backup-form" class="row">
|
||||
<input id="backup-name" placeholder="Name (optional)" maxlength="40" pattern="[A-Za-z0-9_.\-]*" autocomplete="off">
|
||||
<button type="submit">Back up now</button>
|
||||
</form>
|
||||
<table>
|
||||
<thead><tr><th>Backup</th><th>Size</th><th></th></tr></thead>
|
||||
<tbody id="backups"></tbody>
|
||||
</table>
|
||||
<p id="no-backups" class="muted">No backups yet.</p>
|
||||
</section>
|
||||
</div>
|
||||
|
||||
<section>
|
||||
<h2>Console</h2>
|
||||
<pre id="log" tabindex="0" aria-live="off"></pre>
|
||||
<form id="command-form" class="row">
|
||||
<input id="command" placeholder="A console command, like list or say Hello" autocomplete="off" spellcheck="false">
|
||||
<button type="submit">Run</button>
|
||||
</form>
|
||||
</section>
|
||||
</main>
|
||||
|
||||
<main id="signed-out" class="message" hidden>
|
||||
<p>Sign in with a link from the server: run <code>horizon-server panel</code> in the server's folder and open
|
||||
the link it prints. Links work once, for 10 minutes.</p>
|
||||
</main>
|
||||
|
||||
<main id="gone" class="message" hidden>
|
||||
<p>The server isn't answering. It may have stopped: start it again with <code>horizon-server start</code>,
|
||||
then reload this page.</p>
|
||||
</main>
|
||||
|
||||
<div id="toast" role="status" hidden></div>
|
||||
</body>
|
||||
</html>
|
||||
@@ -0,0 +1,128 @@
|
||||
/* The Horizon server panel. Colours and spacing are horizon-theme's tokens (website/src/tokens.css). */
|
||||
:root {
|
||||
--page: #fafafc;
|
||||
--plate-soft: #f3f3f8;
|
||||
--plate: #ebecf4;
|
||||
--surface: #ffffff;
|
||||
--rule: #e2e3ea;
|
||||
--ink: #16181f;
|
||||
--ink-soft: #3b3e49;
|
||||
--muted: #646875;
|
||||
--accent: #5b3fd6;
|
||||
--on-accent: #ffffff;
|
||||
--danger: #b4372a;
|
||||
--success: #1d7a48;
|
||||
--font: "Geist", ui-sans-serif, system-ui, sans-serif;
|
||||
--mono: "Geist Mono", ui-monospace, monospace;
|
||||
--radius: 8px;
|
||||
--radius-plate: 12px;
|
||||
color-scheme: light;
|
||||
}
|
||||
@media (prefers-color-scheme: dark) {
|
||||
:root {
|
||||
--page: #0d0e13;
|
||||
--plate-soft: #181a22;
|
||||
--plate: #20222c;
|
||||
--surface: #16181f;
|
||||
--rule: #24262f;
|
||||
--ink: #ecedf3;
|
||||
--ink-soft: #c5c7d1;
|
||||
--muted: #8b8f9c;
|
||||
--accent: #9a86ff;
|
||||
--on-accent: #0d0e13;
|
||||
--danger: #f07a68;
|
||||
--success: #45c27a;
|
||||
color-scheme: dark;
|
||||
}
|
||||
}
|
||||
|
||||
* { box-sizing: border-box; }
|
||||
[hidden] { display: none !important; }
|
||||
body {
|
||||
margin: 0;
|
||||
background: var(--page);
|
||||
color: var(--ink);
|
||||
font: 14px/1.5 var(--font);
|
||||
}
|
||||
header {
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
gap: 12px;
|
||||
align-items: center;
|
||||
justify-content: space-between;
|
||||
padding: 16px 24px;
|
||||
border-bottom: 1px solid var(--rule);
|
||||
background: var(--surface);
|
||||
}
|
||||
.title { display: flex; flex-wrap: wrap; gap: 12px; align-items: baseline; }
|
||||
h1 { font-size: 18px; font-weight: 500; margin: 0; letter-spacing: -0.01em; }
|
||||
h2 { font-size: 13px; font-weight: 500; margin: 0 0 8px; color: var(--ink-soft); }
|
||||
main { padding: 24px; max-width: 1200px; margin: 0 auto; display: grid; gap: 24px; }
|
||||
section { background: var(--surface); border: 1px solid var(--rule); border-radius: var(--radius-plate); padding: 16px; }
|
||||
.muted { color: var(--muted); }
|
||||
.pill {
|
||||
font-size: 12px;
|
||||
padding: 2px 10px;
|
||||
border-radius: 999px;
|
||||
background: var(--plate);
|
||||
color: var(--ink-soft);
|
||||
}
|
||||
.pill.running { background: color-mix(in srgb, var(--success) 18%, transparent); color: var(--success); }
|
||||
.pill.stopping, .pill.restarting, .pill.starting { background: color-mix(in srgb, var(--accent) 16%, transparent); color: var(--accent); }
|
||||
.pill.down { background: color-mix(in srgb, var(--danger) 16%, transparent); color: var(--danger); }
|
||||
|
||||
.charts { display: grid; grid-template-columns: repeat(auto-fit, minmax(220px, 1fr)); gap: 16px; }
|
||||
figure { margin: 0; }
|
||||
figcaption { font-size: 12px; color: var(--muted); display: flex; justify-content: space-between; }
|
||||
figcaption b { color: var(--ink); font-weight: 500; font-variant-numeric: tabular-nums; }
|
||||
canvas { width: 100%; height: 96px; display: block; }
|
||||
|
||||
.columns { display: grid; grid-template-columns: repeat(auto-fit, minmax(320px, 1fr)); gap: 24px; }
|
||||
table { width: 100%; border-collapse: collapse; font-variant-numeric: tabular-nums; }
|
||||
th { text-align: left; font-weight: 400; font-size: 12px; color: var(--muted); padding: 4px 0; }
|
||||
td { padding: 6px 0; border-top: 1px solid var(--rule); }
|
||||
td:last-child { text-align: right; white-space: nowrap; }
|
||||
td button { margin-left: 4px; }
|
||||
|
||||
button, input {
|
||||
font: inherit;
|
||||
height: 32px;
|
||||
border-radius: var(--radius);
|
||||
border: 1px solid var(--rule);
|
||||
background: var(--plate-soft);
|
||||
color: var(--ink);
|
||||
padding: 0 12px;
|
||||
}
|
||||
button { cursor: pointer; }
|
||||
button:hover { background: var(--plate); }
|
||||
button:disabled { opacity: 0.5; cursor: default; }
|
||||
button[type="submit"] { background: var(--accent); border-color: var(--accent); color: var(--on-accent); }
|
||||
button.danger { color: var(--danger); }
|
||||
input { background: var(--surface); flex: 1; min-width: 0; }
|
||||
input:focus, button:focus-visible { outline: 2px solid var(--accent); outline-offset: 1px; }
|
||||
.row { display: flex; gap: 8px; margin: 8px 0; }
|
||||
|
||||
pre {
|
||||
font: 12px/1.5 var(--mono);
|
||||
background: var(--plate-soft);
|
||||
border-radius: var(--radius);
|
||||
padding: 12px;
|
||||
margin: 0;
|
||||
height: 320px;
|
||||
overflow: auto;
|
||||
white-space: pre-wrap;
|
||||
word-break: break-word;
|
||||
}
|
||||
.message { max-width: 560px; }
|
||||
code { font-family: var(--mono); font-size: 13px; }
|
||||
#toast {
|
||||
position: fixed;
|
||||
bottom: 24px;
|
||||
left: 50%;
|
||||
transform: translateX(-50%);
|
||||
background: var(--ink);
|
||||
color: var(--page);
|
||||
padding: 8px 16px;
|
||||
border-radius: var(--radius);
|
||||
max-width: 90vw;
|
||||
}
|
||||
@@ -0,0 +1,270 @@
|
||||
// The Horizon server panel (docs/server.md, section 6). It polls the control API once a second through
|
||||
// the panel's session; every change is a POST with the X-Horizon header. Text from the server is only
|
||||
// ever set with textContent.
|
||||
"use strict";
|
||||
|
||||
const $ = (id) => document.getElementById(id);
|
||||
let logNext = 0;
|
||||
let metricsSince = 0;
|
||||
const samples = [];
|
||||
let lastStatus = null;
|
||||
let backupsShown = "";
|
||||
|
||||
class SignedOut extends Error {}
|
||||
|
||||
async function api(method, path, body) {
|
||||
let response;
|
||||
try {
|
||||
response = await fetch(path, {
|
||||
method,
|
||||
credentials: "same-origin",
|
||||
headers: { "X-Horizon": "1", "Content-Type": "application/json" },
|
||||
body: body === undefined ? undefined : JSON.stringify(body),
|
||||
});
|
||||
} catch (e) {
|
||||
throw new Error("the server isn't answering");
|
||||
}
|
||||
if (response.status === 401) throw new SignedOut();
|
||||
const value = await response.json().catch(() => ({}));
|
||||
if (!response.ok) throw new Error(value.error || `error ${response.status}`);
|
||||
return value;
|
||||
}
|
||||
|
||||
function show(view) {
|
||||
for (const id of ["app", "signed-out", "gone"]) $(id).hidden = id !== view;
|
||||
for (const id of ["restart", "stop"]) $(id).disabled = view !== "app";
|
||||
}
|
||||
|
||||
let toastTimer;
|
||||
function toast(text) {
|
||||
$("toast").textContent = text;
|
||||
$("toast").hidden = false;
|
||||
clearTimeout(toastTimer);
|
||||
toastTimer = setTimeout(() => ($("toast").hidden = true), 5000);
|
||||
}
|
||||
|
||||
function duration(seconds) {
|
||||
if (seconds == null) return "";
|
||||
const d = Math.floor(seconds / 86400), h = Math.floor(seconds / 3600) % 24, m = Math.floor(seconds / 60) % 60;
|
||||
if (d) return `${d} d ${h} h`;
|
||||
if (h) return `${h} h ${m} min`;
|
||||
return m ? `${m} min` : `${seconds} s`;
|
||||
}
|
||||
|
||||
function bytes(n) {
|
||||
if (n == null) return "–";
|
||||
if (n >= 1e9) return `${(n / 1e9).toFixed(2)} GB`;
|
||||
if (n >= 1e6) return `${(n / 1e6).toFixed(1)} MB`;
|
||||
return `${Math.ceil(n / 1e3)} kB`;
|
||||
}
|
||||
|
||||
function cell(text) {
|
||||
const td = document.createElement("td");
|
||||
td.textContent = text;
|
||||
return td;
|
||||
}
|
||||
|
||||
function button(label, action, danger) {
|
||||
const b = document.createElement("button");
|
||||
b.type = "button";
|
||||
b.textContent = label;
|
||||
if (danger) b.className = "danger";
|
||||
b.addEventListener("click", action);
|
||||
return b;
|
||||
}
|
||||
|
||||
async function run(line) {
|
||||
const reply = await api("POST", "/api/v1/command", { line });
|
||||
return (reply.output || []).join("\n");
|
||||
}
|
||||
|
||||
function renderStatus(status) {
|
||||
lastStatus = status;
|
||||
const phase = $("phase");
|
||||
phase.textContent = status.phase;
|
||||
phase.className = `pill ${status.phase}`;
|
||||
const game = status.sample && status.sample.game;
|
||||
const parts = [`up ${duration(status.engine_uptime_seconds)}`, `horizon-server ${status.version}`];
|
||||
if (status.crashes) parts.push(`${status.crashes} crash${status.crashes > 1 ? "es" : ""}`);
|
||||
$("summary").textContent = parts.join(" · ");
|
||||
|
||||
const players = (game && game.players) || [];
|
||||
$("player-count").textContent = game ? `${players.length} of ${game.max_players}` : "";
|
||||
$("no-players").hidden = players.length > 0;
|
||||
const body = $("players");
|
||||
body.replaceChildren(
|
||||
...players.map((p) => {
|
||||
const tr = document.createElement("tr");
|
||||
const actions = cell("");
|
||||
actions.append(
|
||||
button("Op", async () => toast(await run(`op ${p.name}`).catch((e) => e.message))),
|
||||
button("Kick", async () => {
|
||||
if (confirm(`Kick ${p.name}?`)) toast(await run(`kick ${p.name}`).catch((e) => e.message));
|
||||
}, true),
|
||||
);
|
||||
tr.append(cell(p.name), cell(p.ping_ms == null ? "–" : `${p.ping_ms} ms`), actions);
|
||||
return tr;
|
||||
}),
|
||||
);
|
||||
}
|
||||
|
||||
function renderBackups(list) {
|
||||
const key = JSON.stringify(list);
|
||||
if (key === backupsShown) return;
|
||||
backupsShown = key;
|
||||
$("no-backups").hidden = list.length > 0;
|
||||
$("backups").replaceChildren(
|
||||
...list.map((b) => {
|
||||
const tr = document.createElement("tr");
|
||||
const actions = cell("");
|
||||
actions.append(
|
||||
button("Restore", async () => {
|
||||
if (!confirm(`Restore ${b.name}? The server restarts with that world; the current one is kept in backups/.`)) return;
|
||||
try {
|
||||
await api("POST", "/api/v1/restore", { name: b.name });
|
||||
toast(`Restoring ${b.name}: the server is restarting.`);
|
||||
} catch (e) {
|
||||
toast(e.message);
|
||||
}
|
||||
}, true),
|
||||
);
|
||||
tr.append(cell(b.name), cell(bytes(b.bytes)), actions);
|
||||
return tr;
|
||||
}),
|
||||
);
|
||||
}
|
||||
|
||||
function appendLog(lines) {
|
||||
if (!lines.length) return;
|
||||
const log = $("log");
|
||||
const atBottom = log.scrollTop + log.clientHeight >= log.scrollHeight - 8;
|
||||
log.append(document.createTextNode(lines.join("\n") + "\n"));
|
||||
// Keep the page light: the last 2000 lines, as the server does.
|
||||
const text = log.textContent;
|
||||
const all = text.split("\n");
|
||||
if (all.length > 2100) log.textContent = all.slice(-2000).join("\n");
|
||||
if (atBottom) log.scrollTop = log.scrollHeight;
|
||||
}
|
||||
|
||||
function chart(id, values, { max, unit, line, decimals = 1 }) {
|
||||
const canvas = $(id);
|
||||
const ratio = window.devicePixelRatio || 1;
|
||||
const width = canvas.clientWidth, height = canvas.clientHeight;
|
||||
if (canvas.width !== width * ratio) {
|
||||
canvas.width = width * ratio;
|
||||
canvas.height = height * ratio;
|
||||
}
|
||||
const g = canvas.getContext("2d");
|
||||
g.setTransform(ratio, 0, 0, ratio, 0, 0);
|
||||
g.clearRect(0, 0, width, height);
|
||||
const style = getComputedStyle(document.documentElement);
|
||||
const known = values.filter((v) => v != null);
|
||||
const top = Math.max(max || 0, ...known, 1e-9) * 1.1;
|
||||
if (line != null) {
|
||||
g.strokeStyle = style.getPropertyValue("--rule");
|
||||
g.setLineDash([4, 4]);
|
||||
g.beginPath();
|
||||
const y = height - (line / top) * height;
|
||||
g.moveTo(0, y);
|
||||
g.lineTo(width, y);
|
||||
g.stroke();
|
||||
g.setLineDash([]);
|
||||
}
|
||||
g.strokeStyle = style.getPropertyValue("--accent");
|
||||
g.lineWidth = 1.5;
|
||||
g.beginPath();
|
||||
const span = 600;
|
||||
let drawing = false;
|
||||
values.forEach((v, i) => {
|
||||
if (v == null) {
|
||||
drawing = false;
|
||||
return;
|
||||
}
|
||||
const x = width - ((values.length - 1 - i) / (span - 1)) * width;
|
||||
const y = height - (v / top) * height;
|
||||
if (drawing) g.lineTo(x, y);
|
||||
else g.moveTo(x, y);
|
||||
drawing = true;
|
||||
});
|
||||
g.stroke();
|
||||
const last = values[values.length - 1];
|
||||
$(`${id}-now`).textContent = last == null ? "–" : `${last.toFixed(decimals)}${unit}`;
|
||||
}
|
||||
|
||||
function renderCharts() {
|
||||
chart("tps", samples.map((s) => s.tps), { max: 20, unit: "", line: 20 });
|
||||
chart("mspt", samples.map((s) => s.mspt), { max: 50, unit: " ms", line: 50 });
|
||||
chart("ram", samples.map((s) => (s.rss_bytes == null ? null : s.rss_bytes / 1e9)), { unit: " GB", decimals: 2 });
|
||||
chart("cpu", samples.map((s) => s.cpu_percent), { max: 100, unit: " %", decimals: 0 });
|
||||
$("ram-now").textContent = bytes(samples.length ? samples[samples.length - 1].rss_bytes : null);
|
||||
}
|
||||
|
||||
let ticks = 0;
|
||||
async function poll() {
|
||||
try {
|
||||
const [status, metrics, logs] = await Promise.all([
|
||||
api("GET", "/api/v1/status"),
|
||||
api("GET", `/api/v1/metrics?since=${metricsSince}`),
|
||||
api("GET", `/api/v1/logs?since=${logNext}`),
|
||||
]);
|
||||
show("app");
|
||||
renderStatus(status);
|
||||
for (const s of metrics.samples) {
|
||||
samples.push(s);
|
||||
metricsSince = s.t;
|
||||
}
|
||||
samples.splice(0, Math.max(0, samples.length - 600));
|
||||
renderCharts();
|
||||
logNext = logs.next;
|
||||
appendLog(logs.lines);
|
||||
if (ticks++ % 10 === 0) renderBackups((await api("GET", "/api/v1/backups")).backups);
|
||||
} catch (e) {
|
||||
if (e instanceof SignedOut) show("signed-out");
|
||||
else if (lastStatus) {
|
||||
show("gone");
|
||||
$("phase").textContent = "down";
|
||||
$("phase").className = "pill down";
|
||||
} else show("gone");
|
||||
}
|
||||
}
|
||||
|
||||
function setUp() {
|
||||
$("command-form").addEventListener("submit", async (event) => {
|
||||
event.preventDefault();
|
||||
const line = $("command").value.trim();
|
||||
if (!line) return;
|
||||
$("command").value = "";
|
||||
try {
|
||||
const output = await run(line);
|
||||
appendLog([`> ${line}`]);
|
||||
if (!output) toast("Done.");
|
||||
} catch (e) {
|
||||
toast(e.message);
|
||||
}
|
||||
});
|
||||
$("backup-form").addEventListener("submit", async (event) => {
|
||||
event.preventDefault();
|
||||
const name = $("backup-name").value.trim();
|
||||
toast("Backing up…");
|
||||
try {
|
||||
const made = await api("POST", "/api/v1/backups", name ? { name } : {});
|
||||
toast(`Backed up to backups/${made.name}`);
|
||||
$("backup-name").value = "";
|
||||
renderBackups((await api("GET", "/api/v1/backups")).backups);
|
||||
} catch (e) {
|
||||
toast(e.message);
|
||||
}
|
||||
});
|
||||
$("restart").addEventListener("click", async () => {
|
||||
if (!confirm("Restart the game? Players are disconnected for a moment.")) return;
|
||||
await api("POST", "/api/v1/restart").then(() => toast("Restarting…"), (e) => toast(e.message));
|
||||
});
|
||||
$("stop").addEventListener("click", async () => {
|
||||
if (!confirm("Stop the server? The panel stops with it; start it again on the server.")) return;
|
||||
await api("POST", "/api/v1/stop").then(() => toast("Stopping…"), (e) => toast(e.message));
|
||||
});
|
||||
poll();
|
||||
setInterval(poll, 1000);
|
||||
}
|
||||
|
||||
document.addEventListener("DOMContentLoaded", setUp);
|
||||
@@ -6,14 +6,17 @@
|
||||
//! - `GET /api/v1/logs?since=N`: the log lines after the Nth.
|
||||
//! - `POST /api/v1/command {"line": "..."}`: a console command; the lines it logged.
|
||||
//! - `POST /api/v1/stop`, `POST /api/v1/restart`.
|
||||
//! - `GET /api/v1/metrics?since=T`: the samples taken after T (seconds since 1970), up to 10 minutes.
|
||||
//! - `GET /api/v1/backups`; `POST /api/v1/backups {"name": "..."}` backs up now; `POST /api/v1/restore
|
||||
//! {"name": "..."}` restarts the game with that backup's world.
|
||||
//! - `POST /api/v1/panel/login`: a one-time login link for the web panel (with the token only).
|
||||
|
||||
use crate::{
|
||||
backup,
|
||||
config::Config,
|
||||
engine,
|
||||
http::{self, Request, Response},
|
||||
panel,
|
||||
};
|
||||
use serde_json::{Value, json};
|
||||
use std::{
|
||||
@@ -31,6 +34,8 @@ use std::{
|
||||
const ENDPOINT: &str = ".horizon/api.json";
|
||||
/// The log lines kept for `logs` and the panel's console.
|
||||
const LOG_LINES: usize = 2000;
|
||||
/// The samples kept for the panel's graphs: 10 minutes, one a second.
|
||||
const METRICS: usize = 600;
|
||||
|
||||
/// What the supervisor is doing.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
@@ -98,6 +103,10 @@ pub struct Shared {
|
||||
/// Held while a backup is written: one at a time.
|
||||
pub backing_up: Mutex<()>,
|
||||
pub started: Instant,
|
||||
/// The last samples, oldest first, for the panel's graphs.
|
||||
pub metrics: Mutex<VecDeque<Value>>,
|
||||
/// The panel's address, login links and sessions.
|
||||
pub panel: Mutex<panel::Auth>,
|
||||
}
|
||||
|
||||
impl Shared {
|
||||
@@ -118,8 +127,18 @@ impl Shared {
|
||||
restore: Mutex::new(None),
|
||||
backing_up: Mutex::new(()),
|
||||
started: Instant::now(),
|
||||
metrics: Mutex::new(VecDeque::new()),
|
||||
panel: Mutex::new(panel::Auth::default()),
|
||||
})
|
||||
}
|
||||
/// Keeps one sample for the graphs.
|
||||
pub fn record(&self, sample: Value) {
|
||||
let mut metrics = self.metrics.lock().unwrap();
|
||||
if metrics.len() == METRICS {
|
||||
metrics.pop_front();
|
||||
}
|
||||
metrics.push_back(sample);
|
||||
}
|
||||
pub fn set_phase(&self, phase: Phase) {
|
||||
self.state.lock().unwrap().phase = phase;
|
||||
}
|
||||
@@ -172,7 +191,7 @@ fn status(shared: &Shared) -> Value {
|
||||
}
|
||||
|
||||
/// A random token: two 64-bit hashes keyed by the OS's random hasher seeds, the time and the process.
|
||||
fn random_token() -> String {
|
||||
pub fn random_token() -> String {
|
||||
use std::hash::{BuildHasher, Hasher};
|
||||
(0..2u64)
|
||||
.map(|i| {
|
||||
@@ -189,7 +208,7 @@ fn random_token() -> String {
|
||||
.collect()
|
||||
}
|
||||
|
||||
fn same_token(a: &str, b: &str) -> bool {
|
||||
pub fn same_token(a: &str, b: &str) -> bool {
|
||||
a.len() == b.len() && a.bytes().zip(b.bytes()).fold(0u8, |d, (x, y)| d | (x ^ y)) == 0
|
||||
}
|
||||
|
||||
@@ -238,15 +257,40 @@ pub fn start(shared: Arc<Shared>) -> Result<Endpoint, String> {
|
||||
{
|
||||
return Response::error(403, "wrong Host");
|
||||
}
|
||||
if (request.method.as_str(), request.path.as_str()) == ("POST", "/api/v1/panel/login") {
|
||||
return match shared.panel.lock().unwrap().login_link() {
|
||||
Some(url) => Response::json(200, &json!({ "url": url })),
|
||||
None => Response::error(
|
||||
409,
|
||||
"the panel is off: set [panel] bind in server.toml and restart",
|
||||
),
|
||||
};
|
||||
}
|
||||
route(&shared, request)
|
||||
})
|
||||
.map_err(|e| e.to_string())?;
|
||||
Ok(Endpoint(path))
|
||||
}
|
||||
|
||||
fn route(shared: &Shared, request: &Request) -> Response {
|
||||
/// The API's routes, for the CLI (with the token) and the panel (with a session).
|
||||
pub fn route(shared: &Shared, request: &Request) -> Response {
|
||||
match (request.method.as_str(), request.path.as_str()) {
|
||||
("GET", "/api/v1/status") => Response::json(200, &status(shared)),
|
||||
("GET", "/api/v1/metrics") => {
|
||||
let since: u64 = request
|
||||
.param("since")
|
||||
.and_then(|s| s.parse().ok())
|
||||
.unwrap_or(0);
|
||||
let samples: Vec<Value> = shared
|
||||
.metrics
|
||||
.lock()
|
||||
.unwrap()
|
||||
.iter()
|
||||
.filter(|m| m["t"].as_u64().is_some_and(|t| t > since))
|
||||
.cloned()
|
||||
.collect();
|
||||
Response::json(200, &json!({ "samples": samples }))
|
||||
}
|
||||
("GET", "/api/v1/logs") => {
|
||||
let since = request
|
||||
.param("since")
|
||||
@@ -313,7 +357,7 @@ fn route(shared: &Shared, request: &Request) -> Response {
|
||||
(
|
||||
_,
|
||||
"/api/v1/status" | "/api/v1/logs" | "/api/v1/command" | "/api/v1/stop"
|
||||
| "/api/v1/restart" | "/api/v1/backups" | "/api/v1/restore",
|
||||
| "/api/v1/restart" | "/api/v1/backups" | "/api/v1/restore" | "/api/v1/metrics",
|
||||
) => Response::error(405, "wrong method"),
|
||||
_ => Response::error(404, "no such endpoint"),
|
||||
}
|
||||
|
||||
@@ -158,6 +158,24 @@ pub fn command(dir: &Path, words: &[String]) -> Result<(), String> {
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// `panel`: a one-time login link for the web panel.
|
||||
pub fn panel(dir: &Path) -> Result<(), String> {
|
||||
let reply = running(dir)?.call("POST", "/api/v1/panel/login", None)?;
|
||||
let url = reply["url"].as_str().unwrap_or_default();
|
||||
println!(
|
||||
"Open this link in your browser (it works once, for 10 minutes):\n {url}\n\
|
||||
From another computer: put a tailnet address in [panel] bind, or forward the port first:\n \
|
||||
ssh -L {port}:{target} <this server>",
|
||||
port = url
|
||||
.split('/')
|
||||
.nth(2)
|
||||
.and_then(|h| h.rsplit_once(':'))
|
||||
.map_or("8130", |(_, p)| p),
|
||||
target = url.split('/').nth(2).unwrap_or("127.0.0.1:8130"),
|
||||
);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// `status [--json]`.
|
||||
pub fn status(dir: &Path, as_json: bool) -> Result<(), String> {
|
||||
let Some(client) = Client::open(dir)? else {
|
||||
|
||||
@@ -48,6 +48,10 @@ restart_on_crash = true
|
||||
[backups]
|
||||
every = "6h" # automatic backups while the server runs: 30m, 6h, 1d...; "0" turns them off
|
||||
keep = 12 # automatic backups kept (backups made by hand are never deleted)
|
||||
|
||||
[panel]
|
||||
bind = "127.0.0.1:8130" # the web panel: this computer only, or a tailnet address (100.x); "" turns it off
|
||||
allow_public = false # true lets bind be any address; never put the panel on the open internet
|
||||
"##;
|
||||
|
||||
/// Each typed setting: its section, its name, and the vanilla key it writes.
|
||||
@@ -81,6 +85,8 @@ pub struct Config {
|
||||
pub engine: Engine,
|
||||
#[serde(default)]
|
||||
pub backups: Backups,
|
||||
#[serde(default)]
|
||||
pub panel: Panel,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
|
||||
@@ -117,6 +123,57 @@ pub struct Engine {
|
||||
pub restart_on_crash: bool,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
|
||||
#[serde(default, deny_unknown_fields)]
|
||||
pub struct Panel {
|
||||
pub bind: String,
|
||||
pub allow_public: bool,
|
||||
}
|
||||
|
||||
impl Default for Panel {
|
||||
fn default() -> Self {
|
||||
Self {
|
||||
bind: "127.0.0.1:8130".into(),
|
||||
allow_public: false,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl Panel {
|
||||
/// Where the panel listens; `None` when it is off.
|
||||
pub fn address(&self) -> Result<Option<std::net::SocketAddr>, String> {
|
||||
if self.bind.trim().is_empty() {
|
||||
return Ok(None);
|
||||
}
|
||||
let address: std::net::SocketAddr = self.bind.trim().parse().map_err(|_| {
|
||||
format!(
|
||||
"panel.bind is \"{}\": use an address and a port, like 127.0.0.1:8130",
|
||||
self.bind
|
||||
)
|
||||
})?;
|
||||
if !self.allow_public && !private(address.ip()) {
|
||||
return Err(format!(
|
||||
"panel.bind is \"{}\": the panel listens only on this computer (127.0.0.1) or a tailnet \
|
||||
address (100.64.0.0/10, fd7a:115c:a1e0::/48); reach it from elsewhere over Tailscale or SSH",
|
||||
self.bind
|
||||
));
|
||||
}
|
||||
Ok(Some(address))
|
||||
}
|
||||
}
|
||||
|
||||
/// Loopback, or a Tailscale address: reachable only from this computer or the owner's tailnet.
|
||||
pub fn private(ip: std::net::IpAddr) -> bool {
|
||||
match ip {
|
||||
std::net::IpAddr::V4(v4) => {
|
||||
v4.is_loopback() || (v4.octets()[0] == 100 && (v4.octets()[1] & 0xc0) == 64)
|
||||
}
|
||||
std::net::IpAddr::V6(v6) => {
|
||||
v6.is_loopback() || v6.segments()[..3] == [0xfd7a, 0x115c, 0xa1e0]
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
|
||||
#[serde(default, deny_unknown_fields)]
|
||||
pub struct Backups {
|
||||
@@ -219,6 +276,7 @@ impl Config {
|
||||
));
|
||||
}
|
||||
crate::backup::interval(&self.backups.every)?;
|
||||
self.panel.address()?;
|
||||
if self.server.port == 0 {
|
||||
return Err("server.port must be a port number from 1 to 65535".into());
|
||||
}
|
||||
@@ -320,6 +378,8 @@ pub fn render(config: &Config) -> String {
|
||||
("engine", "restart_on_crash"),
|
||||
("backups", "every"),
|
||||
("backups", "keep"),
|
||||
("panel", "bind"),
|
||||
("panel", "allow_public"),
|
||||
] {
|
||||
set(&mut doc, section, field, &table[section][field]);
|
||||
}
|
||||
@@ -494,6 +554,34 @@ mod tests {
|
||||
assert_eq!(Config::parse(&text).unwrap(), c);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_panel_stays_private() {
|
||||
let panel = |bind: &str, allow_public| Panel {
|
||||
bind: bind.into(),
|
||||
allow_public,
|
||||
};
|
||||
assert!(panel("127.0.0.1:8130", false).address().unwrap().is_some());
|
||||
assert!(panel("[::1]:8130", false).address().unwrap().is_some());
|
||||
assert!(
|
||||
panel("100.101.102.103:8130", false)
|
||||
.address()
|
||||
.unwrap()
|
||||
.is_some()
|
||||
);
|
||||
assert!(
|
||||
panel("[fd7a:115c:a1e0::1]:8130", false)
|
||||
.address()
|
||||
.unwrap()
|
||||
.is_some()
|
||||
);
|
||||
assert_eq!(panel("", false).address().unwrap(), None);
|
||||
assert!(panel("0.0.0.0:8130", false).address().is_err());
|
||||
assert!(panel("100.128.0.1:8130", false).address().is_err());
|
||||
assert!(panel("192.168.1.2:8130", false).address().is_err());
|
||||
assert!(panel("192.168.1.2:8130", true).address().unwrap().is_some());
|
||||
assert!(panel("localhost", false).address().is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn seed_may_be_a_number() {
|
||||
let c = Config::parse("[world]\nseed = -42\n").unwrap();
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
//! Just enough HTTP/1.1 for the control API on 127.0.0.1 (docs/server.md, section 8): one request per
|
||||
//! connection, JSON bodies with a Content-Length. No async runtime and no dependency: a thread per
|
||||
//! connection is plenty for a CLI, a panel tab and an MCP client.
|
||||
//! Just enough HTTP/1.1 for the control API on 127.0.0.1 and the web panel (docs/server.md, sections 6 and
|
||||
//! 8): one request per connection, bodies with a Content-Length. No async runtime and no dependency: a
|
||||
//! thread per connection is plenty for a CLI, a panel tab and an MCP client.
|
||||
|
||||
use std::{
|
||||
io::{BufRead, BufReader, Read, Write},
|
||||
@@ -26,7 +26,8 @@ impl Request {
|
||||
.find(|(k, _)| k.eq_ignore_ascii_case(name))
|
||||
.map(|(_, v)| v.as_str())
|
||||
}
|
||||
/// One `key=value` from the query string (no percent-decoding: the API's values are numbers).
|
||||
/// One `key=value` from the query string (no percent-decoding: the API's values are numbers and
|
||||
/// tokens).
|
||||
pub fn param(&self, key: &str) -> Option<&str> {
|
||||
self.query
|
||||
.split('&')
|
||||
@@ -34,28 +35,50 @@ impl Request {
|
||||
.find(|(k, _)| *k == key)
|
||||
.map(|(_, v)| v)
|
||||
}
|
||||
/// One cookie the browser sent.
|
||||
pub fn cookie(&self, name: &str) -> Option<&str> {
|
||||
self.headers
|
||||
.iter()
|
||||
.filter(|(k, _)| k.eq_ignore_ascii_case("cookie"))
|
||||
.flat_map(|(_, v)| v.split(';'))
|
||||
.filter_map(|c| c.trim().split_once('='))
|
||||
.find(|(k, _)| *k == name)
|
||||
.map(|(_, v)| v)
|
||||
}
|
||||
}
|
||||
|
||||
pub struct Response {
|
||||
pub status: u16,
|
||||
pub content_type: &'static str,
|
||||
pub headers: Vec<(&'static str, String)>,
|
||||
pub body: String,
|
||||
}
|
||||
|
||||
impl Response {
|
||||
pub fn json(status: u16, value: &serde_json::Value) -> Self {
|
||||
Self {
|
||||
status,
|
||||
body: value.to_string(),
|
||||
}
|
||||
Self::text(status, "application/json", value.to_string())
|
||||
}
|
||||
pub fn error(status: u16, message: &str) -> Self {
|
||||
Self::json(status, &serde_json::json!({ "error": message }))
|
||||
}
|
||||
pub fn text(status: u16, content_type: &'static str, body: impl Into<String>) -> Self {
|
||||
Self {
|
||||
status,
|
||||
content_type,
|
||||
headers: Vec::new(),
|
||||
body: body.into(),
|
||||
}
|
||||
}
|
||||
pub fn with(mut self, header: &'static str, value: impl Into<String>) -> Self {
|
||||
self.headers.push((header, value.into()));
|
||||
self
|
||||
}
|
||||
}
|
||||
|
||||
fn reason(status: u16) -> &'static str {
|
||||
match status {
|
||||
200 => "OK",
|
||||
303 => "See Other",
|
||||
400 => "Bad Request",
|
||||
401 => "Unauthorized",
|
||||
403 => "Forbidden",
|
||||
@@ -63,6 +86,7 @@ fn reason(status: u16) -> &'static str {
|
||||
405 => "Method Not Allowed",
|
||||
409 => "Conflict",
|
||||
413 => "Payload Too Large",
|
||||
429 => "Too Many Requests",
|
||||
_ => "Error",
|
||||
}
|
||||
}
|
||||
@@ -112,14 +136,20 @@ fn read_request(stream: &TcpStream) -> Result<Request, Response> {
|
||||
}
|
||||
|
||||
fn write_response(mut stream: &TcpStream, response: &Response) {
|
||||
let _ = write!(
|
||||
stream,
|
||||
"HTTP/1.1 {} {}\r\nContent-Type: application/json\r\nContent-Length: {}\r\nCache-Control: no-store\r\nConnection: close\r\n\r\n{}",
|
||||
let mut head = format!(
|
||||
"HTTP/1.1 {} {}\r\nContent-Type: {}\r\nContent-Length: {}\r\nCache-Control: no-store\r\nConnection: close\r\n",
|
||||
response.status,
|
||||
reason(response.status),
|
||||
response.content_type,
|
||||
response.body.len(),
|
||||
response.body
|
||||
);
|
||||
for (name, value) in &response.headers {
|
||||
head.push_str(&format!("{name}: {value}\r\n"));
|
||||
}
|
||||
head.push_str("\r\n");
|
||||
let _ = stream
|
||||
.write_all(head.as_bytes())
|
||||
.and_then(|()| stream.write_all(response.body.as_bytes()));
|
||||
let _ = stream.flush();
|
||||
}
|
||||
|
||||
|
||||
@@ -9,6 +9,7 @@ mod engine;
|
||||
mod http;
|
||||
mod init;
|
||||
mod lists;
|
||||
mod panel;
|
||||
mod service;
|
||||
mod signals;
|
||||
mod supervisor;
|
||||
@@ -42,6 +43,8 @@ Usage: horizon-server [--dir DIR] <command>
|
||||
service install|uninstall|print [--system]
|
||||
Start the server at boot or login: a systemd unit on Linux (--system: for every user,
|
||||
with sudo), a launchd agent on macOS, a task at logon on Windows
|
||||
panel A one-time login link for the web panel ([panel] in server.toml; 127.0.0.1:8130 by
|
||||
default)
|
||||
import FILE Write server.toml from a vanilla server.properties
|
||||
op NAME, deop NAME
|
||||
whitelist on|off|list, whitelist add|remove NAME
|
||||
@@ -80,6 +83,7 @@ fn main() -> ExitCode {
|
||||
Some("status") => cli::status(&dir, args[1..].iter().any(|a| a == "--json")),
|
||||
Some("cmd") => cli::command(&dir, &args[1..]),
|
||||
Some("logs") => logs(&dir, &args[1..]),
|
||||
Some("panel") => cli::panel(&dir),
|
||||
Some("backup") => cli::backup(&dir, args.get(1).map(String::as_str)),
|
||||
Some("backups") => cli::backups(&dir),
|
||||
Some("service") => service::command(&dir, &args[1..]),
|
||||
|
||||
@@ -0,0 +1,321 @@
|
||||
//! The web panel (docs/server.md, section 6): one page embedded in the binary, served by the supervisor on
|
||||
//! `[panel] bind` (127.0.0.1:8130 by default; a tailnet address to reach it from the owner's devices). It
|
||||
//! uses the control API's routes with a browser session instead of the token.
|
||||
//!
|
||||
//! - **Login.** `horizon-server panel` asks the API for a link with a one-time code, good for 10 minutes;
|
||||
//! opening it swaps the code for an `HttpOnly; SameSite=Strict` session cookie. Anyone who can read the
|
||||
//! server folder's token can make a link, and no one else can. Sessions end when the supervisor does.
|
||||
//! - **Rebinding and CSRF.** The `Host` header must name the panel's own address (`localhost` too on
|
||||
//! loopback, a MagicDNS name on a tailnet). Every POST needs the `X-Horizon: 1` header, which a page from
|
||||
//! another site can't send without the browser asking first.
|
||||
//! - **The page** loads nothing from elsewhere (a strict Content-Security-Policy) and can't be framed.
|
||||
|
||||
use crate::{
|
||||
api::{self, Shared},
|
||||
http::{self, Request, Response},
|
||||
};
|
||||
use std::{
|
||||
collections::VecDeque,
|
||||
net::{SocketAddr, TcpListener},
|
||||
sync::Arc,
|
||||
time::{Duration, Instant},
|
||||
};
|
||||
|
||||
const COOKIE: &str = "horizon_panel";
|
||||
/// How long a login link works.
|
||||
const LINK_LIFE: Duration = Duration::from_secs(600);
|
||||
/// Failed logins allowed per minute before the panel refuses them for a while.
|
||||
const FAILURES_PER_MINUTE: usize = 10;
|
||||
const SESSIONS: usize = 32;
|
||||
|
||||
const PAGE: &str = include_str!("../panel/index.html");
|
||||
const SCRIPT: &str = include_str!("../panel/panel.js");
|
||||
const STYLE: &str = include_str!("../panel/panel.css");
|
||||
|
||||
/// The panel's address, its pending login codes and its sessions.
|
||||
#[derive(Default)]
|
||||
pub struct Auth {
|
||||
address: Option<SocketAddr>,
|
||||
codes: Vec<(String, Instant)>,
|
||||
sessions: VecDeque<String>,
|
||||
failures: VecDeque<Instant>,
|
||||
}
|
||||
|
||||
impl Auth {
|
||||
/// A one-time login link; `None` when the panel is off.
|
||||
pub fn login_link(&mut self) -> Option<String> {
|
||||
let address = self.address?;
|
||||
self.codes.retain(|(_, at)| at.elapsed() < LINK_LIFE);
|
||||
let code = api::random_token();
|
||||
self.codes.push((code.clone(), Instant::now()));
|
||||
Some(format!("http://{address}/login?code={code}"))
|
||||
}
|
||||
|
||||
/// Swaps a login code for a new session.
|
||||
fn redeem(&mut self, code: &str) -> Result<String, Response> {
|
||||
self.failures
|
||||
.retain(|at| at.elapsed() < Duration::from_secs(60));
|
||||
if self.failures.len() >= FAILURES_PER_MINUTE {
|
||||
return Err(page_error(
|
||||
429,
|
||||
"Too many failed logins: wait a minute, then open a new link.",
|
||||
));
|
||||
}
|
||||
self.codes.retain(|(_, at)| at.elapsed() < LINK_LIFE);
|
||||
let Some(i) = self
|
||||
.codes
|
||||
.iter()
|
||||
.position(|(c, _)| api::same_token(c, code))
|
||||
else {
|
||||
self.failures.push_back(Instant::now());
|
||||
return Err(page_error(
|
||||
403,
|
||||
"This login link was used already or has expired. Run `horizon-server panel` for a new one.",
|
||||
));
|
||||
};
|
||||
self.codes.remove(i);
|
||||
let session = api::random_token();
|
||||
if self.sessions.len() == SESSIONS {
|
||||
self.sessions.pop_front();
|
||||
}
|
||||
self.sessions.push_back(session.clone());
|
||||
Ok(session)
|
||||
}
|
||||
|
||||
fn signed_in(&self, request: &Request) -> bool {
|
||||
request
|
||||
.cookie(COOKIE)
|
||||
.is_some_and(|s| self.sessions.iter().any(|t| api::same_token(t, s)))
|
||||
}
|
||||
|
||||
fn sign_out(&mut self, request: &Request) {
|
||||
if let Some(s) = request.cookie(COOKIE) {
|
||||
self.sessions.retain(|t| !api::same_token(t, s));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn page_error(status: u16, message: &str) -> Response {
|
||||
let body = format!(
|
||||
"<!doctype html><meta charset=utf-8><title>Horizon server</title>\
|
||||
<link rel=stylesheet href=/panel.css><main class=message><p>{}</p></main>",
|
||||
message
|
||||
.replace('&', "&")
|
||||
.replace('<', "<")
|
||||
.replace('>', ">")
|
||||
);
|
||||
Response::text(status, "text/html; charset=utf-8", body)
|
||||
}
|
||||
|
||||
/// The `Host` header names the panel itself: its address, `localhost` on loopback, or a tailnet name
|
||||
/// (a MagicDNS short name or `*.ts.net`, with or without the port when `tailscale serve` passes it on).
|
||||
fn host_allowed(host: &str, address: SocketAddr) -> bool {
|
||||
if host == address.to_string() {
|
||||
return true;
|
||||
}
|
||||
let (name, port) = match host.rsplit_once(':') {
|
||||
Some((name, port)) if !name.ends_with(']') || name.starts_with('[') => (name, Some(port)),
|
||||
_ => (host, None),
|
||||
};
|
||||
let same_port = port == Some(&address.port().to_string());
|
||||
if address.ip().is_loopback() && name.eq_ignore_ascii_case("localhost") && same_port {
|
||||
return true;
|
||||
}
|
||||
let tailnet_name = name.to_ascii_lowercase().ends_with(".ts.net")
|
||||
|| (!name.is_empty()
|
||||
&& !name.contains('.')
|
||||
&& !name.contains('[')
|
||||
&& !name.eq_ignore_ascii_case("localhost"));
|
||||
tailnet_name
|
||||
&& (same_port || port.is_none())
|
||||
&& name
|
||||
.chars()
|
||||
.all(|c| c.is_ascii_alphanumeric() || c == '-' || c == '.')
|
||||
}
|
||||
|
||||
fn secure(response: Response) -> Response {
|
||||
response
|
||||
.with(
|
||||
"Content-Security-Policy",
|
||||
"default-src 'none'; script-src 'self'; style-src 'self'; img-src 'self' data:; \
|
||||
connect-src 'self'; frame-ancestors 'none'; base-uri 'none'; form-action 'self'",
|
||||
)
|
||||
.with("X-Content-Type-Options", "nosniff")
|
||||
.with("X-Frame-Options", "DENY")
|
||||
.with("Referrer-Policy", "no-referrer")
|
||||
}
|
||||
|
||||
fn handle(shared: &Shared, address: SocketAddr, request: &Request) -> Response {
|
||||
if !request
|
||||
.header("host")
|
||||
.is_some_and(|h| host_allowed(h, address))
|
||||
{
|
||||
return Response::error(403, "wrong Host");
|
||||
}
|
||||
let method = request.method.as_str();
|
||||
let path = request.path.as_str();
|
||||
match (method, path) {
|
||||
("GET", "/") => return Response::text(200, "text/html; charset=utf-8", PAGE),
|
||||
("GET", "/panel.js") => {
|
||||
return Response::text(200, "text/javascript; charset=utf-8", SCRIPT);
|
||||
}
|
||||
("GET", "/panel.css") => return Response::text(200, "text/css; charset=utf-8", STYLE),
|
||||
("GET", "/login") => {
|
||||
let code = request.param("code").unwrap_or_default();
|
||||
return match shared.panel.lock().unwrap().redeem(code) {
|
||||
Ok(session) => Response::text(303, "text/plain", "")
|
||||
.with("Location", "/")
|
||||
.with(
|
||||
"Set-Cookie",
|
||||
format!("{COOKIE}={session}; HttpOnly; SameSite=Strict; Path=/"),
|
||||
),
|
||||
Err(response) => response,
|
||||
};
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
if method == "POST" && request.header("x-horizon") != Some("1") {
|
||||
return Response::error(403, "missing the X-Horizon header");
|
||||
}
|
||||
if (method, path) == ("POST", "/logout") {
|
||||
shared.panel.lock().unwrap().sign_out(request);
|
||||
return Response::json(200, &serde_json::json!({ "ok": true })).with(
|
||||
"Set-Cookie",
|
||||
format!("{COOKIE}=; HttpOnly; SameSite=Strict; Path=/; Max-Age=0"),
|
||||
);
|
||||
}
|
||||
if !path.starts_with("/api/v1/") {
|
||||
return Response::error(404, "no such page");
|
||||
}
|
||||
if !shared.panel.lock().unwrap().signed_in(request) {
|
||||
return Response::error(
|
||||
401,
|
||||
"sign in with a link from `horizon-server panel` on the server",
|
||||
);
|
||||
}
|
||||
if path == "/api/v1/panel/login" {
|
||||
return Response::error(403, "login links come from `horizon-server panel` only");
|
||||
}
|
||||
api::route(shared, request)
|
||||
}
|
||||
|
||||
/// Starts the panel on `address`.
|
||||
pub fn start(shared: Arc<Shared>, address: SocketAddr) -> Result<(), String> {
|
||||
let listener = TcpListener::bind(address).map_err(|e| e.to_string())?;
|
||||
shared.panel.lock().unwrap().address = Some(address);
|
||||
http::serve(listener, move |request| {
|
||||
secure(handle(&shared, address, request))
|
||||
})
|
||||
.map_err(|e| e.to_string())
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use std::io::{Read, Write};
|
||||
|
||||
#[test]
|
||||
fn hosts() {
|
||||
let local: SocketAddr = "127.0.0.1:8130".parse().unwrap();
|
||||
assert!(host_allowed("127.0.0.1:8130", local));
|
||||
assert!(host_allowed("localhost:8130", local));
|
||||
assert!(!host_allowed("localhost:8131", local));
|
||||
assert!(!host_allowed("evil.example:8130", local));
|
||||
assert!(!host_allowed("127.0.0.1.nip.io:8130", local));
|
||||
let tailnet: SocketAddr = "100.100.1.2:8130".parse().unwrap();
|
||||
assert!(host_allowed("100.100.1.2:8130", tailnet));
|
||||
assert!(host_allowed("myserver:8130", tailnet));
|
||||
assert!(host_allowed("myserver.tail1234.ts.net", tailnet));
|
||||
assert!(!host_allowed("localhost:8130", tailnet));
|
||||
assert!(!host_allowed("evil.example", tailnet));
|
||||
let v6: SocketAddr = "[::1]:8130".parse().unwrap();
|
||||
assert!(host_allowed("[::1]:8130", v6));
|
||||
assert!(!host_allowed("[::2]:8130", v6));
|
||||
}
|
||||
|
||||
/// One raw request to the panel; the status line, the headers and the body.
|
||||
fn send(address: SocketAddr, text: &str) -> (String, String) {
|
||||
let mut stream = std::net::TcpStream::connect(address).unwrap();
|
||||
stream.write_all(text.as_bytes()).unwrap();
|
||||
let mut out = String::new();
|
||||
stream.read_to_string(&mut out).unwrap();
|
||||
let (head, body) = out.split_once("\r\n\r\n").unwrap();
|
||||
(head.to_owned(), body.to_owned())
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn sign_in_with_a_link() {
|
||||
let dir = std::env::temp_dir().join(format!("horizon-server-panel-{}", std::process::id()));
|
||||
std::fs::create_dir_all(&dir).unwrap();
|
||||
let shared = Shared::new(&dir);
|
||||
let listener = TcpListener::bind("127.0.0.1:0").unwrap();
|
||||
let address = listener.local_addr().unwrap();
|
||||
drop(listener);
|
||||
start(shared.clone(), address).unwrap();
|
||||
let host = format!("Host: {address}\r\n");
|
||||
let get = |path: &str, extra: &str| {
|
||||
send(
|
||||
address,
|
||||
&format!("GET {path} HTTP/1.1\r\n{host}{extra}Connection: close\r\n\r\n"),
|
||||
)
|
||||
};
|
||||
// The page itself is public; the API is not.
|
||||
let (head, body) = get("/", "");
|
||||
assert!(head.starts_with("HTTP/1.1 200"), "{head}");
|
||||
assert!(head.contains("Content-Security-Policy"));
|
||||
assert!(body.contains("panel.js"));
|
||||
assert!(get("/api/v1/status", "").0.starts_with("HTTP/1.1 401"));
|
||||
let rebound = send(
|
||||
address,
|
||||
"GET / HTTP/1.1\r\nHost: evil.example\r\nConnection: close\r\n\r\n",
|
||||
);
|
||||
assert!(rebound.0.starts_with("HTTP/1.1 403"));
|
||||
// A link works once.
|
||||
let url = shared.panel.lock().unwrap().login_link().unwrap();
|
||||
let path = url.split_once(&address.to_string()).unwrap().1.to_owned();
|
||||
let (head, _) = get(&path, "");
|
||||
assert!(head.starts_with("HTTP/1.1 303"), "{head}");
|
||||
let cookie = head
|
||||
.lines()
|
||||
.find_map(|l| l.strip_prefix("Set-Cookie: "))
|
||||
.unwrap();
|
||||
assert!(cookie.contains("HttpOnly") && cookie.contains("SameSite=Strict"));
|
||||
let session = cookie.split(';').next().unwrap().to_owned();
|
||||
assert!(get(&path, "").0.starts_with("HTTP/1.1 403"));
|
||||
let with_cookie = format!("Cookie: other=1; {session}\r\n");
|
||||
let (head, body) = get("/api/v1/status", &with_cookie);
|
||||
assert!(head.starts_with("HTTP/1.1 200"), "{head}");
|
||||
assert!(body.contains("\"phase\":\"starting\""));
|
||||
// Changes need the header a foreign page can't send.
|
||||
let post = |extra: &str| {
|
||||
send(
|
||||
address,
|
||||
&format!(
|
||||
"POST /api/v1/restart HTTP/1.1\r\n{host}{with_cookie}{extra}Content-Length: 0\r\nConnection: close\r\n\r\n"
|
||||
),
|
||||
)
|
||||
.0
|
||||
};
|
||||
assert!(post("").starts_with("HTTP/1.1 403"));
|
||||
assert!(!shared.restart.load(std::sync::atomic::Ordering::SeqCst));
|
||||
assert!(post("X-Horizon: 1\r\n").starts_with("HTTP/1.1 200"));
|
||||
assert!(shared.restart.load(std::sync::atomic::Ordering::SeqCst));
|
||||
// Login links come only from the token API.
|
||||
assert!(
|
||||
send(
|
||||
address,
|
||||
&format!(
|
||||
"POST /api/v1/panel/login HTTP/1.1\r\n{host}{with_cookie}X-Horizon: 1\r\nContent-Length: 0\r\nConnection: close\r\n\r\n"
|
||||
),
|
||||
)
|
||||
.0
|
||||
.starts_with("HTTP/1.1 403")
|
||||
);
|
||||
// Wrong codes are counted (the used link above was one), then refused for a while.
|
||||
for _ in 1..FAILURES_PER_MINUTE {
|
||||
assert!(get("/login?code=nope", "").0.starts_with("HTTP/1.1 403"));
|
||||
}
|
||||
assert!(get("/login?code=nope", "").0.starts_with("HTTP/1.1 429"));
|
||||
std::fs::remove_dir_all(&dir).unwrap();
|
||||
}
|
||||
}
|
||||
@@ -79,6 +79,24 @@ pub fn run(dir: &Path) -> Result<(), String> {
|
||||
let _lock = lock(dir)?;
|
||||
let shared = Shared::new(dir);
|
||||
let _endpoint = api::start(shared.clone())?;
|
||||
match config.panel.address() {
|
||||
Ok(Some(address)) => match crate::panel::start(shared.clone(), address) {
|
||||
Ok(()) => note(
|
||||
&shared,
|
||||
"INFO",
|
||||
&format!(
|
||||
"Web panel on http://{address} (`horizon-server panel` prints a login link)"
|
||||
),
|
||||
),
|
||||
Err(e) => note(
|
||||
&shared,
|
||||
"WARN",
|
||||
&format!("The web panel can't listen on {address}: {e}"),
|
||||
),
|
||||
},
|
||||
Ok(None) => {}
|
||||
Err(e) => note(&shared, "WARN", &e),
|
||||
}
|
||||
sample(shared.clone());
|
||||
schedule_backups(shared.clone());
|
||||
let console = console_lines();
|
||||
@@ -239,7 +257,7 @@ fn pump(shared: &Arc<Shared>, from: impl Read + Send + 'static, to_stderr: bool)
|
||||
});
|
||||
}
|
||||
|
||||
/// Every second, the game's RAM, CPU and status, for `status` and (later) the panel's graphs.
|
||||
/// Every second, the game's RAM, CPU and status, for `status` and the panel's graphs.
|
||||
fn sample(shared: Arc<Shared>) {
|
||||
let _ = thread::Builder::new()
|
||||
.name("sampler".into())
|
||||
@@ -280,8 +298,20 @@ fn sample(shared: Arc<Shared>) {
|
||||
control = None;
|
||||
None
|
||||
});
|
||||
let rss = horizon_bench::rss_bytes(pid);
|
||||
shared.record(json!({
|
||||
"t": std::time::SystemTime::now()
|
||||
.duration_since(std::time::UNIX_EPOCH)
|
||||
.map_or(0, |d| d.as_secs()),
|
||||
"tps": game.as_ref().and_then(|g| g["tps"].as_f64()),
|
||||
"mspt": game.as_ref().and_then(|g| g["mspt"]["average"].as_f64()),
|
||||
"mspt_p95": game.as_ref().and_then(|g| g["mspt"]["p95"].as_f64()),
|
||||
"rss_bytes": rss,
|
||||
"cpu_percent": cpu_percent,
|
||||
"players": game.as_ref().and_then(|g| g["players"].as_array().map(Vec::len)),
|
||||
}));
|
||||
shared.state.lock().unwrap().sample = json!({
|
||||
"rss_bytes": horizon_bench::rss_bytes(pid),
|
||||
"rss_bytes": rss,
|
||||
"cpu_percent": cpu_percent,
|
||||
"game": game,
|
||||
});
|
||||
|
||||
Reference in New Issue
Block a user