feat: Phase 0 shells, design system, server skeleton, Docker and CI
- Titano.Ui: DESIGN.md tokens (dark/light), generated 16-px icon set, styles for all standard controls, custom chrome window with snap layouts, rail, job bar, Auto/manual slider, chips, toasts. - Titano desktop shell with sections, Settings (language, theme), About and a --capture screenshot mode. - Titano Server skeleton: env/server.json configuration, self-signed TLS with fingerprint, /health, /server/info, i18n endpoint and the embedded admin panel; in-process server tests. - Docker image (multi-arch, PUID/PGID, health check), compose file, Unraid template; CI, release and nightly workflows; changelog tool. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_012iLMBNwBE2GnphAsu4cjaC
This commit is contained in:
122 files changed
+6838
-22
No files matched your search
@@ -0,0 +1,100 @@
|
||||
/* Titano Server admin — DESIGN.md light tokens (the web admin is light-only). */
|
||||
:root {
|
||||
--bg: #f3f3f3;
|
||||
--chrome: #ffffff;
|
||||
--surface: #ffffff;
|
||||
--card: #ffffff;
|
||||
--card-hover: #f5f5f5;
|
||||
--stroke: #e5e5e5;
|
||||
--stroke-strong: #d1d1d1;
|
||||
--text: #1a1a1a;
|
||||
--text-muted: #616161;
|
||||
--text-faint: #9e9e9e;
|
||||
--accent: #0067c0;
|
||||
--accent-hover: #1975c5;
|
||||
--on-accent: #ffffff;
|
||||
--accent-selected: #e8f1fa;
|
||||
--sun: #e08a1e;
|
||||
--success: #0f7b4f;
|
||||
--warning: #9a6700;
|
||||
--error: #c42b1c;
|
||||
--radius: 6px;
|
||||
--radius-card: 8px;
|
||||
--font: "Segoe UI Variable Text", "Segoe UI", system-ui, -apple-system, "Noto Sans", sans-serif;
|
||||
}
|
||||
|
||||
* { box-sizing: border-box; }
|
||||
html, body { height: 100%; }
|
||||
body { margin: 0; font: 13px/1.45 var(--font); color: var(--text); background: var(--bg); }
|
||||
button, input, select { font: inherit; color: inherit; }
|
||||
a { color: var(--accent); }
|
||||
.num { font-variant-numeric: tabular-nums; }
|
||||
|
||||
/* Shell */
|
||||
.shell { display: grid; grid-template-columns: 220px 1fr; min-height: 100vh; }
|
||||
.sidebar { background: var(--chrome); border-right: 1px solid var(--stroke); display: flex; flex-direction: column; padding: 16px 12px; }
|
||||
.brand { display: flex; align-items: center; gap: 10px; padding: 4px 8px 20px; }
|
||||
.brand img { width: 28px; height: 28px; }
|
||||
.brand strong { display: block; font-size: 14px; }
|
||||
.brand span { display: block; font-size: 11px; color: var(--text-muted); }
|
||||
.nav a { display: flex; align-items: center; gap: 12px; height: 36px; padding: 0 12px; border-radius: var(--radius); color: var(--text); text-decoration: none; margin-bottom: 2px; }
|
||||
.nav a:hover { background: var(--card-hover); }
|
||||
.nav a[aria-current="page"] { background: var(--accent-selected); color: var(--accent); font-weight: 600; }
|
||||
.nav svg { width: 16px; height: 16px; flex: none; }
|
||||
.nav .badge { margin-left: auto; min-width: 18px; height: 16px; padding: 0 5px; border-radius: 8px; background: var(--accent); color: var(--on-accent); font-size: 10px; font-weight: 600; display: inline-flex; align-items: center; justify-content: center; }
|
||||
.sidebar .user { margin-top: auto; border-top: 1px solid var(--stroke); padding: 12px 8px 0; display: flex; align-items: center; gap: 10px; }
|
||||
.avatar { width: 28px; height: 28px; border-radius: 50%; background: var(--accent-selected); color: var(--accent); display: grid; place-items: center; font-weight: 600; }
|
||||
.user .who { flex: 1; min-width: 0; }
|
||||
.user .who strong { display: block; }
|
||||
.user .who span { color: var(--text-muted); font-size: 11px; }
|
||||
|
||||
.main { display: flex; flex-direction: column; min-width: 0; }
|
||||
.header { height: 60px; display: flex; align-items: center; gap: 12px; padding: 0 24px; border-bottom: 1px solid var(--stroke); background: var(--chrome); }
|
||||
.header h1 { font-size: 18px; font-weight: 600; margin: 0; }
|
||||
.header .meta { color: var(--text-muted); }
|
||||
.header .spacer { flex: 1; }
|
||||
.content { padding: 24px; display: grid; gap: 20px; }
|
||||
|
||||
/* Controls */
|
||||
.btn { height: 32px; min-width: 44px; padding: 0 12px; border: 1px solid var(--stroke); border-radius: var(--radius); background: var(--card); cursor: pointer; display: inline-flex; align-items: center; justify-content: center; gap: 8px; }
|
||||
.btn:hover { background: var(--card-hover); border-color: var(--stroke-strong); }
|
||||
.btn:focus-visible, .input:focus-visible, select:focus-visible { outline: 2px solid var(--accent); outline-offset: 2px; }
|
||||
.btn.primary { background: var(--accent); border-color: var(--accent); color: var(--on-accent); font-weight: 600; }
|
||||
.btn.primary:hover { background: var(--accent-hover); }
|
||||
.btn.subtle { border-color: transparent; background: transparent; }
|
||||
.btn.icon { width: 32px; padding: 0; }
|
||||
.btn:disabled { opacity: .4; cursor: default; }
|
||||
.input { height: 32px; width: 100%; padding: 0 10px; border: 1px solid var(--stroke); border-radius: var(--radius); background: var(--card); }
|
||||
.input:hover { border-color: var(--stroke-strong); }
|
||||
.input:focus { border-color: var(--accent); outline: none; }
|
||||
.input[aria-invalid="true"] { border-color: var(--error); }
|
||||
select.input { padding-right: 24px; }
|
||||
|
||||
.panel { background: var(--surface); border: 1px solid var(--stroke); border-radius: var(--radius-card); padding: 18px 20px; }
|
||||
.panel h2 { font-size: 14px; font-weight: 600; margin: 0 0 12px; }
|
||||
.tiles { display: grid; grid-template-columns: repeat(auto-fit, minmax(220px, 1fr)); gap: 20px; }
|
||||
.tile .label { color: var(--text-muted); }
|
||||
.tile .value { font-size: 28px; font-weight: 600; margin-top: 4px; }
|
||||
.tile .value small { font-size: 13px; font-weight: 400; color: var(--text-muted); margin-left: 6px; }
|
||||
.tile .sub { color: var(--text-muted); margin-top: 6px; }
|
||||
.progress { height: 6px; border-radius: 3px; background: var(--stroke); overflow: hidden; margin-top: 10px; }
|
||||
.progress > div { height: 6px; background: var(--accent); }
|
||||
|
||||
.status-ok { color: var(--success); }
|
||||
.status-warn { color: var(--warning); }
|
||||
.status-err { color: var(--error); }
|
||||
|
||||
/* Login */
|
||||
.login { min-height: 100vh; display: grid; place-items: center; padding: 16px; }
|
||||
.login form { width: 360px; max-width: 100%; display: grid; gap: 14px; }
|
||||
.login .brand { padding: 0 0 8px; }
|
||||
.login label { display: grid; gap: 6px; color: var(--text-muted); }
|
||||
.login .error { color: var(--error); min-height: 18px; }
|
||||
|
||||
@media (max-width: 800px) {
|
||||
.shell { grid-template-columns: 1fr; }
|
||||
.sidebar { flex-direction: row; overflow-x: auto; padding: 8px; }
|
||||
.sidebar .brand, .sidebar .user { display: none; }
|
||||
.nav { display: flex; gap: 4px; }
|
||||
.nav a span { display: none; }
|
||||
}
|
||||
@@ -0,0 +1,47 @@
|
||||
// Same API as the desktop clients: cookie session + double-submit CSRF token for the web admin (BRIEF §14.2).
|
||||
export class ApiFailure extends Error {
|
||||
constructor(status, code, message) {
|
||||
super(message);
|
||||
this.status = status;
|
||||
this.code = code;
|
||||
}
|
||||
}
|
||||
|
||||
const SESSION_KEY = "titano.admin.user";
|
||||
|
||||
function csrfToken() {
|
||||
const m = document.cookie.match(/(?:^|; )titano_csrf=([^;]+)/);
|
||||
return m ? decodeURIComponent(m[1]) : "";
|
||||
}
|
||||
|
||||
async function request(method, url, body) {
|
||||
const headers = { Accept: "application/json" };
|
||||
if (body !== undefined) headers["Content-Type"] = "application/json";
|
||||
if (method !== "GET") headers["X-CSRF-Token"] = csrfToken();
|
||||
const res = await fetch(url, { method, headers, credentials: "same-origin", body: body === undefined ? undefined : JSON.stringify(body) });
|
||||
if (res.status === 401 && url !== "/api/v1/auth/login") sessionStorage.removeItem(SESSION_KEY);
|
||||
if (!res.ok) {
|
||||
let err = { code: "http_" + res.status, message: res.statusText };
|
||||
try { err = await res.json(); } catch { /* non-JSON error */ }
|
||||
throw new ApiFailure(res.status, err.code, err.message);
|
||||
}
|
||||
return res.status === 204 ? null : res.json();
|
||||
}
|
||||
|
||||
export const api = {
|
||||
get: (url) => request("GET", url),
|
||||
post: (url, body) => request("POST", url, body ?? {}),
|
||||
patch: (url, body) => request("PATCH", url, body),
|
||||
del: (url) => request("DELETE", url),
|
||||
isSignedIn: () => sessionStorage.getItem(SESSION_KEY) !== null,
|
||||
user: () => JSON.parse(sessionStorage.getItem(SESSION_KEY) ?? "null"),
|
||||
async signIn(username, password) {
|
||||
const r = await request("POST", "/api/v1/auth/login", { username, password, clientName: "admin-web", cookie: true });
|
||||
sessionStorage.setItem(SESSION_KEY, JSON.stringify(r.user));
|
||||
return r;
|
||||
},
|
||||
async signOut() {
|
||||
try { await request("POST", "/api/v1/auth/logout", {}); } catch { /* already gone */ }
|
||||
sessionStorage.removeItem(SESSION_KEY);
|
||||
},
|
||||
};
|
||||
@@ -0,0 +1,102 @@
|
||||
// Titano Server admin panel — vanilla ES modules, no build step (BRIEF §14.8).
|
||||
import { api, ApiFailure } from "./api.js";
|
||||
import { t, loadStrings, applyStrings } from "./i18n.js";
|
||||
import { icons } from "./icons.js";
|
||||
|
||||
const app = document.getElementById("app");
|
||||
const pages = ["dashboard", "users", "archive", "jobs", "settings", "logs", "about"];
|
||||
const pageIcon = { dashboard: "dashboard", users: "users", archive: "archive", jobs: "jobs", settings: "settings", logs: "logs", about: "about" };
|
||||
|
||||
let info = null;
|
||||
|
||||
async function start() {
|
||||
await loadStrings(navigator.language);
|
||||
info = await api.get("/api/v1/server/info").catch(() => null);
|
||||
window.addEventListener("hashchange", render);
|
||||
render();
|
||||
}
|
||||
|
||||
function currentPage() {
|
||||
const p = location.hash.replace(/^#\/?/, "");
|
||||
return pages.includes(p) ? p : "dashboard";
|
||||
}
|
||||
|
||||
function render() {
|
||||
if (!api.isSignedIn()) {
|
||||
renderLogin();
|
||||
return;
|
||||
}
|
||||
renderShell(currentPage());
|
||||
}
|
||||
|
||||
function renderLogin() {
|
||||
app.innerHTML = `
|
||||
<main class="login">
|
||||
<form novalidate>
|
||||
<div class="brand"><img src="favicon.svg" alt=""><div><strong>Titano Server</strong><span class="num">${escapeHtml(info?.name ?? "")} · v${escapeHtml(info?.version ?? "")}</span></div></div>
|
||||
<label><span data-i18n="Admin.Login.User"></span><input class="input" name="username" autocomplete="username" required></label>
|
||||
<label><span data-i18n="Admin.Login.Password"></span><input class="input" name="password" type="password" autocomplete="current-password" required></label>
|
||||
<div class="error" role="alert"></div>
|
||||
<button class="btn primary" type="submit" data-i18n="Admin.Login.SignIn" data-i18n-title="Admin.Login.SignIn.Tip"></button>
|
||||
</form>
|
||||
</main>`;
|
||||
applyStrings(app);
|
||||
const form = app.querySelector("form");
|
||||
const error = form.querySelector(".error");
|
||||
form.addEventListener("submit", async (e) => {
|
||||
e.preventDefault();
|
||||
error.textContent = "";
|
||||
const data = new FormData(form);
|
||||
try {
|
||||
await api.signIn(String(data.get("username")), String(data.get("password")));
|
||||
render();
|
||||
} catch (err) {
|
||||
error.textContent = err instanceof ApiFailure && err.status === 401 ? t("Admin.Login.Failed") : t("Admin.Error.Unreachable");
|
||||
}
|
||||
});
|
||||
form.querySelector("input").focus();
|
||||
}
|
||||
|
||||
function renderShell(page) {
|
||||
const nav = pages.map((p) => `
|
||||
<a href="#/${p}" ${p === page ? 'aria-current="page"' : ""} data-i18n-title="Admin.Nav.${cap(p)}.Tip">${icons[pageIcon[p]]}<span data-i18n="Admin.Nav.${cap(p)}"></span></a>`).join("");
|
||||
const user = api.user();
|
||||
app.innerHTML = `
|
||||
<div class="shell">
|
||||
<aside class="sidebar">
|
||||
<div class="brand"><img src="favicon.svg" alt=""><div><strong>Titano Server</strong><span class="num">${escapeHtml(info?.name ?? "")} · v${escapeHtml(info?.version ?? "")}</span></div></div>
|
||||
<nav class="nav">${nav}</nav>
|
||||
<div class="user">
|
||||
<div class="avatar">${escapeHtml((user?.username ?? "?").slice(0, 1).toUpperCase())}</div>
|
||||
<div class="who"><strong>${escapeHtml(user?.username ?? "")}</strong><span data-i18n="Admin.Role.${cap(user?.role ?? "viewer")}"></span></div>
|
||||
<button class="btn icon subtle" id="signout" data-i18n-title="Admin.SignOut.Tip" aria-label="${escapeHtml(t("Admin.SignOut.Tip"))}">${icons.power}</button>
|
||||
</div>
|
||||
</aside>
|
||||
<div class="main">
|
||||
<header class="header"><h1 data-i18n="Admin.Nav.${cap(page)}"></h1><span class="meta" id="meta"></span><span class="spacer"></span></header>
|
||||
<section class="content" id="content"></section>
|
||||
</div>
|
||||
</div>`;
|
||||
applyStrings(app);
|
||||
app.querySelector("#signout").addEventListener("click", async () => {
|
||||
await api.signOut();
|
||||
render();
|
||||
});
|
||||
const content = app.querySelector("#content");
|
||||
import(`./pages/${page}.js`)
|
||||
.then((m) => m.render(content, { api, t, info, meta: app.querySelector("#meta") }))
|
||||
.catch(() => {
|
||||
content.innerHTML = `<div class="panel"><span data-i18n="Admin.Error.Unreachable"></span></div>`;
|
||||
applyStrings(content);
|
||||
});
|
||||
}
|
||||
|
||||
export function escapeHtml(s) {
|
||||
return String(s).replace(/[&<>"']/g, (c) => ({ "&": "&", "<": "<", ">": ">", '"': """, "'": "'" }[c]));
|
||||
}
|
||||
|
||||
function cap(s) {
|
||||
return s.charAt(0).toUpperCase() + s.slice(1);
|
||||
}
|
||||
|
||||
start();
|
||||
@@ -0,0 +1,17 @@
|
||||
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 256 256" width="256" height="256">
|
||||
<rect x="0" y="0" width="256" height="256" rx="56" fill="#1a1a1e"/>
|
||||
<path d="M142.4 37.1 A92 92 0 0 1 161.0 42.1" fill="none" stroke="#4cc2ff" stroke-width="20" stroke-linecap="round" opacity="0.14"/>
|
||||
<path d="M185.9 56.5 A92 92 0 0 1 199.5 70.1" fill="none" stroke="#4cc2ff" stroke-width="20" stroke-linecap="round" opacity="0.22"/>
|
||||
<path d="M213.9 95.0 A92 92 0 0 1 218.9 113.6" fill="none" stroke="#4cc2ff" stroke-width="20" stroke-linecap="round" opacity="0.3"/>
|
||||
<path d="M218.9 142.4 A92 92 0 0 1 213.9 161.0" fill="none" stroke="#4cc2ff" stroke-width="20" stroke-linecap="round" opacity="0.37"/>
|
||||
<path d="M199.5 185.9 A92 92 0 0 1 185.9 199.5" fill="none" stroke="#4cc2ff" stroke-width="20" stroke-linecap="round" opacity="0.45"/>
|
||||
<path d="M161.0 213.9 A92 92 0 0 1 142.4 218.9" fill="none" stroke="#4cc2ff" stroke-width="20" stroke-linecap="round" opacity="0.53"/>
|
||||
<path d="M113.6 218.9 A92 92 0 0 1 95.0 213.9" fill="none" stroke="#4cc2ff" stroke-width="20" stroke-linecap="round" opacity="0.61"/>
|
||||
<path d="M70.1 199.5 A92 92 0 0 1 56.5 185.9" fill="none" stroke="#4cc2ff" stroke-width="20" stroke-linecap="round" opacity="0.69"/>
|
||||
<path d="M42.1 161.0 A92 92 0 0 1 37.1 142.4" fill="none" stroke="#4cc2ff" stroke-width="20" stroke-linecap="round" opacity="0.77"/>
|
||||
<path d="M37.1 113.6 A92 92 0 0 1 42.1 95.0" fill="none" stroke="#4cc2ff" stroke-width="20" stroke-linecap="round" opacity="0.84"/>
|
||||
<path d="M56.5 70.1 A92 92 0 0 1 70.1 56.5" fill="none" stroke="#4cc2ff" stroke-width="20" stroke-linecap="round" opacity="0.92"/>
|
||||
<path d="M95.0 42.1 A92 92 0 0 1 113.6 37.1" fill="none" stroke="#4cc2ff" stroke-width="20" stroke-linecap="round" opacity="1.0"/>
|
||||
<circle cx="152" cy="104" r="30" fill="#f5a524"/>
|
||||
<circle cx="204" cy="204" r="40" fill="#1a1a1e" stroke="#4cc2ff" stroke-width="6"/><rect x="185" y="188" width="38" height="12" rx="4" fill="#4cc2ff"/><rect x="185" y="208" width="38" height="12" rx="4" fill="#4cc2ff"/>
|
||||
</svg>
|
||||
|
After Width: | Height: | Size: 2.0 KiB |
@@ -0,0 +1,27 @@
|
||||
// Strings come from /api/v1/i18n/{culture}, generated from the same .resx catalog as the desktop apps.
|
||||
let strings = {};
|
||||
|
||||
export async function loadStrings(culture) {
|
||||
try {
|
||||
const res = await fetch(`/api/v1/i18n/${encodeURIComponent(culture || "en")}`);
|
||||
strings = await res.json();
|
||||
} catch {
|
||||
strings = {};
|
||||
}
|
||||
document.documentElement.lang = strings.$culture || "en";
|
||||
document.documentElement.dir = strings.$rtl === "true" ? "rtl" : "ltr";
|
||||
}
|
||||
|
||||
/** Localized string for key with {0}, {1}… placeholders filled from args. */
|
||||
export function t(key, ...args) {
|
||||
const s = strings[key];
|
||||
if (s === undefined) return `⟦${key}⟧`;
|
||||
return s.replace(/\{(\d+)(?:[,:][^}]*)?\}/g, (_, i) => (args[Number(i)] ?? ""));
|
||||
}
|
||||
|
||||
/** Fills data-i18n (text), data-i18n-title (tooltip) and data-i18n-placeholder attributes. */
|
||||
export function applyStrings(root) {
|
||||
root.querySelectorAll("[data-i18n]").forEach((el) => { el.textContent = t(el.dataset.i18n); });
|
||||
root.querySelectorAll("[data-i18n-title]").forEach((el) => { el.title = t(el.dataset.i18nTitle); });
|
||||
root.querySelectorAll("[data-i18n-placeholder]").forEach((el) => { el.placeholder = t(el.dataset.i18nPlaceholder); });
|
||||
}
|
||||
@@ -0,0 +1,16 @@
|
||||
// Generated from branding/ui-icons/icons.py (same 16-px set as the desktop apps).
|
||||
export const icons = {
|
||||
dashboard: `<svg viewBox="0 0 16 16" width="16" height="16" aria-hidden="true"><path d="M2.5 1.5 H6.0 A1 1 0 0 1 7.0 2.5 V6.0 A1 1 0 0 1 6.0 7.0 H2.5 A1 1 0 0 1 1.5 6.0 V2.5 A1 1 0 0 1 2.5 1.5 ZM10 1.5 H13.5 A1 1 0 0 1 14.5 2.5 V6.0 A1 1 0 0 1 13.5 7.0 H10 A1 1 0 0 1 9 6.0 V2.5 A1 1 0 0 1 10 1.5 ZM2.5 9 H6.0 A1 1 0 0 1 7.0 10 V13.5 A1 1 0 0 1 6.0 14.5 H2.5 A1 1 0 0 1 1.5 13.5 V10 A1 1 0 0 1 2.5 9 ZM10 9 H13.5 A1 1 0 0 1 14.5 10 V13.5 A1 1 0 0 1 13.5 14.5 H10 A1 1 0 0 1 9 13.5 V10 A1 1 0 0 1 10 9 Z" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"/></svg>`,
|
||||
users: `<svg viewBox="0 0 16 16" width="16" height="16" aria-hidden="true"><path d="M5 5 A3 3 0 1 0 11 5 A3 3 0 1 0 5 5 Z M2.5 14 A5.5 5.5 0 0 1 13.5 14" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"/></svg>`,
|
||||
archive: `<svg viewBox="0 0 16 16" width="16" height="16" aria-hidden="true"><path d="M2 4.5 H14 V13.5 H2 Z M2 2 H14 V4.5 H2 Z M6 8 H10" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"/></svg>`,
|
||||
jobs: `<svg viewBox="0 0 16 16" width="16" height="16" aria-hidden="true"><path d="M3 8 H13 M3 4 H13 M3 12 H9" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"/></svg>`,
|
||||
settings: `<svg viewBox="0 0 16 16" width="16" height="16" aria-hidden="true"><path d="M5.8 8 A2.2 2.2 0 1 0 10.2 8 A2.2 2.2 0 1 0 5.8 8 Z M8 1.5 V3.5 M8 12.5 V14.5 M1.5 8 H3.5 M12.5 8 H14.5 M3.4 3.4 L4.8 4.8 M11.2 11.2 L12.6 12.6 M3.4 12.6 L4.8 11.2 M11.2 4.8 L12.6 3.4" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"/></svg>`,
|
||||
logs: `<svg viewBox="0 0 16 16" width="16" height="16" aria-hidden="true"><path d="M3.5 1.5 H9.5 L12.5 4.5 V14.5 H3.5 Z M5.5 7 H10.5 M5.5 9.5 H10.5 M5.5 12 H8.5" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"/></svg>`,
|
||||
about: `<svg viewBox="0 0 16 16" width="16" height="16" aria-hidden="true"><path d="M1.5 8 A6.5 6.5 0 1 0 14.5 8 A6.5 6.5 0 1 0 1.5 8 Z M8 7 V11 M8 4.8 V5.2" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"/></svg>`,
|
||||
power: `<svg viewBox="0 0 16 16" width="16" height="16" aria-hidden="true"><path d="M8 1.8 V7.5 M11.54 4.59 A5.5 5.5 0 1 1 4.46 4.59" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"/></svg>`,
|
||||
moon: `<svg viewBox="0 0 16 16" width="16" height="16" aria-hidden="true"><path d="M9.5 1.8 A6.5 6.5 0 1 0 14.2 11.2 A5.5 5.5 0 0 1 9.5 1.8 Z" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"/></svg>`,
|
||||
refresh: `<svg viewBox="0 0 16 16" width="16" height="16" aria-hidden="true"><path d="M10.75 3.24 A5.5 5.5 0 1 1 4.46 3.79 M13.2 2.6 L13.2 5.3 L10.5 5.3" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"/></svg>`,
|
||||
close: `<svg viewBox="0 0 16 16" width="16" height="16" aria-hidden="true"><path d="M4 4 L12 12 M12 4 L4 12" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"/></svg>`,
|
||||
plus: `<svg viewBox="0 0 16 16" width="16" height="16" aria-hidden="true"><path d="M8 3 V13 M3 8 H13" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"/></svg>`,
|
||||
search: `<svg viewBox="0 0 16 16" width="16" height="16" aria-hidden="true"><path d="M2.5 7 A4.5 4.5 0 1 0 11.5 7 A4.5 4.5 0 1 0 2.5 7 Z M10.4 10.4 L14 14" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"/></svg>`,
|
||||
};
|
||||
@@ -1 +1,15 @@
|
||||
<!doctype html><title>Titano</title>
|
||||
<!doctype html>
|
||||
<html lang="en">
|
||||
<head>
|
||||
<meta charset="utf-8">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1">
|
||||
<meta name="color-scheme" content="light">
|
||||
<title>Titano Server</title>
|
||||
<link rel="icon" href="favicon.svg" type="image/svg+xml">
|
||||
<link rel="stylesheet" href="admin.css">
|
||||
<script type="module" src="app.js"></script>
|
||||
</head>
|
||||
<body>
|
||||
<div id="app" aria-live="polite"></div>
|
||||
</body>
|
||||
</html>
|
||||
@@ -0,0 +1,12 @@
|
||||
import { applyStrings } from "../i18n.js";
|
||||
import { escapeHtml } from "../app.js";
|
||||
|
||||
export async function render(root, { info }) {
|
||||
root.innerHTML = `
|
||||
<div class="panel">
|
||||
<h2 data-i18n="Admin.About.Title"></h2>
|
||||
<p class="num">Titano Server ${escapeHtml(info?.version ?? "")} · API ${escapeHtml(String(info?.apiVersion ?? ""))}</p>
|
||||
<p class="num"><span data-i18n="Admin.About.Fingerprint"></span> ${escapeHtml(info?.tlsFingerprint ?? "–")}</p>
|
||||
</div>`;
|
||||
applyStrings(root);
|
||||
}
|
||||
@@ -0,0 +1,18 @@
|
||||
// Dashboard: storage, archive, jobs, render nodes (BRIEF §14.8). Data from the public API only.
|
||||
import { applyStrings } from "../i18n.js";
|
||||
|
||||
export async function render(root, { api, t, info, meta }) {
|
||||
const health = await api.get("/health").catch(() => null);
|
||||
meta.textContent = info ? `v${info.version} · TLS ${info.tlsFingerprint ? "auto" : "proxy"}` : "";
|
||||
root.innerHTML = `
|
||||
<div class="tiles">
|
||||
<div class="panel tile"><div class="label" data-i18n="Admin.Dashboard.Server"></div>
|
||||
<div class="value">${health?.status === "ok" ? `<span class="status-ok">●</span>` : `<span class="status-err">✕</span>`}<small>${health?.status ?? ""}</small></div>
|
||||
<div class="sub num">${info?.name ?? ""}</div></div>
|
||||
<div class="panel tile"><div class="label" data-i18n="Admin.Dashboard.Archive"></div>
|
||||
<div class="value">${health?.checks?.archive === "ok" ? `<span class="status-ok">●</span>` : `<span class="status-warn">▲</span>`}<small>${health?.checks?.archive ?? ""}</small></div></div>
|
||||
<div class="panel tile"><div class="label" data-i18n="Admin.Dashboard.Api"></div>
|
||||
<div class="value num">${info?.apiVersion ?? "–"}</div><div class="sub">${(info?.capabilities ?? []).join(" · ")}</div></div>
|
||||
</div>`;
|
||||
applyStrings(root);
|
||||
}
|
||||
@@ -0,0 +1,66 @@
|
||||
using System.Globalization;
|
||||
using System.Reflection;
|
||||
using Titano.Core.Localization;
|
||||
using Titano.Protocol;
|
||||
using Titano.Server.Configuration;
|
||||
|
||||
namespace Titano.Server.Api;
|
||||
|
||||
/// <summary><c>/health</c>, <c>/api/v1/server/info</c> and <c>/api/v1/i18n/{culture}</c>.</summary>
|
||||
public static class SystemEndpoints
|
||||
{
|
||||
private static readonly string[] AdminAreas = ["Common", "Admin"];
|
||||
|
||||
public static string Version { get; } =
|
||||
typeof(SystemEndpoints).Assembly.GetCustomAttribute<AssemblyInformationalVersionAttribute>()?.InformationalVersion ?? "0.0.0";
|
||||
|
||||
public static void Map(WebApplication app, ServerOptions options, ServerState state)
|
||||
{
|
||||
app.MapGet("/health", () =>
|
||||
{
|
||||
var checks = new Dictionary<string, string>(StringComparer.Ordinal)
|
||||
{
|
||||
["archive"] = Directory.Exists(options.ArchivePath) ? "ok" : "missing",
|
||||
["data"] = Directory.Exists(options.DataPath) ? "ok" : "missing",
|
||||
};
|
||||
return Results.Json(new HealthStatus("ok", Version, checks), ProtocolJson.Default.HealthStatus);
|
||||
});
|
||||
|
||||
var api = app.MapGroup("/api/v1");
|
||||
api.MapGet("/server/info", () => Results.Json(new ServerInfo(
|
||||
options.ServerName,
|
||||
Version,
|
||||
ApiVersion.Current,
|
||||
state.Capabilities,
|
||||
state.TlsFingerprint,
|
||||
["jpeg", "png", "tiff", "dng", "cr2", "cr3", "nef", "arw", "raf", "orf", "rw2", "pef", "heic", "webp"],
|
||||
new ServerLimits(options.MaxUploadBytes, options.ChunkSizeBytes)), ProtocolJson.Default.ServerInfo));
|
||||
|
||||
api.MapGet("/i18n/{culture}", (string culture) =>
|
||||
{
|
||||
CultureInfo ci;
|
||||
try
|
||||
{
|
||||
ci = Languages.BestMatch(CultureInfo.GetCultureInfo(culture));
|
||||
}
|
||||
catch (CultureNotFoundException)
|
||||
{
|
||||
ci = CultureInfo.GetCultureInfo("en");
|
||||
}
|
||||
var strings = new Dictionary<string, string>(StringComparer.Ordinal);
|
||||
foreach (var area in AdminAreas)
|
||||
foreach (var (k, v) in Loc.GetArea(area, ci)) strings[k] = v;
|
||||
strings["$culture"] = ci.Name;
|
||||
strings["$rtl"] = ci.TextInfo.IsRightToLeft ? "true" : "false";
|
||||
return Results.Json(strings, ProtocolJson.Default.DictionaryStringString);
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Process-wide facts computed at startup.</summary>
|
||||
public sealed class ServerState
|
||||
{
|
||||
public string? TlsFingerprint { get; set; }
|
||||
public List<string> Capabilities { get; } = ["uploads", "sync", "jobs", "render-nodes", "events"];
|
||||
public DateTimeOffset StartedAt { get; } = DateTimeOffset.UtcNow;
|
||||
}
|
||||
@@ -0,0 +1,130 @@
|
||||
using System.Text.Json;
|
||||
using System.Text.Json.Serialization;
|
||||
|
||||
namespace Titano.Server.Configuration;
|
||||
|
||||
public enum TlsMode
|
||||
{
|
||||
/// <summary>Self-signed certificate generated at first start (stored under /data/tls).</summary>
|
||||
Auto,
|
||||
|
||||
/// <summary>Certificate and key from PEM files.</summary>
|
||||
Pem,
|
||||
|
||||
/// <summary>Plain HTTP behind a TLS-terminating reverse proxy.</summary>
|
||||
Proxy,
|
||||
}
|
||||
|
||||
public enum DatabaseKind
|
||||
{
|
||||
Postgres,
|
||||
Sqlite,
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Server configuration (BRIEF §14.9): environment variables override <c>/data/server.json</c>, which overrides defaults.
|
||||
/// </summary>
|
||||
public sealed class ServerOptions
|
||||
{
|
||||
public string ServerName { get; set; } = "Titano Server";
|
||||
public string ArchivePath { get; set; } = OperatingSystem.IsWindows() ? @"C:\TitanoArchive" : "/archive";
|
||||
public string DataPath { get; set; } = OperatingSystem.IsWindows() ? Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.CommonApplicationData), "Titano Server") : "/data";
|
||||
public string? AdminUser { get; set; }
|
||||
public string? AdminPassword { get; set; }
|
||||
public DatabaseKind Database { get; set; } = OperatingSystem.IsWindows() ? DatabaseKind.Sqlite : DatabaseKind.Postgres;
|
||||
public string DbHost { get; set; } = "postgres";
|
||||
public int DbPort { get; set; } = 5432;
|
||||
public string DbName { get; set; } = "titano";
|
||||
public string DbUser { get; set; } = "titano";
|
||||
public string? DbPassword { get; set; }
|
||||
public string DbSslMode { get; set; } = "prefer";
|
||||
public int HttpPort { get; set; } = 8080;
|
||||
public int HttpsPort { get; set; } = 8443;
|
||||
public TlsMode TlsMode { get; set; } = TlsMode.Auto;
|
||||
public string? TlsCert { get; set; }
|
||||
public string? TlsKey { get; set; }
|
||||
public string Language { get; set; } = "en";
|
||||
public int Workers { get; set; } = Math.Max(1, Environment.ProcessorCount / 2);
|
||||
public bool Discovery { get; set; } = true;
|
||||
public long MaxUploadBytes { get; set; } = 2L * 1024 * 1024 * 1024;
|
||||
public int ChunkSizeBytes { get; set; } = 8 * 1024 * 1024;
|
||||
public int JobHistoryDays { get; set; } = 90;
|
||||
public int TokenLifetimeDays { get; set; } = 30;
|
||||
|
||||
[JsonIgnore]
|
||||
public string LogPath => Path.Combine(DataPath, "logs");
|
||||
|
||||
[JsonIgnore]
|
||||
public string TlsPath => Path.Combine(DataPath, "tls");
|
||||
|
||||
[JsonIgnore]
|
||||
public string UploadsPath => Path.Combine(DataPath, "uploads");
|
||||
|
||||
/// <summary>Loads <c>{DataPath}/server.json</c> (if present) then applies <c>TITANO_*</c> environment variables.</summary>
|
||||
public static ServerOptions Load(IReadOnlyDictionary<string, string?>? environment = null)
|
||||
{
|
||||
var env = environment ?? ReadEnvironment();
|
||||
string? Env(string name) => env.TryGetValue(name, out var v) && !string.IsNullOrWhiteSpace(v) ? v : null;
|
||||
|
||||
var dataPath = Env("TITANO_DATA_PATH") ?? new ServerOptions().DataPath;
|
||||
var options = new ServerOptions();
|
||||
var file = Path.Combine(dataPath, "server.json");
|
||||
if (File.Exists(file))
|
||||
{
|
||||
try
|
||||
{
|
||||
options = JsonSerializer.Deserialize(File.ReadAllText(file), ServerOptionsJson.Default.ServerOptions) ?? options;
|
||||
}
|
||||
catch (JsonException ex)
|
||||
{
|
||||
throw new InvalidOperationException($"{file} is not valid JSON: {ex.Message}", ex);
|
||||
}
|
||||
}
|
||||
options.DataPath = dataPath;
|
||||
|
||||
options.ServerName = Env("TITANO_SERVER_NAME") ?? options.ServerName;
|
||||
options.ArchivePath = Env("TITANO_ARCHIVE_PATH") ?? options.ArchivePath;
|
||||
options.AdminUser = Env("TITANO_ADMIN_USER") ?? options.AdminUser;
|
||||
options.AdminPassword = Env("TITANO_ADMIN_PASSWORD") ?? options.AdminPassword;
|
||||
if (Env("TITANO_DB") is { } db) options.Database = Enum.Parse<DatabaseKind>(db, ignoreCase: true);
|
||||
options.DbHost = Env("TITANO_DB_HOST") ?? options.DbHost;
|
||||
if (Env("TITANO_DB_PORT") is { } port) options.DbPort = int.Parse(port, System.Globalization.CultureInfo.InvariantCulture);
|
||||
options.DbName = Env("TITANO_DB_NAME") ?? options.DbName;
|
||||
options.DbUser = Env("TITANO_DB_USER") ?? options.DbUser;
|
||||
options.DbPassword = Env("TITANO_DB_PASSWORD") ?? options.DbPassword;
|
||||
options.DbSslMode = Env("TITANO_DB_SSLMODE") ?? options.DbSslMode;
|
||||
if (Env("TITANO_HTTP_PORT") is { } http) options.HttpPort = int.Parse(http, System.Globalization.CultureInfo.InvariantCulture);
|
||||
if (Env("TITANO_HTTPS_PORT") is { } https) options.HttpsPort = int.Parse(https, System.Globalization.CultureInfo.InvariantCulture);
|
||||
if (Env("TITANO_TLS_MODE") is { } tls) options.TlsMode = Enum.Parse<TlsMode>(tls, ignoreCase: true);
|
||||
options.TlsCert = Env("TITANO_TLS_CERT") ?? options.TlsCert;
|
||||
options.TlsKey = Env("TITANO_TLS_KEY") ?? options.TlsKey;
|
||||
options.Language = Env("TITANO_LANG") ?? options.Language;
|
||||
if (Env("TITANO_WORKERS") is { } workers) options.Workers = Math.Max(1, int.Parse(workers, System.Globalization.CultureInfo.InvariantCulture));
|
||||
if (Env("TITANO_DISCOVERY") is { } discovery) options.Discovery = bool.Parse(discovery);
|
||||
options.Validate();
|
||||
return options;
|
||||
}
|
||||
|
||||
private static Dictionary<string, string?> ReadEnvironment()
|
||||
{
|
||||
// Variables may differ only by case on Linux (no_proxy/NO_PROXY); the last one wins.
|
||||
var result = new Dictionary<string, string?>(StringComparer.OrdinalIgnoreCase);
|
||||
foreach (System.Collections.DictionaryEntry e in Environment.GetEnvironmentVariables()) result[(string)e.Key] = (string?)e.Value;
|
||||
return result;
|
||||
}
|
||||
|
||||
public void Validate()
|
||||
{
|
||||
if (!OperatingSystem.IsWindows() && Database == DatabaseKind.Sqlite)
|
||||
throw new InvalidOperationException("TITANO_DB=sqlite is supported on Windows only; use postgres (BRIEF §14.9).");
|
||||
if (TlsMode == TlsMode.Pem && (string.IsNullOrEmpty(TlsCert) || string.IsNullOrEmpty(TlsKey)))
|
||||
throw new InvalidOperationException("TITANO_TLS_MODE=pem requires TITANO_TLS_CERT and TITANO_TLS_KEY.");
|
||||
// Port 0 asks the OS for a free port (used by the in-process test host).
|
||||
if (HttpPort is < 0 or > 65535 || HttpsPort is < 0 or > 65535)
|
||||
throw new InvalidOperationException("Ports must be between 0 and 65535.");
|
||||
}
|
||||
}
|
||||
|
||||
[JsonSourceGenerationOptions(WriteIndented = true, UseStringEnumConverter = true, PropertyNameCaseInsensitive = true)]
|
||||
[JsonSerializable(typeof(ServerOptions))]
|
||||
internal sealed partial class ServerOptionsJson : JsonSerializerContext;
|
||||
@@ -0,0 +1,79 @@
|
||||
using System.Net;
|
||||
using System.Net.Sockets;
|
||||
using System.Security.Cryptography;
|
||||
using System.Security.Cryptography.X509Certificates;
|
||||
using Titano.Server.Configuration;
|
||||
|
||||
namespace Titano.Server.Hosting;
|
||||
|
||||
/// <summary>
|
||||
/// TLS certificate for Kestrel (BRIEF §14.2): self-signed ECDSA P-256 generated once and kept in /data/tls
|
||||
/// (mode auto), loaded from PEM files (mode pem), or none (mode proxy).
|
||||
/// </summary>
|
||||
public static class CertificateStore
|
||||
{
|
||||
public static X509Certificate2? Load(ServerOptions options, ILogger logger)
|
||||
{
|
||||
switch (options.TlsMode)
|
||||
{
|
||||
case TlsMode.Proxy:
|
||||
return null;
|
||||
case TlsMode.Pem:
|
||||
{
|
||||
var pem = X509Certificate2.CreateFromPemFile(options.TlsCert!, options.TlsKey);
|
||||
return Exportable(pem);
|
||||
}
|
||||
default:
|
||||
{
|
||||
Directory.CreateDirectory(options.TlsPath);
|
||||
var path = Path.Combine(options.TlsPath, "server.pfx");
|
||||
if (File.Exists(path))
|
||||
{
|
||||
var existing = X509CertificateLoader.LoadPkcs12FromFile(path, password: null, X509KeyStorageFlags.Exportable);
|
||||
if (existing.NotAfter > DateTime.UtcNow.AddDays(30)) return existing;
|
||||
logger.LogWarning("Self-signed certificate expires {NotAfter:u}; generating a new one (clients will see a new fingerprint).", existing.NotAfter);
|
||||
}
|
||||
var created = CreateSelfSigned(options.ServerName);
|
||||
File.WriteAllBytes(path, created.Export(X509ContentType.Pkcs12));
|
||||
if (!OperatingSystem.IsWindows()) File.SetUnixFileMode(path, UnixFileMode.UserRead | UnixFileMode.UserWrite);
|
||||
logger.LogInformation("Generated self-signed TLS certificate, SHA-256 fingerprint {Fingerprint}", Fingerprint(created));
|
||||
return created;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>SHA-256 fingerprint as colon-separated upper-case hex, as shown to users for trust-on-first-use.</summary>
|
||||
public static string Fingerprint(X509Certificate2 certificate) =>
|
||||
string.Join(':', certificate.GetCertHash(HashAlgorithmName.SHA256).Select(b => b.ToString("X2", System.Globalization.CultureInfo.InvariantCulture)));
|
||||
|
||||
public static X509Certificate2 CreateSelfSigned(string serverName)
|
||||
{
|
||||
using var key = ECDsa.Create(ECCurve.NamedCurves.nistP256);
|
||||
var request = new CertificateRequest(new X500DistinguishedName($"CN={Sanitize(serverName)}, O=Titano"), key, HashAlgorithmName.SHA256);
|
||||
var san = new SubjectAlternativeNameBuilder();
|
||||
san.AddDnsName("localhost");
|
||||
try
|
||||
{
|
||||
var host = Dns.GetHostName();
|
||||
san.AddDnsName(host);
|
||||
foreach (var address in Dns.GetHostAddresses(host).Where(a => a.AddressFamily is AddressFamily.InterNetwork or AddressFamily.InterNetworkV6))
|
||||
san.AddIpAddress(address);
|
||||
}
|
||||
catch (SocketException)
|
||||
{
|
||||
// Without name resolution the certificate still covers localhost.
|
||||
}
|
||||
san.AddIpAddress(IPAddress.Loopback);
|
||||
request.CertificateExtensions.Add(san.Build());
|
||||
request.CertificateExtensions.Add(new X509BasicConstraintsExtension(false, false, 0, true));
|
||||
request.CertificateExtensions.Add(new X509KeyUsageExtension(X509KeyUsageFlags.DigitalSignature, true));
|
||||
request.CertificateExtensions.Add(new X509EnhancedKeyUsageExtension([new Oid("1.3.6.1.5.5.7.3.1")], false));
|
||||
using var certificate = request.CreateSelfSigned(DateTimeOffset.UtcNow.AddDays(-1), DateTimeOffset.UtcNow.AddYears(5));
|
||||
return Exportable(certificate);
|
||||
}
|
||||
|
||||
private static X509Certificate2 Exportable(X509Certificate2 certificate) =>
|
||||
X509CertificateLoader.LoadPkcs12(certificate.Export(X509ContentType.Pkcs12), password: null, X509KeyStorageFlags.Exportable);
|
||||
|
||||
private static string Sanitize(string name) => new(name.Where(c => char.IsLetterOrDigit(c) || c is ' ' or '-' or '.').Take(60).ToArray());
|
||||
}
|
||||
@@ -0,0 +1,70 @@
|
||||
using System.Collections.Frozen;
|
||||
using System.Reflection;
|
||||
using System.Security.Cryptography;
|
||||
|
||||
namespace Titano.Server.Hosting;
|
||||
|
||||
/// <summary>
|
||||
/// Serves the admin panel from embedded resources named <c>admin/…</c> (no build step, single-file friendly),
|
||||
/// with strong ETags, conditional GET and SPA fallback to <c>index.html</c>.
|
||||
/// </summary>
|
||||
public sealed class EmbeddedStaticFiles
|
||||
{
|
||||
private static readonly FrozenDictionary<string, string> ContentTypes = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase)
|
||||
{
|
||||
[".html"] = "text/html; charset=utf-8",
|
||||
[".js"] = "text/javascript; charset=utf-8",
|
||||
[".mjs"] = "text/javascript; charset=utf-8",
|
||||
[".css"] = "text/css; charset=utf-8",
|
||||
[".svg"] = "image/svg+xml",
|
||||
[".png"] = "image/png",
|
||||
[".json"] = "application/json; charset=utf-8",
|
||||
[".ico"] = "image/x-icon",
|
||||
[".woff2"] = "font/woff2",
|
||||
}.ToFrozenDictionary(StringComparer.OrdinalIgnoreCase);
|
||||
|
||||
private readonly FrozenDictionary<string, (byte[] Content, string ETag, string ContentType)> _files;
|
||||
|
||||
public EmbeddedStaticFiles(Assembly assembly, string prefix)
|
||||
{
|
||||
var files = new Dictionary<string, (byte[], string, string)>(StringComparer.OrdinalIgnoreCase);
|
||||
foreach (var name in assembly.GetManifestResourceNames().Where(n => n.StartsWith(prefix, StringComparison.Ordinal)))
|
||||
{
|
||||
using var stream = assembly.GetManifestResourceStream(name)!;
|
||||
using var ms = new MemoryStream();
|
||||
stream.CopyTo(ms);
|
||||
var bytes = ms.ToArray();
|
||||
var path = name[prefix.Length..].Replace('\\', '/');
|
||||
var etag = "\"" + Convert.ToHexString(SHA256.HashData(bytes).AsSpan(0, 12)) + "\"";
|
||||
var type = ContentTypes.TryGetValue(Path.GetExtension(path), out var t) ? t : "application/octet-stream";
|
||||
files[path] = (bytes, etag, type);
|
||||
}
|
||||
_files = files.ToFrozenDictionary(StringComparer.OrdinalIgnoreCase);
|
||||
}
|
||||
|
||||
public int Count => _files.Count;
|
||||
|
||||
public async Task<bool> TryServeAsync(HttpContext context, string relativePath)
|
||||
{
|
||||
var path = relativePath.TrimStart('/');
|
||||
if (path.Length == 0) path = "index.html";
|
||||
if (!_files.TryGetValue(path, out var file))
|
||||
{
|
||||
// Client-side routes (no extension) fall back to the shell.
|
||||
if (Path.HasExtension(path) || !_files.TryGetValue("index.html", out file)) return false;
|
||||
}
|
||||
var response = context.Response;
|
||||
response.Headers.ETag = file.ETag;
|
||||
response.Headers.CacheControl = path.EndsWith(".html", StringComparison.OrdinalIgnoreCase) ? "no-cache" : "public, max-age=3600";
|
||||
response.Headers.XContentTypeOptions = "nosniff";
|
||||
if (context.Request.Headers.IfNoneMatch == file.ETag)
|
||||
{
|
||||
response.StatusCode = StatusCodes.Status304NotModified;
|
||||
return true;
|
||||
}
|
||||
response.ContentType = file.ContentType;
|
||||
response.ContentLength = file.Content.Length;
|
||||
if (!HttpMethods.IsHead(context.Request.Method)) await response.Body.WriteAsync(file.Content, context.RequestAborted);
|
||||
return true;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,54 @@
|
||||
using Titano.Core.Diagnostics;
|
||||
using CoreLogLevel = Titano.Core.Diagnostics.LogLevel;
|
||||
using MsLogLevel = Microsoft.Extensions.Logging.LogLevel;
|
||||
|
||||
namespace Titano.Server.Hosting;
|
||||
|
||||
/// <summary>In-house structured file logging for ASP.NET Core (rotating daily files under /data/logs).</summary>
|
||||
public sealed class FileLoggerProvider(FileLogSink sink) : ILoggerProvider
|
||||
{
|
||||
public ILogger CreateLogger(string categoryName) => new FileLogger(sink, categoryName);
|
||||
|
||||
public void Dispose() => sink.Dispose();
|
||||
|
||||
private sealed class FileLogger(FileLogSink sink, string category) : ILogger
|
||||
{
|
||||
public IDisposable? BeginScope<TState>(TState state) where TState : notnull => null;
|
||||
|
||||
public bool IsEnabled(MsLogLevel logLevel) => logLevel >= MsLogLevel.Information;
|
||||
|
||||
public void Log<TState>(MsLogLevel logLevel, EventId eventId, TState state, Exception? exception, Func<TState, Exception?, string> formatter)
|
||||
{
|
||||
if (!IsEnabled(logLevel)) return;
|
||||
var level = logLevel switch
|
||||
{
|
||||
MsLogLevel.Trace => CoreLogLevel.Trace,
|
||||
MsLogLevel.Debug => CoreLogLevel.Debug,
|
||||
MsLogLevel.Information => CoreLogLevel.Info,
|
||||
MsLogLevel.Warning => CoreLogLevel.Warning,
|
||||
_ => CoreLogLevel.Error,
|
||||
};
|
||||
sink.Write(level, category, formatter(state, exception), exception);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Bridges engine logging (Titano.Core.Diagnostics.Log) into ASP.NET Core logging.</summary>
|
||||
public sealed class LoggerSink(ILoggerFactory factory) : ILogSink
|
||||
{
|
||||
public void Write(CoreLogLevel level, string category, string message, Exception? exception)
|
||||
{
|
||||
var logger = factory.CreateLogger("Titano." + category);
|
||||
var ms = level switch
|
||||
{
|
||||
CoreLogLevel.Trace => MsLogLevel.Trace,
|
||||
CoreLogLevel.Debug => MsLogLevel.Debug,
|
||||
CoreLogLevel.Info => MsLogLevel.Information,
|
||||
CoreLogLevel.Warning => MsLogLevel.Warning,
|
||||
_ => MsLogLevel.Error,
|
||||
};
|
||||
#pragma warning disable CA2254 // Engine messages are preformatted.
|
||||
logger.Log(ms, exception, message);
|
||||
#pragma warning restore CA2254
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,26 @@
|
||||
using Titano.Server.Configuration;
|
||||
|
||||
namespace Titano.Server.Hosting;
|
||||
|
||||
/// <summary>
|
||||
/// <c>Titano.Server --healthcheck</c>: probes the local /health endpoint and exits 0/1, so the container
|
||||
/// HEALTHCHECK needs no curl/wget in the image.
|
||||
/// </summary>
|
||||
public static class HealthProbe
|
||||
{
|
||||
public static async Task<int> RunAsync()
|
||||
{
|
||||
try
|
||||
{
|
||||
var port = ServerOptions.Load().HttpPort;
|
||||
using var http = new HttpClient { Timeout = TimeSpan.FromSeconds(5) };
|
||||
using var response = await http.GetAsync(new Uri($"http://127.0.0.1:{port}/health")).ConfigureAwait(false);
|
||||
return response.IsSuccessStatusCode ? 0 : 1;
|
||||
}
|
||||
catch (Exception ex) when (ex is HttpRequestException or TaskCanceledException or InvalidOperationException)
|
||||
{
|
||||
await Console.Error.WriteLineAsync(ex.Message).ConfigureAwait(false);
|
||||
return 1;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,98 @@
|
||||
using Microsoft.AspNetCore.HttpOverrides;
|
||||
using Microsoft.AspNetCore.Server.Kestrel.Core;
|
||||
using Titano.Core.Diagnostics;
|
||||
using Titano.Protocol;
|
||||
using Titano.Server.Api;
|
||||
using Titano.Server.Configuration;
|
||||
|
||||
namespace Titano.Server.Hosting;
|
||||
|
||||
/// <summary>Builds the Titano Server web application from <see cref="ServerOptions"/> (used by Program and tests).</summary>
|
||||
public static class ServerHost
|
||||
{
|
||||
public static WebApplication Build(ServerOptions options, string[] args)
|
||||
{
|
||||
Directory.CreateDirectory(options.DataPath);
|
||||
Directory.CreateDirectory(options.LogPath);
|
||||
|
||||
var builder = WebApplication.CreateSlimBuilder(args);
|
||||
builder.Logging.ClearProviders();
|
||||
builder.Logging.AddSimpleConsole(c => c.SingleLine = true);
|
||||
builder.Logging.AddProvider(new FileLoggerProvider(new FileLogSink(options.LogPath, "server")));
|
||||
builder.Logging.AddFilter("Microsoft.AspNetCore", Microsoft.Extensions.Logging.LogLevel.Warning);
|
||||
builder.Logging.AddFilter("Microsoft.Hosting.Lifetime", Microsoft.Extensions.Logging.LogLevel.Information);
|
||||
|
||||
using var bootLoggerFactory = LoggerFactory.Create(l => l.AddSimpleConsole(c => c.SingleLine = true));
|
||||
var certificate = CertificateStore.Load(options, bootLoggerFactory.CreateLogger("Titano.Server"));
|
||||
var state = new ServerState { TlsFingerprint = certificate is null ? null : CertificateStore.Fingerprint(certificate) };
|
||||
|
||||
builder.WebHost.ConfigureKestrel(k =>
|
||||
{
|
||||
k.AddServerHeader = false;
|
||||
k.Limits.MaxRequestBodySize = options.ChunkSizeBytes + 64 * 1024;
|
||||
k.ListenAnyIP(options.HttpPort);
|
||||
if (certificate is not null) k.ListenAnyIP(options.HttpsPort, l =>
|
||||
{
|
||||
l.Protocols = HttpProtocols.Http1AndHttp2;
|
||||
l.UseHttps(certificate);
|
||||
});
|
||||
});
|
||||
builder.Services.AddSingleton(options);
|
||||
builder.Services.AddSingleton(state);
|
||||
builder.Services.ConfigureHttpJsonOptions(j => j.SerializerOptions.TypeInfoResolverChain.Insert(0, ProtocolJson.Default));
|
||||
if (options.TlsMode == TlsMode.Proxy)
|
||||
{
|
||||
builder.Services.Configure<ForwardedHeadersOptions>(f =>
|
||||
{
|
||||
f.ForwardedHeaders = ForwardedHeaders.XForwardedFor | ForwardedHeaders.XForwardedProto | ForwardedHeaders.XForwardedHost;
|
||||
f.KnownIPNetworks.Clear();
|
||||
f.KnownProxies.Clear();
|
||||
});
|
||||
}
|
||||
|
||||
var app = builder.Build();
|
||||
Log.SetSink(new LoggerSink(app.Services.GetRequiredService<ILoggerFactory>()));
|
||||
var logger = app.Logger;
|
||||
logger.LogInformation("Titano Server {Version} · archive {Archive} · data {Data} · TLS {Tls}{Fingerprint}",
|
||||
SystemEndpoints.Version, options.ArchivePath, options.DataPath, options.TlsMode,
|
||||
state.TlsFingerprint is null ? string.Empty : " · SHA-256 " + state.TlsFingerprint);
|
||||
|
||||
if (options.TlsMode == TlsMode.Proxy) app.UseForwardedHeaders();
|
||||
|
||||
app.Use(async (context, next) =>
|
||||
{
|
||||
context.Response.Headers[ApiVersion.Header] = ApiVersion.Current.ToString(System.Globalization.CultureInfo.InvariantCulture);
|
||||
context.Response.Headers.XContentTypeOptions = "nosniff";
|
||||
context.Response.Headers["Referrer-Policy"] = "no-referrer";
|
||||
try
|
||||
{
|
||||
await next(context);
|
||||
}
|
||||
catch (Exception ex) when (!context.Response.HasStarted && ex is not OperationCanceledException)
|
||||
{
|
||||
logger.LogError(ex, "Unhandled error on {Method} {Path}", context.Request.Method, context.Request.Path);
|
||||
context.Response.StatusCode = StatusCodes.Status500InternalServerError;
|
||||
await context.Response.WriteAsJsonAsync(new ApiError("internal", "Unexpected server error."), ProtocolJson.Default.ApiError);
|
||||
}
|
||||
});
|
||||
|
||||
var admin = new EmbeddedStaticFiles(typeof(ServerHost).Assembly, "admin/");
|
||||
app.MapGet("/", () => Results.Redirect("/admin/"));
|
||||
app.MapMethods("/admin/{**path}", ["GET", "HEAD"], async (HttpContext context, string? path) =>
|
||||
{
|
||||
// Relative asset URLs need the trailing slash.
|
||||
if (!context.Request.Path.Value!.EndsWith('/') && string.IsNullOrEmpty(path))
|
||||
{
|
||||
context.Response.Redirect("/admin/");
|
||||
return;
|
||||
}
|
||||
if (!await admin.TryServeAsync(context, path ?? string.Empty)) context.Response.StatusCode = StatusCodes.Status404NotFound;
|
||||
});
|
||||
|
||||
SystemEndpoints.Map(app, options, state);
|
||||
|
||||
app.MapFallback("/api/{**path}", () => Results.Json(new ApiError("not_found", "No such endpoint."), ProtocolJson.Default.ApiError, statusCode: 404));
|
||||
app.Lifetime.ApplicationStopping.Register(() => logger.LogInformation("Titano Server stopping"));
|
||||
return app;
|
||||
}
|
||||
}
|
||||
@@ -1,4 +1,11 @@
|
||||
var builder = WebApplication.CreateBuilder(args);
|
||||
var app = builder.Build();
|
||||
app.MapGet("/health", () => Results.Ok(new { status = "ok" }));
|
||||
app.Run();
|
||||
using Titano.Server.Configuration;
|
||||
using Titano.Server.Hosting;
|
||||
|
||||
if (args.Contains("--healthcheck")) return await HealthProbe.RunAsync();
|
||||
|
||||
var app = ServerHost.Build(ServerOptions.Load(), args);
|
||||
await app.RunAsync();
|
||||
return 0;
|
||||
|
||||
/// <summary>Entry point type, visible to the in-process test host.</summary>
|
||||
public partial class Program;
|
||||
Reference in new issue
Block a user