10 Commits

16 changed files with 1095 additions and 102 deletions

View File

@@ -1,3 +1,5 @@
import { WebServer } from "@/web/server";
/** /**
* Centralized logging utility with consistent formatting * Centralized logging utility with consistent formatting
*/ */
@@ -7,6 +9,7 @@ export const logger = {
*/ */
info: (message: string, ...args: any[]) => { info: (message: string, ...args: any[]) => {
console.log(` ${message}`, ...args); console.log(` ${message}`, ...args);
try { WebServer.broadcastLog("info", message); } catch { }
}, },
/** /**
@@ -14,6 +17,7 @@ export const logger = {
*/ */
success: (message: string, ...args: any[]) => { success: (message: string, ...args: any[]) => {
console.log(`${message}`, ...args); console.log(`${message}`, ...args);
try { WebServer.broadcastLog("success", message); } catch { }
}, },
/** /**
@@ -21,6 +25,7 @@ export const logger = {
*/ */
warn: (message: string, ...args: any[]) => { warn: (message: string, ...args: any[]) => {
console.warn(`⚠️ ${message}`, ...args); console.warn(`⚠️ ${message}`, ...args);
try { WebServer.broadcastLog("warning", message); } catch { }
}, },
/** /**
@@ -28,6 +33,7 @@ export const logger = {
*/ */
error: (message: string, ...args: any[]) => { error: (message: string, ...args: any[]) => {
console.error(`${message}`, ...args); console.error(`${message}`, ...args);
try { WebServer.broadcastLog("error", message); } catch { }
}, },
/** /**
@@ -35,5 +41,6 @@ export const logger = {
*/ */
debug: (message: string, ...args: any[]) => { debug: (message: string, ...args: any[]) => {
console.log(`🔍 ${message}`, ...args); console.log(`🔍 ${message}`, ...args);
try { WebServer.broadcastLog("debug", message); } catch { }
}, },
}; };

108
src/web/public/script.js Normal file
View File

@@ -0,0 +1,108 @@
function formatUptime(seconds) {
if (seconds < 0) return "0s";
const days = Math.floor(seconds / (3600 * 24));
const hours = Math.floor((seconds % (3600 * 24)) / 3600);
const minutes = Math.floor((seconds % 3600) / 60);
const secs = Math.floor(seconds % 60);
const parts = [];
if (days > 0) parts.push(`${days}d`);
if (hours > 0) parts.push(`${hours}h`);
if (minutes > 0) parts.push(`${minutes}m`);
parts.push(`${secs}s`);
return parts.join(" ");
}
function updateUptime() {
const el = document.getElementById("uptime-display");
if (!el) return;
const startTimestamp = parseInt(el.getAttribute("data-start-timestamp"), 10);
if (isNaN(startTimestamp)) return;
const now = Date.now();
const elapsedSeconds = (now - startTimestamp) / 1000;
el.textContent = formatUptime(elapsedSeconds);
}
document.addEventListener("DOMContentLoaded", () => {
// Update immediately to prevent stale content flash if possible
updateUptime();
// Update every second
setInterval(updateUptime, 1000);
// WebSocket Connection
const protocol = window.location.protocol === "https:" ? "wss:" : "ws:";
const wsUrl = `${protocol}//${window.location.host}/ws`;
function connectWs() {
const ws = new WebSocket(wsUrl);
const statusIndicator = document.querySelector(".status-indicator");
ws.onopen = () => {
console.log("WS Connected");
if (statusIndicator) statusIndicator.classList.add("online");
};
ws.onmessage = (event) => {
try {
const msg = JSON.parse(event.data);
if (msg.type === "HEARTBEAT") {
console.log("Heartbeat:", msg.data);
// Sync uptime?
// We can optionally verify if client clock is drifting, but let's keep it simple.
} else if (msg.type === "WELCOME") {
console.log(msg.message);
} else if (msg.type === "LOG") {
appendToActivityFeed(msg.data);
}
} catch (e) {
console.error("WS Parse Error", e);
}
};
function appendToActivityFeed(log) {
const list = document.querySelector(".activity-feed");
if (!list) return;
const item = document.createElement("li");
item.className = `activity-item ${log.type}`;
const timeSpan = document.createElement("span");
timeSpan.className = "time";
timeSpan.textContent = log.timestamp;
const messageSpan = document.createElement("span");
messageSpan.className = "message";
messageSpan.textContent = log.message;
item.appendChild(timeSpan);
item.appendChild(messageSpan);
// Prepend to top
list.insertBefore(item, list.firstChild);
// Limit history
if (list.children.length > 50) {
list.removeChild(list.lastChild);
}
}
ws.onclose = () => {
console.log("WS Disconnected");
if (statusIndicator) statusIndicator.classList.remove("online");
// Retry in 5s
setTimeout(connectWs, 5000);
};
ws.onerror = (err) => {
console.error("WS Error", err);
ws.close();
};
}
connectWs();
});

View File

@@ -1,68 +1,607 @@
:root { :root {
--bg-color: #0f172a; /* Color Palette - HSL (Hue, Saturation, Lightness) */
--text-color: #f8fafc; /* Primary (Aurora Cyan) */
--accent-color: #38bdf8; --primary-h: 180;
--card-bg: #1e293b; --primary-s: 100%;
--font-family: system-ui, -apple-system, sans-serif; --primary-l: 50%;
--primary: hsl(var(--primary-h), var(--primary-s), var(--primary-l));
/* Secondary (Aurora Purple) */
--secondary-h: 270;
--secondary-s: 100%;
--secondary-l: 65%;
--secondary: hsl(var(--secondary-h), var(--secondary-s), var(--secondary-l));
/* Backgrounds (Dark Slate) */
--bg-h: 222;
--bg-s: 47%;
--bg-l: 7%;
/* Very Dark */
--bg-color: hsl(var(--bg-h), var(--bg-s), var(--bg-l));
--card-bg-h: 217;
--card-bg-s: 33%;
--card-bg-l: 15%;
--card-bg: hsl(var(--card-bg-h), var(--card-bg-s), var(--card-bg-l));
/* Text */
--text-main: hsl(210, 40%, 98%);
--text-muted: hsl(215, 20%, 65%);
--text-accent: var(--primary);
/* Borders */
--border-color: hsl(215, 25%, 25%);
/* Typography */
--font-heading: 'Outfit', system-ui, sans-serif;
--font-body: 'Inter', system-ui, sans-serif;
/* Spacing & Radii */
--radius-md: 0.75rem;
--radius-lg: 1rem;
--header-height: 4rem;
/* Effects */
--shadow-sm: 0 1px 2px 0 rgb(0 0 0 / 0.05);
--shadow-md: 0 4px 6px -1px rgb(0 0 0 / 0.2), 0 2px 4px -2px rgb(0 0 0 / 0.1);
--shadow-glow: 0 0 15px hsla(var(--primary-h), var(--primary-s), 50%, 0.15);
}
*,
*::before,
*::after {
box-sizing: border-box;
} }
body { body {
background-color: var(--bg-color); background-color: var(--bg-color);
color: var(--text-color); color: var(--text-main);
font-family: var(--font-family); font-family: var(--font-body);
margin: 0; margin: 0;
line-height: 1.5; line-height: 1.6;
display: flex; display: flex;
flex-direction: column; flex-direction: column;
min-height: 100vh; min-height: 100vh;
-webkit-font-smoothing: antialiased;
} }
h1,
h2,
h3,
h4,
h5,
h6 {
font-family: var(--font-heading);
margin-top: 0;
line-height: 1.2;
color: var(--text-main);
}
h1 {
font-weight: 700;
}
/* Header */
header { header {
background-color: var(--card-bg); background: rgba(15, 23, 42, 0.8);
padding: 1rem 2rem; /* Semi-transparent */
border-bottom: 1px solid #334155; backdrop-filter: blur(12px);
-webkit-backdrop-filter: blur(12px);
border-bottom: 1px solid var(--border-color);
height: var(--header-height);
padding: 0 2rem;
display: flex; display: flex;
justify-content: space-between; justify-content: space-between;
align-items: center; align-items: center;
position: sticky;
top: 0;
z-index: 50;
} }
header h1 { header h1 {
margin: 0;
font-size: 1.5rem; font-size: 1.5rem;
color: var(--accent-color); margin: 0;
background: linear-gradient(135deg, var(--primary), var(--secondary));
-webkit-background-clip: text;
background-clip: text;
-webkit-text-fill-color: transparent;
letter-spacing: -0.02em;
} }
header nav a {
color: var(--text-muted);
text-decoration: none;
font-weight: 500;
margin-left: 1.5rem;
transition: color 0.15s ease;
font-size: 0.95rem;
}
header nav a:hover {
color: var(--primary);
}
/* Main Layout */
main { main {
flex: 1; flex: 1;
padding: 2rem; padding: 2rem;
max-width: 1200px; max-width: 1200px;
margin: 0 auto; margin: 0 auto;
width: 100%; width: 100%;
box-sizing: border-box;
} }
/* Card Component */
.card { .card {
background-color: var(--card-bg); background-color: var(--card-bg);
border-radius: 0.5rem; border: 1px solid var(--border-color);
padding: 1.5rem; border-radius: var(--radius-lg);
padding: 2rem;
margin-bottom: 1.5rem;
box-shadow: var(--shadow-md);
position: relative;
overflow: hidden;
transition: transform 0.2s ease, box-shadow 0.2s ease, border-color 0.2s ease;
}
.card:hover {
transform: translateY(-2px);
box-shadow: var(--shadow-glow), var(--shadow-md);
border-color: hsla(var(--primary-h), var(--primary-s), 50%, 0.3);
}
.card h2 {
font-size: 1.25rem;
margin-bottom: 1rem; margin-bottom: 1rem;
border: 1px solid #334155; color: var(--text-main);
box-shadow: 0 4px 6px -1px rgba(0, 0, 0, 0.1); display: flex;
align-items: center;
gap: 0.5rem;
} }
footer { .card p {
text-align: center; color: var(--text-muted);
padding: 1rem; margin-bottom: 0;
color: #94a3b8; font-size: 0.95rem;
font-size: 0.875rem;
border-top: 1px solid #334155;
} }
/* Links */
a { a {
color: var(--accent-color); color: var(--primary);
text-decoration: none; text-decoration: none;
transition: opacity 0.2s;
} }
a:hover { a:hover {
text-decoration: underline; opacity: 0.8;
}
/* Buttons (Future Proofing) */
.btn {
display: inline-flex;
align-items: center;
justify-content: center;
padding: 0.5rem 1rem;
border-radius: var(--radius-md);
font-weight: 600;
font-family: var(--font-heading);
cursor: pointer;
transition: all 0.2s ease;
border: none;
font-size: 0.9rem;
text-decoration: none;
}
.btn-primary {
background: linear-gradient(135deg, var(--primary), hsl(var(--primary-h), 90%, 45%));
color: #000;
/* Contrast text on Cyan */
box-shadow: 0 4px 6px -1px hsla(var(--primary-h), var(--primary-s), 50%, 0.2);
}
.btn-primary:hover {
filter: brightness(1.1);
box-shadow: 0 6px 8px -1px hsla(var(--primary-h), var(--primary-s), 50%, 0.3);
}
/* Forms & Inputs */
input[type="text"],
input[type="email"],
input[type="password"],
textarea,
select {
width: 100%;
padding: 0.75rem 1rem;
background-color: rgba(15, 23, 42, 0.5);
border: 1px solid var(--border-color);
border-radius: var(--radius-md);
color: var(--text-main);
font-family: var(--font-body);
font-size: 0.95rem;
transition: all 0.2s;
}
input:focus,
textarea:focus,
select:focus {
outline: none;
border-color: var(--primary);
box-shadow: 0 0 0 2px hsla(var(--primary-h), var(--primary-s), 50%, 0.2);
background-color: rgba(15, 23, 42, 0.8);
}
/* Tables */
table {
width: 100%;
border-collapse: collapse;
margin: 1rem 0;
}
th {
text-align: left;
padding: 1rem;
background-color: rgba(15, 23, 42, 0.5);
color: var(--text-muted);
font-weight: 600;
font-size: 0.85rem;
text-transform: uppercase;
letter-spacing: 0.05em;
border-bottom: 1px solid var(--border-color);
}
td {
padding: 1rem;
border-bottom: 1px solid #1e293b;
/* Fallback or specific border */
border-bottom: 1px solid rgba(255, 255, 255, 0.05);
color: var(--text-main);
}
tr:last-child td {
border-bottom: none;
}
tr:hover td {
background-color: rgba(255, 255, 255, 0.02);
}
/* Footer */
footer {
padding: 2rem;
text-align: center;
color: var(--text-muted);
font-size: 0.875rem;
border-top: 1px solid var(--border-color);
background: var(--bg-color);
}
/* Utilities */
.text-gradient {
background: linear-gradient(135deg, var(--primary), var(--secondary));
-webkit-background-clip: text;
background-clip: text;
-webkit-text-fill-color: transparent;
}
/* Animations & Micro-Interactions */
@keyframes fadeIn {
from {
opacity: 0;
transform: translateY(10px);
}
to {
opacity: 1;
transform: translateY(0);
}
}
@keyframes slideUp {
from {
opacity: 0;
transform: translateY(20px);
}
to {
opacity: 1;
transform: translateY(0);
}
}
/* Entry Animations */
.fade-in {
animation: fadeIn 0.4s ease-out forwards;
}
/* Stagger animations for children using nth-child */
main>* {
opacity: 0;
/* Initially hidden */
animation: slideUp 0.5s ease-out forwards;
}
main>*:nth-child(1) {
animation-delay: 0.1s;
}
main>*:nth-child(2) {
animation-delay: 0.2s;
}
main>*:nth-child(3) {
animation-delay: 0.3s;
}
main>*:nth-child(4) {
animation-delay: 0.4s;
}
/* Dynamic Background */
body::before {
content: '';
position: fixed;
top: 0;
left: 0;
width: 100vw;
height: 100vh;
background:
radial-gradient(circle at 15% 50%, hsla(var(--primary-h), var(--primary-s), var(--primary-l), 0.08), transparent 25%),
radial-gradient(circle at 85% 30%, hsla(var(--secondary-h), var(--secondary-s), var(--secondary-l), 0.08), transparent 25%);
z-index: -1;
pointer-events: none;
}
/* Link Interactions */
a {
position: relative;
transition: color 0.2s ease, opacity 0.2s ease;
}
header nav a::after {
content: '';
position: absolute;
bottom: -4px;
left: 0;
width: 0%;
height: 2px;
background: var(--primary);
transition: width 0.3s cubic-bezier(0.4, 0, 0.2, 1);
}
header nav a:hover::after {
width: 100%;
}
/* Accessibility: Reduced Motion */
@media (prefers-reduced-motion: reduce) {
*,
*::before,
*::after {
animation-duration: 0.01ms !important;
animation-iteration-count: 1 !important;
transition-duration: 0.01ms !important;
scroll-behavior: auto !important;
}
}
/* Mobile Responsiveness */
@media (max-width: 768px) {
:root {
--header-height: 3.5rem;
/* Compact header on mobile */
}
body {
font-size: 14px;
/* Slightly smaller base font */
}
/* Layout Adjustments */
header {
padding: 0 1rem;
}
header nav a {
margin-left: 1rem;
font-size: 0.9rem;
}
main {
padding: 1rem;
width: 100%;
max-width: 100%;
}
/* Typography Scaling */
h1 {
font-size: 1.75rem;
}
h2 {
font-size: 1.5rem;
}
h3 {
font-size: 1.25rem;
}
/* Card Adjustments */
.card {
padding: 1.25rem;
border-radius: var(--radius-md);
/* Slightly smaller radius */
}
/* Stack flex containers if needed (general util) */
.flex-col-mobile {
flex-direction: column !important;
}
/* Touch Targets */
.btn,
a,
input,
select {
min-height: 44px;
/* Compliance with touch target guidelines */
}
/* Horizontal scroll for wide tables */
.table-container {
overflow-x: auto;
-webkit-overflow-scrolling: touch;
margin-left: -1rem;
margin-right: -1rem;
padding-left: 1rem;
padding-right: 1rem;
}
}
/* Dashboard Layout */
.dashboard-grid {
display: grid;
grid-template-columns: repeat(4, 1fr);
gap: 1.5rem;
margin-bottom: 2rem;
}
.stat-card {
background: var(--card-bg);
border: 1px solid var(--border-color);
padding: 1.5rem;
border-radius: var(--radius-lg);
text-align: center;
box-shadow: var(--shadow-sm);
}
.stat-card h3 {
font-size: 0.85rem;
text-transform: uppercase;
letter-spacing: 0.05em;
color: var(--text-muted);
margin-bottom: 0.5rem;
}
.stat-card .stat-value {
font-size: 2rem;
font-weight: 700;
color: var(--text-main);
font-family: var(--font-heading);
}
.dashboard-main {
grid-column: 1 / -1;
display: grid;
grid-template-columns: 2fr 1fr;
gap: 1.5rem;
}
.panel {
background: var(--card-bg);
border: 1px solid var(--border-color);
border-radius: var(--radius-lg);
padding: 1.5rem;
display: flex;
flex-direction: column;
}
.panel.control-panel {
grid-column: 1 / -1;
}
.panel-header {
display: flex;
justify-content: space-between;
align-items: center;
margin-bottom: 1rem;
border-bottom: 1px solid var(--border-color);
padding-bottom: 0.75rem;
}
.panel-header h2 {
font-size: 1.1rem;
margin: 0;
}
/* Activity Feed */
.activity-feed {
list-style: none;
padding: 0;
margin: 0;
max-height: 300px;
overflow-y: auto;
}
.activity-item {
display: flex;
gap: 1rem;
padding: 0.75rem 0;
border-bottom: 1px solid rgba(255, 255, 255, 0.05);
font-size: 0.9rem;
}
.activity-item .time {
color: var(--text-muted);
font-family: monospace;
}
.activity-item.info .message { color: var(--text-main); }
.activity-item.success .message { color: hsl(150, 60%, 45%); }
.activity-item.warning .message { color: hsl(35, 90%, 60%); }
.activity-item.error .message { color: hsl(0, 80%, 60%); }
.badge.live {
background: hsla(0, 100%, 50%, 0.2);
color: hsl(0, 100%, 60%);
padding: 0.25rem 0.5rem;
border-radius: 4px;
font-size: 0.7rem;
font-weight: bold;
text-transform: uppercase;
animation: pulse 2s infinite;
}
@keyframes pulse {
0% { opacity: 1; }
50% { opacity: 0.5; }
100% { opacity: 1; }
}
/* Mock Chart */
.mock-chart-container {
height: 200px;
display: flex;
align-items: flex-end;
gap: 4px;
padding-top: 1rem;
border-bottom: 1px solid var(--border-color);
margin-bottom: 0.5rem;
}
.mock-chart-bar {
flex: 1;
background: var(--primary);
opacity: 0.5;
border-radius: 2px 2px 0 0;
transition: height 0.5s ease;
}
.mock-chart-bar:hover {
opacity: 0.8;
}
.metrics-legend {
font-size: 0.8rem;
color: var(--text-muted);
text-align: center;
}
/* Responsive Dashboard */
@media (max-width: 768px) {
.dashboard-grid {
grid-template-columns: 1fr 1fr; /* 2 columns on tablet/mobile */
}
.dashboard-main {
grid-template-columns: 1fr; /* Stack panels */
}
} }

View File

@@ -7,7 +7,17 @@ describe("Web Router", () => {
const res = await router(req); const res = await router(req);
expect(res.status).toBe(200); expect(res.status).toBe(200);
expect(res.headers.get("Content-Type")).toBe("text/html"); expect(res.headers.get("Content-Type")).toBe("text/html");
expect(await res.text()).toContain("Aurora Web"); const text = await res.text();
expect(text).toContain("Aurora Web");
expect(text).toContain("Uptime:");
expect(text).toContain('id="uptime-display"');
});
it("should return dashboard page on /dashboard", async () => {
const req = new Request("http://localhost/dashboard");
const res = await router(req);
expect(res.status).toBe(200);
expect(await res.text()).toContain("Live Activity");
}); });
it("should return health check on /health", async () => { it("should return health check on /health", async () => {

View File

@@ -1,5 +1,6 @@
import { homeRoute } from "./routes/home"; import { homeRoute } from "./routes/home";
import { healthRoute } from "./routes/health"; import { healthRoute } from "./routes/health";
import { dashboardRoute } from "./routes/dashboard";
import { file } from "bun"; import { file } from "bun";
import { join, resolve } from "path"; import { join, resolve } from "path";
@@ -19,12 +20,6 @@ export async function router(request: Request): Promise<Response> {
const relativePath = url.pathname.replace(/^\/public/, ""); const relativePath = url.pathname.replace(/^\/public/, "");
// Resolve full path // Resolve full path
// We use join with relativePath. If relativePath starts with /, join handles it correctly
// effectively treating it as a segment.
// However, to be extra safe with 'resolve', we ensure we are resolving from publicDir.
// simple join(publicDir, relativePath) is usually enough with 'bun'.
// But we use 'resolve' to handle .. segments correctly.
// We prepend '.' to relativePath to ensure it's treated as relative to publicDir logic
const normalizedRelative = relativePath.startsWith("/") ? "." + relativePath : relativePath; const normalizedRelative = relativePath.startsWith("/") ? "." + relativePath : relativePath;
const requestedPath = resolve(publicDir, normalizedRelative); const requestedPath = resolve(publicDir, normalizedRelative);
@@ -35,8 +30,6 @@ export async function router(request: Request): Promise<Response> {
return new Response(staticFile); return new Response(staticFile);
} }
} else { } else {
// If path traversal detected, return 403 or 404.
// 403 indicates we caught them.
return new Response("Forbidden", { status: 403 }); return new Response("Forbidden", { status: 403 });
} }
} }
@@ -47,6 +40,9 @@ export async function router(request: Request): Promise<Response> {
if (url.pathname === "/health") { if (url.pathname === "/health") {
return healthRoute(); return healthRoute();
} }
if (url.pathname === "/dashboard") {
return dashboardRoute();
}
} }
return new Response("Not Found", { status: 404 }); return new Response("Not Found", { status: 404 });

View File

@@ -0,0 +1,95 @@
import { BaseLayout } from "../views/layout";
import { AuroraClient } from "@/lib/BotClient";
export function dashboardRoute(): Response {
// Gather real data where possible, mock where not
const guildCount = AuroraClient.guilds.cache.size;
const userCount = AuroraClient.guilds.cache.reduce((acc, guild) => acc + guild.memberCount, 0); // Approximation
const commandCount = AuroraClient.commands.size;
const ping = AuroraClient.ws.ping;
// In a real app, these would be dynamic charts or lists
const mockedActivity = [
{ time: "10:42:01", type: "info", message: "User 'Syntax' ran /profile" },
{ time: "10:41:55", type: "success", message: "Task 'HourlyCleanup' completed" },
{ time: "10:40:12", type: "warning", message: "API Latency spike detected (150ms)" },
{ time: "10:39:00", type: "info", message: "Bot connected to Gateway" },
];
const content = `
<div class="dashboard-grid">
<!-- Top Stats Row -->
<div class="stat-card">
<h3>Servers</h3>
<div class="stat-value">${guildCount}</div>
</div>
<div class="stat-card">
<h3>Users</h3>
<div class="stat-value">${userCount}</div>
</div>
<div class="stat-card">
<h3>Commands</h3>
<div class="stat-value">${commandCount}</div>
</div>
<div class="stat-card">
<h3>Ping</h3>
<div class="stat-value">${ping < 0 ? "?" : ping}ms</div>
</div>
<!-- Main Content Area -->
<div class="dashboard-main">
<div class="panel activity-panel">
<div class="panel-header">
<h2>Live Activity</h2>
<span class="badge live">LIVE</span>
</div>
<ul class="activity-feed">
${mockedActivity.map(log => `
<li class="activity-item ${log.type}">
<span class="time">${log.time}</span>
<span class="message">${log.message}</span>
</li>
`).join('')}
<li class="activity-item info"><span class="time">--:--:--</span> <span class="message">Waiting for events...</span></li>
</ul>
</div>
<div class="panel metrics-panel">
<div class="panel-header">
<h2>System Metrics</h2>
</div>
<div class="mock-chart-container">
<div class="mock-chart-bar" style="height: 40%"></div>
<div class="mock-chart-bar" style="height: 60%"></div>
<div class="mock-chart-bar" style="height: 30%"></div>
<div class="mock-chart-bar" style="height: 80%"></div>
<div class="mock-chart-bar" style="height: 50%"></div>
<div class="mock-chart-bar" style="height: 90%"></div>
<div class="mock-chart-bar" style="height: 45%"></div>
</div>
<div class="metrics-legend">
<span>CPU Load (Mock)</span>
</div>
</div>
</div>
<!-- Control Panel -->
<div class="panel control-panel">
<div class="panel-header">
<h2>Quick Actions</h2>
</div>
<div class="action-buttons">
<button class="btn btn-secondary" disabled>Clear Cache</button>
<button class="btn btn-secondary" disabled>Reload Commands</button>
<button class="btn btn-danger" disabled>Restart Bot</button>
</div>
</div>
</div>
`;
const html = BaseLayout({ title: "Dashboard", content });
return new Response(html, {
headers: { "Content-Type": "text/html" },
});
}

View File

@@ -6,10 +6,6 @@ export function homeRoute(): Response {
<h2>Welcome</h2> <h2>Welcome</h2>
<p>The Aurora web server is up and running!</p> <p>The Aurora web server is up and running!</p>
</div> </div>
<div class="card">
<h3>Status</h3>
<p>System operational.</p>
</div>
`; `;
const html = BaseLayout({ title: "Home", content }); const html = BaseLayout({ title: "Home", content });

View File

@@ -4,21 +4,82 @@ import type { Server } from "bun";
export class WebServer { export class WebServer {
private static server: Server<unknown> | null = null; private static server: Server<unknown> | null = null;
private static heartbeatInterval: ReturnType<typeof setInterval> | null = null;
public static start() { public static start(port?: number) {
this.server = Bun.serve({ this.server = Bun.serve({
port: env.PORT || 3000, port: port ?? (typeof env.PORT === "string" ? parseInt(env.PORT) : 3000),
fetch: router, fetch: (req, server) => {
const url = new URL(req.url);
if (url.pathname === "/ws") {
// Upgrade the request to a WebSocket
// We pass dummy data for now
if (server.upgrade(req, { data: undefined })) {
return undefined;
}
return new Response("WebSocket upgrade failed", { status: 500 });
}
return router(req);
},
websocket: {
open(ws) {
// console.log("ws: client connected");
ws.subscribe("status-updates");
ws.send(JSON.stringify({ type: "WELCOME", message: "Connected to Aurora WebSocket" }));
},
message(ws, message) {
// Handle incoming messages if needed
},
close(ws) {
// console.log("ws: client disconnected");
ws.unsubscribe("status-updates");
},
},
}); });
console.log(`🌐 Web server listening on http://localhost:${this.server.port}`); console.log(`🌐 Web server listening on http://localhost:${this.server.port}`);
// Start a heartbeat loop
this.heartbeatInterval = setInterval(() => {
if (this.server) {
const uptime = process.uptime();
this.server.publish("status-updates", JSON.stringify({
type: "HEARTBEAT",
data: {
uptime,
timestamp: Date.now()
}
}));
}
}, 5000);
} }
public static stop() { public static stop() {
if (this.heartbeatInterval) {
clearInterval(this.heartbeatInterval);
this.heartbeatInterval = null;
}
if (this.server) { if (this.server) {
this.server.stop(); this.server.stop();
console.log("🛑 Web server stopped"); console.log("🛑 Web server stopped");
this.server = null; this.server = null;
} }
} }
public static get port(): number | undefined {
return this.server?.port;
}
public static broadcastLog(type: string, message: string) {
if (this.server) {
this.server.publish("status-updates", JSON.stringify({
type: "LOG",
data: {
timestamp: new Date().toLocaleTimeString(),
type,
message
}
}));
}
}
} }

View File

@@ -0,0 +1,24 @@
import { describe, expect, it } from "bun:test";
import { formatUptime } from "./format";
describe("formatUptime", () => {
it("formats seconds correctly", () => {
expect(formatUptime(45)).toBe("45s");
});
it("formats minutes and seconds", () => {
expect(formatUptime(65)).toBe("1m 5s");
});
it("formats hours, minutes, and seconds", () => {
expect(formatUptime(3665)).toBe("1h 1m 5s");
});
it("formats days correctly", () => {
expect(formatUptime(90061)).toBe("1d 1h 1m 1s");
});
it("handles zero", () => {
expect(formatUptime(0)).toBe("0s");
});
});

20
src/web/utils/format.ts Normal file
View File

@@ -0,0 +1,20 @@
/**
* Formats a duration in seconds into a human-readable string.
* Example: 3665 -> "1h 1m 5s"
*/
export function formatUptime(seconds: number): string {
if (seconds < 0) return "0s";
const days = Math.floor(seconds / (3600 * 24));
const hours = Math.floor((seconds % (3600 * 24)) / 3600);
const minutes = Math.floor((seconds % 3600) / 60);
const secs = Math.floor(seconds % 60);
const parts = [];
if (days > 0) parts.push(`${days}d`);
if (hours > 0) parts.push(`${hours}h`);
if (minutes > 0) parts.push(`${minutes}m`);
parts.push(`${secs}s`);
return parts.join(" ");
}

View File

@@ -1,4 +1,5 @@
import { escapeHtml } from "../utils/html"; import { escapeHtml } from "../utils/html";
import { formatUptime } from "../utils/format";
interface LayoutProps { interface LayoutProps {
title: string; title: string;
@@ -7,6 +8,12 @@ interface LayoutProps {
export function BaseLayout({ title, content }: LayoutProps): string { export function BaseLayout({ title, content }: LayoutProps): string {
const safeTitle = escapeHtml(title); const safeTitle = escapeHtml(title);
// Calculate uptime for the footer
const uptimeSeconds = process.uptime();
const startTimestamp = Date.now() - (uptimeSeconds * 1000);
const initialUptimeString = formatUptime(uptimeSeconds);
return `<!DOCTYPE html> return `<!DOCTYPE html>
<html lang="en"> <html lang="en">
<head> <head>
@@ -15,20 +22,33 @@ export function BaseLayout({ title, content }: LayoutProps): string {
<title>${safeTitle} | Aurora</title> <title>${safeTitle} | Aurora</title>
<link rel="stylesheet" href="/style.css"> <link rel="stylesheet" href="/style.css">
<meta name="description" content="Aurora Bot Web Interface"> <meta name="description" content="Aurora Bot Web Interface">
<link rel="preconnect" href="https://fonts.googleapis.com">
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
<link href="https://fonts.googleapis.com/css2?family=Inter:wght@400;500;600&family=Outfit:wght@500;600;700&display=swap" rel="stylesheet">
</head> </head>
<body> <body>
<header> <header>
<h1>Aurora Web</h1> <h1>Aurora Web</h1>
<nav> <nav>
<a href="/">Home</a> <a href="/">Home</a>
<a href="/dashboard">Dashboard</a>
</nav> </nav>
</header> </header>
<main> <main>
${content} ${content}
</main> </main>
<footer> <footer>
<div class="footer-content">
<p>&copy; ${new Date().getFullYear()} Aurora Bot</p> <p>&copy; ${new Date().getFullYear()} Aurora Bot</p>
<div class="footer-status">
<span class="status-indicator online">●</span>
<span>System Operational</span>
<span class="separator">|</span>
<span>Uptime: <span id="uptime-display" data-start-timestamp="${Math.floor(startTimestamp)}">${initialUptimeString}</span></span>
</div>
</div>
</footer> </footer>
<script src="/script.js" defer></script>
</body> </body>
</html>`; </html>`;
} }

46
src/web/websocket.test.ts Normal file
View File

@@ -0,0 +1,46 @@
import { describe, expect, it, afterAll, beforeAll } from "bun:test";
import { WebServer } from "./server";
describe("WebSocket Server", () => {
// Start server on a random port
const port = 0;
beforeAll(() => {
WebServer.start(port);
});
afterAll(() => {
WebServer.stop();
});
it("should accept websocket connection and send welcome message", async () => {
const port = WebServer.port;
expect(port).toBeDefined();
const ws = new WebSocket(`ws://localhost:${port}/ws`);
const messagePromise = new Promise<any>((resolve) => {
ws.onmessage = (event) => {
resolve(JSON.parse(event.data as string));
};
});
const msg = await messagePromise;
expect(msg.type).toBe("WELCOME");
expect(msg.message).toContain("Connected");
ws.close();
});
it("should reject non-ws upgrade requests on /ws endpoint via http", async () => {
const port = WebServer.port;
// Just a normal fetch to /ws should fail with 426 Upgrade Required usually,
// but our implementation returns "WebSocket upgrade failed" 500 or undefined -> 101 Switching Protocols if valid.
// If we send a normal GET request to /ws without Upgrade headers, server.upgrade(req) returns false.
// So it returns status 500 "WebSocket upgrade failed" based on our code.
const res = await fetch(`http://localhost:${port}/ws`);
expect(res.status).toBe(500);
expect(await res.text()).toBe("WebSocket upgrade failed");
});
});

View File

@@ -0,0 +1,38 @@
# 2026-01-07-move-status-to-footer
**Status:** Done
**Created:** 2026-01-07
**Tags:** ui, layout, enhancement
## 1. Context & User Story
* **As a:** User of the Web Interface
* **I want to:** see the system status and uptime information in the footer of every page
* **So that:** the main content area is less cluttered and status information is globally available.
## 2. Technical Requirements
### Data Model Changes
- [ ] N/A
### API / Interface
- [x] **Home Page:** Remove the "Status" card from the main content.
- [x] **Layout:** Update `BaseLayout` (or `layout.ts`) to accept or calculate uptime/status information and render it in the `<footer>`.
## 3. Constraints & Validations (CRITICAL)
- **Visuals:** The footer should remain clean and not be overcrowded.
- **Functionality:** The existing client-side uptime counter (via `#uptime-display` in `script.js`) must continue to work. Ensure the ID or data attributes it relies on are preserved in the new location.
## 4. Acceptance Criteria
1. [x] The "Status" card is removed from the Home page content.
2. [x] The Footer displays "System Operational" and the running Uptime counter.
3. [x] navigation to other pages (if any) still shows the status in the footer.
## 5. Implementation Plan
- [x] Edit `src/web/routes/home.ts` to remove the Status card.
- [x] Edit `src/web/views/layout.ts` to add the Status HTML structure to the footer.
- [x] Verify `script.js` selector targets the new element correctly.
## Implementation Notes
- Moved Status/Uptime logic from `home.ts` to `layout.ts` (footer).
- Calculated server-side uptime for initial rendering to prevent flash.
- Preserved `id="uptime-display"` and `data-start-timestamp` for `script.js` compatibility.
- Updated tests to verify uptime presence in global layout.

View File

@@ -0,0 +1,50 @@
# 2026-01-07-web-interface-feature-expansion
**Status:** Draft
**Created:** 2026-01-07
**Tags:** product-design, feature-request, ui
## 1. Context & User Story
* **As a:** Bot Administrator
* **I want to:** have more useful features on the web dashboard
* **So that:** getting insights into the bot's performance and managing it becomes easier than using text commands.
## 2. Technical Requirements
### Proposed Features
1. **Live Console / Activity Feed:**
* Stream abbreviated logs or important events (e.g., "User X joined", "Command Y executed").
2. **Metrics Dashboard:**
* Visual charts for command usage (Top 5 commands).
* Memory usage and CPU load over time.
* API Latency gauge.
3. **Command Palette / Control Panel:**
* Buttons to clear cache, reload configuration, or restart specific services.
4. **Guild/User Browser:**
* Read-only list of top guilds or users by activity/economy balance.
### Data Model Changes
- [ ] May require exposing existing Service data to the Web module.
### API / Interface
- [ ] `GET /api/stats` or `WS` subscription for metrics.
- [ ] `GET /api/logs` (tail).
## 3. Constraints & Validations (CRITICAL)
- **Security:** Modifying bot state (Control Panel) requires strict authentication/authorization (Future Ticket). For now, read-only/safe actions only.
- **Privacy:** Do not expose sensitive user PII in the web logs or dashboard without encryption/masking.
## 4. Acceptance Criteria
1. [ ] A list of prioritized features is approved.
2. [ ] UI Mockups (code or image) for the "Dashboard" view.
3. [ ] Data sources for these features are identified in the codebase.
## 5. Implementation Plan
- [x] **Phase 1:** Brainstorm & Mockup (This Ticket).
- [ ] **Phase 2:** Create individual implementation tickets for selected features (e.g., "Implement Metrics Graph").
## Implementation Notes
- Created `/dashboard` route with a code-based mockup.
- Implemented responsive CSS Grid layout for the dashboard.
- Integrated real `AuroraClient` data for Server Count, User Count, and Command Count.
- Added placeholder UI for "Live Activity" and "Metrics".
- Next steps: Connect WebSocket "HEARTBEAT" to the dashboard metrics and implement real logger streaming.

View File

@@ -1,59 +0,0 @@
# 2026-01-07-web-server-foundation: Web Server Infrastructure Foundation
**Status:** Done
**Created:** 2026-01-07
**Tags:** infrastructure, web, core
## 1. Context & User Story
* **As a:** Developer
* **I want to:** Establish a lightweight, integrated web server foundation within the existing codebase.
* **So that:** We can serve internal tools (Workbench) or public pages (Leaderboard) with minimal friction, avoiding complex separate build pipelines.
## 2. Technical Requirements
### Architecture
- **Native Bun Server:** Use `Bun.serve()` for high performance.
- **Exposure:** The server port must be exposed in `docker-compose.yml` to be accessible outside the container.
- **Rendering Strategy:** **Server-Side Rendering (SSR) via Template Literals**.
- *Why?* Zero dependencies. No build step (like Vite/Webpack) required. We can simply write functions that return HTML strings.
- *Client Side:* Minimal Vanilla JS or a lightweight drop-in library (like HTMX or Alpine from CDN) can be used if interactivity is needed later.
### File Organization (`src/web/`)
We will separate the web infrastructure from game modules to keep concerns clean.
- `src/web/server.ts`: Main server class/entry point.
- `src/web/router.ts`: Simple routing logic.
- `src/web/routes/`: Individual route handlers (e.g., `home.ts`, `health.ts`).
- `src/web/views/`: Reusable HTML template functions (Header, Footer, Layouts).
- `src/web/public/`: Static assets (CSS, Images) served directly.
### API / Interface
- **GET /health**: Returns `{ status: "ok", uptime: <seconds> }`.
- **GET /**: Renders a basic HTML landing page using the View system.
## 3. Constraints & Validations (CRITICAL)
- **Zero Frameworks:** No Express/NestJS.
- **Zero Build Tools:** No Webpack/Vite. The code must be runnable directly by `bun run`.
- **Docker Integration:** Port 3000 (or env `PORT`) must be mapped in Docker Compose.
- **Static Files:** Must implement a handler to check `src/web/public` for file requests.
## 4. Acceptance Criteria
1. [x] `docker-compose up` exposes port 3000.
2. [x] `http://localhost:3000` loads a styled HTML page (verifying static asset serving + SSR).
3. [x] `http://localhost:3000/health` returns JSON.
4. [x] Folder structure established as defined above.
## 5. Implementation Plan
- [x] **Infrastructure**: Create `src/web/` directory structure.
- [x] **Core Logic**: Implement `WebServer` class in `src/web/server.ts` with routing and static file serving logic.
- [x] **Integration**: Bind `WebServer.start()` to `src/index.ts`.
- [x] **Docker**: Update `docker-compose.yml` to map port `3000:3000`.
- [x] **Views**: Create a basic `BaseLayout` function in `src/web/views/layout.ts`.
- [x] **Env**: Add `PORT` to `config.ts` / `env.ts`.
## Implementation Notes
- Created `src/web` directory with `router.ts`, `server.ts` and subdirectories `routes`, `views`, `public`.
- Implemented `WebServer` class using `Bun.serve`.
- Added basic CSS and layout system.
- Added `PORT` to `src/lib/env.ts` (default 3000).
- Integrated into `src/index.ts` to start on boot and graceful shutdown.
- Fixed unrelated typing issues in `src/commands/admin/note.ts` and `src/db/indexes.test.ts` to pass strict CI checks.
- Verified with `bun test` and `bun x tsc`.

View File

@@ -0,0 +1,42 @@
# 2026-01-07-websocket-realtime-data
**Status:** Done
**Created:** 2026-01-07
**Tags:** feature, websocket, realtime, research
## 1. Context & User Story
* **As a:** Developer
* **I want to:** implement a WebSocket connection between the frontend and the Aurora server
* **So that:** I can stream real-time data (profiling, logs, events) to the dashboard without manual page refreshes.
## 2. Technical Requirements
### Data Model Changes
- [ ] N/A
### API / Interface
- [x] **Endpoint:** `/ws` (Upgrade Upgrade: websocket).
- [x] **Protocol:** Define a simple JSON message format (e.g., `{ type: "UPDATE", data: { ... } }`).
## 3. Constraints & Validations (CRITICAL)
- **Bun Support:** Use Bun's native `Bun.serve({ websocket: { ... } })` capabilities if possible.
- **Security:** Ensure that the WebSocket endpoint is not publicly abusable (consider simple token or origin check if necessary, though internal usage is primary context for now).
- **Performance:** Do not flood the client. Throttle updates if necessary.
## 4. Acceptance Criteria
1. [x] Server accepts WebSocket connections on `/ws`.
2. [x] Client (`script.js`) successfully connects to the WebSocket.
3. [x] Server sends a "Hello" or "Ping" packet.
4. [x] Client receives and logs the packet.
5. [x] (Stretch) Stream basic uptime or heartbeat every 5 seconds.
## 5. Implementation Plan
- [x] Modify `src/web/server.ts` to handle `websocket` upgrade in `Bun.serve`.
- [x] Create a message handler object/function to manage connected clients.
- [x] Update `src/web/public/script.js` to initialize `WebSocket`.
- [x] Test connection stability.
## Implementation Notes
- Enabled `websocket` in `Bun.serve` within `src/web/server.ts`.
- Implemented a heartbeat mechanism broadcasting `HEARTBEAT` events every 5s.
- Updated `script.js` to auto-connect, handle reconnects, and update a visual "online" indicator.
- Added `src/web/websocket.test.ts` to verify protocol upgrades and messaging.