1093 lines
50 KiB
HTML
1093 lines
50 KiB
HTML
<!DOCTYPE html>
|
|
<html lang="en" data-bs-theme="dark">
|
|
<head>
|
|
<meta charset="UTF-8">
|
|
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
|
<title>Jakach Logging</title>
|
|
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/css/bootstrap.min.css" rel="stylesheet">
|
|
<link href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.11.3/font/bootstrap-icons.min.css" rel="stylesheet">
|
|
<style>
|
|
body { font-size: .875rem; }
|
|
.sidebar { position: fixed; top: 0; left: 0; bottom: 0; width: 220px; padding-top: 56px; z-index: 100; border-right: 1px solid var(--bs-border-color); }
|
|
.sidebar .nav-link { color: var(--bs-secondary-color); padding: .5rem 1rem; border-radius: 0; }
|
|
.sidebar .nav-link:hover, .sidebar .nav-link.active { color: var(--bs-body-color); background: var(--bs-tertiary-bg); }
|
|
.sidebar .nav-link i { margin-right: .5rem; }
|
|
.main { margin-left: 220px; padding-top: 56px; }
|
|
.navbar-brand i { margin-right: .5rem; }
|
|
.stat-card { border-left: 3px solid var(--bs-border-color); }
|
|
.stat-card.critical { border-left-color: var(--bs-danger); }
|
|
.stat-card.warning { border-left-color: var(--bs-warning); }
|
|
.stat-card.info { border-left-color: var(--bs-info); }
|
|
.card-header .btn-sm { font-size: .75rem; }
|
|
.page-section { display: none; }
|
|
.page-section.active { display: block; }
|
|
.badge-severity { text-transform: uppercase; font-size: .65rem; letter-spacing: .5px; }
|
|
.alert-row { cursor: pointer; }
|
|
.alert-row:hover { background: var(--bs-tertiary-bg); }
|
|
.log-line { font-family: 'SFMono-Regular', Consolas, 'Liberation Mono', Menlo, monospace; font-size: .8rem; max-width: 500px; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
|
|
.empty-state { text-align: center; padding: 4rem 1rem; color: var(--bs-secondary-color); }
|
|
.empty-state i { font-size: 3rem; margin-bottom: 1rem; }
|
|
.toast-container { z-index: 1060; }
|
|
#detailModal .modal-body { max-height: 70vh; overflow-y: auto; }
|
|
pre.raw-line { background: var(--bs-tertiary-bg); padding: .75rem; border-radius: .375rem; font-size: .8rem; white-space: pre-wrap; word-break: break-all; max-height: 200px; overflow-y: auto; }
|
|
.login-container { display: flex; align-items: center; justify-content: center; min-height: 100vh; }
|
|
.login-card { max-width: 420px; width: 100%; }
|
|
.login-container .navbar-brand { font-size: 1.5rem; }
|
|
.login-footer { position: fixed; bottom: 1rem; left: 0; right: 0; text-align: center; font-size: .8rem; color: var(--bs-secondary-color); }
|
|
@media (max-width: 768px) { .sidebar { display: none; } .main { margin-left: 0; } }
|
|
</style>
|
|
</head>
|
|
<body>
|
|
|
|
<div id="appLogin" class="login-container">
|
|
<div class="login-card">
|
|
<div class="text-center mb-4">
|
|
<h3 class="navbar-brand"><i class="bi bi-terminal-plus"></i> Jakach Logging</h3>
|
|
<p class="text-secondary">Log analysis & alerting system</p>
|
|
</div>
|
|
<div class="card">
|
|
<div class="card-body p-4 text-center">
|
|
<i class="bi bi-shield-lock" style="font-size:3rem;display:block;margin-bottom:1rem"></i>
|
|
<h5>Sign in required</h5>
|
|
<div id="authErrorBox" class="alert alert-danger d-none" role="alert"></div>
|
|
<p class="text-secondary mb-4">Authenticate with your Jakach account to access the system.</p>
|
|
<a id="loginBtn" class="btn btn-primary btn-lg w-100" href="#">
|
|
<i class="bi bi-box-arrow-in-right me-2"></i>Log in using Jakach Login
|
|
</a>
|
|
</div>
|
|
</div>
|
|
<div class="login-footer">Powered by <a href="https://auth.jakach.ch" class="text-secondary">Jakach Auth</a></div>
|
|
</div>
|
|
</div>
|
|
|
|
<div id="appMain" style="display:none">
|
|
<nav class="navbar navbar-expand navbar-dark bg-dark fixed-top">
|
|
<div class="container-fluid">
|
|
<a class="navbar-brand" href="#"><i class="bi bi-terminal-plus"></i>Jakach Logging</a>
|
|
<div class="d-flex align-items-center gap-2 ms-auto">
|
|
<span class="badge bg-danger d-none" id="criticalBadge">0</span>
|
|
<span class="badge bg-warning text-dark d-none" id="warningBadge">0</span>
|
|
<span class="text-secondary small me-2 d-none d-md-inline" id="userDisplay"></span>
|
|
<button class="btn btn-outline-secondary btn-sm" id="refreshBtn" title="Refresh"><i class="bi bi-arrow-clockwise"></i></button>
|
|
<div class="form-check form-switch ms-2">
|
|
<input class="form-check-input" type="checkbox" id="autoRefresh" checked>
|
|
<label class="form-check-label" for="autoRefresh" style="font-size:.8rem">Auto</label>
|
|
</div>
|
|
<button class="btn btn-outline-danger btn-sm" id="logoutBtn" title="Logout"><i class="bi bi-box-arrow-right"></i></button>
|
|
</div>
|
|
</div>
|
|
</nav>
|
|
|
|
<div class="sidebar">
|
|
<ul class="nav flex-column">
|
|
<li class="nav-item"><a class="nav-link active" href="#" data-page="dashboard"><i class="bi bi-speedometer2"></i>Dashboard</a></li>
|
|
<li class="nav-item"><a class="nav-link" href="#" data-page="alerts"><i class="bi bi-bell"></i>Alerts</a></li>
|
|
<li class="nav-item"><a class="nav-link" href="#" data-page="logs"><i class="bi bi-search"></i>Logs</a></li>
|
|
<li class="nav-item"><a class="nav-link" href="#" data-page="sources"><i class="bi bi-database"></i>Sources</a></li>
|
|
<li class="nav-item"><a class="nav-link" href="#" data-page="rules"><i class="bi bi-sliders"></i>Rules</a></li>
|
|
<li class="nav-item"><a class="nav-link" href="#" data-page="settings"><i class="bi bi-gear"></i>Settings</a></li>
|
|
</ul>
|
|
</div>
|
|
|
|
<div class="main">
|
|
<div class="container-fluid p-3">
|
|
|
|
<!-- DASHBOARD -->
|
|
<div class="page-section active" id="page-dashboard">
|
|
<div class="d-flex justify-content-between align-items-center mb-3">
|
|
<h5 class="mb-0"><i class="bi bi-speedometer2 me-2"></i>Dashboard</h5>
|
|
<small class="text-secondary" id="lastUpdated"></small>
|
|
</div>
|
|
<div class="row g-3 mb-3" id="statCards"></div>
|
|
<div class="row g-3">
|
|
<div class="col-lg-8">
|
|
<div class="card h-100">
|
|
<div class="card-header d-flex justify-content-between align-items-center">
|
|
<span><i class="bi bi-bell me-1"></i>Recent Critical Alerts</span>
|
|
<a href="#" data-page="alerts" class="btn btn-outline-secondary btn-sm">View all</a>
|
|
</div>
|
|
<div class="card-body p-0">
|
|
<div class="table-responsive"><table class="table table-sm table-borderless mb-0"><tbody id="dashboardAlerts"><tr><td colspan="4" class="empty-state"><i class="bi bi-check-circle"></i><p class="mb-0">No alerts yet</p></td></tr></tbody></table></div>
|
|
</div>
|
|
</div>
|
|
</div>
|
|
<div class="col-lg-4">
|
|
<div class="card h-100">
|
|
<div class="card-header"><i class="bi bi-pie-chart me-1"></i>Alert Distribution</div>
|
|
<div class="card-body" id="chartContainer"><div class="empty-state"><i class="bi bi-bar-chart"></i><p class="mb-0">No data</p></div></div>
|
|
</div>
|
|
</div>
|
|
</div>
|
|
</div>
|
|
|
|
<!-- ALERTS -->
|
|
<div class="page-section" id="page-alerts">
|
|
<div class="d-flex justify-content-between align-items-center mb-3">
|
|
<h5 class="mb-0"><i class="bi bi-bell me-2"></i>Alerts</h5>
|
|
<div class="d-flex gap-2">
|
|
<select class="form-select form-select-sm" id="filterSeverity" style="width:auto">
|
|
<option value="">All Severities</option>
|
|
<option value="emergency">Emergency</option>
|
|
<option value="critical_high">Critical High</option>
|
|
<option value="critical">Critical</option>
|
|
<option value="critical_low">Critical Low</option>
|
|
<option value="error">Error</option>
|
|
<option value="warning_high">Warning High</option>
|
|
<option value="warning">Warning</option>
|
|
<option value="warning_low">Warning Low</option>
|
|
<option value="notice">Notice</option>
|
|
<option value="info">Info</option>
|
|
<option value="debug">Debug</option>
|
|
</select>
|
|
<select class="form-select form-select-sm" id="filterStatus" style="width:auto">
|
|
<option value="">All Statuses</option>
|
|
<option value="open">Open</option>
|
|
<option value="acknowledged">Acknowledged</option>
|
|
<option value="resolved">Resolved</option>
|
|
</select>
|
|
<div class="input-group input-group-sm" style="width:220px">
|
|
<input type="text" class="form-control" id="searchInput" placeholder="Search logs..." maxlength="100">
|
|
<button class="btn btn-outline-secondary" id="searchBtn"><i class="bi bi-search"></i></button>
|
|
</div>
|
|
<button class="btn btn-outline-secondary btn-sm" id="refreshAlertsBtn"><i class="bi bi-arrow-clockwise"></i></button>
|
|
</div>
|
|
</div>
|
|
<div class="card">
|
|
<div class="card-body p-0">
|
|
<div class="table-responsive">
|
|
<table class="table table-hover table-sm mb-0" id="alertsTable">
|
|
<thead class="table-dark"><tr>
|
|
<th style="width:60px;cursor:pointer" onclick="sortAlerts('id')">ID <i class="bi bi-arrow-down-up" style="font-size:.7rem"></i></th>
|
|
<th style="width:90px;cursor:pointer" onclick="sortAlerts('severity')">Severity <i class="bi bi-arrow-down-up" style="font-size:.7rem"></i></th>
|
|
<th style="width:100px;cursor:pointer" onclick="sortAlerts('status')">Status <i class="bi bi-arrow-down-up" style="font-size:.7rem"></i></th>
|
|
<th>Message</th>
|
|
<th style="cursor:pointer" onclick="sortAlerts('source_name')">Source <i class="bi bi-arrow-down-up" style="font-size:.7rem"></i></th>
|
|
<th style="width:170px;cursor:pointer" onclick="sortAlerts('created_at')">Created <i class="bi bi-arrow-down-up" style="font-size:.7rem"></i></th>
|
|
<th style="width:100px"></th>
|
|
</tr></thead>
|
|
<tbody id="alertsBody"><tr><td colspan="7" class="empty-state"><i class="bi bi-inbox"></i><p class="mb-0">No alerts match those filters</p></td></tr></tbody>
|
|
</table>
|
|
</div>
|
|
</div>
|
|
<div class="card-footer d-flex justify-content-between align-items-center py-2">
|
|
<small class="text-secondary" id="alertsCount">0 alerts</small>
|
|
</div>
|
|
</div>
|
|
</div>
|
|
|
|
<!-- LOGS -->
|
|
<div class="page-section" id="page-logs">
|
|
<div class="d-flex justify-content-between align-items-center mb-3">
|
|
<h5 class="mb-0"><i class="bi bi-search me-2"></i>Log Search</h5>
|
|
<small class="text-secondary" id="logsCount"></small>
|
|
</div>
|
|
<div class="card mb-3">
|
|
<div class="card-body py-3">
|
|
<div class="input-group">
|
|
<input type="text" class="form-control" id="logSearchInput" placeholder="Search all log lines..." maxlength="200">
|
|
<button class="btn btn-primary" id="logSearchBtn"><i class="bi bi-search me-1"></i>Search</button>
|
|
</div>
|
|
<small class="text-secondary mt-1 d-block">Use <code>*</code> as wildcard. <code>bla</code> matches "blabla". <code>*</code> shows all logs. Separate terms match all (AND).</small>
|
|
</div>
|
|
</div>
|
|
<div class="card">
|
|
<div class="card-body p-0">
|
|
<div class="table-responsive">
|
|
<table class="table table-sm table-hover mb-0">
|
|
<thead class="table-dark"><tr>
|
|
<th style="width:60px">ID</th>
|
|
<th style="width:170px">Time</th>
|
|
<th>Line</th>
|
|
<th>Source</th>
|
|
</tr></thead>
|
|
<tbody id="logsBody"><tr><td colspan="4" class="empty-state"><i class="bi bi-search"></i><p class="mb-0">Enter a search query above</p></td></tr></tbody>
|
|
</table>
|
|
</div>
|
|
</div>
|
|
</div>
|
|
</div>
|
|
|
|
<!-- SOURCES -->
|
|
<div class="page-section" id="page-sources">
|
|
<div class="d-flex justify-content-between align-items-center mb-3">
|
|
<h5 class="mb-0"><i class="bi bi-database me-2"></i>Log Sources</h5>
|
|
<button class="btn btn-primary btn-sm" onclick="resetSourceForm();setTimeout(()=>bootstrap.Modal.getOrCreateInstance(document.getElementById('sourceModal')).show(),50)"><i class="bi bi-plus-lg"></i> Add Source</button>
|
|
</div>
|
|
<div class="card">
|
|
<div class="card-body p-0">
|
|
<div class="table-responsive">
|
|
<table class="table table-sm mb-0">
|
|
<thead class="table-dark"><tr>
|
|
<th>Name</th><th>Type</th><th>Address</th><th>Labels</th><th>Status</th><th style="width:100px"></th>
|
|
</tr></thead>
|
|
<tbody id="sourcesBody"><tr><td colspan="6" class="empty-state"><i class="bi bi-database"></i><p class="mb-0">No sources configured</p></td></tr></tbody>
|
|
</table>
|
|
</div>
|
|
</div>
|
|
</div>
|
|
</div>
|
|
|
|
<!-- RULES -->
|
|
<div class="page-section" id="page-rules">
|
|
<div class="d-flex justify-content-between align-items-center mb-3">
|
|
<h5 class="mb-0"><i class="bi bi-sliders me-2"></i>Alert Rules</h5>
|
|
<button class="btn btn-primary btn-sm" onclick="resetRuleForm();setTimeout(()=>bootstrap.Modal.getOrCreateInstance(document.getElementById('ruleModal')).show(),50)"><i class="bi bi-plus-lg"></i> Add Rule</button>
|
|
</div>
|
|
<div class="card">
|
|
<div class="card-body p-0">
|
|
<div class="table-responsive">
|
|
<table class="table table-sm mb-0">
|
|
<thead class="table-dark"><tr>
|
|
<th>Name</th><th>Pattern</th><th>Severity</th><th>Rate Limit</th><th>Status</th><th style="width:60px"></th>
|
|
</tr></thead>
|
|
<tbody id="rulesBody"><tr><td colspan="6" class="empty-state"><i class="bi bi-sliders"></i><p class="mb-0">No rules configured</p></td></tr></tbody>
|
|
</table>
|
|
</div>
|
|
</div>
|
|
</div>
|
|
</div>
|
|
|
|
<!-- SETTINGS -->
|
|
<div class="page-section" id="page-settings">
|
|
<div class="d-flex justify-content-between align-items-center mb-3">
|
|
<h5 class="mb-0"><i class="bi bi-gear me-2"></i>Settings</h5>
|
|
</div>
|
|
<div class="row g-3">
|
|
<div class="col-md-6">
|
|
<div class="card mb-3">
|
|
<div class="card-header"><i class="bi bi-info-circle me-1"></i>System Info</div>
|
|
<div class="card-body">
|
|
<dl class="row mb-0">
|
|
<dt class="col-sm-4">Health</dt><dd class="col-sm-8"><span id="sysHealth" class="badge bg-secondary">checking...</span></dd>
|
|
<dt class="col-sm-4">Auth Server</dt><dd class="col-sm-8"><a href="https://auth.jakach.ch" target="_blank">auth.jakach.ch</a></dd>
|
|
<dt class="col-sm-4">Logged in as</dt><dd class="col-sm-8" id="settingsUser">—</dd>
|
|
<dt class="col-sm-4">DB Path</dt><dd class="col-sm-8"><code>/app/data/logging.db</code></dd>
|
|
<dt class="col-sm-4">Worker</dt><dd class="col-sm-8"><code>php bin/consume</code></dd>
|
|
</dl>
|
|
</div>
|
|
</div>
|
|
<div class="card">
|
|
<div class="card-header"><i class="bi bi-book me-1"></i>Quick Reference</div>
|
|
<div class="card-body">
|
|
<p class="mb-1"><strong>File sources</strong> — path to a log file on the worker container</p>
|
|
<p class="mb-1"><strong>TCP/UDP sources</strong> — <code>tcp://0.0.0.0:9514</code></p>
|
|
<p class="mb-0"><strong>Rules</strong> — PHP regex patterns, e.g. <code>/error/i</code></p>
|
|
</div>
|
|
</div>
|
|
</div>
|
|
<div class="col-md-6">
|
|
<div class="card mb-3">
|
|
<div class="card-header"><i class="bi bi-shield-check me-1"></i>Security</div>
|
|
<div class="card-body">
|
|
<div class="mb-3">
|
|
<label class="form-label">Allowed User Tokens</label>
|
|
<p class="small text-secondary">Only these Jakach user tokens can access this system. Leave empty to allow any authenticated Jakach user.</p>
|
|
<textarea class="form-control font-monospace" id="allowedTokensInput" rows="4" placeholder="One user_token per line"></textarea>
|
|
</div>
|
|
<button class="btn btn-primary btn-sm" id="saveTokensBtn"><i class="bi bi-floppy"></i> Save</button>
|
|
<small id="tokenSaveStatus" class="ms-2"></small>
|
|
</div>
|
|
</div>
|
|
<div class="card mb-3">
|
|
<div class="card-header"><i class="bi bi-telegram me-1"></i>Telegram Notifications</div>
|
|
<div class="card-body">
|
|
<p class="small text-secondary">Send alerts to a Telegram chat via a bot.</p>
|
|
<div class="mb-2">
|
|
<label class="form-label">Bot Token</label>
|
|
<input type="text" class="form-control" id="telegramBotToken" placeholder="123456:ABC-DEF1234ghIkl-zyx57W2v1u123ew11">
|
|
</div>
|
|
<div class="mb-2">
|
|
<label class="form-label">Chat ID</label>
|
|
<input type="text" class="form-control" id="telegramChatId" placeholder="-1001234567890">
|
|
</div>
|
|
<button class="btn btn-primary btn-sm" id="saveTelegramBtn"><i class="bi bi-floppy"></i> Save</button>
|
|
<small id="telegramSaveStatus" class="ms-2"></small>
|
|
<button class="btn btn-outline-secondary btn-sm ms-2" id="testTelegramBtn"><i class="bi bi-send"></i> Test</button>
|
|
</div>
|
|
</div>
|
|
<div class="card">
|
|
<div class="card-header"><i class="bi bi-info-circle me-1"></i>How to get your user token</div>
|
|
<div class="card-body small">
|
|
<ol class="mb-0 ps-3">
|
|
<li>Log in at <a href="https://auth.jakach.ch" target="_blank">auth.jakach.ch</a></li>
|
|
<li>Your <code>user_token</code> is shown in your profile</li>
|
|
<li>Paste it above to grant access</li>
|
|
</ol>
|
|
</div>
|
|
</div>
|
|
</div>
|
|
</div>
|
|
</div>
|
|
|
|
</div>
|
|
</div>
|
|
</div>
|
|
|
|
<!-- Alert Detail Modal -->
|
|
<div class="modal fade" id="detailModal" tabindex="-1">
|
|
<div class="modal-dialog modal-lg modal-dialog-scrollable">
|
|
<div class="modal-content">
|
|
<div class="modal-header"><h5 class="modal-title">Alert Detail</h5><button type="button" class="btn-close" data-bs-dismiss="modal"></button></div>
|
|
<div class="modal-body" id="detailBody"></div>
|
|
<div class="modal-footer d-flex justify-content-between">
|
|
<div>
|
|
<select class="form-select form-select-sm" id="statusSelect">
|
|
<option value="open">Open</option>
|
|
<option value="acknowledged">Acknowledge</option>
|
|
<option value="resolved">Resolved</option>
|
|
</select>
|
|
</div>
|
|
<div>
|
|
<button class="btn btn-primary btn-sm" id="updateStatusBtn"><i class="bi bi-check2"></i> Update</button>
|
|
<button class="btn btn-secondary btn-sm" data-bs-dismiss="modal">Close</button>
|
|
</div>
|
|
</div>
|
|
</div></div></div>
|
|
|
|
<!-- Source Modal -->
|
|
<div class="modal fade" id="sourceModal" tabindex="-1">
|
|
<div class="modal-dialog">
|
|
<div class="modal-content">
|
|
<form id="sourceForm">
|
|
<div class="modal-header"><h5 class="modal-title" id="sourceModalLabel">Add Source</h5><button type="button" class="btn-close" data-bs-dismiss="modal"></button></div>
|
|
<div class="modal-body">
|
|
<div class="mb-3">
|
|
<label class="form-label">Name</label>
|
|
<input type="hidden" name="id" id="sourceFormId" value="">
|
|
<div class="mb-3">
|
|
<label class="form-label">Name</label>
|
|
<input type="text" class="form-control" name="name" id="sourceFormName" required placeholder="e.g. nginx-access">
|
|
</div>
|
|
<div class="mb-3">
|
|
<label class="form-label">Type</label>
|
|
<select class="form-select" name="type" id="sourceFormType" required>
|
|
<option value="file">File</option>
|
|
<option value="tcp">TCP</option>
|
|
<option value="udp">UDP</option>
|
|
<option value="http">HTTP</option>
|
|
</select>
|
|
</div>
|
|
<div class="mb-3">
|
|
<label class="form-label">Address</label>
|
|
<input type="text" class="form-control" name="address" id="sourceFormAddress" required placeholder="/var/log/nginx/access.log or tcp://0.0.0.0:9514">
|
|
</div>
|
|
<div class="mb-3">
|
|
<label class="form-label">Labels <small class="text-secondary">(JSON)</small></label>
|
|
<input type="text" class="form-control" name="labels" id="sourceFormLabels" placeholder='{"env":"prod"}'>
|
|
</div>
|
|
<div class="form-check mb-3">
|
|
<input class="form-check-input" type="checkbox" name="active" id="sourceFormActive" checked>
|
|
<label class="form-check-label" for="sourceFormActive">Active</label>
|
|
</div>
|
|
</div>
|
|
<div class="modal-footer">
|
|
<button type="submit" class="btn btn-primary" id="sourceFormSubmit">Add Source</button>
|
|
<button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Cancel</button>
|
|
</div>
|
|
</form>
|
|
</div></div></div>
|
|
|
|
<!-- Rule Modal -->
|
|
<div class="modal fade" id="ruleModal" tabindex="-1">
|
|
<div class="modal-dialog">
|
|
<div class="modal-content">
|
|
<form id="ruleForm">
|
|
<div class="modal-header"><h5 class="modal-title" id="ruleModalTitle">Add Alert Rule</h5><button type="button" class="btn-close" data-bs-dismiss="modal"></button></div>
|
|
<div class="modal-body">
|
|
<input type="hidden" name="id" id="ruleFormId" value="">
|
|
<div class="mb-3">
|
|
<label class="form-label">Name</label>
|
|
<input type="text" class="form-control" name="name" id="ruleFormName" required placeholder="e.g. SSH Login">
|
|
</div>
|
|
<div class="mb-3">
|
|
<label class="form-label">Pattern <small class="text-secondary">(PHP regex)</small></label>
|
|
<input type="text" class="form-control" name="pattern" id="ruleFormPattern" required placeholder="/sshd.*Accepted/i">
|
|
</div>
|
|
<div class="mb-3">
|
|
<label class="form-label">Severity</label>
|
|
<select class="form-select" name="severity" id="ruleFormSeverity" required>
|
|
<option value="emergency">Emergency</option>
|
|
<option value="critical_high">Critical High</option>
|
|
<option value="critical">Critical</option>
|
|
<option value="critical_low">Critical Low</option>
|
|
<option value="error">Error</option>
|
|
<option value="warning_high">Warning High</option>
|
|
<option value="warning" selected>Warning</option>
|
|
<option value="warning_low">Warning Low</option>
|
|
<option value="notice">Notice</option>
|
|
<option value="info">Info</option>
|
|
<option value="debug">Debug</option>
|
|
</select>
|
|
</div>
|
|
<div class="mb-3">
|
|
<label class="form-label">Rate Limit <small class="text-secondary">(seconds, empty = no limit)</small></label>
|
|
<input type="number" class="form-control" name="rate_limit_seconds" id="ruleFormRateLimit" placeholder="60">
|
|
</div>
|
|
<div class="form-check mb-3">
|
|
<input class="form-check-input" type="checkbox" name="active" id="ruleFormActive" checked>
|
|
<label class="form-check-label" for="ruleFormActive">Active</label>
|
|
</div>
|
|
</div>
|
|
<div class="modal-footer">
|
|
<button type="submit" class="btn btn-primary" id="ruleFormSubmit">Add Rule</button>
|
|
<button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Cancel</button>
|
|
</div>
|
|
</form>
|
|
</div></div></div>
|
|
|
|
<!-- Toast -->
|
|
<div class="toast-container position-fixed bottom-0 end-0 p-3"></div>
|
|
|
|
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/js/bootstrap.bundle.min.js"></script>
|
|
<script>
|
|
const API = window.location.origin;
|
|
|
|
let state = { alerts: [], sources: [], rules: [], counts: [], user: null, sortField: 'created_at', sortDir: 'desc' };
|
|
let autoRefreshInterval = null;
|
|
let currentAlertId = null;
|
|
|
|
// --- Auth ---
|
|
async function checkAuth() {
|
|
try {
|
|
const res = await api('/auth/me');
|
|
if (res.user) {
|
|
state.user = res.user;
|
|
document.getElementById('userDisplay').textContent = res.user.username;
|
|
document.getElementById('settingsUser').textContent = res.user.username + ' (' + res.user.user_token.substring(0, 12) + '...)';
|
|
document.getElementById('appLogin').style.display = 'none';
|
|
document.getElementById('appMain').style.display = '';
|
|
initApp();
|
|
return true;
|
|
}
|
|
if (res.login_url) {
|
|
showLogin(res.error, res.login_url);
|
|
} else if (res.error) {
|
|
showLogin(res.error);
|
|
} else {
|
|
showLogin();
|
|
}
|
|
return false;
|
|
} catch (e) {
|
|
if (e.login_url) {
|
|
showLogin('Session expired. Please log in again.', e.login_url);
|
|
} else {
|
|
showLogin('Cannot connect to server: ' + e.message);
|
|
}
|
|
}
|
|
return false;
|
|
}
|
|
|
|
function showLogin(errorMsg, loginUrl) {
|
|
document.getElementById('appLogin').style.display = '';
|
|
document.getElementById('appMain').style.display = 'none';
|
|
const cbUrl = window.location.origin + '/oauth.php?redirect=' + encodeURIComponent(window.location.href);
|
|
const href = loginUrl || ('https://auth.jakach.ch/?send_to=' + encodeURIComponent(cbUrl));
|
|
document.getElementById('loginBtn').href = href;
|
|
const errorBox = document.getElementById('authErrorBox');
|
|
if (errorMsg) {
|
|
errorBox.textContent = errorMsg;
|
|
errorBox.classList.remove('d-none');
|
|
document.getElementById('loginBtn').innerHTML = '<i class="bi bi-box-arrow-in-right me-2"></i>Try again';
|
|
} else {
|
|
errorBox.classList.add('d-none');
|
|
document.getElementById('loginBtn').innerHTML = '<i class="bi bi-box-arrow-in-right me-2"></i>Log in using Jakach Login';
|
|
}
|
|
}
|
|
|
|
async function logout() {
|
|
try {
|
|
await api('/auth/logout', { method: 'POST' });
|
|
} catch (e) {}
|
|
state.user = null;
|
|
showLogin();
|
|
}
|
|
|
|
document.getElementById('logoutBtn').addEventListener('click', logout);
|
|
|
|
// --- Navigation ---
|
|
document.querySelectorAll('[data-page]').forEach(el => {
|
|
el.addEventListener('click', e => {
|
|
e.preventDefault();
|
|
showPage(el.dataset.page);
|
|
});
|
|
});
|
|
|
|
function showPage(name) {
|
|
document.querySelectorAll('.page-section').forEach(p => p.classList.remove('active'));
|
|
document.getElementById('page-' + name).classList.add('active');
|
|
document.querySelectorAll('.sidebar .nav-link').forEach(l => l.classList.remove('active'));
|
|
document.querySelector(`.sidebar .nav-link[data-page="${name}"]`)?.classList.add('active');
|
|
loadPage(name);
|
|
}
|
|
|
|
function loadPage(name) {
|
|
switch (name) {
|
|
case 'dashboard': loadDashboard(); break;
|
|
case 'alerts': loadAlerts(); break;
|
|
case 'logs': break;
|
|
case 'sources': loadSources(); break;
|
|
case 'rules': loadRules(); break;
|
|
case 'settings': loadSettings(); break;
|
|
}
|
|
}
|
|
|
|
// --- API Helpers ---
|
|
async function api(path, opts = {}) {
|
|
const res = await fetch(API + path, {
|
|
headers: { 'Accept': 'application/json', ...(opts.body ? { 'Content-Type': 'application/json' } : {}) },
|
|
...opts,
|
|
});
|
|
const data = await res.json();
|
|
if (!res.ok) {
|
|
const err = new Error(data.error || 'Request failed');
|
|
err.login_url = data.login_url;
|
|
err.status = res.status;
|
|
throw err;
|
|
}
|
|
return data;
|
|
}
|
|
|
|
function toast(msg, type = 'success') {
|
|
const container = document.querySelector('.toast-container');
|
|
const el = document.createElement('div');
|
|
el.className = `toast align-items-center text-bg-${type} border-0`;
|
|
el.role = 'alert';
|
|
el.innerHTML = `<div class="d-flex"><div class="toast-body">${msg}</div><button type="button" class="btn-close btn-close-white me-2 m-auto" data-bs-dismiss="toast"></button></div>`;
|
|
container.appendChild(el);
|
|
const t = new bootstrap.Toast(el);
|
|
t.show();
|
|
el.addEventListener('hidden.bs.toast', () => el.remove());
|
|
}
|
|
|
|
function severityBadge(s) {
|
|
const map = {
|
|
debug: 'secondary', info: 'info', notice: 'info',
|
|
warning_low: 'warning', warning: 'warning', warning_high: 'warning',
|
|
error: 'danger',
|
|
critical_low: 'danger', critical: 'danger', critical_high: 'danger',
|
|
emergency: 'dark',
|
|
};
|
|
const label = s.replace(/_/g, ' ');
|
|
return `<span class="badge badge-severity bg-${map[s] || 'secondary'}">${label}</span>`;
|
|
}
|
|
|
|
function statusBadge(s) {
|
|
const map = { open: 'danger', acknowledged: 'warning', resolved: 'success' };
|
|
return `<span class="badge bg-${map[s] || 'secondary'}">${s}</span>`;
|
|
}
|
|
|
|
function timeAgo(dateStr) {
|
|
const sec = Math.floor((Date.now() - new Date(dateStr).getTime()) / 1000);
|
|
if (sec < 5) return 'just now';
|
|
if (sec < 60) return sec + 's ago';
|
|
const min = Math.floor(sec / 60);
|
|
if (min < 60) return min + 'm ago';
|
|
const hrs = Math.floor(min / 60);
|
|
if (hrs < 24) return hrs + 'h ago';
|
|
return new Date(dateStr).toLocaleString();
|
|
}
|
|
|
|
// --- DASHBOARD ---
|
|
async function loadDashboard() {
|
|
try {
|
|
const [countsRes, alertsRes] = await Promise.all([
|
|
api('/alerts/counts'),
|
|
api('/alerts?limit=10&severity=critical&status=open'),
|
|
]);
|
|
const counts = Array.isArray(countsRes) ? countsRes : (countsRes.data || []);
|
|
const alerts = alertsRes.data || [];
|
|
|
|
const total = counts.filter(c => c.status !== 'resolved').reduce((s, c) => s + parseInt(c.count), 0);
|
|
const critical = counts.filter(c => c.severity === 'critical' && c.status !== 'resolved').reduce((s, c) => s + parseInt(c.count), 0);
|
|
const warning = counts.filter(c => c.severity === 'warning' && c.status !== 'resolved').reduce((s, c) => s + parseInt(c.count), 0);
|
|
const open = counts.filter(c => c.status === 'open').reduce((s, c) => s + parseInt(c.count), 0);
|
|
|
|
document.getElementById('statCards').innerHTML = `
|
|
<div class="col-md-3"><div class="card stat-card critical"><div class="card-body"><h6 class="card-subtitle text-secondary mb-1">Critical</h6><h3 class="mb-0 text-danger">${critical}</h3></div></div></div>
|
|
<div class="col-md-3"><div class="card stat-card warning"><div class="card-body"><h6 class="card-subtitle text-secondary mb-1">Warnings</h6><h3 class="mb-0 text-warning">${warning}</h3></div></div></div>
|
|
<div class="col-md-3"><div class="card stat-card"><div class="card-body"><h6 class="card-subtitle text-secondary mb-1">Open</h6><h3 class="mb-0">${open}</h3></div></div></div>
|
|
<div class="col-md-3"><div class="card stat-card"><div class="card-body"><h6 class="card-subtitle text-secondary mb-1">Total Active</h6><h3 class="mb-0">${total}</h3></div></div></div>
|
|
`;
|
|
|
|
document.getElementById('criticalBadge').textContent = critical;
|
|
document.getElementById('criticalBadge').classList.toggle('d-none', critical === 0);
|
|
document.getElementById('warningBadge').textContent = warning;
|
|
document.getElementById('warningBadge').classList.toggle('d-none', warning === 0);
|
|
|
|
const tbody = document.getElementById('dashboardAlerts');
|
|
if (!alerts.length) {
|
|
tbody.innerHTML = '<tr><td colspan="4" class="empty-state"><i class="bi bi-check-circle"></i><p class="mb-0">No critical alerts</p></td></tr>';
|
|
} else {
|
|
tbody.innerHTML = alerts.map(a => `<tr class="alert-row" onclick="showAlert(${a.id})">
|
|
<td>${severityBadge(a.severity)}</td>
|
|
<td>${esc(a.rule_name)}</td>
|
|
<td class="log-line">${esc(a.message)}</td>
|
|
<td class="text-secondary" style="white-space:nowrap">${timeAgo(a.created_at)}</td>
|
|
</tr>`).join('');
|
|
}
|
|
|
|
const chartEl = document.getElementById('chartContainer');
|
|
const severityGroups = { critical: ['critical_high','critical','critical_low','emergency'], warning: ['warning_high','warning','warning_low','error'], info: ['notice','info','debug'] };
|
|
const severityCounts = { critical: 0, warning: 0, info: 0 };
|
|
counts.forEach(c => {
|
|
if (c.status === 'resolved') return;
|
|
for (const [group, levels] of Object.entries(severityGroups)) {
|
|
if (levels.includes(c.severity)) {
|
|
severityCounts[group] += parseInt(c.count);
|
|
break;
|
|
}
|
|
}
|
|
});
|
|
const maxVal = Math.max(...Object.values(severityCounts), 1);
|
|
chartEl.innerHTML = `<div class="d-flex align-items-end gap-2" style="height:120px">${Object.entries(severityCounts).map(([sev, cnt]) => {
|
|
const color = { critical: 'danger', warning: 'warning', info: 'info' }[sev] || 'secondary';
|
|
const pct = (cnt / maxVal) * 100;
|
|
return `<div class="d-flex flex-column align-items-center flex-fill"><div class="bg-${color}" style="width:100%;height:${pct}%;min-height:4px;border-radius:4px 4px 0 0"></div><small class="mt-1">${sev}<br><strong>${cnt}</strong></small></div>`;
|
|
}).join('')}</div>`;
|
|
|
|
document.getElementById('lastUpdated').textContent = 'Updated ' + new Date().toLocaleTimeString();
|
|
} catch (e) { console.error('dashboard error', e); }
|
|
}
|
|
|
|
// --- ALERTS ---
|
|
async function loadAlerts() {
|
|
const severity = document.getElementById('filterSeverity').value;
|
|
const status = document.getElementById('filterStatus').value;
|
|
const query = document.getElementById('searchInput').value.trim();
|
|
|
|
let url;
|
|
if (query) {
|
|
url = '/alerts/search?q=' + encodeURIComponent(query) + '&limit=100';
|
|
} else {
|
|
const params = new URLSearchParams({ limit: 100, offset: 0 });
|
|
if (severity) params.set('severity', severity);
|
|
if (status) params.set('status', status);
|
|
url = '/alerts?' + params.toString();
|
|
}
|
|
|
|
try {
|
|
const res = await api(url);
|
|
const alerts = res.data || [];
|
|
state.alerts = alerts;
|
|
renderAlerts(query);
|
|
} catch (e) { console.error('alerts error', e); }
|
|
}
|
|
|
|
function renderAlerts(query) {
|
|
let sorted = [...state.alerts];
|
|
const field = state.sortField;
|
|
const dir = state.sortDir;
|
|
sorted.sort((a, b) => {
|
|
let va = a[field], vb = b[field];
|
|
if (field === 'severity') {
|
|
const order = ['debug','info','notice','warning_low','warning','warning_high','error','critical_low','critical','critical_high','emergency'];
|
|
va = order.indexOf(va);
|
|
vb = order.indexOf(vb);
|
|
} else if (field === 'created_at') {
|
|
va = new Date(va).getTime();
|
|
vb = new Date(vb).getTime();
|
|
} else {
|
|
va = (va || '').toString().toLowerCase();
|
|
vb = (vb || '').toString().toLowerCase();
|
|
if (va < vb) return dir === 'asc' ? -1 : 1;
|
|
if (va > vb) return dir === 'asc' ? 1 : -1;
|
|
return 0;
|
|
}
|
|
return dir === 'asc' ? va - vb : vb - va;
|
|
});
|
|
|
|
const tbody = document.getElementById('alertsBody');
|
|
if (!sorted.length) {
|
|
tbody.innerHTML = '<tr><td colspan="7" class="empty-state"><i class="bi bi-inbox"></i><p class="mb-0">No alerts match those filters</p></td></tr>';
|
|
} else {
|
|
tbody.innerHTML = sorted.map(a => `<tr class="alert-row" onclick="showAlert(${a.id})">
|
|
<td class="text-secondary">#${a.id}</td>
|
|
<td>${severityBadge(a.severity)}</td>
|
|
<td>${statusBadge(a.status)}</td>
|
|
<td class="log-line">${esc(a.message)}</td>
|
|
<td>${esc(a.source_name || '—')}</td>
|
|
<td class="text-secondary" style="white-space:nowrap">${new Date(a.created_at).toLocaleString()}</td>
|
|
<td style="white-space:nowrap">
|
|
${a.status === 'open' ? `<button class="btn btn-outline-success btn-sm py-0 me-1" onclick="event.stopPropagation();quickAction(${a.id},'acknowledged')" title="Acknowledge"><i class="bi bi-check"></i></button>` : ''}
|
|
${a.status !== 'resolved' ? `<button class="btn btn-outline-secondary btn-sm py-0" onclick="event.stopPropagation();quickAction(${a.id},'resolved')" title="Resolve"><i class="bi bi-check-all"></i></button>` : ''}
|
|
</td>
|
|
</tr>`).join('');
|
|
}
|
|
const label = document.getElementById('searchInput').value.trim() ? 'search results' : 'alerts';
|
|
document.getElementById('alertsCount').textContent = sorted.length + ' ' + label;
|
|
}
|
|
|
|
function sortAlerts(field) {
|
|
if (state.sortField === field) {
|
|
state.sortDir = state.sortDir === 'asc' ? 'desc' : 'asc';
|
|
} else {
|
|
state.sortField = field;
|
|
state.sortDir = 'asc';
|
|
}
|
|
renderAlerts();
|
|
}
|
|
|
|
document.getElementById('searchBtn').addEventListener('click', loadAlerts);
|
|
document.getElementById('searchInput').addEventListener('keydown', e => { if (e.key === 'Enter') loadAlerts(); });
|
|
|
|
function showAlert(id) {
|
|
const a = state.alerts.find(x => x.id === id);
|
|
if (!a) return;
|
|
currentAlertId = id;
|
|
document.getElementById('detailBody').innerHTML = `
|
|
<dl class="row mb-0">
|
|
<dt class="col-sm-3">ID</dt><dd class="col-sm-9">#${a.id}</dd>
|
|
<dt class="col-sm-3">Rule</dt><dd class="col-sm-9">${esc(a.rule_name)}</dd>
|
|
<dt class="col-sm-3">Severity</dt><dd class="col-sm-9">${severityBadge(a.severity)}</dd>
|
|
<dt class="col-sm-3">Status</dt><dd class="col-sm-9">${statusBadge(a.status)}</dd>
|
|
<dt class="col-sm-3">Source</dt><dd class="col-sm-9">${esc(a.source_name || '—')}</dd>
|
|
<dt class="col-sm-3">Created</dt><dd class="col-sm-9">${new Date(a.created_at).toLocaleString()}</dd>
|
|
<dt class="col-sm-3">Message</dt><dd class="col-sm-9">${esc(a.message)}</dd>
|
|
<dt class="col-sm-3">Raw Line</dt><dd class="col-sm-9"><pre class="raw-line">${esc(a.raw_line)}</pre></dd>
|
|
</dl>`;
|
|
document.getElementById('statusSelect').value = a.status;
|
|
setTimeout(() => bootstrap.Modal.getOrCreateInstance(document.getElementById('detailModal')).show(), 50);
|
|
}
|
|
|
|
document.getElementById('updateStatusBtn').addEventListener('click', async () => {
|
|
const newStatus = document.getElementById('statusSelect').value;
|
|
if (currentAlertId) await updateAlertStatus(currentAlertId, newStatus);
|
|
bootstrap.Modal.getInstance(document.getElementById('detailModal')).hide();
|
|
});
|
|
|
|
async function updateAlertStatus(id, status) {
|
|
try {
|
|
await api(`/alerts/${id}/status`, { method: 'POST', body: JSON.stringify({ status }) });
|
|
toast('Alert #' + id + ' ' + status);
|
|
loadPage(document.querySelector('.sidebar .nav-link.active')?.dataset.page || 'dashboard');
|
|
} catch (e) { toast('Failed to update status', 'danger'); }
|
|
}
|
|
|
|
async function quickAction(id, status) {
|
|
try {
|
|
await api(`/alerts/${id}/status`, { method: 'POST', body: JSON.stringify({ status }) });
|
|
toast('Alert #' + id + ' ' + status);
|
|
loadPage(document.querySelector('.sidebar .nav-link.active')?.dataset.page || 'dashboard');
|
|
} catch (e) { toast('Failed', 'danger'); }
|
|
}
|
|
|
|
document.getElementById('filterSeverity').addEventListener('change', loadAlerts);
|
|
document.getElementById('filterStatus').addEventListener('change', loadAlerts);
|
|
document.getElementById('refreshAlertsBtn').addEventListener('click', loadAlerts);
|
|
|
|
// --- SOURCES ---
|
|
async function loadSources() {
|
|
try {
|
|
const res = await api('/sources');
|
|
const sources = res.data || [];
|
|
state.sources = sources;
|
|
const tbody = document.getElementById('sourcesBody');
|
|
if (!sources.length) {
|
|
tbody.innerHTML = '<tr><td colspan="6" class="empty-state"><i class="bi bi-database"></i><p class="mb-0">No sources configured</p></td></tr>';
|
|
} else {
|
|
tbody.innerHTML = sources.map(s => `<tr>
|
|
<td><strong>${esc(s.name)}</strong></td>
|
|
<td><span class="badge bg-secondary">${s.type}</span></td>
|
|
<td><code>${esc(s.address)}</code></td>
|
|
<td><small>${s.labels && Object.keys(s.labels).length ? esc(JSON.stringify(s.labels)) : '—'}</small></td>
|
|
<td>${s.active ? '<span class="badge bg-success">Active</span>' : '<span class="badge bg-secondary">Inactive</span>'}</td>
|
|
<td><button class="btn btn-outline-primary btn-sm py-0 me-1" onclick="editSource(${s.id})"><i class="bi bi-pencil"></i></button><button class="btn btn-outline-danger btn-sm py-0" onclick="deleteSource(${s.id})"><i class="bi bi-trash"></i></button></td>
|
|
</tr>`).join('');
|
|
}
|
|
} catch (e) { console.error('sources error', e); }
|
|
}
|
|
|
|
async function deleteSource(id) {
|
|
if (!confirm('Delete source?')) return;
|
|
try {
|
|
await api('/sources/' + id, { method: 'DELETE' });
|
|
toast('Source deleted');
|
|
loadSources();
|
|
} catch (e) { toast('Delete failed', 'danger'); }
|
|
}
|
|
|
|
function editSource(id) {
|
|
const s = state.sources.find(x => x.id === id);
|
|
if (!s) return;
|
|
document.getElementById('sourceModalLabel').textContent = 'Edit Source';
|
|
document.getElementById('sourceFormSubmit').textContent = 'Update Source';
|
|
document.getElementById('sourceFormId').value = s.id;
|
|
document.getElementById('sourceFormName').value = s.name;
|
|
document.getElementById('sourceFormType').value = s.type;
|
|
document.getElementById('sourceFormAddress').value = s.address;
|
|
document.getElementById('sourceFormLabels').value = s.labels && Object.keys(s.labels).length ? JSON.stringify(s.labels) : '';
|
|
document.getElementById('sourceFormActive').checked = s.active;
|
|
setTimeout(() => bootstrap.Modal.getOrCreateInstance(document.getElementById('sourceModal')).show(), 50);
|
|
}
|
|
|
|
function resetSourceForm() {
|
|
document.getElementById('sourceModalLabel').textContent = 'Add Source';
|
|
document.getElementById('sourceFormSubmit').textContent = 'Add Source';
|
|
document.getElementById('sourceFormId').value = '';
|
|
document.getElementById('sourceForm').reset();
|
|
document.getElementById('sourceFormActive').checked = true;
|
|
}
|
|
|
|
document.getElementById('sourceModal').addEventListener('hidden.bs.modal', resetSourceForm);
|
|
|
|
document.getElementById('sourceForm').addEventListener('submit', async e => {
|
|
e.preventDefault();
|
|
const data = Object.fromEntries(new FormData(e.target));
|
|
if (data.labels) { try { data.labels = JSON.parse(data.labels); } catch { data.labels = {}; } }
|
|
else { data.labels = {}; }
|
|
data.active = !!data.active;
|
|
const id = data.id;
|
|
delete data.id;
|
|
try {
|
|
if (id) {
|
|
await api('/sources/' + id, { method: 'PUT', body: JSON.stringify(data) });
|
|
toast('Source updated');
|
|
} else {
|
|
await api('/sources', { method: 'POST', body: JSON.stringify(data) });
|
|
toast('Source added');
|
|
}
|
|
bootstrap.Modal.getInstance(document.getElementById('sourceModal')).hide();
|
|
loadSources();
|
|
} catch (err) { toast('Failed to save source', 'danger'); }
|
|
});
|
|
|
|
// --- RULES ---
|
|
async function loadRules() {
|
|
try {
|
|
const res = await api('/rules');
|
|
const rules = res.data || [];
|
|
state.rules = rules;
|
|
const tbody = document.getElementById('rulesBody');
|
|
if (!rules.length) {
|
|
tbody.innerHTML = '<tr><td colspan="6" class="empty-state"><i class="bi bi-sliders"></i><p class="mb-0">No rules configured</p></td></tr>';
|
|
} else {
|
|
tbody.innerHTML = rules.map(r => `<tr>
|
|
<td><strong>${esc(r.name)}</strong></td>
|
|
<td><code>${esc(r.pattern)}</code></td>
|
|
<td>${severityBadge(r.severity)}</td>
|
|
<td>${r.rate_limit_seconds ? r.rate_limit_seconds + 's' : '—'}</td>
|
|
<td>${r.active ? '<span class="badge bg-success">Active</span>' : '<span class="badge bg-secondary">Inactive</span>'}</td>
|
|
<td><button class="btn btn-outline-primary btn-sm py-0 me-1" onclick="editRule(${r.id})"><i class="bi bi-pencil"></i></button><button class="btn btn-outline-danger btn-sm py-0" onclick="deleteRule(${r.id})"><i class="bi bi-trash"></i></button></td>
|
|
</tr>`).join('');
|
|
}
|
|
} catch (e) { console.error('rules error', e); }
|
|
}
|
|
|
|
async function deleteRule(id) {
|
|
if (!confirm('Delete rule?')) return;
|
|
try {
|
|
await api('/rules/' + id, { method: 'DELETE' });
|
|
toast('Rule deleted');
|
|
loadRules();
|
|
} catch (e) { toast('Delete failed', 'danger'); }
|
|
}
|
|
|
|
function editRule(id) {
|
|
const r = state.rules.find(x => x.id === id);
|
|
if (!r) return;
|
|
document.getElementById('ruleModalTitle').textContent = 'Edit Rule';
|
|
document.getElementById('ruleFormSubmit').textContent = 'Update Rule';
|
|
document.getElementById('ruleFormId').value = r.id;
|
|
document.getElementById('ruleFormName').value = r.name;
|
|
document.getElementById('ruleFormPattern').value = r.pattern;
|
|
document.getElementById('ruleFormSeverity').value = r.severity;
|
|
document.getElementById('ruleFormRateLimit').value = r.rate_limit_seconds || '';
|
|
document.getElementById('ruleFormActive').checked = r.active;
|
|
setTimeout(() => bootstrap.Modal.getOrCreateInstance(document.getElementById('ruleModal')).show(), 50);
|
|
}
|
|
|
|
function resetRuleForm() {
|
|
document.getElementById('ruleModalTitle').textContent = 'Add Alert Rule';
|
|
document.getElementById('ruleFormSubmit').textContent = 'Add Rule';
|
|
document.getElementById('ruleFormId').value = '';
|
|
document.getElementById('ruleForm').reset();
|
|
document.getElementById('ruleFormActive').checked = true;
|
|
}
|
|
|
|
document.getElementById('ruleModal').addEventListener('hidden.bs.modal', resetRuleForm);
|
|
|
|
document.getElementById('ruleForm').addEventListener('submit', async e => {
|
|
e.preventDefault();
|
|
const data = Object.fromEntries(new FormData(e.target));
|
|
if (data.rate_limit_seconds) data.rate_limit_seconds = parseInt(data.rate_limit_seconds);
|
|
else data.rate_limit_seconds = null;
|
|
data.active = !!data.active;
|
|
|
|
const id = data.id;
|
|
delete data.id;
|
|
|
|
try {
|
|
if (id) {
|
|
await api('/rules/' + id, { method: 'PUT', body: JSON.stringify(data) });
|
|
toast('Rule updated');
|
|
} else {
|
|
await api('/rules', { method: 'POST', body: JSON.stringify(data) });
|
|
toast('Rule added');
|
|
}
|
|
bootstrap.Modal.getInstance(document.getElementById('ruleModal')).hide();
|
|
loadRules();
|
|
} catch (err) { toast('Failed to save rule', 'danger'); }
|
|
});
|
|
|
|
// --- SETTINGS ---
|
|
async function loadSettings() {
|
|
try {
|
|
await api('/health');
|
|
document.getElementById('sysHealth').textContent = 'Healthy';
|
|
document.getElementById('sysHealth').className = 'badge bg-success';
|
|
} catch {
|
|
document.getElementById('sysHealth').textContent = 'Unreachable';
|
|
document.getElementById('sysHealth').className = 'badge bg-danger';
|
|
}
|
|
|
|
try {
|
|
const res = await api('/config/allowed_tokens');
|
|
const tokens = res.tokens || [];
|
|
document.getElementById('allowedTokensInput').value = tokens.join('\n');
|
|
} catch (e) { console.error('load tokens error', e); }
|
|
|
|
try {
|
|
const res = await api('/config/telegram');
|
|
document.getElementById('telegramBotToken').value = res.bot_token || '';
|
|
document.getElementById('telegramChatId').value = res.chat_id || '';
|
|
} catch (e) { console.error('load telegram error', e); }
|
|
}
|
|
|
|
document.getElementById('saveTokensBtn').addEventListener('click', async () => {
|
|
const raw = document.getElementById('allowedTokensInput').value;
|
|
const tokens = raw.split('\n').map(t => t.trim()).filter(t => t.length > 0);
|
|
const statusEl = document.getElementById('tokenSaveStatus');
|
|
statusEl.textContent = 'Saving...';
|
|
statusEl.className = 'ms-2 text-secondary';
|
|
try {
|
|
await api('/config/allowed_tokens', {
|
|
method: 'PUT',
|
|
body: JSON.stringify({ tokens }),
|
|
});
|
|
statusEl.textContent = 'Saved';
|
|
statusEl.className = 'ms-2 text-success';
|
|
toast('Allowed tokens updated');
|
|
setTimeout(() => { statusEl.textContent = ''; }, 3000);
|
|
} catch (e) {
|
|
statusEl.textContent = 'Failed';
|
|
statusEl.className = 'ms-2 text-danger';
|
|
toast('Failed to save tokens', 'danger');
|
|
}
|
|
});
|
|
|
|
document.getElementById('saveTelegramBtn').addEventListener('click', async () => {
|
|
const botToken = document.getElementById('telegramBotToken').value.trim();
|
|
const chatId = document.getElementById('telegramChatId').value.trim();
|
|
const statusEl = document.getElementById('telegramSaveStatus');
|
|
statusEl.textContent = 'Saving...';
|
|
statusEl.className = 'ms-2 text-secondary';
|
|
try {
|
|
await api('/config/telegram', {
|
|
method: 'PUT',
|
|
body: JSON.stringify({ bot_token: botToken, chat_id: chatId }),
|
|
});
|
|
statusEl.textContent = 'Saved';
|
|
statusEl.className = 'ms-2 text-success';
|
|
toast('Telegram config saved');
|
|
setTimeout(() => { statusEl.textContent = ''; }, 3000);
|
|
} catch (e) {
|
|
statusEl.textContent = 'Failed';
|
|
statusEl.className = 'ms-2 text-danger';
|
|
toast('Failed to save Telegram config', 'danger');
|
|
}
|
|
});
|
|
|
|
document.getElementById('testTelegramBtn').addEventListener('click', async () => {
|
|
const btn = document.getElementById('testTelegramBtn');
|
|
btn.disabled = true;
|
|
btn.innerHTML = '<span class="spinner-border spinner-border-sm"></span> Sending...';
|
|
try {
|
|
await api('/ingest', {
|
|
method: 'POST',
|
|
body: JSON.stringify({ line: 'Jakach Logging: test notification from settings — PHP Warning: test alert', source: 'test' }),
|
|
});
|
|
toast('Test alert sent. Check Telegram.');
|
|
} catch (e) { toast('Failed to send test', 'danger'); }
|
|
btn.disabled = false;
|
|
btn.innerHTML = '<i class="bi bi-send"></i> Test';
|
|
});
|
|
|
|
// --- LOGS ---
|
|
async function loadLogs(query) {
|
|
if (!query) {
|
|
query = document.getElementById('logSearchInput').value.trim();
|
|
if (!query) {
|
|
document.getElementById('logsBody').innerHTML = '<tr><td colspan="4" class="empty-state"><i class="bi bi-search"></i><p class="mb-0">Enter a search query above</p></td></tr>';
|
|
document.getElementById('logsCount').textContent = '';
|
|
return;
|
|
}
|
|
}
|
|
|
|
try {
|
|
const res = await api('/logs/search?q=' + encodeURIComponent(query) + '&limit=200');
|
|
const entries = res.data || [];
|
|
const tbody = document.getElementById('logsBody');
|
|
if (!entries.length) {
|
|
tbody.innerHTML = '<tr><td colspan="4" class="empty-state"><i class="bi bi-inbox"></i><p class="mb-0">No results for "' + esc(query) + '"</p></td></tr>';
|
|
} else {
|
|
tbody.innerHTML = entries.map(e => `<tr>
|
|
<td class="text-secondary" style="font-size:.75rem">#${e.id}</td>
|
|
<td class="text-secondary" style="white-space:nowrap;font-size:.8rem">${new Date(e.created_at).toLocaleString()}</td>
|
|
<td style="font-family:monospace;font-size:.8rem;max-width:600px;overflow:hidden;text-overflow:ellipsis;white-space:nowrap">${esc(e.line)}</td>
|
|
<td>${e.source_name ? '<span class="badge bg-secondary">' + esc(e.source_name) + '</span>' : '—'}</td>
|
|
</tr>`).join('');
|
|
}
|
|
document.getElementById('logsCount').textContent = entries.length + ' results';
|
|
} catch (e) { console.error('logs error', e); }
|
|
}
|
|
|
|
document.getElementById('logSearchBtn').addEventListener('click', () => loadLogs());
|
|
document.getElementById('logSearchInput').addEventListener('keydown', e => { if (e.key === 'Enter') loadLogs(); });
|
|
|
|
// --- Helpers ---
|
|
function esc(s) {
|
|
const d = document.createElement('div');
|
|
d.textContent = s || '';
|
|
return d.innerHTML;
|
|
}
|
|
|
|
// --- Auto-refresh ---
|
|
document.getElementById('autoRefresh').addEventListener('change', () => {
|
|
if (document.getElementById('autoRefresh').checked) startAutoRefresh();
|
|
else stopAutoRefresh();
|
|
});
|
|
|
|
function startAutoRefresh() {
|
|
stopAutoRefresh();
|
|
autoRefreshInterval = setInterval(() => {
|
|
const active = document.querySelector('.page-section.active');
|
|
if (active) loadPage(active.id.replace('page-', ''));
|
|
}, 5000);
|
|
}
|
|
|
|
function stopAutoRefresh() {
|
|
if (autoRefreshInterval) clearInterval(autoRefreshInterval);
|
|
autoRefreshInterval = null;
|
|
}
|
|
|
|
document.getElementById('refreshBtn').addEventListener('click', () => {
|
|
const active = document.querySelector('.page-section.active');
|
|
if (active) loadPage(active.id.replace('page-', ''));
|
|
});
|
|
|
|
// --- Init ---
|
|
function initApp() {
|
|
startAutoRefresh();
|
|
loadDashboard();
|
|
document.querySelectorAll('[data-page]').forEach(el => {
|
|
el.addEventListener('click', e => {
|
|
e.preventDefault();
|
|
showPage(el.dataset.page);
|
|
});
|
|
});
|
|
}
|
|
|
|
checkAuth();
|
|
</script>
|
|
</body>
|
|
</html> |