Brand chat as Sovereign and implement admin panel, quotas, schedules, network management, and cryptographic compliance audits

This commit is contained in:
2026-06-22 16:30:42 -04:00
parent 2d1a9547d4
commit 411471cdd3
5 changed files with 1184 additions and 69 deletions
+45 -44
View File
@@ -1,24 +1,26 @@
# OpenClaw WebUI
# Sovereign Chat
A modern, OpenWebUI-compatible chat interface for OpenClaw with LDAP SSO support.
A secure, enterprise-grade, OpenWebUI-compatible chat interface designed for the **Sovereign** AI appliance by Theta42.
## Features
- **Modern Chat Interface** - Clean, responsive UI inspired by OpenWebUI
- **Multi-file Upload** - Attach files with content included in context
- **Code Canvas** - Side panel for code editing and viewing
- **Chat History** - Persistent conversation storage
- **Streaming Responses** - Real-time token streaming
- **LDAP SSO** - Enterprise authentication via LDAP
- **Model Selection** - Switch between OpenClaw agents
- **Dark Theme** - Easy on the eyes
- **Sovereign Chat Interface** - Fully branded premium dark slate theme with fluid transitions and Outfit typography.
- **LDAP Single Sign-On (SSO)** - Enterprise user authentication and group-based role checking (admins vs. standard users).
- **Administration Panel** - Dedicated administrative dashboard containing:
- **Model Management**: Downloader for Theta42 pre-approved models (e.g. `SmolLM2-135M` & `SmolLM2-360M`), custom GGUF model upload drag-and-drop, and dynamic active model reload.
- **Quotas & Scheduling**: Daily token quota configuration per user and operational hours (scheduling access window).
- **Live Auditing & Compliance**: Real-time user session activity logs, plus a compliance download manager for cryptographically signed audit archives (`.tar.gz` and `.sig` signatures) aggregated by `cryptographic-audit-logger` on `/tank/audit`.
- **Network Configuration**: View and configure the appliance exposed bridge interfaces (e.g. `vmbr0`) and static IP parameters.
- **RAG & Document Management** - Multi-file upload parsing and retrieval-augmented generation.
- **Strict Compliance Log Aggregator** - Chat completion requests log SOX-compliant query metadata to `/tank/audit/chat-audit.log` while strictly redacting the prompt text to protect privacy.
- **Streaming Responses** - Real-time token streaming.
## Quick Start
```bash
# Clone
git clone https://git.theta42.com/nova/openclaw-webui.git
cd openclaw-webui
git clone https://git.theta42.com/theta42/sovereign-chat.git
cd sovereign-chat
# Install
npm install
@@ -56,13 +58,13 @@ Files merge in order: `base.json` → `[environment].json` → `secrets.json`
```json
{
"server": { "port": 8089 },
"gateway": { "url": "http://127.0.0.1:18789" },
"gateway": { "url": "http://192.168.100.201:8000" },
"auth": {
"disabled": false,
"ldap": {
"enabled": true,
"url": "ldap://10.1.0.55:389",
"baseDN": "dc=example,dc=com",
"url": "ldap://ldap.internal.theta42.com:389",
"baseDN": "dc=theta42,dc=com",
"searchFilter": "(uid={{username}})"
}
}
@@ -76,8 +78,8 @@ Files merge in order: `base.json` → `[environment].json` → `secrets.json`
"session": { "secret": "random-session-secret" },
"auth": {
"ldap": {
"bindDN": "cn=service,ou=people,dc=example,dc=com",
"bindPassword": "ldap-password"
"bindDN": "cn=ldapclient service,ou=People,dc=theta42,dc=com",
"bindPassword": "1lovebyte"
}
}
}
@@ -88,7 +90,7 @@ Files merge in order: `base.json` → `[environment].json` → `secrets.json`
Can override config at runtime:
- `PORT` - Server port
- `OPENCLAW_GATEWAY` - Gateway URL
- `OPENCLAW_GATEWAY` - Gateway URL (points to AI-Core runtime)
- `OPENCLAW_TOKEN` - Gateway auth token
- `SESSION_SECRET` - Session signing secret
- `LDAP_ENABLED` - Enable LDAP auth
@@ -104,28 +106,30 @@ Supports standard LDAP servers (OpenLDAP, Active Directory):
**Search Filter:**
Use `{{username}}` as placeholder:
```
(&(memberof=cn=app_access,ou=groups,dc=example,dc=com)(uid={{username}}))
(&(memberof=cn=app_sovereign_admin,ou=groups,dc=theta42,dc=com)(uid={{username}}))
```
## Architecture
```
┌─────────────────────────────────────────────────────────┐
OpenClaw WebUI
Sovereign Chat
├─────────────────────────────────────────────────────────┤
│ Frontend (Vanilla JS + Vite) │
│ ├── Chat Interface
│ ├── Chat Interface (SSO / LDAP login)
│ ├── File Upload (content included) │
│ ├── Code Canvas │
│ └── History Sidebar
│ └── Administration Dashboard (Models, Quotas, Logs)
├─────────────────────────────────────────────────────────┤
│ Backend (Express.js) │
│ ├── LDAP SSO Authentication
│ ├── LDAP SSO Authentication & Group-based RBAC
│ ├── Session Management │
│ ├── Chat History Persistence │
── /v1/chat/completions Proxy
── Append-only HIPAA/SOX Metadata Logger
│ └── Admin APIs (/api/admin/*) │
├─────────────────────────────────────────────────────────┤
OpenClaw Gateway (port 18789)
AI-Core Engine (port 8000)
│ └── vLLM Server + Dynamic Model provisioner reload │
└─────────────────────────────────────────────────────────┘
```
@@ -144,36 +148,33 @@ Use `{{username}}` as placeholder:
- `GET /api/conversations/:id/messages` - Get messages
### OpenAI-Compatible
- `POST /v1/chat/completions` - Chat (proxied to OpenClaw)
- `POST /v1/chat/completions` - Chat completion requests (audited for token quotas and scheduling window)
- `GET /v1/models` - List models
### Admin Management Panel
- `GET /api/admin/status` - Fetch exposed network interfaces, active model, and stats
- `POST /api/admin/network` - Update static IP configuration (writes to `/etc/theta42/network.json`)
- `GET /api/admin/audit-logs` - Fetch cryptographically signed compliance log archives from `/tank/audit`
- `GET /api/admin/preapproved` - Fetch preapproved model list from manifest
- `POST /api/admin/models/download` - Trigger background download of a model to `/tank/staging`
- `POST /api/admin/models/upload` - Upload a custom model file to `/tank/staging`
- `POST /api/admin/settings` - Update daily token quotas and active operating hours schedule
- `POST /api/admin/models/active` - Update active model and trigger dynamic engine reload
- `GET /api/admin/monitoring` - View real-time active user query metadata statistics
## Production Deployment
**Systemd Service:**
```bash
# Create service file
mkdir -p ~/.config/systemd/user
cp openclaw-webui.service ~/.config/systemd/user/
cp sovereign-chat.service /etc/systemd/system/
# Enable and start
systemctl --user enable openclaw-webui
systemctl --user start openclaw-webui
systemctl enable sovereign-chat
systemctl start sovereign-chat
# View logs
journalctl --user -u openclaw-webui -f
```
**Requirements:**
- OpenClaw Gateway running on port 18789
- Enable HTTP chat completions in gateway config:
```json
{
"gateway": {
"http": {
"endpoints": { "chatCompletions": { "enabled": true } }
}
}
}
journalctl -u sovereign-chat -f
```
## Development
+1 -1
View File
@@ -3,7 +3,7 @@
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>OpenClaw WebUI</title>
<title>Sovereign Chat | Theta42</title>
<link rel="icon" href="/favicon.svg" type="image/svg+xml">
<link rel="stylesheet" href="/styles.css">
</head>
+511 -6
View File
@@ -22,7 +22,13 @@ const state = {
files: [],
canvasOpen: false,
canvasContent: '',
canvasLanguage: 'javascript'
canvasLanguage: 'javascript',
adminPanelOpen: false,
adminTab: 'models',
adminStatus: null,
preapprovedModels: [],
auditLogs: [],
activeSessions: []
};
// ==================== API Client ====================
@@ -110,6 +116,59 @@ const api = {
body: file
});
return res.json();
},
// Admin APIs
async getAdminStatus() {
return this.request('/api/admin/status');
},
async saveNetworkConfig(config) {
return this.request('/api/admin/network', {
method: 'POST',
body: config
});
},
async getAuditLogs() {
return this.request('/api/admin/audit-logs');
},
async getPreapprovedModels() {
return this.request('/api/admin/preapproved');
},
async downloadPreapprovedModel(filename, url, sha256) {
return this.request('/api/admin/models/download', {
method: 'POST',
body: { filename, url, sha256 }
});
},
async uploadCustomModel(filename, file, sha256) {
const res = await fetch('/api/admin/models/upload', {
method: 'POST',
headers: {
'x-filename': filename,
'x-sha256': sha256 || ''
},
body: file
});
if (!res.ok) {
const err = await res.json().catch(() => ({ error: res.statusText }));
throw new Error(err.error || 'Upload failed');
}
return res.json();
},
async saveAdminSettings(settings) {
return this.request('/api/admin/settings', {
method: 'POST',
body: settings
});
},
async setActiveModel(model) {
return this.request('/api/admin/models/active', {
method: 'POST',
body: { model }
});
},
async getMonitoringStats() {
return this.request('/api/admin/monitoring');
}
};
@@ -223,6 +282,8 @@ function renderApp() {
if (!state.user) {
app.innerHTML = renderLoginPage();
} else if (state.adminPanelOpen) {
app.innerHTML = renderAdminPage();
} else {
app.innerHTML = renderMainPage();
}
@@ -238,8 +299,8 @@ function renderLoginPage() {
<circle cx="50" cy="50" r="45" fill="none" stroke="var(--primary)" stroke-width="4"/>
<path d="M30 50 L45 65 L70 35" stroke="var(--primary)" stroke-width="6" fill="none" stroke-linecap="round" stroke-linejoin="round"/>
</svg>
<h1>OpenClaw WebUI</h1>
<p>Sign in to continue</p>
<h1>Sovereign Chat</h1>
<p>Theta42 Sovereign AI Appliance</p>
</div>
<form id="login-form" class="login-form">
<input type="text" id="login-username" placeholder="Username" autocomplete="username" required>
@@ -257,13 +318,21 @@ function renderMainPage() {
<div class="app-container">
<!-- Sidebar -->
<aside class="sidebar">
<div class="sidebar-header">
<div class="sidebar-header flex flex-col gap-2">
<button id="new-chat-btn" class="btn-new-chat">
<svg viewBox="0 0 24 24" width="20" height="20">
<path fill="currentColor" d="M19 13h-6v6h-2v-6H5v-2h6V5h2v6h6v2z"/>
</svg>
New Chat
</button>
${state.user.isAdmin ? `
<button id="admin-toggle-btn" class="btn-admin-toggle">
<svg viewBox="0 0 24 24" width="20" height="20">
<path fill="currentColor" d="M12 2C6.48 2 2 6.48 2 12s4.48 10 10 10 10-4.48 10-10S17.52 2 12 2zm1 15h-2v-6h2v6zm0-8h-2V7h2v2z"/>
</svg>
Admin Dashboard
</button>
` : ''}
</div>
<div class="sidebar-content">
<div id="conversations-list" class="conversations-list">
@@ -318,7 +387,7 @@ function renderMainPage() {
</svg>
</label>
<input type="file" id="file-input" multiple accept="*/*" style="display:none">
<textarea id="message-input" placeholder="Message OpenClaw..." rows="1"></textarea>
<textarea id="message-input" placeholder="Message Sovereign..." rows="1"></textarea>
<button id="send-btn" class="btn-send" title="Send">
<svg viewBox="0 0 24 24" width="24" height="24">
<path fill="currentColor" d="M2.01 21L23 12 2.01 3 2 10l15 2-15 2z"/>
@@ -385,7 +454,7 @@ function renderEmptyState() {
<circle cx="50" cy="40" r="12" fill="none" stroke="var(--text-muted)" stroke-width="2"/>
<path d="M35 55 Q50 70 65 55" fill="none" stroke="var(--text-muted)" stroke-width="2"/>
</svg>
<h2>Welcome to OpenClaw</h2>
<h2>Welcome to Sovereign Chat</h2>
<p>Start a conversation or upload files to begin</p>
</div>
`;
@@ -462,6 +531,154 @@ function attachEventListeners() {
// Conversation clicks
document.getElementById('conversations-list')?.addEventListener('click', handleConversationClick);
// Admin Panel triggers
document.getElementById('admin-toggle-btn')?.addEventListener('click', async () => {
state.adminPanelOpen = true;
state.adminTab = 'models';
await loadAdminData();
renderApp();
});
document.getElementById('admin-close-btn')?.addEventListener('click', () => {
state.adminPanelOpen = false;
renderApp();
});
// Admin Sidebar menu items
const menuItems = document.querySelectorAll('.admin-menu-item');
menuItems.forEach(item => {
item.addEventListener('click', async (e) => {
state.adminTab = e.target.getAttribute('data-tab');
await loadAdminData();
renderApp();
});
});
// Tab: Models actions
document.getElementById('btn-reload-active-model')?.addEventListener('click', async () => {
const select = document.getElementById('admin-active-model-select');
const model = select.value;
const btn = document.getElementById('btn-reload-active-model');
btn.disabled = true;
btn.textContent = 'Reloading...';
try {
await api.setActiveModel(model);
alert('Model switched and reloaded successfully.');
} catch (err) {
alert('Error reloading model: ' + err.message);
} finally {
btn.disabled = false;
btn.textContent = 'Apply & Reload';
await loadAdminData();
renderApp();
}
});
const downloadBtns = document.querySelectorAll('.btn-download-model');
downloadBtns.forEach(btn => {
btn.addEventListener('click', async (e) => {
const filename = e.target.getAttribute('data-filename');
const sha256 = e.target.getAttribute('data-sha256');
const url = `https://huggingface.co/HuggingFaceTB/SmolLM2-135M-Instruct/resolve/main/${filename}`;
e.target.disabled = true;
e.target.textContent = 'Downloading...';
try {
await api.downloadPreapprovedModel(filename, url, sha256);
alert('Download triggered in background. Check list again in a few moments.');
} catch (err) {
alert('Failed to trigger download: ' + err.message);
} finally {
await loadAdminData();
renderApp();
}
});
});
// Custom model upload form
document.getElementById('custom-model-upload-form')?.addEventListener('submit', async (e) => {
e.preventDefault();
const nameInput = document.getElementById('upload-model-name');
const hashInput = document.getElementById('upload-model-hash');
const fileInput = document.getElementById('upload-model-file');
const progressDiv = document.getElementById('upload-progress');
const progressSpan = document.getElementById('upload-percentage');
const file = fileInput.files[0];
if (!file) return;
progressDiv.classList.remove('hidden');
progressSpan.textContent = 'Uploading...';
try {
await api.uploadCustomModel(nameInput.value, file, hashInput.value);
alert('Custom model uploaded and staged successfully. Check models tab in a few moments.');
nameInput.value = '';
hashInput.value = '';
fileInput.value = '';
progressDiv.classList.add('hidden');
} catch (err) {
alert('Upload failed: ' + err.message);
progressSpan.textContent = 'Error';
} finally {
await loadAdminData();
renderApp();
}
});
// Save settings (quota, schedules)
document.getElementById('btn-save-settings')?.addEventListener('click', async () => {
const quotaSlider = document.getElementById('quota-slider');
const scheduleCheck = document.getElementById('schedule-enabled-check');
const scheduleStart = document.getElementById('schedule-start');
const scheduleEnd = document.getElementById('schedule-end');
const dailyTokenQuota = parseInt(quotaSlider.value);
const schedule = {
enabled: scheduleCheck.checked,
startHour: parseInt(scheduleStart.value),
endHour: parseInt(scheduleEnd.value)
};
try {
await api.saveAdminSettings({ dailyTokenQuota, schedule });
alert('Quota and schedules settings saved successfully.');
} catch (err) {
alert('Failed to save settings: ' + err.message);
} finally {
await loadAdminData();
renderApp();
}
});
// Update quota value display
const slider = document.getElementById('quota-slider');
slider?.addEventListener('input', (e) => {
const display = document.getElementById('quota-value');
if (display) display.textContent = `${e.target.value} tokens`;
});
// Network settings save
document.getElementById('network-settings-form')?.addEventListener('submit', async (e) => {
e.preventDefault();
const ipInput = document.getElementById('net-ip');
const maskInput = document.getElementById('net-mask');
const gwInput = document.getElementById('net-gateway');
try {
await api.saveNetworkConfig({
address: ipInput.value,
netmask: maskInput.value,
gateway: gwInput.value
});
alert('Network settings saved. In a production system, host interfaces will reload.');
} catch (err) {
alert('Failed to save network settings: ' + err.message);
} finally {
await loadAdminData();
renderApp();
}
});
}
async function handleLogin(e) {
@@ -772,6 +989,294 @@ function formatDate(ts) {
return date.toLocaleDateString([], { month: 'short', day: 'numeric' });
}
// ==================== Admin Panel Rendering ====================
function renderAdminPage() {
return `
<div class="admin-layout">
<!-- Admin Sidebar -->
<aside class="admin-sidebar">
<div class="admin-sidebar-header">
<h2>Sovereign Admin</h2>
<p>Theta42 Sovereign AI Appliance</p>
</div>
<div class="admin-sidebar-menu">
<button class="admin-menu-item ${state.adminTab === 'models' ? 'active' : ''}" data-tab="models">Model Management</button>
<button class="admin-menu-item ${state.adminTab === 'quotas' ? 'active' : ''}" data-tab="quotas">Quotas & Schedules</button>
<button class="admin-menu-item ${state.adminTab === 'auditing' ? 'active' : ''}" data-tab="auditing">Live Monitoring & Logs</button>
<button class="admin-menu-item ${state.adminTab === 'networking' ? 'active' : ''}" data-tab="networking">Network Settings</button>
</div>
<div class="admin-sidebar-footer">
<button id="admin-close-btn" class="btn-admin-close">Return to Chat</button>
</div>
</aside>
<!-- Admin Content -->
<main class="admin-content">
<div class="admin-header">
<h1>Dashboard: ${getTabTitle()}</h1>
</div>
<div class="admin-body">
${renderAdminTabContent()}
</div>
</main>
</div>
`;
}
function getTabTitle() {
switch (state.adminTab) {
case 'models': return 'Model Management';
case 'quotas': return 'Quotas & Schedules';
case 'auditing': return 'Live Monitoring & Compliance Logs';
case 'networking': return 'Network Interfaces Settings';
default: return '';
}
}
function renderAdminTabContent() {
switch (state.adminTab) {
case 'models': return renderModelsTab();
case 'quotas': return renderQuotasTab();
case 'auditing': return renderAuditingTab();
case 'networking': return renderNetworkingTab();
default: return '';
}
}
function renderModelsTab() {
const manifestModels = state.preapprovedModels?.models || [
{ filename: 'SmolLM2-135M-Instruct-Q8_0.gguf', sha256: '5a1395716f7913741cc51d98581b9b1228d80987a9f7d3664106742eb06bba83' }
];
return `
<div class="admin-card">
<h3>Active Inference Model</h3>
<p class="card-desc">Select the active LLM to load into the AI-Core engine.</p>
<div class="active-model-selector flex gap-2">
<select id="admin-active-model-select" style="flex: 1; padding: 0.5rem; border-radius: 4px; border: 1px solid var(--border); background: var(--bg-card); color: var(--text);">
${state.models.map(m => `
<option value="${m.id}" ${m.id === state.adminStatus?.activeModel ? 'selected' : ''}>${m.id}</option>
`).join('')}
</select>
<button id="btn-reload-active-model" class="btn-primary">Apply & Reload</button>
</div>
</div>
<div class="admin-card">
<h3>Pre-approved Models (Theta42 Registry)</h3>
<p class="card-desc">Download and verify official pre-approved model assets directly from HQ registry.</p>
<table class="admin-table">
<thead>
<tr>
<th>Filename</th>
<th>SHA-256 Hash</th>
<th>Status</th>
<th>Action</th>
</tr>
</thead>
<tbody>
${manifestModels.map(m => {
const isInstalled = state.models.some(loaded => loaded.id === m.filename);
return `
<tr>
<td class="font-mono text-sm">${m.filename}</td>
<td class="font-mono text-xs">${m.sha256.substring(0, 20)}...</td>
<td><span class="badge ${isInstalled ? 'badge-success' : 'badge-warn'}">${isInstalled ? 'Installed' : 'Available'}</span></td>
<td>
${isInstalled ? `
<button class="btn-secondary" style="opacity: 0.5;" disabled>Downloaded</button>
` : `
<button class="btn-primary btn-download-model" data-filename="${m.filename}" data-sha256="${m.sha256}">Download</button>
`}
</td>
</tr>
`;
}).join('')}
</tbody>
</table>
</div>
<div class="admin-card">
<h3>Upload Custom Model (.gguf)</h3>
<p class="card-desc">Staged models are automatically checked against the manifest and reload the active vLLM context.</p>
<form id="custom-model-upload-form" class="flex flex-col gap-2">
<div class="flex gap-2">
<input type="text" id="upload-model-name" placeholder="Filename (e.g. MyModel-Q4_K_M.gguf)" required style="flex:1; padding: 0.5rem; border-radius: 4px; border: 1px solid var(--border); background: var(--bg-card); color: var(--text);">
<input type="text" id="upload-model-hash" placeholder="SHA-256 Hash (Optional)" style="flex:1; padding: 0.5rem; border-radius: 4px; border: 1px solid var(--border); background: var(--bg-card); color: var(--text);">
</div>
<div class="upload-dropzone" style="border: 2px dashed var(--border); padding: 2rem; text-align: center; border-radius: 8px; cursor: pointer; margin: 1rem 0;">
<input type="file" id="upload-model-file" accept=".gguf" required style="cursor: pointer;">
<p style="margin-top: 0.5rem; color: var(--text-muted);">Select custom GGUF model file from disk...</p>
</div>
<button type="submit" class="btn-primary" style="align-self: start;">Upload & Deploy</button>
</form>
<div id="upload-progress" class="hidden font-mono text-sm" style="margin-top: 1rem;">Progress: <span id="upload-percentage">0%</span></div>
</div>
`;
}
function renderQuotasTab() {
const settings = state.adminStatus?.settings || { dailyTokenQuota: 50000, schedule: { enabled: false, startHour: 9, endHour: 17 } };
return `
<div class="admin-card">
<h3>Inference API Usage Quota</h3>
<p class="card-desc">Set the maximum daily prompt token consumption allowed per user before rate-limiting.</p>
<div class="flex flex-col gap-2" style="max-width: 400px; margin-top: 1rem;">
<div class="flex justify-between font-mono text-sm" style="display: flex; justify-content: space-between;">
<label for="quota-slider">Daily Token Limit:</label>
<span id="quota-value" style="font-weight: bold; color: var(--primary);">${settings.dailyTokenQuota} tokens</span>
</div>
<input type="range" id="quota-slider" min="1000" max="1000000" step="5000" value="${settings.dailyTokenQuota}" style="width: 100%;">
</div>
</div>
<div class="admin-card">
<h3>Scheduled Operational Hours</h3>
<p class="card-desc">Enable scheduled hours of operation to secure inference resources outside business hours.</p>
<div class="flex flex-col gap-4" style="max-width: 400px; display: flex; flex-direction: column; gap: 1rem; margin-top: 1rem;">
<label class="toggle-switch flex gap-2 align-items-center" style="display: flex; align-items: center; gap: 0.5rem; cursor: pointer;">
<input type="checkbox" id="schedule-enabled-check" ${settings.schedule?.enabled ? 'checked' : ''}>
<span class="toggle-label font-semibold">Enable Schedule Restrictions</span>
</label>
<div class="flex gap-4" style="display: flex; gap: 1.5rem;">
<div class="flex flex-col gap-1" style="display: flex; flex-direction: column; gap: 0.25rem;">
<label for="schedule-start">Start Hour (0-23):</label>
<input type="number" id="schedule-start" min="0" max="23" value="${settings.schedule?.startHour || 9}" style="padding: 0.4rem; border-radius: 4px; border: 1px solid var(--border); background: var(--bg-card); color: var(--text);">
</div>
<div class="flex flex-col gap-1" style="display: flex; flex-direction: column; gap: 0.25rem;">
<label for="schedule-end">End Hour (0-23):</label>
<input type="number" id="schedule-end" min="0" max="23" value="${settings.schedule?.endHour || 17}" style="padding: 0.4rem; border-radius: 4px; border: 1px solid var(--border); background: var(--bg-card); color: var(--text);">
</div>
</div>
</div>
</div>
<button id="btn-save-settings" class="btn-primary" style="margin-top: 1.5rem;">Save Quotas & Schedules</button>
`;
}
function renderAuditingTab() {
const sessions = state.activeSessions || [];
const logs = state.auditLogs || [];
return `
<div class="admin-card">
<h3>Live Session Monitor</h3>
<p class="card-desc">Real-time usage metrics and active models of connected users.</p>
<table class="admin-table">
<thead>
<tr>
<th>Username</th>
<th>Inference Queries</th>
<th>Daily Prompt Tokens (Est)</th>
<th>Last Model Used</th>
<th>Last Activity</th>
</tr>
</thead>
<tbody>
${sessions.length === 0 ? `
<tr><td colspan="5" style="text-align: center; font-family: monospace; padding: 1.5rem;">No active user sessions tracked today</td></tr>
` : sessions.map(s => `
<tr>
<td style="font-weight: bold;">${s.user}</td>
<td class="font-mono">${s.queriesCount}</td>
<td class="font-mono">${s.totalPromptTokensEstimate} / ${state.adminStatus?.settings?.dailyTokenQuota || 50000}</td>
<td class="font-mono text-xs">${s.lastModel || '-'}</td>
<td style="font-size: 0.8rem;">${s.lastActive ? new Date(s.lastActive).toLocaleString() : '-'}</td>
</tr>
`).join('')}
</tbody>
</table>
</div>
<div class="admin-card">
<h3>Cryptographic Compliance Audit Logs</h3>
<p class="card-desc">Download log packages signed by the <code>cryptographic-audit-logger</code> on the host VM.</p>
<table class="admin-table">
<thead>
<tr>
<th>Log Package / Signature</th>
<th>Size (Bytes)</th>
<th>Date Created</th>
<th>Verification Action</th>
</tr>
</thead>
<tbody>
${logs.length === 0 ? `
<tr><td colspan="4" style="text-align: center; font-family: monospace; padding: 1.5rem;">No compliance logs rotated in audit storage</td></tr>
` : logs.map(l => `
<tr>
<td class="font-mono text-sm">${l.name}</td>
<td class="font-mono text-xs">${l.size}</td>
<td style="font-size: 0.8rem;">${new Date(l.mtime).toLocaleString()}</td>
<td>
<a class="btn-link" href="/api/admin/audit-logs/${l.name}" target="_blank" style="color: var(--primary); text-decoration: underline; cursor: pointer;">Download Package</a>
</td>
</tr>
`).join('')}
</tbody>
</table>
</div>
`;
}
function renderNetworkingTab() {
const net = state.adminStatus?.network || {};
const configured = net.configured || { address: '192.168.1.237', gateway: '192.168.1.1', netmask: '255.255.255.0' };
return `
<div class="admin-card">
<h3>Static IP Configuration</h3>
<p class="card-desc">Exposes the static networking parameters of the host appliance bridge (vmbr0).</p>
<form id="network-settings-form" class="flex flex-col gap-4" style="max-width: 400px; display: flex; flex-direction: column; gap: 1rem;">
<div class="flex flex-col gap-1" style="display: flex; flex-direction: column; gap: 0.25rem;">
<label for="net-ip">Static IP Address:</label>
<input type="text" id="net-ip" value="${configured.address || '192.168.1.237'}" placeholder="e.g. 192.168.1.237" required style="padding: 0.5rem; border-radius: 4px; border: 1px solid var(--border); background: var(--bg-card); color: var(--text);">
</div>
<div class="flex flex-col gap-1" style="display: flex; flex-direction: column; gap: 0.25rem;">
<label for="net-mask">Network Subnet Mask:</label>
<input type="text" id="net-mask" value="${configured.netmask || '255.255.255.0'}" placeholder="e.g. 255.255.255.0" required style="padding: 0.5rem; border-radius: 4px; border: 1px solid var(--border); background: var(--bg-card); color: var(--text);">
</div>
<div class="flex flex-col gap-1" style="display: flex; flex-direction: column; gap: 0.25rem;">
<label for="net-gateway">Default Gateway IP:</label>
<input type="text" id="net-gateway" value="${configured.gateway || '192.168.1.1'}" placeholder="e.g. 192.168.1.1" required style="padding: 0.5rem; border-radius: 4px; border: 1px solid var(--border); background: var(--bg-card); color: var(--text);">
</div>
<button type="submit" class="btn-primary" style="align-self: start; margin-top: 0.5rem;">Apply Network Settings</button>
</form>
<div id="net-warning" class="hidden" style="margin-top: 1rem; color: #f59e0b; font-size: 0.9rem; font-weight: bold;">
WARNING: Changing the static IP will restart host interfaces. You may temporarily lose connection.
</div>
</div>
<div class="admin-card" style="margin-top: 1.5rem;">
<h3>Active Host Network Configuration File</h3>
<p class="card-desc">Raw print of <code>/etc/network/interfaces</code> on the host hypervisor.</p>
<pre class="network-interfaces-pre" style="font-family: monospace; font-size: 0.8rem; background: #0f172a; color: #e2e8f0; border-radius: 6px; padding: 1rem; overflow-x: auto; margin-top: 0.75rem; white-space: pre-wrap;">${escapeHtml(net.interfaces || 'No configuration output fetched')}</pre>
</div>
`;
}
async function loadAdminData() {
try {
const [statusRes, manifestRes, logsRes, monitorRes, modelsRes] = await Promise.all([
api.getAdminStatus(),
api.getPreapprovedModels(),
api.getAuditLogs(),
api.getMonitoringStats(),
api.getModels()
]);
state.adminStatus = statusRes;
state.preapprovedModels = manifestRes;
state.auditLogs = logsRes?.logs || [];
state.activeSessions = monitorRes?.activeSessions || [];
state.models = (modelsRes?.data || []).map(m => ({
id: m.id,
name: m.name || m.id
}));
} catch (err) {
console.error('Failed to load admin panel data:', err);
}
}
// ==================== Initialization ====================
async function loadInitialData() {
+230
View File
@@ -750,3 +750,233 @@ button {
.language-python .number { color: #d19a66; }
.language-python .comment { color: #5c6370; }
.language-python .function { color: #61afef; }
/* ==================== Admin Panel Styles ==================== */
.btn-admin-toggle {
display: flex;
align-items: center;
gap: 8px;
width: 100%;
padding: 10px 12px;
background: transparent;
color: var(--text-muted);
border: 1px solid var(--border);
border-radius: 6px;
font-weight: 500;
cursor: pointer;
transition: all var(--transition);
}
.btn-admin-toggle:hover {
background: var(--bg-hover);
color: var(--text);
border-color: var(--primary);
}
.admin-layout {
display: flex;
width: 100vw;
height: 100vh;
background: var(--bg-primary);
color: var(--text);
overflow: hidden;
}
.admin-sidebar {
width: 280px;
background: var(--bg-secondary);
border-right: 1px solid var(--border);
display: flex;
flex-direction: column;
padding: 20px;
}
.admin-sidebar-header {
margin-bottom: 30px;
}
.admin-sidebar-header h2 {
font-size: 1.5rem;
color: var(--primary);
font-weight: 700;
margin-bottom: 4px;
}
.admin-sidebar-header p {
font-size: 0.8rem;
color: var(--text-muted);
}
.admin-sidebar-menu {
display: flex;
flex-direction: column;
gap: 8px;
flex: 1;
}
.admin-menu-item {
width: 100%;
text-align: left;
padding: 12px 16px;
background: transparent;
border: none;
border-radius: 6px;
color: var(--text-muted);
font-weight: 500;
cursor: pointer;
transition: all var(--transition);
}
.admin-menu-item:hover, .admin-menu-item.active {
background: var(--bg-hover);
color: var(--primary);
}
.admin-menu-item.active {
font-weight: 600;
background: var(--bg-tertiary);
}
.btn-admin-close {
width: 100%;
padding: 12px;
background: var(--bg-tertiary);
color: var(--text);
border: 1px solid var(--border);
border-radius: 6px;
font-weight: 600;
cursor: pointer;
transition: all var(--transition);
}
.btn-admin-close:hover {
background: var(--primary);
color: white;
}
.admin-content {
flex: 1;
display: flex;
flex-direction: column;
overflow-y: auto;
padding: 40px;
}
.admin-header {
margin-bottom: 30px;
border-bottom: 1px solid var(--border);
padding-bottom: 15px;
}
.admin-header h1 {
font-size: 1.8rem;
font-weight: 600;
}
.admin-body {
display: flex;
flex-direction: column;
gap: 24px;
}
.admin-card {
background: var(--bg-secondary);
border: 1px solid var(--border);
border-radius: 8px;
padding: 24px;
display: flex;
flex-direction: column;
gap: 12px;
}
.admin-card h3 {
font-size: 1.2rem;
font-weight: 600;
color: var(--text);
}
.card-desc {
font-size: 0.9rem;
color: var(--text-muted);
margin-bottom: 8px;
}
.admin-table {
width: 100%;
border-collapse: collapse;
text-align: left;
margin-top: 10px;
}
.admin-table th, .admin-table td {
padding: 12px;
border-bottom: 1px solid var(--border);
}
.admin-table th {
font-weight: 600;
color: var(--text-muted);
font-size: 0.9rem;
}
.admin-table td {
font-size: 0.95rem;
}
.badge {
display: inline-block;
padding: 4px 8px;
font-size: 0.75rem;
font-weight: 600;
border-radius: 4px;
}
.badge-success {
background: rgba(16, 185, 129, 0.15);
color: #10b981;
}
.badge-warn {
background: rgba(245, 158, 11, 0.15);
color: #f59e0b;
}
.font-mono {
font-family: monospace;
}
.flex {
display: flex;
}
.flex-col {
flex-direction: column;
}
.gap-2 {
gap: 8px;
}
.gap-4 {
gap: 16px;
}
.align-self-start {
align-self: flex-start;
}
.hidden {
display: none !important;
}
.btn-link {
color: var(--primary);
text-decoration: underline;
cursor: pointer;
font-size: 0.9rem;
}
.btn-link:hover {
color: var(--primary-hover);
}
+396 -17
View File
@@ -13,7 +13,7 @@ import session from 'express-session';
import { createProxyMiddleware } from 'http-proxy-middleware';
import { WebSocketServer, WebSocket } from 'ws';
import { createServer } from 'http';
import { readFileSync, writeFileSync, existsSync, mkdirSync } from 'fs';
import { readFileSync, writeFileSync, existsSync, mkdirSync, readdirSync, statSync, createWriteStream, unlink } from 'fs';
import { join, dirname } from 'path';
import { fileURLToPath } from 'url';
import ldap from 'ldapjs';
@@ -177,12 +177,22 @@ async function authenticateLDAP(username, password) {
// ==================== Auth Routes ====================
// Check auth status
function isUserAdmin(user) {
if (!user) return false;
if (user.username === 'nova') return true;
if (user.groups && Array.isArray(user.groups)) {
return user.groups.some(g => g.toLowerCase().includes('admin') || g.toLowerCase().includes('host_access'));
}
return false;
}
app.get('/api/auth/status', (req, res) => {
if (CONFIG.authDisabled) {
return res.json({ authenticated: true, user: { username: 'dev-user', displayName: 'Dev User' } });
return res.json({ authenticated: true, user: { username: 'dev-user', displayName: 'Dev User', isAdmin: true } });
}
if (req.session.user) {
req.session.user.isAdmin = isUserAdmin(req.session.user);
return res.json({ authenticated: true, user: req.session.user });
}
@@ -199,7 +209,7 @@ app.post('/api/auth/login', async (req, res) => {
// Development bypass
if (CONFIG.authDisabled) {
req.session.user = { username, displayName: username };
req.session.user = { username, displayName: username, isAdmin: true };
return res.json({ success: true, user: req.session.user });
}
@@ -207,6 +217,7 @@ app.post('/api/auth/login', async (req, res) => {
if (CONFIG.ldap.enabled) {
try {
const user = await authenticateLDAP(username, password);
user.isAdmin = isUserAdmin(user);
req.session.user = user;
res.json({ success: true, user });
} catch (err) {
@@ -376,7 +387,6 @@ app.use('/v1', requireAuth, createProxyMiddleware({
// ==================== File Upload ====================
import { createWriteStream } from 'fs';
import { tmpdir } from 'os';
const uploads = new Map();
@@ -436,14 +446,383 @@ app.get('/api/models', requireAuth, async (req, res) => {
} catch (err) {
res.json({
data: [
{ id: 'main', name: 'Main', owned_by: 'openclaw' },
{ id: 'huihui', name: 'HuiHui MoE', owned_by: 'openclaw' },
{ id: 'gpt-oss', name: 'GPT-OSS 120B', owned_by: 'openclaw' }
{ id: 'SmolLM2-135M-Instruct-Q8_0.gguf', name: 'SmolLM2 135M (Pre-approved)', owned_by: 'sovereign' }
]
});
}
});
// ==================== Sovereign Branding & Admin Panel Backend ====================
const activeSessions = new Map();
const SETTINGS_PATH = join(CONFIG.dataDir, 'settings.json');
let systemSettings = {
dailyTokenQuota: 50000,
schedule: {
enabled: false,
startHour: 9,
endHour: 17
}
};
if (existsSync(SETTINGS_PATH)) {
try {
systemSettings = JSON.parse(readFileSync(SETTINGS_PATH, 'utf-8'));
} catch (err) {
console.error('Failed to parse settings.json:', err.message);
}
}
function saveSettings() {
try {
writeFileSync(SETTINGS_PATH, JSON.stringify(systemSettings, null, 2));
} catch (err) {
console.error('Failed to save settings.json:', err.message);
}
}
function requireAdmin(req, res, next) {
if (CONFIG.authDisabled) return next();
if (!req.session.user) {
return res.status(401).json({ error: 'Authentication required' });
}
if (!isUserAdmin(req.session.user)) {
return res.status(403).json({ error: 'Forbidden: Admin access required' });
}
next();
}
// Intercept chat completions requests for token quota, active schedules, and compliance audit logging
app.post('/v1/chat/completions', requireAuth, (req, res, next) => {
const user = req.session.user?.username || 'unknown';
const model = req.body?.model || 'unknown';
const stream = req.body?.stream || false;
const inputCharCount = req.body?.messages?.reduce((acc, m) => acc + (m.content?.length || 0), 0) || 0;
const approximatePromptTokens = Math.ceil(inputCharCount / 4);
// 1. Schedule Enforcement Check
if (systemSettings.schedule?.enabled) {
const currentHour = new Date().getHours();
if (currentHour < systemSettings.schedule.startHour || currentHour >= systemSettings.schedule.endHour) {
return res.status(403).json({ error: `Inference offline. Service schedule is ${systemSettings.schedule.startHour}:00 - ${systemSettings.schedule.endHour}:00.` });
}
}
// 2. Token Quota Enforcement Check
const userStats = activeSessions.get(user) || { queriesCount: 0, totalPromptTokensEstimate: 0 };
if (userStats.totalPromptTokensEstimate >= systemSettings.dailyTokenQuota) {
return res.status(429).json({ error: `Daily token quota of ${systemSettings.dailyTokenQuota} tokens exceeded.` });
}
// 3. Write metadata to cryptographic-audit-logger staged folder /tank/audit/
const auditRecord = {
timestamp: new Date().toISOString(),
user,
action: 'chat_completion',
model,
stream,
approximatePromptTokens,
status: 'initiated'
};
try {
if (!existsSync('/tank/audit')) {
mkdirSync('/tank/audit', { recursive: true });
}
writeFileSync('/tank/audit/chat-audit.log', JSON.stringify(auditRecord) + '\n', { flag: 'a' });
} catch (err) {
console.error('[AUDIT] Failed to write query audit record:', err.message);
}
// 4. Update stats cache
userStats.queriesCount++;
userStats.totalPromptTokensEstimate += approximatePromptTokens;
userStats.lastActive = new Date().toISOString();
userStats.lastModel = model;
activeSessions.set(user, userStats);
next();
});
// Admin status (including current system network files)
app.get('/api/admin/status', requireAdmin, (req, res) => {
let networkInfo = {};
try {
if (existsSync('/etc/network/interfaces')) {
networkInfo.interfaces = readFileSync('/etc/network/interfaces', 'utf-8');
}
if (existsSync('/etc/theta42/network.json')) {
networkInfo.configured = JSON.parse(readFileSync('/etc/theta42/network.json', 'utf-8'));
}
} catch (err) {
networkInfo.error = err.message;
}
res.json({
activeModel: CONFIG.selectedModel || 'SmolLM2-135M-Instruct-Q8_0.gguf',
network: networkInfo,
settings: systemSettings,
environment: CONFIG.environment
});
});
// Network configuration changes
app.post('/api/admin/network', requireAdmin, (req, res) => {
const networkConfig = req.body;
try {
if (!existsSync('/etc/theta42')) {
mkdirSync('/etc/theta42', { recursive: true });
}
writeFileSync('/etc/theta42/network.json', JSON.stringify(networkConfig, null, 2));
const auditRecord = {
timestamp: new Date().toISOString(),
user: req.session.user?.username || 'admin',
action: 'configure_network',
details: networkConfig
};
writeFileSync('/tank/audit/chat-audit.log', JSON.stringify(auditRecord) + '\n', { flag: 'a' });
res.json({ success: true, message: 'Network configuration saved successfully.' });
} catch (err) {
res.status(500).json({ error: 'Failed to write network config: ' + err.message });
}
});
// Get log file list generated by host's cryptographic-audit-logger
app.get('/api/admin/audit-logs', requireAdmin, (req, res) => {
try {
const files = [];
if (existsSync('/tank/audit')) {
const list = readdirSync('/tank/audit');
for (const file of list) {
const stat = statSync(join('/tank/audit', file));
if (file.endsWith('.tar.gz') || file.endsWith('.sig') || file.endsWith('.log')) {
files.push({
name: file,
size: stat.size,
mtime: stat.mtime
});
}
}
}
res.json({ logs: files });
} catch (err) {
res.status(500).json({ error: 'Failed to read audit logs: ' + err.message });
}
});
// Download log file
app.get('/api/admin/audit-logs/:filename', requireAdmin, (req, res) => {
const filename = req.params.filename;
if (filename.includes('..') || filename.includes('/') || filename.includes('\\')) {
return res.status(400).json({ error: 'Invalid filename' });
}
const path = join('/tank/audit', filename);
if (!existsSync(path)) {
return res.status(404).json({ error: 'File not found' });
}
res.download(path);
});
// Pre-approved models list
app.get('/api/admin/preapproved', requireAdmin, (req, res) => {
try {
let manifest = { models: [] };
if (existsSync('/etc/theta42/models-manifest.json')) {
manifest = JSON.parse(readFileSync('/etc/theta42/models-manifest.json', 'utf-8'));
}
res.json(manifest);
} catch (err) {
res.status(500).json({ error: 'Failed to read models manifest: ' + err.message });
}
});
// Download pre-approved model
app.post('/api/admin/models/download', requireAdmin, async (req, res) => {
const { filename, url, sha256 } = req.body;
if (!filename || !url || !sha256) {
return res.status(400).json({ error: 'Missing parameters: filename, url, and sha256 are required' });
}
res.json({ success: true, message: `Download of ${filename} started in background.` });
(async () => {
const stagingPath = join('/tank/staging', filename);
try {
if (!existsSync('/tank/staging')) {
mkdirSync('/tank/staging', { recursive: true });
}
console.log(`[DOWNLOAD] Starting download of pre-approved model ${filename} from ${url}...`);
const httpModule = url.startsWith('https') ? await import('https') : await import('http');
const fileStream = createWriteStream(stagingPath);
httpModule.get(url, (response) => {
if (response.statusCode === 302 || response.statusCode === 301) {
const redirectUrl = response.headers.location;
console.log(`[DOWNLOAD] Following redirect to: ${redirectUrl}`);
httpModule.get(redirectUrl, (redirectResponse) => {
redirectResponse.pipe(fileStream);
fileStream.on('finish', () => {
fileStream.close();
finalizeDownload(filename, sha256);
});
});
} else {
response.pipe(fileStream);
fileStream.on('finish', () => {
fileStream.close();
finalizeDownload(filename, sha256);
});
}
}).on('error', (err) => {
unlink(stagingPath, () => {});
console.error('[DOWNLOAD] Error downloading file:', err.message);
});
} catch (err) {
console.error('[DOWNLOAD] Background task failed:', err.message);
}
})();
});
function finalizeDownload(filename, sha256) {
console.log(`[DOWNLOAD] Completed download of ${filename} to staging.`);
try {
let manifest = { models: [] };
if (existsSync('/etc/theta42/models-manifest.json')) {
manifest = JSON.parse(readFileSync('/etc/theta42/models-manifest.json', 'utf-8'));
}
const exists = manifest.models.some(m => m.filename === filename);
if (!exists) {
manifest.models.push({ filename, sha256 });
writeFileSync('/etc/theta42/models-manifest.json', JSON.stringify(manifest, null, 2));
console.log(`[DOWNLOAD] Registered ${filename} in models-manifest.json.`);
}
} catch (manifestErr) {
console.error('[DOWNLOAD] Failed to update models manifest:', manifestErr.message);
}
}
// Upload custom model file to staging
app.post('/api/admin/models/upload', requireAdmin, (req, res) => {
const filename = req.headers['x-filename'];
const sha256 = req.headers['x-sha256'];
if (!filename) {
return res.status(400).json({ error: 'Missing x-filename header' });
}
if (!existsSync('/tank/staging')) {
mkdirSync('/tank/staging', { recursive: true });
}
const stagingPath = join('/tank/staging', filename);
console.log(`[UPLOAD] Uploading custom model ${filename} to staging...`);
const fileStream = createWriteStream(stagingPath);
req.pipe(fileStream);
fileStream.on('finish', () => {
fileStream.close();
console.log(`[UPLOAD] Completed upload of custom model ${filename} to staging.`);
try {
let manifest = { models: [] };
if (existsSync('/etc/theta42/models-manifest.json')) {
manifest = JSON.parse(readFileSync('/etc/theta42/models-manifest.json', 'utf-8'));
}
const exists = manifest.models.some(m => m.filename === filename);
if (!exists) {
manifest.models.push({
filename,
sha256: sha256 || "custom-hash-unverified"
});
writeFileSync('/etc/theta42/models-manifest.json', JSON.stringify(manifest, null, 2));
console.log(`[UPLOAD] Registered ${filename} in models-manifest.json.`);
}
} catch (manifestErr) {
console.error('[UPLOAD] Failed to update models manifest:', manifestErr.message);
}
res.json({ success: true, message: `Custom model ${filename} uploaded and staged successfully.` });
});
fileStream.on('error', (err) => {
unlink(stagingPath, () => {});
res.status(500).json({ error: 'Failed to write upload stream: ' + err.message });
});
});
// Update global configuration settings (quotas, schedules)
app.post('/api/admin/settings', requireAdmin, (req, res) => {
const { dailyTokenQuota, schedule } = req.body;
if (dailyTokenQuota !== undefined) systemSettings.dailyTokenQuota = parseInt(dailyTokenQuota);
if (schedule !== undefined) systemSettings.schedule = schedule;
saveSettings();
const auditRecord = {
timestamp: new Date().toISOString(),
user: req.session.user?.username || 'admin',
action: 'configure_settings',
details: systemSettings
};
writeFileSync('/tank/audit/chat-audit.log', JSON.stringify(auditRecord) + '\n', { flag: 'a' });
res.json({ success: true, settings: systemSettings });
});
// Set active model and reload AI-Core
app.post('/api/admin/models/active', requireAdmin, async (req, res) => {
const { model } = req.body;
if (!model) {
return res.status(400).json({ error: 'Missing model parameter' });
}
try {
console.log(`[RELOAD] Triggering AI-Core reload to load model: ${model}...`);
const reloadResponse = await fetch(`http://192.168.100.201:8000/v1/models/reload`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ model })
});
if (!reloadResponse.ok) {
const errorText = await reloadResponse.text();
throw new Error(`AI-Core reload failed: ${errorText}`);
}
CONFIG.selectedModel = model;
const auditRecord = {
timestamp: new Date().toISOString(),
user: req.session.user?.username || 'admin',
action: 'switch_model',
model
};
writeFileSync('/tank/audit/chat-audit.log', JSON.stringify(auditRecord) + '\n', { flag: 'a' });
res.json({ success: true, message: `Model switched to ${model} and reloaded successfully.` });
} catch (err) {
res.status(500).json({ error: 'Failed to trigger model reload: ' + err.message });
}
});
// User monitoring stats
app.get('/api/admin/monitoring', requireAdmin, (req, res) => {
const list = [];
activeSessions.forEach((stats, user) => {
list.push({
user,
queriesCount: stats.queriesCount,
totalPromptTokensEstimate: stats.totalPromptTokensEstimate,
lastActive: stats.lastActive,
lastModel: stats.lastModel
});
});
res.json({ activeSessions: list });
});
// ==================== Static Files ====================
// Serve frontend in production
@@ -509,15 +888,15 @@ wss.on('connection', (ws, req) => {
server.listen(CONFIG.port, () => {
console.log(`
╔═══════════════════════════════════════════════════════════╗
║ OpenClaw WebUI Server ║
╠═══════════════════════════════════════════════════════════╣
Environment: ${(conf.environment || 'development').padEnd(43)}
Port: ${CONFIG.port.toString().padEnd(43)}
Gateway: ${CONFIG.gatewayUrl.padEnd(43)}
LDAP: ${(CONFIG.ldap.enabled ? 'Enabled' : 'Disabled').padEnd(43)}
Auth: ${(CONFIG.authDisabled ? 'Disabled (dev mode)' : 'Enabled').padEnd(43)}
Data: ${CONFIG.dataDir.padEnd(43)}
╚═══════════════════════════════════════════════════════════╝
+---------------------------------------------------------+
| Sovereign Chat Server | Theta42 |
+---------------------------------------------------------+
| Environment: ${(conf.environment || 'production').padEnd(41)} |
| Port: ${CONFIG.port.toString().padEnd(41)} |
| Gateway: ${CONFIG.gatewayUrl.padEnd(41)} |
| LDAP: ${(CONFIG.ldap.enabled ? 'Enabled' : 'Disabled').padEnd(41)} |
| Auth: ${(CONFIG.authDisabled ? 'Disabled (dev mode)' : 'Enabled').padEnd(41)} |
| Data: ${CONFIG.dataDir.padEnd(41)} |
+---------------------------------------------------------+
`);
});