feat: secure frontend and provider ingress
This commit is contained in:
@@ -15,6 +15,7 @@ import {
|
||||
|
||||
interface RuntimeConfig {
|
||||
port: number;
|
||||
providerPort: number;
|
||||
databaseUrl: string;
|
||||
providerToken: string;
|
||||
heartbeatTimeoutMs: number;
|
||||
@@ -62,6 +63,7 @@ function readNumberEnv(name: string): number {
|
||||
function readConfig(): RuntimeConfig {
|
||||
return {
|
||||
port: readNumberEnv("PORT"),
|
||||
providerPort: readNumberEnv("PROVIDER_PORT"),
|
||||
databaseUrl: requiredEnv("DATABASE_URL"),
|
||||
providerToken: requiredEnv("PROVIDER_TOKEN"),
|
||||
heartbeatTimeoutMs: readNumberEnv("HEARTBEAT_TIMEOUT_MS"),
|
||||
@@ -408,20 +410,10 @@ async function dispatchTask(req: Request): Promise<Response> {
|
||||
return jsonResponse({ ok: true, taskId, status: "dispatched", providerOnline: true });
|
||||
}
|
||||
|
||||
async function route(req: Request, server: Server<WsData>): Promise<Response | undefined> {
|
||||
async function route(req: Request): Promise<Response> {
|
||||
const url = new URL(req.url);
|
||||
if (req.method === "OPTIONS") return jsonResponse({ ok: true });
|
||||
|
||||
if (url.pathname === "/ws/provider") {
|
||||
const token = url.searchParams.get("token") ?? req.headers.get("x-provider-token");
|
||||
if (token !== config.providerToken) {
|
||||
await recordEvent("provider_auth_failed", "unknown", { remote: req.headers.get("x-forwarded-for") ?? null });
|
||||
return jsonResponse({ ok: false, error: "invalid provider token" }, 401);
|
||||
}
|
||||
const upgraded = server.upgrade(req, { data: {} satisfies WsData });
|
||||
return upgraded ? undefined : jsonResponse({ ok: false, error: "websocket upgrade failed" }, 400);
|
||||
}
|
||||
|
||||
try {
|
||||
if (url.pathname === "/" || url.pathname === "/health") {
|
||||
return jsonResponse({ ok: true, service: "unidesk-core", dbReady, startedAt: serviceStartedAt.toISOString() });
|
||||
@@ -443,6 +435,23 @@ async function route(req: Request, server: Server<WsData>): Promise<Response | u
|
||||
}
|
||||
}
|
||||
|
||||
async function providerRoute(req: Request, server: Server<WsData>): Promise<Response | undefined> {
|
||||
const url = new URL(req.url);
|
||||
if (url.pathname === "/" || url.pathname === "/health") {
|
||||
return jsonResponse({ ok: true, service: "unidesk-provider-ingress", activeSocketCount: activeProviders.size });
|
||||
}
|
||||
if (url.pathname !== "/ws/provider") {
|
||||
return jsonResponse({ ok: false, error: "provider ingress only accepts /ws/provider", path: url.pathname }, 404);
|
||||
}
|
||||
const token = url.searchParams.get("token") ?? req.headers.get("x-provider-token");
|
||||
if (token !== config.providerToken) {
|
||||
await recordEvent("provider_auth_failed", "unknown", { remote: req.headers.get("x-forwarded-for") ?? null });
|
||||
return jsonResponse({ ok: false, error: "invalid provider token" }, 401);
|
||||
}
|
||||
const upgraded = server.upgrade(req, { data: {} satisfies WsData });
|
||||
return upgraded ? undefined : jsonResponse({ ok: false, error: "websocket upgrade failed" }, 400);
|
||||
}
|
||||
|
||||
function readLimit(url: URL, defaultLimit: number): number {
|
||||
const raw = url.searchParams.get("limit");
|
||||
if (raw === null) return defaultLimit;
|
||||
@@ -453,10 +462,16 @@ function readLimit(url: URL, defaultLimit: number): number {
|
||||
|
||||
await initDatabaseWithRetry();
|
||||
|
||||
const server = Bun.serve<WsData>({
|
||||
const apiServer = Bun.serve<WsData>({
|
||||
port: config.port,
|
||||
hostname: "0.0.0.0",
|
||||
fetch: route,
|
||||
});
|
||||
|
||||
const providerServer = Bun.serve<WsData>({
|
||||
port: config.providerPort,
|
||||
hostname: "0.0.0.0",
|
||||
fetch: providerRoute,
|
||||
websocket: {
|
||||
open(ws) {
|
||||
logger("info", "provider_socket_open", { remoteAddress: ws.remoteAddress });
|
||||
@@ -481,4 +496,8 @@ setInterval(() => {
|
||||
markStaleProvidersOffline().catch((error) => logger("error", "heartbeat_sweep_failed", { error: errorToJson(error) }));
|
||||
}, 10_000);
|
||||
|
||||
logger("info", "server_listening", { url: `http://0.0.0.0:${server.port}`, logFile: config.logFile });
|
||||
logger("info", "server_listening", {
|
||||
apiUrl: `http://0.0.0.0:${apiServer.port}`,
|
||||
providerIngressUrl: `ws://0.0.0.0:${providerServer.port}/ws/provider`,
|
||||
logFile: config.logFile,
|
||||
});
|
||||
|
||||
@@ -5,5 +5,9 @@
|
||||
"scripts": {
|
||||
"start": "bun run src/index.ts",
|
||||
"check": "tsc -p tsconfig.json --noEmit"
|
||||
},
|
||||
"dependencies": {
|
||||
"react": "18.3.1",
|
||||
"react-dom": "18.3.1"
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,153 +1,626 @@
|
||||
const rawCfg = window.UNIDESK_CONFIG || { coreApiUrl: "http://127.0.0.1:18080", corePort: "18080" };
|
||||
const cfg = { ...rawCfg, coreApiUrl: resolveCoreApiUrl(rawCfg) };
|
||||
const state = { overview: null, nodes: [], events: [], tasks: [], activeModule: "ops", activeTab: "overview", lastRefresh: null };
|
||||
const cfg = window.UNIDESK_CONFIG || { apiBaseUrl: "/api", authUsername: "admin" };
|
||||
const h = React.createElement;
|
||||
const { useEffect, useMemo, useState } = React;
|
||||
|
||||
const $ = (id) => document.getElementById(id);
|
||||
const fmtTime = (value) => value ? new Date(value).toLocaleTimeString() : "--";
|
||||
const compactJson = (value) => JSON.stringify(value ?? {}, null, 0);
|
||||
const MODULES = [
|
||||
{ id: "ops", label: "运行总览", code: "OPS", tabs: [
|
||||
{ id: "status", label: "态势总览" },
|
||||
{ id: "events", label: "事件摘要" },
|
||||
{ id: "logs", label: "服务日志" },
|
||||
] },
|
||||
{ id: "nodes", label: "资源节点", code: "NODE", tabs: [
|
||||
{ id: "list", label: "节点清单" },
|
||||
{ id: "labels", label: "资源标签" },
|
||||
{ id: "heartbeats", label: "心跳状态" },
|
||||
] },
|
||||
{ id: "tasks", label: "任务调度", code: "TASK", tabs: [
|
||||
{ id: "dispatch", label: "下发任务" },
|
||||
{ id: "history", label: "任务历史" },
|
||||
{ id: "results", label: "执行结果" },
|
||||
] },
|
||||
{ id: "config", label: "系统配置", code: "CFG", tabs: [
|
||||
{ id: "topology", label: "连接拓扑" },
|
||||
{ id: "auth", label: "认证策略" },
|
||||
{ id: "security", label: "安全边界" },
|
||||
] },
|
||||
];
|
||||
|
||||
function resolveCoreApiUrl(config) {
|
||||
const api = new URL(config.coreApiUrl, window.location.href);
|
||||
const pageHost = window.location.hostname;
|
||||
const apiIsLoopback = api.hostname === "127.0.0.1" || api.hostname === "localhost";
|
||||
const pageIsLoopback = pageHost === "127.0.0.1" || pageHost === "localhost";
|
||||
if (apiIsLoopback && !pageIsLoopback) {
|
||||
api.hostname = pageHost;
|
||||
api.port = String(config.corePort || api.port || "18080");
|
||||
}
|
||||
return api.origin;
|
||||
function fmtDate(value) {
|
||||
if (!value) return "--";
|
||||
const date = new Date(value);
|
||||
if (Number.isNaN(date.getTime())) return "--";
|
||||
return date.toLocaleString("zh-CN", { hour12: false });
|
||||
}
|
||||
|
||||
function setConnection(ok, text) {
|
||||
const dot = $("conn-dot");
|
||||
dot.className = `dot ${ok ? "ok" : "fail"}`;
|
||||
$("conn-text").textContent = text;
|
||||
function fmtClock(value) {
|
||||
return value.toLocaleTimeString("zh-CN", { hour12: false });
|
||||
}
|
||||
|
||||
async function api(path, options) {
|
||||
const res = await fetch(`${cfg.coreApiUrl}${path}`, options);
|
||||
const json = await res.json();
|
||||
if (!res.ok || json.ok === false) throw new Error(json.error?.message || json.error || `HTTP ${res.status}`);
|
||||
return json;
|
||||
function fmtDuration(seconds) {
|
||||
if (!Number.isFinite(seconds)) return "--";
|
||||
if (seconds < 60) return `${seconds}s`;
|
||||
if (seconds < 3600) return `${Math.floor(seconds / 60)}m ${seconds % 60}s`;
|
||||
return `${Math.floor(seconds / 3600)}h ${Math.floor((seconds % 3600) / 60)}m`;
|
||||
}
|
||||
|
||||
function metric(label, value, hint) {
|
||||
return `<article class="metric"><div class="label">${label}</div><div class="value">${value}</div><div class="hint">${hint}</div></article>`;
|
||||
function summarizeValue(value) {
|
||||
if (value === null || value === undefined) return "--";
|
||||
if (typeof value === "boolean") return value ? "是" : "否";
|
||||
if (typeof value === "number") return String(value);
|
||||
if (typeof value === "string") return value.length > 80 ? `${value.slice(0, 77)}...` : value;
|
||||
if (Array.isArray(value)) return `${value.length} 项`;
|
||||
if (typeof value === "object") return `${Object.keys(value).length} 字段`;
|
||||
return String(value);
|
||||
}
|
||||
|
||||
function renderMetrics() {
|
||||
const o = state.overview || {};
|
||||
$("metric-grid").innerHTML = [
|
||||
metric("DB Ready", o.dbReady ? "YES" : "NO", "PostgreSQL central state"),
|
||||
metric("Online Nodes", o.onlineNodeCount ?? 0, `${o.nodeCount ?? 0} registered`),
|
||||
metric("Active Sockets", o.activeSocketCount ?? 0, "Provider WebSocket"),
|
||||
metric("Pending Tasks", o.pendingTaskCount ?? 0, "queued / running"),
|
||||
].join("");
|
||||
$("refresh-age").textContent = state.lastRefresh ? `刷新 ${fmtTime(state.lastRefresh)}` : "--";
|
||||
function objectEntries(value) {
|
||||
if (!value || typeof value !== "object" || Array.isArray(value)) return [];
|
||||
return Object.entries(value);
|
||||
}
|
||||
|
||||
function renderNodes() {
|
||||
$("node-count").textContent = `${state.nodes.length} nodes`;
|
||||
$("nodes-body").innerHTML = state.nodes.map((node) => `
|
||||
<tr>
|
||||
<td><span class="badge ${node.status}">${node.status}</span></td>
|
||||
<td><div>${node.name}</div><div class="code">${node.providerId}</div></td>
|
||||
<td class="code">${compactJson(node.labels)}</td>
|
||||
<td>${fmtTime(node.lastHeartbeat)}</td>
|
||||
</tr>
|
||||
`).join("") || `<tr><td colspan="4">暂无 Provider 节点</td></tr>`;
|
||||
if (state.nodes[0] && !$("dispatch-provider").value) $("dispatch-provider").value = state.nodes[0].providerId;
|
||||
function safeId(value) {
|
||||
return String(value).replace(/[^a-zA-Z0-9_-]/g, "_");
|
||||
}
|
||||
|
||||
function renderEvents() {
|
||||
$("events-body").innerHTML = state.events.map((event) => `
|
||||
<tr>
|
||||
<td class="code">${event.id}</td>
|
||||
<td>${event.type}</td>
|
||||
<td class="code">${event.source}</td>
|
||||
<td class="code">${compactJson(event.payload)}</td>
|
||||
<td>${fmtTime(event.createdAt)}</td>
|
||||
</tr>
|
||||
`).join("") || `<tr><td colspan="5">暂无事件</td></tr>`;
|
||||
}
|
||||
|
||||
function render() {
|
||||
renderMetrics();
|
||||
renderNodes();
|
||||
renderEvents();
|
||||
document.querySelectorAll("[data-panel]").forEach((panel) => {
|
||||
const key = panel.getAttribute("data-panel");
|
||||
panel.style.display = state.activeTab === "overview" ? "" : key === state.activeTab ? "" : key === "overview" && state.activeModule === "ops" ? "" : "none";
|
||||
});
|
||||
}
|
||||
|
||||
async function refresh() {
|
||||
async function requestJson(path, options = {}) {
|
||||
const headers = new Headers(options.headers || {});
|
||||
if (options.body && !headers.has("content-type")) headers.set("content-type", "application/json");
|
||||
const response = await fetch(path, { credentials: "same-origin", ...options, headers });
|
||||
const text = await response.text();
|
||||
let body = null;
|
||||
try {
|
||||
const [overview, nodes, events] = await Promise.all([
|
||||
api("/api/overview"),
|
||||
api("/api/nodes"),
|
||||
api("/api/events?limit=100"),
|
||||
]);
|
||||
state.overview = overview;
|
||||
state.nodes = nodes.nodes || [];
|
||||
state.events = events.events || [];
|
||||
state.lastRefresh = new Date();
|
||||
setConnection(true, "核心在线");
|
||||
render();
|
||||
} catch (error) {
|
||||
setConnection(false, error.message);
|
||||
body = text ? JSON.parse(text) : null;
|
||||
} catch {
|
||||
body = { text };
|
||||
}
|
||||
if (!response.ok || body?.ok === false) {
|
||||
const message = body?.error?.message || body?.error || `HTTP ${response.status}`;
|
||||
const error = new Error(message);
|
||||
error.status = response.status;
|
||||
throw error;
|
||||
}
|
||||
return body;
|
||||
}
|
||||
|
||||
function bindNav() {
|
||||
document.querySelectorAll(".module").forEach((btn) => {
|
||||
btn.addEventListener("click", () => {
|
||||
document.querySelectorAll(".module").forEach((b) => b.classList.remove("active"));
|
||||
btn.classList.add("active");
|
||||
state.activeModule = btn.dataset.module;
|
||||
if (state.activeModule === "nodes") setTab("nodes");
|
||||
if (state.activeModule === "tasks") setTab("dispatch");
|
||||
if (state.activeModule === "config") setTab("events");
|
||||
if (state.activeModule === "ops") setTab("overview");
|
||||
});
|
||||
});
|
||||
document.querySelectorAll(".tab").forEach((btn) => btn.addEventListener("click", () => setTab(btn.dataset.tab)));
|
||||
function StatusBadge({ status, children }) {
|
||||
const normalized = String(status || "unknown").toLowerCase();
|
||||
return h("span", { className: `status-badge ${normalized}` }, children || status || "unknown");
|
||||
}
|
||||
|
||||
function setTab(tab) {
|
||||
state.activeTab = tab;
|
||||
document.querySelectorAll(".tab").forEach((b) => b.classList.toggle("active", b.dataset.tab === tab));
|
||||
render();
|
||||
function MetricCard({ label, value, hint, tone }) {
|
||||
return h("article", { className: `metric-card ${tone || ""}` },
|
||||
h("div", { className: "metric-label" }, label),
|
||||
h("div", { className: "metric-value" }, value),
|
||||
h("div", { className: "metric-hint" }, hint),
|
||||
);
|
||||
}
|
||||
|
||||
function bindDispatch() {
|
||||
$("dispatch-form").addEventListener("submit", async (event) => {
|
||||
function Panel({ title, eyebrow, actions, children, className }) {
|
||||
return h("section", { className: `panel ${className || ""}` },
|
||||
h("div", { className: "panel-head" },
|
||||
h("div", null,
|
||||
eyebrow ? h("p", { className: "panel-eyebrow" }, eyebrow) : null,
|
||||
h("h2", null, title),
|
||||
),
|
||||
actions ? h("div", { className: "panel-actions" }, actions) : null,
|
||||
),
|
||||
h("div", { className: "panel-body" }, children),
|
||||
);
|
||||
}
|
||||
|
||||
function RawButton({ title, data, onOpen, testId }) {
|
||||
return h("button", {
|
||||
type: "button",
|
||||
className: "ghost-btn",
|
||||
"data-testid": testId,
|
||||
onClick: () => onOpen(title, data),
|
||||
}, "查看原始JSON");
|
||||
}
|
||||
|
||||
function RawDialog({ raw, onClose }) {
|
||||
if (!raw) return null;
|
||||
return h("div", { className: "modal-backdrop", role: "presentation" },
|
||||
h("section", { className: "raw-dialog", role: "dialog", "aria-modal": "true", "aria-label": raw.title },
|
||||
h("div", { className: "raw-dialog-head" },
|
||||
h("h2", null, raw.title),
|
||||
h("button", { type: "button", className: "ghost-btn", onClick: onClose }, "关闭"),
|
||||
),
|
||||
h("pre", { className: "raw-json", "data-testid": "raw-json" }, JSON.stringify(raw.data, null, 2)),
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
function LabelChips({ labels, limit = 8 }) {
|
||||
const entries = objectEntries(labels).slice(0, limit);
|
||||
if (entries.length === 0) return h("span", { className: "muted" }, "无标签");
|
||||
return h("div", { className: "chip-row" },
|
||||
entries.map(([key, value]) => h("span", { key, className: "data-chip" },
|
||||
h("b", null, key),
|
||||
h("span", null, summarizeValue(value)),
|
||||
)),
|
||||
);
|
||||
}
|
||||
|
||||
function DataSummary({ data, empty = "无数据" }) {
|
||||
if (data === null || data === undefined) return h("span", { className: "muted" }, empty);
|
||||
if (typeof data !== "object") return h("span", { className: "summary-value" }, summarizeValue(data));
|
||||
if (Array.isArray(data)) return h("span", { className: "summary-value" }, `${data.length} 项列表`);
|
||||
const entries = Object.entries(data).slice(0, 5);
|
||||
if (entries.length === 0) return h("span", { className: "muted" }, empty);
|
||||
return h("div", { className: "summary-grid" }, entries.map(([key, value]) =>
|
||||
h("span", { key, className: "summary-item" }, h("b", null, key), h("span", null, summarizeValue(value))),
|
||||
));
|
||||
}
|
||||
|
||||
function EmptyState({ title, text }) {
|
||||
return h("div", { className: "empty-state" }, h("strong", null, title), h("span", null, text));
|
||||
}
|
||||
|
||||
function LoginScreen({ onLogin }) {
|
||||
const [username, setUsername] = useState(cfg.authUsername || "admin");
|
||||
const [password, setPassword] = useState("");
|
||||
const [error, setError] = useState("");
|
||||
const [busy, setBusy] = useState(false);
|
||||
|
||||
async function submit(event) {
|
||||
event.preventDefault();
|
||||
const providerId = $("dispatch-provider").value.trim();
|
||||
const command = $("dispatch-command").value;
|
||||
const payloadText = $("dispatch-payload").value.trim();
|
||||
setBusy(true);
|
||||
setError("");
|
||||
try {
|
||||
const payload = payloadText ? JSON.parse(payloadText) : {};
|
||||
const result = await api("/api/dispatch", {
|
||||
const session = await requestJson("/login", { method: "POST", body: JSON.stringify({ username, password }) });
|
||||
onLogin(session);
|
||||
} catch (err) {
|
||||
setError(err.message || "登录失败");
|
||||
} finally {
|
||||
setBusy(false);
|
||||
}
|
||||
}
|
||||
|
||||
return h("main", { className: "login-screen", "data-testid": "login-screen" },
|
||||
h("section", { className: "login-card" },
|
||||
h("div", { className: "login-brand" }, h("span", { className: "brand-mark" }, "UD"), h("div", null, h("h1", null, "UniDesk"), h("p", null, "Control Plane Login"))),
|
||||
h("form", { className: "login-form", onSubmit: submit },
|
||||
h("label", null, "账号", h("input", { name: "username", autoComplete: "username", value: username, onChange: (event) => setUsername(event.target.value) })),
|
||||
h("label", null, "密码", h("input", { name: "password", type: "password", autoComplete: "current-password", value: password, onChange: (event) => setPassword(event.target.value) })),
|
||||
error ? h("div", { className: "form-error" }, error) : null,
|
||||
h("button", { type: "submit", disabled: busy }, busy ? "登录中" : "登录"),
|
||||
),
|
||||
h("div", { className: "login-note" }, "默认账号由 config.json 注入;公网入口只暴露前端登录面。"),
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
function TopBar({ connection, lastRefresh, onRefresh, onLogout, session, clock }) {
|
||||
return h("header", { className: "topbar" },
|
||||
h("div", null, h("p", { className: "eyebrow" }, "Distributed Work Platform"), h("h1", null, "UniDesk 控制平面")),
|
||||
h("div", { className: "status-strip" },
|
||||
h("span", { className: `dot ${connection.ok ? "ok" : "fail"}` }),
|
||||
h("span", { "data-testid": "conn-text" }, connection.text),
|
||||
h("span", null, lastRefresh ? `刷新 ${fmtClock(lastRefresh)}` : "未刷新"),
|
||||
h("span", null, fmtClock(clock)),
|
||||
h("span", { className: "user-pill" }, session?.user?.username || "--"),
|
||||
h("button", { type: "button", className: "ghost-btn", onClick: onRefresh }, "刷新"),
|
||||
h("button", { type: "button", className: "ghost-btn danger", onClick: onLogout }, "退出"),
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
function Sidebar({ activeModule, onChange }) {
|
||||
return h("aside", { className: "rail", "aria-label": "主模块" },
|
||||
h("div", { className: "brand" }, h("span", { className: "brand-mark" }, "UD"), h("span", { className: "brand-text" }, "UniDesk")),
|
||||
MODULES.map((module) => h("button", {
|
||||
key: module.id,
|
||||
type: "button",
|
||||
className: `module ${activeModule === module.id ? "active" : ""}`,
|
||||
onClick: () => onChange(module.id),
|
||||
}, h("span", { className: "module-code" }, module.code), h("span", null, module.label))),
|
||||
);
|
||||
}
|
||||
|
||||
function TabBar({ module, activeTab, onChange }) {
|
||||
return h("nav", { className: "tabs", "aria-label": `${module.label} 子功能` },
|
||||
module.tabs.map((tab) => h("button", {
|
||||
key: tab.id,
|
||||
type: "button",
|
||||
className: `tab ${activeTab === tab.id ? "active" : ""}`,
|
||||
onClick: () => onChange(tab.id),
|
||||
}, tab.label)),
|
||||
);
|
||||
}
|
||||
|
||||
function OverviewPage({ data, onRaw }) {
|
||||
const overview = data.overview || {};
|
||||
const onlineNodes = data.nodes.filter((node) => node.status === "online");
|
||||
const recentTasks = data.tasks.slice(0, 5);
|
||||
return h("div", { className: "page-grid overview-grid" },
|
||||
h(Panel, { title: "核心指标", eyebrow: "Control" },
|
||||
h("div", { className: "metric-grid" },
|
||||
h(MetricCard, { label: "数据库", value: overview.dbReady ? "READY" : "WAIT", hint: "PostgreSQL internal network", tone: overview.dbReady ? "ok" : "warn" }),
|
||||
h(MetricCard, { label: "在线节点", value: overview.onlineNodeCount ?? 0, hint: `${overview.nodeCount ?? 0} registered`, tone: "ok" }),
|
||||
h(MetricCard, { label: "WebSocket", value: overview.activeSocketCount ?? 0, hint: "Provider ingress sockets" }),
|
||||
h(MetricCard, { label: "待处理任务", value: overview.pendingTaskCount ?? 0, hint: `uptime ${fmtDuration(overview.uptimeSeconds ?? 0)}` }),
|
||||
),
|
||||
),
|
||||
h(Panel, { title: "本机 Provider", eyebrow: "Self Connected" },
|
||||
onlineNodes.length === 0 ? h(EmptyState, { title: "暂无在线节点", text: "provider-gateway 未完成自接入" }) :
|
||||
h("div", { className: "node-card-list" }, onlineNodes.slice(0, 4).map((node) => h(NodeCard, { key: node.providerId, node, onRaw }))),
|
||||
),
|
||||
h(Panel, { title: "最近任务", eyebrow: "Dispatch" },
|
||||
recentTasks.length === 0 ? h(EmptyState, { title: "暂无任务", text: "可以在任务调度模块发起 docker.ps 或 echo" }) :
|
||||
h("div", { className: "compact-list" }, recentTasks.map((task) => h(TaskCompactRow, { key: task.id, task, onRaw }))),
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
function NodeCard({ node, onRaw }) {
|
||||
return h("article", { className: "node-card" },
|
||||
h("div", { className: "node-card-head" },
|
||||
h("div", null, h("strong", null, node.name), h("code", null, node.providerId)),
|
||||
h(StatusBadge, { status: node.status }),
|
||||
),
|
||||
h(LabelChips, { labels: node.labels, limit: 6 }),
|
||||
h("div", { className: "node-card-foot" },
|
||||
h("span", null, `心跳 ${fmtDate(node.lastHeartbeat)}`),
|
||||
h(RawButton, { title: `Provider ${node.providerId}`, data: node, onOpen: onRaw, testId: `raw-node-${safeId(node.providerId)}` }),
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
function EventsPage({ events, onRaw }) {
|
||||
return h(Panel, { title: "事件摘要", eyebrow: "Latest 100" },
|
||||
events.length === 0 ? h(EmptyState, { title: "暂无事件", text: "Provider 注册、心跳超时和任务状态会写入事件流" }) :
|
||||
h("div", { className: "table-wrap" }, h("table", null,
|
||||
h("thead", null, h("tr", null, h("th", null, "ID"), h("th", null, "类型"), h("th", null, "来源"), h("th", null, "摘要"), h("th", null, "时间"), h("th", null, "操作"))),
|
||||
h("tbody", null, events.map((event) => h("tr", { key: event.id },
|
||||
h("td", null, h("code", null, event.id)),
|
||||
h("td", null, h(StatusBadge, { status: event.type }, event.type)),
|
||||
h("td", null, h("code", null, event.source)),
|
||||
h("td", null, h(DataSummary, { data: event.payload })),
|
||||
h("td", null, fmtDate(event.createdAt)),
|
||||
h("td", null, h(RawButton, { title: `Event ${event.id}`, data: event, onOpen: onRaw })),
|
||||
))),
|
||||
)),
|
||||
);
|
||||
}
|
||||
|
||||
function LogsPage({ logs, onRaw }) {
|
||||
return h(Panel, { title: "服务日志", eyebrow: "Core Recent" },
|
||||
logs.length === 0 ? h(EmptyState, { title: "暂无日志", text: "backend-core 内存日志会在请求和 provider 事件后出现" }) :
|
||||
h("div", { className: "log-list" }, logs.slice(-80).reverse().map((log, index) => h("article", { key: index, className: `log-row ${log.level || "info"}` },
|
||||
h("span", null, fmtDate(log.ts)),
|
||||
h("b", null, log.level || "info"),
|
||||
h("strong", null, log.message || "log"),
|
||||
h(DataSummary, { data: log.data, empty: "无附加字段" }),
|
||||
h(RawButton, { title: `Log ${log.message || index}`, data: log, onOpen: onRaw }),
|
||||
))),
|
||||
);
|
||||
}
|
||||
|
||||
function NodeListPage({ nodes, onRaw }) {
|
||||
return h(Panel, { title: "节点清单", eyebrow: `${nodes.length} Providers` },
|
||||
nodes.length === 0 ? h(EmptyState, { title: "暂无 Provider 节点", text: "确认 provider-gateway 已连接 provider ingress" }) :
|
||||
h("div", { className: "table-wrap" }, h("table", null,
|
||||
h("thead", null, h("tr", null, h("th", null, "状态"), h("th", null, "Provider"), h("th", null, "资源标签"), h("th", null, "连接时间"), h("th", null, "最后心跳"), h("th", null, "操作"))),
|
||||
h("tbody", null, nodes.map((node) => h("tr", { key: node.providerId },
|
||||
h("td", null, h(StatusBadge, { status: node.status })),
|
||||
h("td", null, h("strong", null, node.name), h("code", null, node.providerId)),
|
||||
h("td", null, h(LabelChips, { labels: node.labels, limit: 5 })),
|
||||
h("td", null, fmtDate(node.connectedAt)),
|
||||
h("td", null, fmtDate(node.lastHeartbeat)),
|
||||
h("td", null, h(RawButton, { title: `Provider ${node.providerId}`, data: node, onOpen: onRaw, testId: `raw-node-table-${safeId(node.providerId)}` })),
|
||||
))),
|
||||
)),
|
||||
);
|
||||
}
|
||||
|
||||
function LabelsPage({ nodes }) {
|
||||
const labels = useMemo(() => {
|
||||
const rows = [];
|
||||
for (const node of nodes) {
|
||||
for (const [key, value] of objectEntries(node.labels)) rows.push({ providerId: node.providerId, name: node.name, key, value });
|
||||
}
|
||||
return rows;
|
||||
}, [nodes]);
|
||||
return h(Panel, { title: "资源标签", eyebrow: "Structured Labels" },
|
||||
labels.length === 0 ? h(EmptyState, { title: "暂无标签", text: "provider-gateway 注册消息会同步资源标签" }) :
|
||||
h("div", { className: "label-matrix" }, labels.map((row) => h("article", { key: `${row.providerId}-${row.key}`, className: "label-card" },
|
||||
h("span", null, row.key),
|
||||
h("strong", null, summarizeValue(row.value)),
|
||||
h("code", null, row.providerId),
|
||||
))),
|
||||
);
|
||||
}
|
||||
|
||||
function HeartbeatPage({ nodes }) {
|
||||
return h(Panel, { title: "心跳状态", eyebrow: "Provider Liveness" },
|
||||
nodes.length === 0 ? h(EmptyState, { title: "无心跳", text: "等待 provider 注册和 heartbeat" }) :
|
||||
h("div", { className: "heartbeat-list" }, nodes.map((node) => h("article", { key: node.providerId, className: "heartbeat-row" },
|
||||
h("span", { className: `pulse ${node.status}` }),
|
||||
h("div", null, h("strong", null, node.name), h("code", null, node.providerId)),
|
||||
h("div", null, h("span", null, "connected"), h("b", null, fmtDate(node.connectedAt))),
|
||||
h("div", null, h("span", null, "last heartbeat"), h("b", null, fmtDate(node.lastHeartbeat))),
|
||||
))),
|
||||
);
|
||||
}
|
||||
|
||||
function DispatchPage({ nodes, onDispatched, onRaw }) {
|
||||
const onlineNodes = nodes.filter((node) => node.status === "online");
|
||||
const [providerId, setProviderId] = useState(onlineNodes[0]?.providerId || nodes[0]?.providerId || "");
|
||||
const [command, setCommand] = useState("docker.ps");
|
||||
const [source, setSource] = useState("frontend");
|
||||
const [note, setNote] = useState("operator-check");
|
||||
const [priority, setPriority] = useState("normal");
|
||||
const [rawOpen, setRawOpen] = useState(false);
|
||||
const [rawPayload, setRawPayload] = useState("");
|
||||
const [busy, setBusy] = useState(false);
|
||||
const [result, setResult] = useState(null);
|
||||
const [error, setError] = useState("");
|
||||
|
||||
useEffect(() => {
|
||||
if (!providerId && (onlineNodes[0]?.providerId || nodes[0]?.providerId)) setProviderId(onlineNodes[0]?.providerId || nodes[0].providerId);
|
||||
}, [nodes.length, onlineNodes.length, providerId]);
|
||||
|
||||
function structuredPayload() {
|
||||
return { source, note, priority };
|
||||
}
|
||||
|
||||
function revealRawPayload() {
|
||||
setRawPayload(JSON.stringify(structuredPayload(), null, 2));
|
||||
setRawOpen(true);
|
||||
}
|
||||
|
||||
async function submit(event) {
|
||||
event.preventDefault();
|
||||
setBusy(true);
|
||||
setError("");
|
||||
try {
|
||||
const payload = rawOpen ? JSON.parse(rawPayload || "{}") : structuredPayload();
|
||||
const response = await requestJson(`${cfg.apiBaseUrl}/dispatch`, {
|
||||
method: "POST",
|
||||
headers: { "content-type": "application/json" },
|
||||
body: JSON.stringify({ providerId, command, payload }),
|
||||
});
|
||||
$("dispatch-result").textContent = JSON.stringify(result, null, 2);
|
||||
await refresh();
|
||||
} catch (error) {
|
||||
$("dispatch-result").textContent = `ERROR: ${error.message}`;
|
||||
setResult(response);
|
||||
await onDispatched();
|
||||
} catch (err) {
|
||||
setError(err.message || "下发失败");
|
||||
} finally {
|
||||
setBusy(false);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
return h("div", { className: "page-grid dispatch-grid" },
|
||||
h(Panel, { title: "下发任务", eyebrow: "Real WebSocket Dispatch" },
|
||||
h("form", { className: "dispatch-form", onSubmit: submit },
|
||||
h("label", null, "Provider", h("select", { value: providerId, onChange: (event) => setProviderId(event.target.value) },
|
||||
nodes.map((node) => h("option", { key: node.providerId, value: node.providerId }, `${node.name} / ${node.providerId}`)),
|
||||
)),
|
||||
h("label", null, "Command", h("select", { value: command, onChange: (event) => setCommand(event.target.value) },
|
||||
h("option", { value: "docker.ps" }, "docker.ps"),
|
||||
h("option", { value: "echo" }, "echo"),
|
||||
)),
|
||||
h("label", null, "来源", h("input", { value: source, onChange: (event) => setSource(event.target.value) })),
|
||||
h("label", null, "备注", h("input", { value: note, onChange: (event) => setNote(event.target.value) })),
|
||||
h("label", null, "优先级", h("select", { value: priority, onChange: (event) => setPriority(event.target.value) },
|
||||
h("option", { value: "normal" }, "normal"),
|
||||
h("option", { value: "low" }, "low"),
|
||||
h("option", { value: "urgent" }, "urgent"),
|
||||
)),
|
||||
h("div", { className: "dispatch-actions" },
|
||||
h("button", { type: "button", className: "ghost-btn", onClick: revealRawPayload }, "查看原始JSON"),
|
||||
h("button", { type: "submit", disabled: busy || !providerId }, busy ? "下发中" : "下发任务"),
|
||||
),
|
||||
rawOpen ? h("label", { className: "raw-editor-label" }, "高级 Payload", h("textarea", { className: "raw-editor", value: rawPayload, onChange: (event) => setRawPayload(event.target.value) })) : null,
|
||||
error ? h("div", { className: "form-error wide" }, error) : null,
|
||||
),
|
||||
),
|
||||
h(Panel, { title: "下发结果", eyebrow: "Response" },
|
||||
result ? h("div", { className: "result-card" },
|
||||
h(StatusBadge, { status: result.status || "queued" }, result.status || "queued"),
|
||||
h("dl", null,
|
||||
h("dt", null, "Task ID"), h("dd", null, h("code", null, result.taskId || "--")),
|
||||
h("dt", null, "Provider 在线"), h("dd", null, summarizeValue(result.providerOnline)),
|
||||
),
|
||||
h(RawButton, { title: "Dispatch Response", data: result, onOpen: onRaw }),
|
||||
) : h(EmptyState, { title: "等待操作", text: "任务响应会以结构化结果卡展示" }),
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
function tick() {
|
||||
$("clock").textContent = new Date().toLocaleTimeString();
|
||||
function TaskCompactRow({ task, onRaw }) {
|
||||
return h("article", { className: "compact-row" },
|
||||
h(StatusBadge, { status: task.status }),
|
||||
h("div", null, h("strong", null, task.command), h("code", null, task.id)),
|
||||
h("span", null, fmtDate(task.updatedAt)),
|
||||
h(RawButton, { title: `Task ${task.id}`, data: task, onOpen: onRaw }),
|
||||
);
|
||||
}
|
||||
|
||||
bindNav();
|
||||
bindDispatch();
|
||||
tick();
|
||||
setInterval(tick, 1000);
|
||||
refresh();
|
||||
setInterval(refresh, 5000);
|
||||
function TaskHistoryPage({ tasks, onRaw }) {
|
||||
return h(Panel, { title: "任务历史", eyebrow: `${tasks.length} Tasks` },
|
||||
tasks.length === 0 ? h(EmptyState, { title: "暂无任务", text: "下发任务后会在这里看到生命周期" }) :
|
||||
h("div", { className: "table-wrap" }, h("table", null,
|
||||
h("thead", null, h("tr", null, h("th", null, "状态"), h("th", null, "任务"), h("th", null, "Provider"), h("th", null, "载荷摘要"), h("th", null, "更新时间"), h("th", null, "操作"))),
|
||||
h("tbody", null, tasks.map((task) => h("tr", { key: task.id },
|
||||
h("td", null, h(StatusBadge, { status: task.status })),
|
||||
h("td", null, h("strong", null, task.command), h("code", null, task.id)),
|
||||
h("td", null, h("code", null, task.providerId)),
|
||||
h("td", null, h(DataSummary, { data: task.payload })),
|
||||
h("td", null, fmtDate(task.updatedAt)),
|
||||
h("td", null, h(RawButton, { title: `Task ${task.id}`, data: task, onOpen: onRaw })),
|
||||
))),
|
||||
)),
|
||||
);
|
||||
}
|
||||
|
||||
function TaskResultsPage({ tasks, onRaw }) {
|
||||
const finished = tasks.filter((task) => ["succeeded", "failed"].includes(task.status));
|
||||
return h(Panel, { title: "执行结果", eyebrow: "Finished Tasks" },
|
||||
finished.length === 0 ? h(EmptyState, { title: "暂无结果", text: "任务完成后展示 provider 返回的结构化摘要" }) :
|
||||
h("div", { className: "result-grid" }, finished.map((task) => h("article", { key: task.id, className: "result-card" },
|
||||
h("div", { className: "node-card-head" }, h("strong", null, task.command), h(StatusBadge, { status: task.status })),
|
||||
h("code", null, task.id),
|
||||
h(DataSummary, { data: task.result, empty: "无执行输出" }),
|
||||
h(RawButton, { title: `Task Result ${task.id}`, data: task, onOpen: onRaw }),
|
||||
))),
|
||||
);
|
||||
}
|
||||
|
||||
function TopologyPage({ data }) {
|
||||
const overview = data.overview || {};
|
||||
return h("div", { className: "page-grid topology-grid" },
|
||||
h(Panel, { title: "公开入口", eyebrow: "Public" },
|
||||
h("div", { className: "endpoint-list" },
|
||||
h("article", null, h("b", null, "Frontend"), h("span", null, cfg.frontendPublicUrl || window.location.origin), h(StatusBadge, { status: "online" }, "public")),
|
||||
h("article", null, h("b", null, "Provider Ingress"), h("span", null, cfg.providerIngressPublicUrl || "ws://public/ws/provider"), h(StatusBadge, { status: "online" }, "public")),
|
||||
),
|
||||
),
|
||||
h(Panel, { title: "内部服务", eyebrow: "Docker Network Only" },
|
||||
h("div", { className: "endpoint-list" },
|
||||
h("article", null, h("b", null, "backend-core API"), h("span", null, "http://backend-core:8080"), h(StatusBadge, { status: "internal" }, "internal")),
|
||||
h("article", null, h("b", null, "database"), h("span", null, "postgres://database:5432/unidesk"), h(StatusBadge, { status: "internal" }, "internal")),
|
||||
),
|
||||
),
|
||||
h(Panel, { title: "运行态", eyebrow: "Runtime" },
|
||||
h("div", { className: "metric-grid" },
|
||||
h(MetricCard, { label: "DB Ready", value: overview.dbReady ? "YES" : "NO", hint: "internal health" }),
|
||||
h(MetricCard, { label: "Online Nodes", value: overview.onlineNodeCount ?? 0, hint: "provider-gateway self-link" }),
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
function AuthPage({ session }) {
|
||||
return h(Panel, { title: "认证策略", eyebrow: "Frontend Login" },
|
||||
h("div", { className: "policy-grid" },
|
||||
h("article", null, h("span", null, "默认账号"), h("strong", null, cfg.authUsername || "admin")),
|
||||
h("article", null, h("span", null, "当前会话"), h("strong", null, session?.user?.username || "--")),
|
||||
h("article", null, h("span", null, "Session TTL"), h("strong", null, `${cfg.sessionTtlSeconds || 0}s`)),
|
||||
h("article", null, h("span", null, "API 访问"), h("strong", null, "同源 Cookie 保护")),
|
||||
),
|
||||
h("p", { className: "muted paragraph" }, "浏览器只访问 frontend 同源接口;frontend 容器使用 Docker 内网代理 backend-core API。"),
|
||||
);
|
||||
}
|
||||
|
||||
function SecurityPage() {
|
||||
return h(Panel, { title: "安全边界", eyebrow: "Exposure Rule" },
|
||||
h("div", { className: "security-board" },
|
||||
h("article", { className: "allow" }, h("b", null, "允许公网"), h("span", null, "frontend 登录入口"), h("span", null, "provider ingress WebSocket/health")),
|
||||
h("article", { className: "deny" }, h("b", null, "禁止公网"), h("span", null, "backend-core REST API"), h("span", null, "PostgreSQL database")),
|
||||
h("article", null, h("b", null, "数据库卷"), h("span", null, "named volume unidesk_pgdata_10gb"), h("span", null, "CLI stop/start 不删除数据卷")),
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
function WorkArea({ activeModule, activeTab, data, session, refresh, onRaw }) {
|
||||
if (activeModule === "ops" && activeTab === "status") return h(OverviewPage, { data, onRaw });
|
||||
if (activeModule === "ops" && activeTab === "events") return h(EventsPage, { events: data.events, onRaw });
|
||||
if (activeModule === "ops" && activeTab === "logs") return h(LogsPage, { logs: data.logs, onRaw });
|
||||
if (activeModule === "nodes" && activeTab === "list") return h(NodeListPage, { nodes: data.nodes, onRaw });
|
||||
if (activeModule === "nodes" && activeTab === "labels") return h(LabelsPage, { nodes: data.nodes });
|
||||
if (activeModule === "nodes" && activeTab === "heartbeats") return h(HeartbeatPage, { nodes: data.nodes });
|
||||
if (activeModule === "tasks" && activeTab === "dispatch") return h(DispatchPage, { nodes: data.nodes, onDispatched: refresh, onRaw });
|
||||
if (activeModule === "tasks" && activeTab === "history") return h(TaskHistoryPage, { tasks: data.tasks, onRaw });
|
||||
if (activeModule === "tasks" && activeTab === "results") return h(TaskResultsPage, { tasks: data.tasks, onRaw });
|
||||
if (activeModule === "config" && activeTab === "topology") return h(TopologyPage, { data });
|
||||
if (activeModule === "config" && activeTab === "auth") return h(AuthPage, { session });
|
||||
if (activeModule === "config" && activeTab === "security") return h(SecurityPage);
|
||||
return h(EmptyState, { title: "未找到页面", text: "请选择左侧主模块和顶部子功能标签" });
|
||||
}
|
||||
|
||||
function Shell({ session, onLogout }) {
|
||||
const [activeModule, setActiveModule] = useState("ops");
|
||||
const [activeTabs, setActiveTabs] = useState({ ops: "status", nodes: "list", tasks: "dispatch", config: "topology" });
|
||||
const [data, setData] = useState({ overview: null, nodes: [], events: [], tasks: [], logs: [] });
|
||||
const [connection, setConnection] = useState({ ok: false, text: "连接中" });
|
||||
const [lastRefresh, setLastRefresh] = useState(null);
|
||||
const [clock, setClock] = useState(new Date());
|
||||
const [raw, setRaw] = useState(null);
|
||||
|
||||
const module = MODULES.find((item) => item.id === activeModule) || MODULES[0];
|
||||
const activeTab = activeTabs[activeModule] || module.tabs[0].id;
|
||||
|
||||
async function refresh() {
|
||||
try {
|
||||
const [overview, nodes, events, tasks, logs] = await Promise.all([
|
||||
requestJson(`${cfg.apiBaseUrl}/overview`),
|
||||
requestJson(`${cfg.apiBaseUrl}/nodes`),
|
||||
requestJson(`${cfg.apiBaseUrl}/events?limit=100`),
|
||||
requestJson(`${cfg.apiBaseUrl}/tasks?limit=100`),
|
||||
requestJson("/logs?limit=100"),
|
||||
]);
|
||||
setData({
|
||||
overview,
|
||||
nodes: nodes.nodes || [],
|
||||
events: events.events || [],
|
||||
tasks: tasks.tasks || [],
|
||||
logs: logs.logs || [],
|
||||
});
|
||||
setConnection({ ok: true, text: "核心在线" });
|
||||
setLastRefresh(new Date());
|
||||
} catch (err) {
|
||||
setConnection({ ok: false, text: err.message || "连接失败" });
|
||||
if (err.status === 401) onLogout(false);
|
||||
}
|
||||
}
|
||||
|
||||
useEffect(() => {
|
||||
refresh();
|
||||
const timer = setInterval(refresh, 5000);
|
||||
return () => clearInterval(timer);
|
||||
}, []);
|
||||
|
||||
useEffect(() => {
|
||||
const timer = setInterval(() => setClock(new Date()), 1000);
|
||||
return () => clearInterval(timer);
|
||||
}, []);
|
||||
|
||||
function setTab(tab) {
|
||||
setActiveTabs((prev) => ({ ...prev, [activeModule]: tab }));
|
||||
}
|
||||
|
||||
function openRaw(title, rawData) {
|
||||
setRaw({ title, data: rawData });
|
||||
}
|
||||
|
||||
return h("div", { className: "shell", "data-testid": "app-shell" },
|
||||
h(Sidebar, { activeModule, onChange: setActiveModule }),
|
||||
h("main", { className: "workspace" },
|
||||
h(TopBar, { connection, lastRefresh, onRefresh: refresh, onLogout: () => onLogout(true), session, clock }),
|
||||
h(TabBar, { module, activeTab, onChange: setTab }),
|
||||
h(WorkArea, { activeModule, activeTab, data, session, refresh, onRaw: openRaw }),
|
||||
),
|
||||
h(RawDialog, { raw, onClose: () => setRaw(null) }),
|
||||
);
|
||||
}
|
||||
|
||||
function App() {
|
||||
const [checking, setChecking] = useState(true);
|
||||
const [session, setSession] = useState(null);
|
||||
|
||||
async function loadSession() {
|
||||
setChecking(true);
|
||||
try {
|
||||
const current = await requestJson("/api/session");
|
||||
setSession(current.authenticated ? current : null);
|
||||
} catch {
|
||||
setSession(null);
|
||||
} finally {
|
||||
setChecking(false);
|
||||
}
|
||||
}
|
||||
|
||||
async function logout(callServer) {
|
||||
if (callServer) {
|
||||
try { await requestJson("/logout", { method: "POST" }); } catch { /* ignore logout network errors */ }
|
||||
}
|
||||
setSession(null);
|
||||
}
|
||||
|
||||
useEffect(() => { loadSession(); }, []);
|
||||
|
||||
if (checking) return h("main", { className: "loading-screen" }, h("div", { className: "brand-mark" }, "UD"), h("span", null, "加载会话"));
|
||||
if (!session) return h(LoginScreen, { onLogin: setSession });
|
||||
return h(Shell, { session, onLogout: logout });
|
||||
}
|
||||
|
||||
ReactDOM.createRoot(document.getElementById("root")).render(h(App));
|
||||
|
||||
@@ -8,61 +8,9 @@
|
||||
<script>window.UNIDESK_CONFIG = __UNIDESK_CONFIG__;</script>
|
||||
</head>
|
||||
<body>
|
||||
<div class="shell">
|
||||
<aside class="rail" aria-label="Main modules">
|
||||
<div class="brand">
|
||||
<span class="brand-mark">UD</span>
|
||||
<span class="brand-text">UniDesk</span>
|
||||
</div>
|
||||
<button class="module active" data-module="ops">运行总览</button>
|
||||
<button class="module" data-module="nodes">资源节点</button>
|
||||
<button class="module" data-module="tasks">任务调度</button>
|
||||
<button class="module" data-module="config">系统配置</button>
|
||||
</aside>
|
||||
<main class="workspace">
|
||||
<header class="topbar">
|
||||
<div>
|
||||
<p class="eyebrow">Distributed Work Platform</p>
|
||||
<h1>控制平面</h1>
|
||||
</div>
|
||||
<div class="status-strip">
|
||||
<span id="conn-dot" class="dot warn"></span>
|
||||
<span id="conn-text">连接中</span>
|
||||
<span id="clock">--:--:--</span>
|
||||
</div>
|
||||
</header>
|
||||
<nav class="tabs" aria-label="Sub modules">
|
||||
<button class="tab active" data-tab="overview">Overview</button>
|
||||
<button class="tab" data-tab="nodes">Live Nodes</button>
|
||||
<button class="tab" data-tab="events">Event Log</button>
|
||||
<button class="tab" data-tab="dispatch">Dispatch</button>
|
||||
</nav>
|
||||
<section class="content-grid">
|
||||
<section class="panel metrics-panel" data-panel="overview">
|
||||
<div class="panel-head"><h2>核心指标</h2><span id="refresh-age">--</span></div>
|
||||
<div class="metric-grid" id="metric-grid"></div>
|
||||
</section>
|
||||
<section class="panel table-panel" data-panel="nodes">
|
||||
<div class="panel-head"><h2>Provider 节点</h2><span id="node-count">0</span></div>
|
||||
<div class="table-wrap"><table><thead><tr><th>状态</th><th>Provider</th><th>标签</th><th>最后心跳</th></tr></thead><tbody id="nodes-body"></tbody></table></div>
|
||||
</section>
|
||||
<section class="panel table-panel" data-panel="events">
|
||||
<div class="panel-head"><h2>事件流</h2><span>最近 100 条</span></div>
|
||||
<div class="table-wrap"><table><thead><tr><th>ID</th><th>类型</th><th>来源</th><th>载荷</th><th>时间</th></tr></thead><tbody id="events-body"></tbody></table></div>
|
||||
</section>
|
||||
<section class="panel dispatch-panel" data-panel="dispatch">
|
||||
<div class="panel-head"><h2>调度试运行</h2><span>真实 WebSocket 下发</span></div>
|
||||
<form id="dispatch-form" class="dispatch-form">
|
||||
<label>Provider ID<input id="dispatch-provider" placeholder="main-server" /></label>
|
||||
<label>Command<select id="dispatch-command"><option value="docker.ps">docker.ps</option><option value="echo">echo</option></select></label>
|
||||
<label class="wide">Payload JSON<textarea id="dispatch-payload">{"source":"frontend"}</textarea></label>
|
||||
<button type="submit">下发任务</button>
|
||||
</form>
|
||||
<pre id="dispatch-result" class="result-block">等待操作</pre>
|
||||
</section>
|
||||
</section>
|
||||
</main>
|
||||
</div>
|
||||
<div id="root"></div>
|
||||
<script src="/vendor/react.production.min.js" defer></script>
|
||||
<script src="/vendor/react-dom.production.min.js" defer></script>
|
||||
<script src="/app.js" defer></script>
|
||||
</body>
|
||||
</html>
|
||||
|
||||
@@ -1,41 +1,46 @@
|
||||
:root {
|
||||
--bg: #111820;
|
||||
--panel: #17212b;
|
||||
--panel-2: #1d2a35;
|
||||
--line: #30404d;
|
||||
--line-soft: #24323e;
|
||||
--text: #dce7ec;
|
||||
--muted: #8496a3;
|
||||
--accent: #e2a329;
|
||||
--accent-2: #4bb7aa;
|
||||
--danger: #d86b55;
|
||||
--ok: #6fbe73;
|
||||
--rail: #0c1218;
|
||||
--shadow: 0 16px 40px rgba(0, 0, 0, 0.28);
|
||||
font-family: "DIN Condensed", "Aptos Narrow", "Liberation Sans Narrow", "Noto Sans", sans-serif;
|
||||
--bg: #0d141a;
|
||||
--bg-grid: rgba(255,255,255,0.025);
|
||||
--rail: #080d12;
|
||||
--panel: #131d26;
|
||||
--panel-2: #182530;
|
||||
--panel-3: #0f1820;
|
||||
--line: #2b3a45;
|
||||
--line-soft: #1f2d37;
|
||||
--text: #d7e3e7;
|
||||
--muted: #81939f;
|
||||
--faint: #546672;
|
||||
--accent: #d7a13a;
|
||||
--accent-2: #4eb7a8;
|
||||
--danger: #cf6a54;
|
||||
--ok: #71bf78;
|
||||
--warn: #d7a13a;
|
||||
--shadow: 0 18px 46px rgba(0, 0, 0, 0.32);
|
||||
font-family: "Aptos Narrow", "DIN Condensed", "Liberation Sans Narrow", "Noto Sans", sans-serif;
|
||||
}
|
||||
|
||||
* { box-sizing: border-box; }
|
||||
html, body { min-height: 100%; }
|
||||
html, body, #root { min-height: 100%; }
|
||||
body {
|
||||
margin: 0;
|
||||
color: var(--text);
|
||||
background:
|
||||
linear-gradient(135deg, rgba(226, 163, 41, 0.08), transparent 28%),
|
||||
linear-gradient(315deg, rgba(75, 183, 170, 0.08), transparent 30%),
|
||||
repeating-linear-gradient(90deg, rgba(255,255,255,0.025) 0, rgba(255,255,255,0.025) 1px, transparent 1px, transparent 36px),
|
||||
linear-gradient(135deg, rgba(215, 161, 58, 0.08), transparent 28%),
|
||||
linear-gradient(315deg, rgba(78, 183, 168, 0.07), transparent 32%),
|
||||
repeating-linear-gradient(90deg, var(--bg-grid) 0, var(--bg-grid) 1px, transparent 1px, transparent 34px),
|
||||
repeating-linear-gradient(0deg, rgba(255,255,255,0.014) 0, rgba(255,255,255,0.014) 1px, transparent 1px, transparent 28px),
|
||||
var(--bg);
|
||||
font-size: 13px;
|
||||
letter-spacing: 0.01em;
|
||||
}
|
||||
|
||||
button, input, select, textarea {
|
||||
font: inherit;
|
||||
}
|
||||
button, input, select, textarea { font: inherit; }
|
||||
button { cursor: pointer; }
|
||||
code, pre, textarea { font-family: "Cascadia Mono", "IBM Plex Mono", "Liberation Mono", monospace; }
|
||||
|
||||
.shell {
|
||||
display: grid;
|
||||
grid-template-columns: 176px minmax(0, 1fr);
|
||||
grid-template-columns: 184px minmax(0, 1fr);
|
||||
min-height: 100vh;
|
||||
}
|
||||
|
||||
@@ -45,14 +50,17 @@ button, input, select, textarea {
|
||||
height: 100vh;
|
||||
padding: 12px 10px;
|
||||
border-right: 1px solid var(--line);
|
||||
background: linear-gradient(180deg, #0a1015, var(--rail));
|
||||
background: linear-gradient(180deg, #060a0f, var(--rail));
|
||||
}
|
||||
|
||||
.brand {
|
||||
.brand, .login-brand {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 9px;
|
||||
height: 40px;
|
||||
}
|
||||
|
||||
.brand {
|
||||
height: 42px;
|
||||
padding: 0 5px 12px;
|
||||
border-bottom: 1px solid var(--line-soft);
|
||||
margin-bottom: 10px;
|
||||
@@ -61,8 +69,8 @@ button, input, select, textarea {
|
||||
.brand-mark {
|
||||
display: grid;
|
||||
place-items: center;
|
||||
width: 32px;
|
||||
height: 26px;
|
||||
width: 34px;
|
||||
height: 27px;
|
||||
border: 1px solid var(--accent);
|
||||
color: var(--accent);
|
||||
font-weight: 800;
|
||||
@@ -75,20 +83,25 @@ button, input, select, textarea {
|
||||
letter-spacing: 0.14em;
|
||||
}
|
||||
|
||||
.module, .tab, .dispatch-form button {
|
||||
.module {
|
||||
display: grid;
|
||||
grid-template-columns: 42px 1fr;
|
||||
align-items: center;
|
||||
width: 100%;
|
||||
min-height: 34px;
|
||||
margin: 4px 0;
|
||||
padding: 6px 8px;
|
||||
border: 1px solid transparent;
|
||||
border-left: 3px solid transparent;
|
||||
color: var(--muted);
|
||||
background: transparent;
|
||||
cursor: pointer;
|
||||
text-align: left;
|
||||
}
|
||||
|
||||
.module {
|
||||
display: block;
|
||||
width: 100%;
|
||||
padding: 8px 10px;
|
||||
margin: 4px 0;
|
||||
text-align: left;
|
||||
border-left: 3px solid transparent;
|
||||
.module-code {
|
||||
color: var(--faint);
|
||||
font-size: 10px;
|
||||
letter-spacing: 0.16em;
|
||||
}
|
||||
|
||||
.module:hover, .module.active {
|
||||
@@ -108,11 +121,11 @@ button, input, select, textarea {
|
||||
align-items: center;
|
||||
gap: 14px;
|
||||
min-height: 54px;
|
||||
padding: 0 0 10px;
|
||||
padding-bottom: 10px;
|
||||
border-bottom: 1px solid var(--line);
|
||||
}
|
||||
|
||||
.eyebrow {
|
||||
.eyebrow, .panel-eyebrow {
|
||||
margin: 0 0 2px;
|
||||
color: var(--accent);
|
||||
font-size: 10px;
|
||||
@@ -121,30 +134,36 @@ button, input, select, textarea {
|
||||
}
|
||||
|
||||
h1, h2 { margin: 0; font-weight: 650; }
|
||||
h1 { font-size: 22px; letter-spacing: 0.08em; }
|
||||
h2 { font-size: 14px; text-transform: uppercase; letter-spacing: 0.09em; }
|
||||
h1 { font-size: 21px; letter-spacing: 0.07em; }
|
||||
h2 { font-size: 14px; text-transform: uppercase; letter-spacing: 0.08em; }
|
||||
|
||||
.status-strip {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 8px;
|
||||
padding: 7px 9px;
|
||||
padding: 6px 8px;
|
||||
border: 1px solid var(--line);
|
||||
background: rgba(0,0,0,0.14);
|
||||
background: rgba(0,0,0,0.16);
|
||||
color: var(--muted);
|
||||
white-space: nowrap;
|
||||
}
|
||||
|
||||
.dot {
|
||||
.dot, .pulse {
|
||||
width: 8px;
|
||||
height: 8px;
|
||||
border-radius: 999px;
|
||||
background: var(--muted);
|
||||
box-shadow: 0 0 0 2px rgba(255,255,255,0.06);
|
||||
}
|
||||
.dot.ok { background: var(--ok); }
|
||||
.dot.warn { background: var(--accent); }
|
||||
.dot.fail { background: var(--danger); }
|
||||
.dot.ok, .pulse.online { background: var(--ok); }
|
||||
.dot.fail, .pulse.offline { background: var(--danger); }
|
||||
|
||||
.user-pill {
|
||||
padding: 2px 7px;
|
||||
border: 1px solid var(--line-soft);
|
||||
color: var(--text);
|
||||
background: var(--panel-3);
|
||||
}
|
||||
|
||||
.tabs {
|
||||
display: flex;
|
||||
@@ -153,32 +172,44 @@ h2 { font-size: 14px; text-transform: uppercase; letter-spacing: 0.09em; }
|
||||
overflow-x: auto;
|
||||
}
|
||||
|
||||
.tab {
|
||||
padding: 7px 12px;
|
||||
border-color: var(--line);
|
||||
background: rgba(12, 18, 24, 0.58);
|
||||
.tab, .ghost-btn {
|
||||
border: 1px solid var(--line);
|
||||
background: rgba(12, 18, 24, 0.62);
|
||||
color: var(--muted);
|
||||
min-width: 108px;
|
||||
}
|
||||
|
||||
.tab {
|
||||
min-width: 112px;
|
||||
padding: 7px 12px;
|
||||
}
|
||||
|
||||
.tab.active, .tab:hover {
|
||||
color: var(--text);
|
||||
border-color: var(--accent-2);
|
||||
background: rgba(75, 183, 170, 0.12);
|
||||
background: rgba(78, 183, 168, 0.12);
|
||||
}
|
||||
|
||||
.content-grid {
|
||||
display: grid;
|
||||
grid-template-columns: minmax(320px, 0.9fr) minmax(520px, 1.6fr);
|
||||
gap: 10px;
|
||||
align-items: stretch;
|
||||
.ghost-btn {
|
||||
min-height: 28px;
|
||||
padding: 4px 8px;
|
||||
}
|
||||
.ghost-btn:hover { color: var(--text); border-color: var(--accent); }
|
||||
.ghost-btn.danger:hover { border-color: var(--danger); color: #ffd7cf; }
|
||||
|
||||
.page-grid {
|
||||
display: grid;
|
||||
grid-template-columns: minmax(340px, 0.95fr) minmax(520px, 1.55fr);
|
||||
gap: 10px;
|
||||
align-items: start;
|
||||
}
|
||||
|
||||
.overview-grid .panel:nth-child(3), .dispatch-grid .panel:first-child, .topology-grid .panel:nth-child(3) { grid-column: 1 / -1; }
|
||||
|
||||
.panel {
|
||||
border: 1px solid var(--line);
|
||||
background: linear-gradient(180deg, rgba(255,255,255,0.035), rgba(255,255,255,0.015)), var(--panel);
|
||||
box-shadow: var(--shadow);
|
||||
min-width: 0;
|
||||
border: 1px solid var(--line);
|
||||
background: linear-gradient(180deg, rgba(255,255,255,0.035), rgba(255,255,255,0.012)), var(--panel);
|
||||
box-shadow: var(--shadow);
|
||||
}
|
||||
|
||||
.panel-head {
|
||||
@@ -186,50 +217,110 @@ h2 { font-size: 14px; text-transform: uppercase; letter-spacing: 0.09em; }
|
||||
justify-content: space-between;
|
||||
align-items: center;
|
||||
gap: 10px;
|
||||
height: 38px;
|
||||
padding: 0 10px;
|
||||
min-height: 40px;
|
||||
padding: 7px 10px;
|
||||
border-bottom: 1px solid var(--line);
|
||||
color: var(--muted);
|
||||
}
|
||||
|
||||
.metrics-panel { grid-column: 1 / 2; }
|
||||
.table-panel[data-panel="nodes"] { grid-column: 2 / 3; }
|
||||
.table-panel[data-panel="events"], .dispatch-panel { grid-column: 1 / -1; }
|
||||
.panel-actions { display: flex; gap: 6px; align-items: center; }
|
||||
.panel-body { padding: 10px; }
|
||||
|
||||
.metric-grid {
|
||||
display: grid;
|
||||
grid-template-columns: repeat(2, minmax(0, 1fr));
|
||||
grid-template-columns: repeat(4, minmax(0, 1fr));
|
||||
gap: 8px;
|
||||
padding: 10px;
|
||||
}
|
||||
|
||||
.metric {
|
||||
.metric-card {
|
||||
min-height: 76px;
|
||||
padding: 10px;
|
||||
min-height: 74px;
|
||||
border: 1px solid var(--line-soft);
|
||||
background: var(--panel-2);
|
||||
}
|
||||
|
||||
.metric .label {
|
||||
.metric-card.ok { border-color: rgba(113, 191, 120, 0.42); }
|
||||
.metric-card.warn { border-color: rgba(215, 161, 58, 0.45); }
|
||||
.metric-label {
|
||||
color: var(--muted);
|
||||
font-size: 11px;
|
||||
text-transform: uppercase;
|
||||
letter-spacing: 0.12em;
|
||||
}
|
||||
.metric .value {
|
||||
.metric-value {
|
||||
margin-top: 8px;
|
||||
color: var(--text);
|
||||
font-size: 24px;
|
||||
font-weight: 720;
|
||||
font-size: 23px;
|
||||
font-weight: 760;
|
||||
}
|
||||
.metric .hint {
|
||||
margin-top: 3px;
|
||||
color: var(--muted);
|
||||
font-size: 11px;
|
||||
.metric-hint { margin-top: 3px; color: var(--muted); font-size: 11px; }
|
||||
|
||||
.node-card-list, .compact-list, .log-list, .heartbeat-list, .endpoint-list, .policy-grid, .security-board, .result-grid {
|
||||
display: grid;
|
||||
gap: 8px;
|
||||
}
|
||||
|
||||
.table-wrap { overflow: auto; max-height: 46vh; }
|
||||
table { width: 100%; border-collapse: collapse; min-width: 680px; }
|
||||
.node-card, .compact-row, .log-row, .heartbeat-row, .endpoint-list article, .policy-grid article, .security-board article, .result-card, .label-card {
|
||||
border: 1px solid var(--line-soft);
|
||||
background: var(--panel-3);
|
||||
}
|
||||
|
||||
.node-card, .result-card { padding: 9px; }
|
||||
.node-card-head {
|
||||
display: flex;
|
||||
justify-content: space-between;
|
||||
gap: 10px;
|
||||
margin-bottom: 8px;
|
||||
}
|
||||
.node-card code, .compact-row code, td code {
|
||||
display: block;
|
||||
margin-top: 2px;
|
||||
color: #bcd2d7;
|
||||
font-size: 12px;
|
||||
}
|
||||
.node-card-foot {
|
||||
display: flex;
|
||||
justify-content: space-between;
|
||||
align-items: center;
|
||||
gap: 10px;
|
||||
margin-top: 8px;
|
||||
color: var(--muted);
|
||||
}
|
||||
|
||||
.status-badge {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
min-height: 22px;
|
||||
padding: 2px 7px;
|
||||
border: 1px solid var(--line);
|
||||
color: var(--muted);
|
||||
background: rgba(0,0,0,0.18);
|
||||
text-transform: uppercase;
|
||||
font-size: 11px;
|
||||
}
|
||||
.status-badge.online, .status-badge.succeeded, .status-badge.public { color: var(--ok); border-color: rgba(113, 191, 120, 0.45); }
|
||||
.status-badge.offline, .status-badge.failed { color: var(--danger); border-color: rgba(207, 106, 84, 0.45); }
|
||||
.status-badge.running, .status-badge.dispatched, .status-badge.accepted, .status-badge.internal { color: var(--accent-2); border-color: rgba(78, 183, 168, 0.45); }
|
||||
.status-badge.queued, .status-badge.warn { color: var(--warn); border-color: rgba(215, 161, 58, 0.45); }
|
||||
|
||||
.chip-row, .summary-grid {
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
gap: 5px;
|
||||
}
|
||||
.data-chip, .summary-item, .summary-value {
|
||||
display: inline-flex;
|
||||
gap: 5px;
|
||||
align-items: center;
|
||||
min-height: 22px;
|
||||
padding: 2px 6px;
|
||||
border: 1px solid var(--line-soft);
|
||||
background: rgba(255,255,255,0.03);
|
||||
color: var(--muted);
|
||||
}
|
||||
.data-chip b, .summary-item b { color: var(--accent-2); font-weight: 650; }
|
||||
|
||||
.table-wrap { overflow: auto; max-height: calc(100vh - 174px); }
|
||||
table { width: 100%; border-collapse: collapse; min-width: 760px; }
|
||||
th, td {
|
||||
padding: 7px 9px;
|
||||
border-bottom: 1px solid var(--line-soft);
|
||||
@@ -239,37 +330,42 @@ th, td {
|
||||
th {
|
||||
position: sticky;
|
||||
top: 0;
|
||||
background: #121b24;
|
||||
z-index: 1;
|
||||
background: #111a22;
|
||||
color: var(--accent);
|
||||
font-size: 11px;
|
||||
text-transform: uppercase;
|
||||
letter-spacing: 0.11em;
|
||||
z-index: 1;
|
||||
}
|
||||
td { color: var(--text); }
|
||||
.code, code {
|
||||
font-family: "Cascadia Mono", "IBM Plex Mono", "Liberation Mono", monospace;
|
||||
font-size: 12px;
|
||||
color: #bfd7dc;
|
||||
}
|
||||
.badge {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
gap: 5px;
|
||||
padding: 2px 7px;
|
||||
border: 1px solid var(--line);
|
||||
color: var(--muted);
|
||||
background: rgba(0,0,0,0.18);
|
||||
}
|
||||
.badge.online { color: var(--ok); border-color: rgba(111, 190, 115, 0.45); }
|
||||
.badge.offline { color: var(--danger); border-color: rgba(216, 107, 85, 0.45); }
|
||||
|
||||
.dispatch-panel { min-height: 230px; }
|
||||
.compact-row, .heartbeat-row, .log-row, .endpoint-list article, .policy-grid article {
|
||||
display: grid;
|
||||
grid-template-columns: auto minmax(180px, 1fr) auto auto;
|
||||
align-items: center;
|
||||
gap: 10px;
|
||||
padding: 8px;
|
||||
}
|
||||
.log-row { grid-template-columns: 150px 52px 160px minmax(220px, 1fr) auto; }
|
||||
.log-row.error { border-color: rgba(207, 106, 84, 0.48); }
|
||||
.log-row.warn { border-color: rgba(215, 161, 58, 0.48); }
|
||||
.heartbeat-row { grid-template-columns: auto minmax(220px, 1fr) minmax(180px, auto) minmax(180px, auto); }
|
||||
.heartbeat-row span, .endpoint-list span, .policy-grid span { color: var(--muted); }
|
||||
.heartbeat-row b { display: block; margin-top: 2px; }
|
||||
|
||||
.label-matrix {
|
||||
display: grid;
|
||||
grid-template-columns: repeat(auto-fill, minmax(180px, 1fr));
|
||||
gap: 8px;
|
||||
}
|
||||
.label-card { padding: 8px; }
|
||||
.label-card span { display: block; color: var(--muted); font-size: 11px; text-transform: uppercase; letter-spacing: 0.1em; }
|
||||
.label-card strong { display: block; margin: 5px 0; }
|
||||
|
||||
.dispatch-form {
|
||||
display: grid;
|
||||
grid-template-columns: 1fr 180px auto;
|
||||
grid-template-columns: 1.2fr 180px 150px 1fr 140px auto;
|
||||
gap: 8px;
|
||||
padding: 10px;
|
||||
align-items: end;
|
||||
}
|
||||
.dispatch-form label {
|
||||
@@ -280,50 +376,148 @@ td { color: var(--text); }
|
||||
text-transform: uppercase;
|
||||
letter-spacing: 0.12em;
|
||||
}
|
||||
.dispatch-form .wide { grid-column: 1 / -1; }
|
||||
.dispatch-actions { display: flex; gap: 6px; align-items: end; }
|
||||
.dispatch-actions button[type="submit"], .login-form button[type="submit"] {
|
||||
min-height: 32px;
|
||||
padding: 0 12px;
|
||||
border: 1px solid var(--accent);
|
||||
color: #151107;
|
||||
background: var(--accent);
|
||||
font-weight: 760;
|
||||
}
|
||||
.raw-editor-label, .wide { grid-column: 1 / -1; }
|
||||
input, select, textarea {
|
||||
width: 100%;
|
||||
border: 1px solid var(--line);
|
||||
color: var(--text);
|
||||
background: #0d151c;
|
||||
background: #0b1218;
|
||||
padding: 7px 8px;
|
||||
outline: none;
|
||||
}
|
||||
textarea { min-height: 76px; resize: vertical; font-family: "Cascadia Mono", "IBM Plex Mono", monospace; }
|
||||
.dispatch-form button {
|
||||
height: 33px;
|
||||
padding: 0 14px;
|
||||
border-color: var(--accent);
|
||||
color: #130f08;
|
||||
background: var(--accent);
|
||||
font-weight: 700;
|
||||
textarea { min-height: 96px; resize: vertical; }
|
||||
input:focus, select:focus, textarea:focus { border-color: var(--accent-2); }
|
||||
|
||||
.result-card dl {
|
||||
display: grid;
|
||||
grid-template-columns: 90px 1fr;
|
||||
gap: 5px 8px;
|
||||
margin: 8px 0;
|
||||
}
|
||||
.result-block {
|
||||
margin: 0 10px 10px;
|
||||
padding: 8px;
|
||||
max-height: 170px;
|
||||
overflow: auto;
|
||||
border: 1px solid var(--line-soft);
|
||||
background: #0d151c;
|
||||
color: #bfd7dc;
|
||||
.result-card dt { color: var(--muted); }
|
||||
.result-card dd { margin: 0; }
|
||||
.result-grid { grid-template-columns: repeat(auto-fill, minmax(280px, 1fr)); }
|
||||
|
||||
.endpoint-list article { grid-template-columns: 150px minmax(220px, 1fr) auto; }
|
||||
.policy-grid { grid-template-columns: repeat(4, minmax(0, 1fr)); }
|
||||
.policy-grid article { grid-template-columns: 1fr; align-items: start; }
|
||||
.policy-grid strong { font-size: 16px; }
|
||||
.paragraph { margin: 10px 0 0; }
|
||||
.security-board { grid-template-columns: repeat(3, minmax(0, 1fr)); }
|
||||
.security-board article { padding: 10px; display: grid; gap: 5px; }
|
||||
.security-board .allow { border-color: rgba(113,191,120,0.45); }
|
||||
.security-board .deny { border-color: rgba(207,106,84,0.45); }
|
||||
.security-board span { color: var(--muted); }
|
||||
|
||||
.empty-state {
|
||||
display: grid;
|
||||
gap: 4px;
|
||||
min-height: 88px;
|
||||
place-content: center;
|
||||
border: 1px dashed var(--line);
|
||||
color: var(--muted);
|
||||
text-align: center;
|
||||
}
|
||||
.empty-state strong { color: var(--text); }
|
||||
.muted { color: var(--muted); }
|
||||
|
||||
.login-screen, .loading-screen {
|
||||
min-height: 100vh;
|
||||
display: grid;
|
||||
place-items: center;
|
||||
padding: 18px;
|
||||
}
|
||||
.loading-screen { gap: 10px; align-content: center; color: var(--muted); }
|
||||
.login-card {
|
||||
width: min(440px, 100%);
|
||||
border: 1px solid var(--line);
|
||||
background: linear-gradient(180deg, rgba(255,255,255,0.045), rgba(255,255,255,0.018)), var(--panel);
|
||||
box-shadow: var(--shadow);
|
||||
padding: 18px;
|
||||
}
|
||||
.login-brand { padding-bottom: 14px; border-bottom: 1px solid var(--line-soft); margin-bottom: 14px; }
|
||||
.login-brand h1 { font-size: 24px; }
|
||||
.login-brand p { margin: 2px 0 0; color: var(--muted); text-transform: uppercase; letter-spacing: 0.14em; font-size: 11px; }
|
||||
.login-form { display: grid; gap: 10px; }
|
||||
.login-form label { display: grid; gap: 5px; color: var(--muted); }
|
||||
.login-note { margin-top: 12px; color: var(--muted); font-size: 12px; }
|
||||
.form-error {
|
||||
padding: 7px 8px;
|
||||
border: 1px solid rgba(207,106,84,0.5);
|
||||
color: #ffd7cf;
|
||||
background: rgba(207,106,84,0.1);
|
||||
}
|
||||
|
||||
@media (max-width: 980px) {
|
||||
.modal-backdrop {
|
||||
position: fixed;
|
||||
inset: 0;
|
||||
z-index: 20;
|
||||
display: grid;
|
||||
place-items: center;
|
||||
padding: 18px;
|
||||
background: rgba(0,0,0,0.58);
|
||||
}
|
||||
.raw-dialog {
|
||||
width: min(920px, 96vw);
|
||||
max-height: 86vh;
|
||||
border: 1px solid var(--line);
|
||||
background: #0a1015;
|
||||
box-shadow: var(--shadow);
|
||||
}
|
||||
.raw-dialog-head {
|
||||
display: flex;
|
||||
justify-content: space-between;
|
||||
align-items: center;
|
||||
gap: 10px;
|
||||
padding: 10px;
|
||||
border-bottom: 1px solid var(--line);
|
||||
}
|
||||
.raw-json {
|
||||
max-height: calc(86vh - 58px);
|
||||
overflow: auto;
|
||||
margin: 0;
|
||||
padding: 10px;
|
||||
color: #c5dadd;
|
||||
font-size: 12px;
|
||||
line-height: 1.45;
|
||||
}
|
||||
|
||||
@media (max-width: 1120px) {
|
||||
.metric-grid, .policy-grid, .security-board { grid-template-columns: repeat(2, minmax(0, 1fr)); }
|
||||
.dispatch-form { grid-template-columns: 1fr 1fr; }
|
||||
.dispatch-actions { align-items: center; }
|
||||
.page-grid { grid-template-columns: 1fr; }
|
||||
.overview-grid .panel:nth-child(3), .dispatch-grid .panel:first-child, .topology-grid .panel:nth-child(3) { grid-column: 1; }
|
||||
}
|
||||
|
||||
@media (max-width: 760px) {
|
||||
body { font-size: 12px; }
|
||||
.shell { grid-template-columns: 1fr; }
|
||||
.rail {
|
||||
position: static;
|
||||
height: auto;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 6px;
|
||||
overflow-x: auto;
|
||||
border-right: 0;
|
||||
border-bottom: 1px solid var(--line);
|
||||
}
|
||||
.brand { border-bottom: 0; margin-bottom: 0; padding-bottom: 0; flex: 0 0 auto; }
|
||||
.module { width: auto; white-space: nowrap; border-left: 0; border-bottom: 2px solid transparent; }
|
||||
.module { width: auto; min-width: 120px; grid-template-columns: 1fr; border-left: 0; border-bottom: 2px solid transparent; }
|
||||
.module.active, .module:hover { border-bottom-color: var(--accent); }
|
||||
.content-grid { grid-template-columns: 1fr; }
|
||||
.metrics-panel, .table-panel[data-panel="nodes"], .table-panel[data-panel="events"], .dispatch-panel { grid-column: 1; }
|
||||
.dispatch-form { grid-template-columns: 1fr; }
|
||||
.workspace { padding: 10px; }
|
||||
.topbar { align-items: flex-start; flex-direction: column; }
|
||||
.status-strip { flex-wrap: wrap; white-space: normal; }
|
||||
.metric-grid, .policy-grid, .security-board, .dispatch-form { grid-template-columns: 1fr; }
|
||||
.compact-row, .heartbeat-row, .log-row, .endpoint-list article { grid-template-columns: 1fr; align-items: start; }
|
||||
.tab { min-width: 104px; }
|
||||
}
|
||||
|
||||
@@ -1,20 +1,41 @@
|
||||
import { appendFileSync, mkdirSync, readFileSync } from "node:fs";
|
||||
import { createHmac, randomBytes, timingSafeEqual } from "node:crypto";
|
||||
import { dirname, join } from "node:path";
|
||||
|
||||
interface RuntimeConfig {
|
||||
port: number;
|
||||
corePublicUrl: string;
|
||||
coreInternalUrl: string;
|
||||
frontendPublicUrl: string;
|
||||
providerIngressPublicUrl: string;
|
||||
authUsername: string;
|
||||
authPassword: string;
|
||||
sessionSecret: string;
|
||||
sessionTtlSeconds: number;
|
||||
logFile: string;
|
||||
}
|
||||
|
||||
interface SessionPayload {
|
||||
username: string;
|
||||
expiresAt: number;
|
||||
nonce: string;
|
||||
}
|
||||
|
||||
type JsonValue = string | number | boolean | null | JsonValue[] | { [key: string]: JsonValue };
|
||||
|
||||
const sessionCookieName = "unidesk_session";
|
||||
const config = readConfig();
|
||||
const logger = createLogger("frontend", config.logFile);
|
||||
const publicDir = join(import.meta.dir, "..", "public");
|
||||
const vendorDir = join(import.meta.dir, "..", "node_modules");
|
||||
const indexHtml = readFileSync(join(publicDir, "index.html"), "utf8").replace(
|
||||
"__UNIDESK_CONFIG__",
|
||||
JSON.stringify({ coreApiUrl: config.corePublicUrl, corePort: new URL(config.corePublicUrl).port }),
|
||||
JSON.stringify({
|
||||
frontendPublicUrl: config.frontendPublicUrl,
|
||||
providerIngressPublicUrl: config.providerIngressPublicUrl,
|
||||
authUsername: config.authUsername,
|
||||
sessionTtlSeconds: config.sessionTtlSeconds,
|
||||
apiBaseUrl: "/api",
|
||||
}),
|
||||
);
|
||||
|
||||
function requiredEnv(name: string): string {
|
||||
@@ -37,7 +58,13 @@ function readNumberEnv(name: string): number {
|
||||
function readConfig(): RuntimeConfig {
|
||||
return {
|
||||
port: readNumberEnv("PORT"),
|
||||
corePublicUrl: requiredEnv("CORE_PUBLIC_URL"),
|
||||
coreInternalUrl: requiredEnv("CORE_INTERNAL_URL"),
|
||||
frontendPublicUrl: requiredEnv("FRONTEND_PUBLIC_URL"),
|
||||
providerIngressPublicUrl: requiredEnv("PROVIDER_INGRESS_PUBLIC_URL"),
|
||||
authUsername: requiredEnv("AUTH_USERNAME"),
|
||||
authPassword: requiredEnv("AUTH_PASSWORD"),
|
||||
sessionSecret: requiredEnv("SESSION_SECRET"),
|
||||
sessionTtlSeconds: readNumberEnv("SESSION_TTL_SECONDS"),
|
||||
logFile: requiredEnv("LOG_FILE"),
|
||||
};
|
||||
}
|
||||
@@ -45,7 +72,9 @@ function readConfig(): RuntimeConfig {
|
||||
function createLogger(service: string, logFile: string) {
|
||||
mkdirSync(dirname(logFile), { recursive: true });
|
||||
return (level: "debug" | "info" | "warn" | "error", message: string, data?: JsonValue): void => {
|
||||
const entry = { ts: new Date().toISOString(), service, level, message, data };
|
||||
const entry = data === undefined
|
||||
? { ts: new Date().toISOString(), service, level, message }
|
||||
: { ts: new Date().toISOString(), service, level, message, data };
|
||||
const line = `${JSON.stringify(entry)}\n`;
|
||||
try {
|
||||
appendFileSync(logFile, line, "utf8");
|
||||
@@ -58,41 +87,199 @@ function createLogger(service: string, logFile: string) {
|
||||
}
|
||||
|
||||
function contentType(pathname: string): string {
|
||||
if (pathname.endsWith(".html")) return "text/html; charset=utf-8";
|
||||
if (pathname.endsWith(".css")) return "text/css; charset=utf-8";
|
||||
if (pathname.endsWith(".js")) return "text/javascript; charset=utf-8";
|
||||
if (pathname.endsWith(".svg")) return "image/svg+xml";
|
||||
if (pathname.endsWith(".ico")) return "image/x-icon";
|
||||
return "text/plain; charset=utf-8";
|
||||
}
|
||||
|
||||
function jsonResponse(body: JsonValue, status = 200): Response {
|
||||
function jsonResponse(body: unknown, status = 200, extraHeaders?: HeadersInit): Response {
|
||||
const headers = new Headers({ "content-type": "application/json; charset=utf-8" });
|
||||
if (extraHeaders !== undefined) {
|
||||
new Headers(extraHeaders).forEach((value, key) => headers.set(key, value));
|
||||
}
|
||||
return new Response(JSON.stringify(body, null, 2), {
|
||||
status,
|
||||
headers: { "content-type": "application/json; charset=utf-8" },
|
||||
headers,
|
||||
});
|
||||
}
|
||||
|
||||
function signPayload(payload: string): string {
|
||||
return createHmac("sha256", config.sessionSecret).update(payload).digest("base64url");
|
||||
}
|
||||
|
||||
function safeEqual(a: string, b: string): boolean {
|
||||
const left = Buffer.from(a);
|
||||
const right = Buffer.from(b);
|
||||
return left.length === right.length && timingSafeEqual(left, right);
|
||||
}
|
||||
|
||||
function createSession(username: string): { token: string; expiresAt: number } {
|
||||
const expiresAt = Date.now() + config.sessionTtlSeconds * 1000;
|
||||
const payload: SessionPayload = { username, expiresAt, nonce: randomBytes(12).toString("base64url") };
|
||||
const encoded = Buffer.from(JSON.stringify(payload), "utf8").toString("base64url");
|
||||
return { token: `${encoded}.${signPayload(encoded)}`, expiresAt };
|
||||
}
|
||||
|
||||
function verifySession(token: string | undefined): SessionPayload | null {
|
||||
if (!token) return null;
|
||||
const [encoded, signature, extra] = token.split(".");
|
||||
if (!encoded || !signature || extra !== undefined) return null;
|
||||
if (!safeEqual(signPayload(encoded), signature)) return null;
|
||||
try {
|
||||
const payload = JSON.parse(Buffer.from(encoded, "base64url").toString("utf8")) as Partial<SessionPayload>;
|
||||
if (payload.username !== config.authUsername || typeof payload.expiresAt !== "number" || payload.expiresAt <= Date.now()) return null;
|
||||
if (typeof payload.nonce !== "string") return null;
|
||||
return payload as SessionPayload;
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
function parseCookies(header: string | null): Record<string, string> {
|
||||
const cookies: Record<string, string> = {};
|
||||
if (!header) return cookies;
|
||||
for (const item of header.split(";")) {
|
||||
const index = item.indexOf("=");
|
||||
if (index === -1) continue;
|
||||
const key = item.slice(0, index).trim();
|
||||
const value = item.slice(index + 1).trim();
|
||||
try {
|
||||
cookies[key] = decodeURIComponent(value);
|
||||
} catch {
|
||||
cookies[key] = value;
|
||||
}
|
||||
}
|
||||
return cookies;
|
||||
}
|
||||
|
||||
function sessionFromRequest(req: Request): SessionPayload | null {
|
||||
return verifySession(parseCookies(req.headers.get("cookie"))[sessionCookieName]);
|
||||
}
|
||||
|
||||
function setSessionCookie(token: string): string {
|
||||
return `${sessionCookieName}=${encodeURIComponent(token)}; HttpOnly; SameSite=Lax; Path=/; Max-Age=${config.sessionTtlSeconds}`;
|
||||
}
|
||||
|
||||
function clearSessionCookie(): string {
|
||||
return `${sessionCookieName}=; HttpOnly; SameSite=Lax; Path=/; Max-Age=0`;
|
||||
}
|
||||
|
||||
async function readLoginBody(req: Request): Promise<{ username: string; password: string }> {
|
||||
const contentTypeHeader = req.headers.get("content-type") ?? "";
|
||||
if (contentTypeHeader.includes("application/x-www-form-urlencoded") || contentTypeHeader.includes("multipart/form-data")) {
|
||||
const form = await req.formData();
|
||||
return { username: String(form.get("username") ?? ""), password: String(form.get("password") ?? "") };
|
||||
}
|
||||
const body = (await req.json()) as { username?: unknown; password?: unknown };
|
||||
return {
|
||||
username: typeof body.username === "string" ? body.username : "",
|
||||
password: typeof body.password === "string" ? body.password : "",
|
||||
};
|
||||
}
|
||||
|
||||
async function login(req: Request): Promise<Response> {
|
||||
try {
|
||||
const body = await readLoginBody(req);
|
||||
if (body.username !== config.authUsername || body.password !== config.authPassword) {
|
||||
logger("warn", "login_failed", { username: body.username });
|
||||
return jsonResponse({ ok: false, error: "invalid credentials" }, 401);
|
||||
}
|
||||
const session = createSession(body.username);
|
||||
logger("info", "login_succeeded", { username: body.username, expiresAt: new Date(session.expiresAt).toISOString() });
|
||||
return jsonResponse(
|
||||
{ ok: true, user: { username: body.username }, expiresAt: new Date(session.expiresAt).toISOString() },
|
||||
200,
|
||||
{ "set-cookie": setSessionCookie(session.token) },
|
||||
);
|
||||
} catch (error) {
|
||||
logger("error", "login_failed", { error: error instanceof Error ? error.message : String(error) });
|
||||
return jsonResponse({ ok: false, error: "invalid login request" }, 400);
|
||||
}
|
||||
}
|
||||
|
||||
function logout(): Response {
|
||||
return jsonResponse({ ok: true }, 200, { "set-cookie": clearSessionCookie() });
|
||||
}
|
||||
|
||||
function sessionResponse(req: Request): Response {
|
||||
const session = sessionFromRequest(req);
|
||||
if (session === null) return jsonResponse({ ok: true, authenticated: false });
|
||||
return jsonResponse({ ok: true, authenticated: true, user: { username: session.username }, expiresAt: new Date(session.expiresAt).toISOString() });
|
||||
}
|
||||
|
||||
async function proxyApi(req: Request, url: URL): Promise<Response> {
|
||||
if (sessionFromRequest(req) === null) {
|
||||
return jsonResponse({ ok: false, error: "authentication required" }, 401);
|
||||
}
|
||||
const upstreamUrl = new URL(`${url.pathname}${url.search}`, config.coreInternalUrl);
|
||||
const headers = new Headers(req.headers);
|
||||
headers.delete("host");
|
||||
headers.delete("connection");
|
||||
headers.delete("content-length");
|
||||
headers.delete("cookie");
|
||||
const init: RequestInit = { method: req.method, headers, redirect: "manual" };
|
||||
if (req.method !== "GET" && req.method !== "HEAD") {
|
||||
init.body = await req.arrayBuffer();
|
||||
}
|
||||
const upstream = await fetch(upstreamUrl, init);
|
||||
const responseHeaders = new Headers();
|
||||
const upstreamContentType = upstream.headers.get("content-type");
|
||||
if (upstreamContentType !== null) responseHeaders.set("content-type", upstreamContentType);
|
||||
return new Response(await upstream.arrayBuffer(), { status: upstream.status, headers: responseHeaders });
|
||||
}
|
||||
|
||||
function vendorPath(pathname: string): string | null {
|
||||
if (pathname === "/vendor/react.production.min.js") return join(vendorDir, "react", "umd", "react.production.min.js");
|
||||
if (pathname === "/vendor/react-dom.production.min.js") return join(vendorDir, "react-dom", "umd", "react-dom.production.min.js");
|
||||
return null;
|
||||
}
|
||||
|
||||
async function staticResponse(pathname: string): Promise<Response> {
|
||||
const vendor = vendorPath(pathname);
|
||||
const filePath = vendor ?? join(publicDir, pathname.replace(/^\/+/, ""));
|
||||
const file = Bun.file(filePath);
|
||||
if (!(await file.exists())) {
|
||||
return jsonResponse({ ok: false, error: "not found", path: pathname }, 404);
|
||||
}
|
||||
return new Response(file, { headers: { "content-type": contentType(pathname) } });
|
||||
}
|
||||
|
||||
const server = Bun.serve({
|
||||
port: config.port,
|
||||
hostname: "0.0.0.0",
|
||||
async fetch(req) {
|
||||
const url = new URL(req.url);
|
||||
logger("debug", "request", { path: url.pathname });
|
||||
if (url.pathname === "/health") {
|
||||
return jsonResponse({ ok: true, service: "unidesk-frontend", coreApiUrl: config.corePublicUrl });
|
||||
try {
|
||||
if (url.pathname === "/health") {
|
||||
return jsonResponse({ ok: true, service: "unidesk-frontend", frontendPublicUrl: config.frontendPublicUrl });
|
||||
}
|
||||
if (url.pathname === "/login" && req.method === "POST") return login(req);
|
||||
if (url.pathname === "/logout" && req.method === "POST") return logout();
|
||||
if (url.pathname === "/api/session") return sessionResponse(req);
|
||||
if (url.pathname.startsWith("/api/") || url.pathname === "/logs") return proxyApi(req, url);
|
||||
if (url.pathname === "/" || url.pathname === "/index.html") {
|
||||
return new Response(indexHtml, { headers: { "content-type": "text/html; charset=utf-8" } });
|
||||
}
|
||||
const safePath = url.pathname.replace(/^\/+/, "");
|
||||
if (safePath.includes("..") || safePath.includes("\0")) {
|
||||
return jsonResponse({ ok: false, error: "invalid path" }, 400);
|
||||
}
|
||||
return staticResponse(url.pathname);
|
||||
} catch (error) {
|
||||
logger("error", "request_failed", { path: url.pathname, error: error instanceof Error ? error.message : String(error) });
|
||||
return jsonResponse({ ok: false, error: "request failed" }, 500);
|
||||
}
|
||||
if (url.pathname === "/" || url.pathname === "/index.html") {
|
||||
return new Response(indexHtml, { headers: { "content-type": "text/html; charset=utf-8" } });
|
||||
}
|
||||
const safePath = url.pathname.replace(/^\/+/, "");
|
||||
if (safePath.includes("..")) {
|
||||
return jsonResponse({ ok: false, error: "invalid path" }, 400);
|
||||
}
|
||||
const file = Bun.file(join(publicDir, safePath));
|
||||
if (!(await file.exists())) {
|
||||
return jsonResponse({ ok: false, error: "not found", path: url.pathname }, 404);
|
||||
}
|
||||
return new Response(file, { headers: { "content-type": contentType(url.pathname) } });
|
||||
},
|
||||
});
|
||||
|
||||
logger("info", "server_listening", { url: `http://0.0.0.0:${server.port}`, coreApiUrl: config.corePublicUrl, logFile: config.logFile });
|
||||
logger("info", "server_listening", {
|
||||
url: `http://0.0.0.0:${server.port}`,
|
||||
coreInternalUrl: config.coreInternalUrl,
|
||||
frontendPublicUrl: config.frontendPublicUrl,
|
||||
providerIngressPublicUrl: config.providerIngressPublicUrl,
|
||||
logFile: config.logFile,
|
||||
});
|
||||
|
||||
Reference in New Issue
Block a user