mirror of
https://github.com/ChuckBuilds/LEDMatrix.git
synced 2026-10-04 22:35:08 +00:00
* fix(web): escape quotes in every HTML escaper, not just & < >
The escapers are all `div.textContent = x; return div.innerHTML`. That
round-trip escapes &, < and > -- the only characters the HTML serializer
must escape in a text node -- and leaves quotes alone. Every widget then
interpolates the result into a quoted attribute value:
value="${escapeHtml(v)}" title="${escapeHtml(v)}"
so a value of `x" onmouseover="alert(1)` closes the attribute and adds an
event handler of its own. CodeQL reported this 83 times
(js/incomplete-html-attribute-sanitization) across the widget files.
It is one bug, not 83: the widgets each carry a standalone fallback that
did escape quotes, but they all prefer BaseWidget.escapeHtml when
window.BaseWidget exists -- which it always does in the shipped page -- so
the correct fallbacks were dead code and the incomplete shared one ran.
Fixed at each source instead of at the call sites.
app-shell.js already documented this exact gap in a comment and worked
around it by building DOM nodes by hand; that workaround stays (setting a
property cannot be got wrong), the comment is now accurate.
cache.html's delete button interpolated the cache key into
`onclick="deleteCacheFile('...')"`. Escaping cannot help there -- the
browser HTML-decodes the attribute before parsing it as JS, so `'`
becomes a real `'` again -- so the key moves to a data-cache-key
attribute that the handler reads back.
url-input.js additionally wrote a value straight into an <a href> after
validating it against a schema-supplied protocol list, and that list
accepted any RFC 3986 scheme -- "javascript" included. Scriptable schemes
(javascript, data, vbscript, blob, filesystem) are now refused both when
the list is normalised and when a URL is checked against it, and the
render path routes its href through the same check instead of emitting
whatever was stored (js/xss-through-dom).
test/js/unit/test_html_escaping.js reads each escaper out of the shipped
file and runs it, so losing the quote handling again fails a test rather
than a scan.
Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
* fix(security): stop request-supplied names from reaching paths outside their base
Three of the py/path-injection alerts were live, not lint:
* GET /api/v3/plugins/<plugin_id>/static/<path:file_path> read any file
whose resolved path *string-prefixed* the plugin directory. Flask's
default converter forbids a slash but not dots, and
get_plugin_directory('..') returned the parent of the plugins directory
because it exists -- so every file under the project root then prefixed
that directory, config/config_secrets.json included. The prefix check
was also wrong on its own terms: with plugin dir "plugin-repos/foo",
"../foo-evil/x" resolves to "plugin-repos/foo-evil/x", whose string does
start with "plugin-repos/foo".
* POST /api/v3/plugins/of-the-day/json/delete interpolated the request
body's file_id into f"{file_id}.json" and unlinked it, unvalidated. A
file_id of "../../../../etc/something" deleted that file. This is the
one finding in the batch that destroyed data rather than exposing it.
* POST /api/v3/cache/delete passed the body's key through
CacheManager.clear_cache to DiskCache, which joined it as a filename and
called os.remove. Same shape, same result. The guard goes in
DiskCache.get_cache_path, the single choke point get/set/clear share, so
every caller is covered rather than just this route. Real keys are the
stems of files already flat in the cache directory -- that is how
list_cache_files derives them -- so nothing legitimate is turned away.
The rest of the cluster (web_interface/app.py's asset route, the plugin
update handler, _get_plugin_version, the plugin-schema read in config.py)
was guarded in ways that held, but each had grown its own version of the
check. They now go through one helper, src/common/path_safety.py, which
returns the *sanitised value* rather than a verdict -- so a caller cannot
validate one string and open another, which is how the two real bugs
above were shaped.
Also: WiFiManager.connect_to_network took the SSID and password straight
from POST /api/v3/wifi/connect into nmcli's argv. There is no shell there,
so CodeQL's py/command-line-injection alert overstates the risk -- but
nmcli reads a leading "-" as an option, so an SSID of "--ask" asks nmcli
to run differently rather than to join a network. Both values are now
checked for shape (802.11's 32-octet SSID limit, WPA's 8-63 char
passphrase or 64-char hex key, no control characters, no leading dash)
before any subprocess runs.
test/test_path_traversal_guards.py asserts on the filesystem, not just
the status code: a handler that returns 403 and deletes the file anyway
would pass the weaker check. Twelve of its cases fail against the
unpatched code.
Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
* fix(web): refuse a plugin id that is not a plain name, don't truncate it
pages_v3 and scripts/dev_server.py ran request ids through
os.path.basename and carried on with what came out, so "../weather"
rendered the config form for "weather". Nothing escaped the plugins
directory -- the relative_to guards held -- but the handler answered a
request nobody made, and validating one string while the filesystem sees
another is the shape both live traversals earlier in this branch had.
Same treatment as the rest: safe_path_component rejects rather than
truncates, resolve_under returns the path it checked, and the call sites
use what those return. The three handlers that had hand-rolled
resolve-and-relative_to blocks lose about twenty lines to the shared one.
Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
* docs(web): say what the plugin web_ui iframe actually is
The docstring claimed the fragment runs "in a sandboxed iframe". The
iframe in plugin_config.html carries no sandbox attribute, so the
fragment runs with the interface's own origin. That is fine -- the file
belongs to an installed plugin, and an installed plugin already runs
Python on the device, so the trust boundary is install rather than this
route -- but a comment promising containment that is not there is worse
than no comment. This is the context for the py/reflective-xss alert on
this handler.
Also drops the now-unused os/os.path imports.
Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
* fix(web): inline url-input's scheme guard at the previewLink.href sink
CodeQL flagged this line as a new high-severity js/xss-through-dom alert
on this PR even though it is already covered by SCRIPTABLE_SCHEMES: the
guard reached the sink through safeHref -> isValidUrl, two function calls
away, which its DOM-based-XSS sanitizer recognition does not trace.
Behavior is unchanged -- same scheme check, same SCRIPTABLE_SCHEMES list,
same allowedProtocols gate -- just inlined directly above the
previewLink.href assignment it guards, so the barrier is visible in the
same scope as the sink.
Added a regression test that runs the shipped onInput handler (not just
the extracted helpers) against a mocked DOM, so a future change that
reintroduces an unguarded previewLink.href assignment fails here.
Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
* fix(security): address CodeRabbit findings on the CodeQL triage PR
- src/wifi_manager.py: reject non-ASCII WPA-PSK passphrases before any
credential-saving or connect flow runs. NetworkManager only accepts
printable ASCII passphrases (or a 64-char hex key); a non-ASCII value
was previously saved/attempted before nmcli itself rejected it.
- web_interface/blueprints/api_v3/config.py: fail closed when the
plugin config schema path can't be resolved under the plugins
directory (e.g. a symlinked plugin dir). Previously this fell
through with secret_fields left empty, so submitted credentials for
that plugin were saved as ordinary, unencrypted configuration.
- web_interface/static/v3/js/widgets/plugin-file-manager.js: stop
splicing the JSON day/column key into an inline oninput="..." handler
string. escHtml() escapes quotes for a normal HTML attribute, but the
browser HTML-decodes the attribute before running it as script, which
undoes that escaping and lets a crafted column name (e.g. from an
uploaded JSON file) break out of the JS string and execute. Cell
edits now travel through data-day/data-col attributes read by one
delegated 'input' listener instead.
While in this file: fixed 6 pre-existing missing-')' typos on
multi-line safeSetHTML(...) calls (already flagged by Biome in this
PR's own CodeRabbit run as syntax errors blocking its lint pass).
These predate this PR (present on main too) but made the whole file
fail to parse in any JS engine, which is a bigger problem than the
XSS finding itself and directly touches the same lines.
Added/extended regression tests for each fix; full suites pass
(pytest: 4580 passed, 62 skipped; JS: 84 assertions).
Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
---------
Co-authored-by: Claude Opus 5 <noreply@anthropic.com>
767 lines
28 KiB
HTML
767 lines
28 KiB
HTML
<div class="bg-white rounded-lg shadow p-6">
|
|
<div class="border-b border-gray-200 pb-4 mb-6">
|
|
<h2 class="text-lg font-semibold text-gray-900">System Logs</h2>
|
|
<p class="mt-1 text-sm text-gray-600">View real-time logs from the LED matrix service for troubleshooting.</p>
|
|
</div>
|
|
|
|
<!-- Currently displayed plugin -->
|
|
<div id="current-plugin-banner" class="hidden mb-4 flex items-center gap-2 text-sm bg-blue-50 border border-blue-200 text-blue-800 rounded-lg px-3 py-2">
|
|
<i class="fas fa-tv"></i>
|
|
<span>Now showing: <strong id="current-plugin-mode">-</strong>
|
|
<span id="current-plugin-id-wrap" class="hidden">(plugin: <code id="current-plugin-id" class="bg-blue-100 px-1 rounded"></code>)</span>
|
|
</span>
|
|
<button id="current-plugin-filter-btn" class="hidden ml-auto btn bg-blue-600 hover:bg-blue-700 text-white px-2 py-0.5 rounded text-xs">
|
|
Filter to this plugin
|
|
</button>
|
|
</div>
|
|
|
|
<!-- Controls -->
|
|
<div class="flex flex-wrap items-center justify-between gap-4 mb-6">
|
|
<div class="flex items-center space-x-4">
|
|
<!-- Log Mode Toggle -->
|
|
<div class="flex items-center space-x-2">
|
|
<label class="flex items-center">
|
|
<input type="checkbox" id="log-realtime-toggle" class="form-control h-4 w-4" checked>
|
|
<span class="ml-2 text-sm font-medium">Real-time</span>
|
|
</label>
|
|
<span class="text-sm text-gray-600">|</span>
|
|
<button id="refresh-logs-btn" class="btn bg-gray-600 hover:bg-gray-700 text-white px-3 py-1 rounded text-sm">
|
|
<i class="fas fa-sync-alt mr-1"></i>Refresh
|
|
</button>
|
|
</div>
|
|
|
|
<!-- Log Level Filter -->
|
|
<select id="log-level-filter" class="form-control text-sm">
|
|
<option value="">All Levels</option>
|
|
<option value="ERROR">Errors Only</option>
|
|
<option value="WARNING">Warnings & Errors</option>
|
|
<option value="INFO">Info & Above</option>
|
|
</select>
|
|
|
|
<!-- Plugin Filter -->
|
|
<select id="log-plugin-filter" class="form-control text-sm">
|
|
<option value="">All Plugins</option>
|
|
</select>
|
|
|
|
<!-- Search -->
|
|
<div class="relative">
|
|
<input type="text" id="log-search" placeholder="Search logs..." class="form-control text-sm pl-8 pr-4 py-1 w-48">
|
|
<i class="fas fa-search absolute left-3 top-1/2 transform -translate-y-1/2 text-gray-400 text-xs"></i>
|
|
</div>
|
|
</div>
|
|
|
|
<div class="flex items-center space-x-2">
|
|
<!-- Auto-scroll toggle -->
|
|
<label class="flex items-center">
|
|
<input type="checkbox" id="log-autoscroll" class="form-control h-4 w-4" checked>
|
|
<span class="ml-2 text-sm">Auto-scroll</span>
|
|
</label>
|
|
|
|
<!-- Clear logs -->
|
|
<button id="clear-logs-btn" class="btn bg-red-600 hover:bg-red-700 text-white px-3 py-1 rounded text-sm">
|
|
<i class="fas fa-trash mr-1"></i>Clear
|
|
</button>
|
|
|
|
<!-- Download logs -->
|
|
<button id="download-logs-btn" class="btn bg-green-600 hover:bg-green-700 text-white px-3 py-1 rounded text-sm">
|
|
<i class="fas fa-download mr-1"></i>Download
|
|
</button>
|
|
</div>
|
|
</div>
|
|
|
|
<!-- Log Display -->
|
|
<div class="relative">
|
|
<div id="logs-container" class="bg-gray-900 text-gray-100 font-mono text-sm rounded-lg p-3 border border-gray-700 shadow-inner relative" style="height: 500px; min-height: 400px; max-height: 70vh;">
|
|
<div id="logs-loading" class="absolute inset-0 flex items-center justify-center text-gray-400 bg-gray-900">
|
|
<div class="text-center">
|
|
<i class="fas fa-spinner fa-spin text-2xl mb-2"></i>
|
|
<p>Loading logs...</p>
|
|
</div>
|
|
</div>
|
|
<div id="logs-display" class="hidden absolute inset-0 overflow-y-auto bg-gray-900">
|
|
<div class="logs-content p-0">
|
|
<!-- Logs will be inserted here -->
|
|
</div>
|
|
</div>
|
|
<div id="logs-empty" class="hidden absolute inset-0 flex items-center justify-center text-gray-400 bg-gray-900">
|
|
<div class="text-center">
|
|
<i class="fas fa-file-alt text-4xl mb-2"></i>
|
|
<p>No logs available</p>
|
|
<p class="text-sm mt-2">Logs will appear here when the service runs</p>
|
|
</div>
|
|
</div>
|
|
</div>
|
|
|
|
<!-- Log stats -->
|
|
<div id="log-stats" class="absolute top-2 right-2 bg-black bg-opacity-70 text-white text-xs px-3 py-1.5 rounded-md backdrop-blur-sm hidden">
|
|
<i class="fas fa-list-ul mr-1"></i>
|
|
<span id="log-count">0</span> entries
|
|
</div>
|
|
</div>
|
|
|
|
<!-- Connection Status -->
|
|
<div id="log-connection-status" class="mt-4 text-sm text-gray-600 flex items-center space-x-2">
|
|
<div class="w-2 h-2 bg-green-500 rounded-full"></div>
|
|
<span>Connected to log stream</span>
|
|
</div>
|
|
</div>
|
|
|
|
<script>
|
|
// Global variables - use window properties to avoid redeclaration errors with HTMX reloads
|
|
// Initialize only if not already defined
|
|
if (typeof window._logsEventSource === 'undefined') {
|
|
window._logsEventSource = null;
|
|
}
|
|
if (typeof window._allLogs === 'undefined') {
|
|
window._allLogs = [];
|
|
}
|
|
if (typeof window._filteredLogs === 'undefined') {
|
|
window._filteredLogs = [];
|
|
}
|
|
if (typeof window._logContainer === 'undefined') {
|
|
window._logContainer = null;
|
|
}
|
|
if (typeof window._logsContent === 'undefined') {
|
|
window._logsContent = null;
|
|
}
|
|
if (typeof window._isRealtime === 'undefined') {
|
|
window._isRealtime = true;
|
|
}
|
|
if (typeof window._MAX_LOGS === 'undefined') {
|
|
window._MAX_LOGS = 500; // Maximum number of logs to keep in memory
|
|
}
|
|
|
|
// Use window properties directly to avoid redeclaration issues
|
|
// Clean up any existing event source before reinitializing
|
|
if (window._logsEventSource) {
|
|
window._logsEventSource.close();
|
|
window._logsEventSource = null;
|
|
}
|
|
|
|
// Reset arrays on reload
|
|
window._allLogs = [];
|
|
window._filteredLogs = [];
|
|
|
|
// Initialize immediately (this script runs when the partial is loaded)
|
|
(function() {
|
|
window._logContainer = document.getElementById('logs-container');
|
|
window._logsContent = document.querySelector('#logs-display .logs-content');
|
|
|
|
// Logs container initialized successfully
|
|
|
|
initializeLogs();
|
|
|
|
// Event listeners - remove old ones first to prevent duplicates
|
|
const realtimeToggle = document.getElementById('log-realtime-toggle');
|
|
const refreshBtn = document.getElementById('refresh-logs-btn');
|
|
const levelFilter = document.getElementById('log-level-filter');
|
|
const pluginFilter = document.getElementById('log-plugin-filter');
|
|
const searchInput = document.getElementById('log-search');
|
|
const autoscrollToggle = document.getElementById('log-autoscroll');
|
|
const clearBtn = document.getElementById('clear-logs-btn');
|
|
const downloadBtn = document.getElementById('download-logs-btn');
|
|
|
|
// Clone and replace to remove old listeners
|
|
if (realtimeToggle) {
|
|
const newToggle = realtimeToggle.cloneNode(true);
|
|
realtimeToggle.parentNode.replaceChild(newToggle, realtimeToggle);
|
|
newToggle.addEventListener('change', toggleRealtime);
|
|
}
|
|
if (refreshBtn) {
|
|
const newBtn = refreshBtn.cloneNode(true);
|
|
refreshBtn.parentNode.replaceChild(newBtn, refreshBtn);
|
|
newBtn.addEventListener('click', refreshLogs);
|
|
}
|
|
if (levelFilter) {
|
|
const newFilter = levelFilter.cloneNode(true);
|
|
levelFilter.parentNode.replaceChild(newFilter, levelFilter);
|
|
newFilter.addEventListener('change', filterLogs);
|
|
}
|
|
if (pluginFilter) {
|
|
const newFilter = pluginFilter.cloneNode(true);
|
|
pluginFilter.parentNode.replaceChild(newFilter, pluginFilter);
|
|
newFilter.addEventListener('change', filterLogs);
|
|
}
|
|
if (searchInput) {
|
|
const newInput = searchInput.cloneNode(true);
|
|
searchInput.parentNode.replaceChild(newInput, searchInput);
|
|
newInput.addEventListener('input', filterLogs);
|
|
}
|
|
if (autoscrollToggle) {
|
|
const newToggle = autoscrollToggle.cloneNode(true);
|
|
autoscrollToggle.parentNode.replaceChild(newToggle, autoscrollToggle);
|
|
newToggle.addEventListener('change', toggleAutoscroll);
|
|
}
|
|
if (clearBtn) {
|
|
const newBtn = clearBtn.cloneNode(true);
|
|
clearBtn.parentNode.replaceChild(newBtn, clearBtn);
|
|
newBtn.addEventListener('click', clearLogs);
|
|
}
|
|
if (downloadBtn) {
|
|
const newBtn = downloadBtn.cloneNode(true);
|
|
downloadBtn.parentNode.replaceChild(newBtn, downloadBtn);
|
|
newBtn.addEventListener('click', downloadLogs);
|
|
}
|
|
const currentPluginFilterBtn = document.getElementById('current-plugin-filter-btn');
|
|
if (currentPluginFilterBtn) {
|
|
const newBtn = currentPluginFilterBtn.cloneNode(true);
|
|
currentPluginFilterBtn.parentNode.replaceChild(newBtn, currentPluginFilterBtn);
|
|
newBtn.addEventListener('click', function() {
|
|
const pluginFilterEl = document.getElementById('log-plugin-filter');
|
|
if (pluginFilterEl && window._currentPluginId) {
|
|
pluginFilterEl.value = window._currentPluginId;
|
|
filterLogs();
|
|
}
|
|
});
|
|
}
|
|
|
|
refreshCurrentPluginStatus();
|
|
if (window._currentPluginPollTimer) {
|
|
clearInterval(window._currentPluginPollTimer);
|
|
}
|
|
window._currentPluginPollTimer = setInterval(refreshCurrentPluginStatus, 5000);
|
|
|
|
// Handle window resize for responsive height
|
|
window.addEventListener('resize', function() {
|
|
if (window._logContainer) {
|
|
// Force a reflow to update sizing
|
|
window._logContainer.style.display = 'none';
|
|
window._logContainer.offsetHeight; // Trigger reflow
|
|
window._logContainer.style.display = '';
|
|
|
|
// Re-evaluate scroll position after resize
|
|
setTimeout(function() {
|
|
const distanceFromBottom = window._logContainer.scrollHeight - window._logContainer.scrollTop - window._logContainer.clientHeight;
|
|
window._isUserNearBottom = distanceFromBottom <= window._scrollThreshold;
|
|
}, 100);
|
|
}
|
|
});
|
|
})();
|
|
|
|
function initializeLogs() {
|
|
// Load initial logs
|
|
loadLogs();
|
|
|
|
// Setup SSE for real-time logs
|
|
setupRealtimeLogs();
|
|
|
|
// Setup auto-scroll
|
|
setupAutoscroll();
|
|
}
|
|
|
|
function loadLogs() {
|
|
showLoading();
|
|
|
|
fetch('/api/v3/logs')
|
|
.then(response => response.json())
|
|
.then(data => {
|
|
hideLoading();
|
|
|
|
if (data.status === 'success' && data.data && data.data.logs) {
|
|
processLogs(data.data.logs);
|
|
updateLogStats();
|
|
} else {
|
|
showEmptyState();
|
|
}
|
|
})
|
|
.catch(error => {
|
|
hideLoading();
|
|
showError('Failed to load logs: ' + error.message);
|
|
});
|
|
}
|
|
|
|
function setupRealtimeLogs() {
|
|
if (window._logsEventSource) {
|
|
window._logsEventSource.close();
|
|
}
|
|
|
|
window._logsEventSource = new EventSource('/api/v3/stream/logs');
|
|
|
|
window._logsEventSource.onopen = function() {
|
|
document.getElementById('log-connection-status').innerHTML = `
|
|
<div class="w-2 h-2 bg-green-500 rounded-full"></div>
|
|
<span>Connected to log stream</span>
|
|
`;
|
|
};
|
|
|
|
window._logsEventSource.onmessage = function(event) {
|
|
const data = JSON.parse(event.data);
|
|
|
|
if (data.logs && window._isRealtime) {
|
|
processLogs(data.logs, true);
|
|
updateLogStats();
|
|
|
|
// Use the new smart scroll function
|
|
scrollToBottomIfNeeded();
|
|
}
|
|
};
|
|
|
|
window._logsEventSource.onerror = function() {
|
|
document.getElementById('log-connection-status').innerHTML = `
|
|
<div class="w-2 h-2 bg-red-500 rounded-full"></div>
|
|
<span>Disconnected from log stream</span>
|
|
`;
|
|
|
|
// Attempt to reconnect after 5 seconds
|
|
setTimeout(setupRealtimeLogs, 5000);
|
|
};
|
|
}
|
|
|
|
function processLogs(logsText, append = false) {
|
|
if (!append) {
|
|
window._allLogs = [];
|
|
if (window._logsContent) {
|
|
window._logsContent.innerHTML = '';
|
|
}
|
|
|
|
// Container cleared for new logs
|
|
}
|
|
|
|
// Parse journalctl output
|
|
const lines = logsText.split('\n').filter(line => line.trim());
|
|
|
|
lines.forEach(line => {
|
|
// Skip empty lines
|
|
if (!line.trim()) return;
|
|
|
|
// journalctl (--output=short-iso) emits: "YYYY-MM-DDTHH:MM:SS+ZZZZ hostname service[pid]: message"
|
|
// Example: "2024-01-15T10:23:45+0000 raspberrypi ledmatrix[1234]: INFO - plugin.nhl_scoreboard - [Plugin: nhl_scoreboard] Updated scores"
|
|
// Also accept the older syslog-style "MMM DD HH:MM:SS" timestamp for compatibility.
|
|
|
|
let timestamp = '';
|
|
let level = 'INFO';
|
|
let message = line;
|
|
let plugin = '';
|
|
let rest = null;
|
|
|
|
const isoMatch = line.match(/^(\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(?:\.\d+)?(?:[+-]\d{2}:?\d{2}|Z))\s+(.*)$/);
|
|
const syslogMatch = !isoMatch && line.match(/^([A-Z][a-z]{2}\s+\d{1,2}\s+\d{2}:\d{2}:\d{2})\s+(.*)$/);
|
|
|
|
if (isoMatch) {
|
|
timestamp = isoMatch[1];
|
|
rest = isoMatch[2];
|
|
} else if (syslogMatch) {
|
|
timestamp = syslogMatch[1];
|
|
rest = syslogMatch[2];
|
|
} else {
|
|
// If no timestamp, use current time
|
|
timestamp = new Date().toLocaleString('en-US', {
|
|
month: 'short',
|
|
day: '2-digit',
|
|
hour: '2-digit',
|
|
minute: '2-digit',
|
|
second: '2-digit',
|
|
hour12: false
|
|
});
|
|
}
|
|
|
|
if (rest !== null) {
|
|
// Find the message part (after hostname + service name/pid)
|
|
const messageMatch = rest.match(/:\s*(.+)$/);
|
|
if (messageMatch) {
|
|
message = messageMatch[1];
|
|
|
|
// Detect log level from message
|
|
if (message.match(/\b(ERROR|CRITICAL|FATAL)\b/i)) {
|
|
level = 'ERROR';
|
|
} else if (message.match(/\b(WARNING|WARN)\b/i)) {
|
|
level = 'WARNING';
|
|
} else if (message.match(/\bDEBUG\b/i)) {
|
|
level = 'DEBUG';
|
|
} else if (message.match(/\bINFO\b/i)) {
|
|
level = 'INFO';
|
|
}
|
|
|
|
// Clean up level prefix from message if it exists
|
|
message = message.replace(/^(ERROR|WARNING|WARN|INFO|DEBUG)\s*[-:]\s*/i, '');
|
|
|
|
// journalctl already carries its own timestamp; strip the app's
|
|
// internal "YYYY-MM-DD HH:MM:SS.mmm - LEVEL - logger.name - "
|
|
// prefix (see ContextualFormatter in src/logging_config.py) so
|
|
// it isn't duplicated in the displayed message.
|
|
message = message.replace(
|
|
/^\d{4}-\d{2}-\d{2}\s+\d{2}:\d{2}:\d{2}(?:\.\d+)?\s*-\s*(ERROR|WARNING|WARN|INFO|DEBUG|CRITICAL)\s*-\s*[\w.]+\s*-\s*/i,
|
|
''
|
|
);
|
|
|
|
// Extract the "[Plugin: <id>]" context tag emitted by
|
|
// ContextualFormatter for every plugin logger (see
|
|
// src/logging_config.py PluginLoggerAdapter), and pull it out
|
|
// of the displayed message into its own field.
|
|
const pluginMatch = message.match(/^\[Plugin:\s*([^\]]+)\]\s*/);
|
|
if (pluginMatch) {
|
|
plugin = pluginMatch[1].trim();
|
|
message = message.replace(pluginMatch[0], '');
|
|
}
|
|
} else {
|
|
message = rest;
|
|
}
|
|
}
|
|
|
|
const logEntry = {
|
|
timestamp: timestamp,
|
|
level: level,
|
|
plugin: plugin,
|
|
message: message,
|
|
raw: line,
|
|
id: Date.now() + Math.random()
|
|
};
|
|
|
|
// Don't add duplicate entries when appending
|
|
if (!append || !window._allLogs.find(log => log.raw === line)) {
|
|
window._allLogs.push(logEntry);
|
|
}
|
|
});
|
|
|
|
// Trim logs if we exceed the maximum
|
|
if (window._allLogs.length > window._MAX_LOGS) {
|
|
window._allLogs = window._allLogs.slice(-window._MAX_LOGS);
|
|
}
|
|
|
|
updatePluginFilterOptions();
|
|
filterLogs();
|
|
}
|
|
|
|
function updatePluginFilterOptions() {
|
|
const pluginFilterEl = document.getElementById('log-plugin-filter');
|
|
if (!pluginFilterEl) return;
|
|
|
|
const previousValue = pluginFilterEl.value;
|
|
const plugins = Array.from(new Set(window._allLogs.map(log => log.plugin).filter(Boolean))).sort();
|
|
|
|
pluginFilterEl.innerHTML = '<option value="">All Plugins</option>' +
|
|
plugins.map(p => `<option value="${escapeHtml(p)}">${escapeHtml(p)}</option>`).join('');
|
|
|
|
// Restore previous selection if it's still a valid option
|
|
if (previousValue && plugins.includes(previousValue)) {
|
|
pluginFilterEl.value = previousValue;
|
|
}
|
|
}
|
|
|
|
function renderLogs() {
|
|
if (window._filteredLogs.length === 0) {
|
|
showEmptyState();
|
|
return;
|
|
}
|
|
|
|
showLogs();
|
|
|
|
if (window._logsContent) {
|
|
window._logsContent.innerHTML = '';
|
|
}
|
|
|
|
window._filteredLogs.forEach(log => {
|
|
const logElement = document.createElement('div');
|
|
logElement.className = `log-entry py-1 px-2 hover:bg-gray-800 rounded transition-colors duration-150 ${getLogLevelClass(log.level)}`;
|
|
const pluginBadge = log.plugin
|
|
? `<span class="log-plugin flex-shrink-0 px-2 py-0.5 rounded text-xs font-semibold bg-purple-700 text-white" title="Plugin: ${escapeHtml(log.plugin)}">${escapeHtml(log.plugin)}</span>`
|
|
: '';
|
|
logElement.innerHTML = `
|
|
<div class="flex items-start gap-3 text-xs font-mono">
|
|
<span class="log-timestamp text-gray-400 flex-shrink-0 w-32">${escapeHtml(log.timestamp)}</span>
|
|
<span class="log-level flex-shrink-0 px-2 py-0.5 rounded text-xs font-semibold ${getLogLevelBadgeClass(log.level)}">${log.level}</span>
|
|
${pluginBadge}
|
|
<span class="log-message flex-1 ${getLogLevelTextClass(log.level)} break-words">${escapeHtml(log.message)}</span>
|
|
</div>
|
|
`;
|
|
if (window._logsContent) {
|
|
window._logsContent.appendChild(logElement);
|
|
}
|
|
});
|
|
}
|
|
|
|
function getLogLevelClass(level) {
|
|
// Background color for the entire log entry row
|
|
const classes = {
|
|
'ERROR': 'log-level-error',
|
|
'WARNING': 'log-level-warning',
|
|
'INFO': '',
|
|
'DEBUG': 'log-level-debug'
|
|
};
|
|
return classes[level] || '';
|
|
}
|
|
|
|
function getLogLevelBadgeClass(level) {
|
|
const classes = {
|
|
'ERROR': 'bg-red-600 text-white',
|
|
'WARNING': 'bg-yellow-600 text-white',
|
|
'INFO': 'bg-blue-600 text-white',
|
|
'DEBUG': 'bg-gray-600 text-white'
|
|
};
|
|
return classes[level] || 'bg-gray-600 text-white';
|
|
}
|
|
|
|
function getLogLevelTextClass(level) {
|
|
const classes = {
|
|
'ERROR': 'text-red-300',
|
|
'WARNING': 'text-yellow-300',
|
|
'INFO': 'text-gray-200',
|
|
'DEBUG': 'text-gray-400'
|
|
};
|
|
return classes[level] || 'text-gray-300';
|
|
}
|
|
|
|
function filterLogs() {
|
|
const levelFilterEl = document.getElementById('log-level-filter');
|
|
const pluginFilterEl = document.getElementById('log-plugin-filter');
|
|
const searchEl = document.getElementById('log-search');
|
|
if (!levelFilterEl || !searchEl) return;
|
|
|
|
const levelFilter = levelFilterEl.value;
|
|
const pluginFilter = pluginFilterEl ? pluginFilterEl.value : '';
|
|
const searchTerm = searchEl.value.toLowerCase();
|
|
|
|
window._filteredLogs = window._allLogs.filter(log => {
|
|
// Level filter
|
|
if (levelFilter) {
|
|
const levels = {
|
|
'ERROR': ['ERROR'],
|
|
'WARNING': ['ERROR', 'WARNING'],
|
|
'INFO': ['ERROR', 'WARNING', 'INFO']
|
|
};
|
|
|
|
if (!levels[levelFilter].includes(log.level)) {
|
|
return false;
|
|
}
|
|
}
|
|
|
|
// Plugin filter
|
|
if (pluginFilter && log.plugin !== pluginFilter) {
|
|
return false;
|
|
}
|
|
|
|
// Search filter
|
|
if (searchTerm && !log.message.toLowerCase().includes(searchTerm) &&
|
|
!(log.plugin && log.plugin.toLowerCase().includes(searchTerm))) {
|
|
return false;
|
|
}
|
|
|
|
return true;
|
|
});
|
|
|
|
renderLogs();
|
|
updateLogStats();
|
|
}
|
|
|
|
function toggleRealtime() {
|
|
const toggleEl = document.getElementById('log-realtime-toggle');
|
|
if (!toggleEl) return;
|
|
|
|
window._isRealtime = toggleEl.checked;
|
|
|
|
if (window._isRealtime) {
|
|
setupRealtimeLogs();
|
|
} else if (window._logsEventSource) {
|
|
window._logsEventSource.close();
|
|
window._logsEventSource = null;
|
|
}
|
|
}
|
|
|
|
function refreshLogs() {
|
|
loadLogs();
|
|
if (typeof showNotification !== 'undefined') {
|
|
showNotification('Logs refreshed', 'success');
|
|
}
|
|
}
|
|
|
|
function clearLogs() {
|
|
window._allLogs = [];
|
|
window._filteredLogs = [];
|
|
if (window._logsContent) {
|
|
window._logsContent.innerHTML = '';
|
|
}
|
|
showEmptyState();
|
|
updateLogStats();
|
|
if (typeof showNotification !== 'undefined') {
|
|
showNotification('Logs cleared', 'info');
|
|
}
|
|
}
|
|
|
|
function downloadLogs() {
|
|
if (window._filteredLogs.length === 0) {
|
|
if (typeof showNotification !== 'undefined') {
|
|
showNotification('No logs to download', 'warning');
|
|
}
|
|
return;
|
|
}
|
|
|
|
const logText = window._filteredLogs.map(log => log.raw).join('\n');
|
|
const blob = new Blob([logText], { type: 'text/plain' });
|
|
const url = URL.createObjectURL(blob);
|
|
|
|
const a = document.createElement('a');
|
|
a.href = url;
|
|
a.download = `ledmatrix-logs-${new Date().toISOString().slice(0, 19)}.txt`;
|
|
document.body.appendChild(a);
|
|
a.click();
|
|
document.body.removeChild(a);
|
|
URL.revokeObjectURL(url);
|
|
|
|
if (typeof showNotification !== 'undefined') {
|
|
showNotification('Logs downloaded', 'success');
|
|
}
|
|
}
|
|
|
|
// Track if user is near bottom for smart auto-scroll
|
|
if (typeof window._isUserNearBottom === 'undefined') {
|
|
window._isUserNearBottom = true;
|
|
}
|
|
if (typeof window._scrollThreshold === 'undefined') {
|
|
window._scrollThreshold = 100; // pixels from bottom to consider "near bottom"
|
|
}
|
|
|
|
function setupAutoscroll() {
|
|
if (!window._logsContent) return;
|
|
|
|
const observer = new MutationObserver(function() {
|
|
// Use requestAnimationFrame for better timing
|
|
requestAnimationFrame(scrollToBottomIfNeeded);
|
|
});
|
|
observer.observe(window._logsContent, { childList: true });
|
|
|
|
// Also listen for manual scroll events to detect when user is not at bottom
|
|
if (window._logContainer) {
|
|
window._logContainer.addEventListener('scroll', function() {
|
|
const distanceFromBottom = window._logContainer.scrollHeight - window._logContainer.scrollTop - window._logContainer.clientHeight;
|
|
window._isUserNearBottom = distanceFromBottom <= window._scrollThreshold;
|
|
});
|
|
}
|
|
}
|
|
|
|
function scrollToBottomIfNeeded() {
|
|
const autoscrollEl = document.getElementById('log-autoscroll');
|
|
if (autoscrollEl && autoscrollEl.checked && window._logContainer && window._isUserNearBottom) {
|
|
// Use requestAnimationFrame for smooth scrolling
|
|
requestAnimationFrame(function() {
|
|
// Remember current scroll position
|
|
const previousScrollHeight = window._logContainer.scrollHeight;
|
|
|
|
// Scroll to bottom
|
|
window._logContainer.scrollTop = window._logContainer.scrollHeight;
|
|
|
|
// Ensure we're actually at the bottom after a brief delay
|
|
setTimeout(function() {
|
|
if (window._logContainer.scrollTop + window._logContainer.clientHeight >= window._logContainer.scrollHeight - 10) {
|
|
window._isUserNearBottom = true;
|
|
}
|
|
}, 50);
|
|
});
|
|
}
|
|
}
|
|
|
|
function scrollToBottom() {
|
|
// Legacy function for backward compatibility
|
|
if (window._logContainer) {
|
|
window._logContainer.scrollTop = window._logContainer.scrollHeight;
|
|
window._isUserNearBottom = true;
|
|
}
|
|
}
|
|
|
|
function toggleAutoscroll() {
|
|
const autoscrollEl = document.getElementById('log-autoscroll');
|
|
if (!autoscrollEl || !autoscrollEl.checked) {
|
|
// Don't auto-scroll if unchecked or element doesn't exist
|
|
window._isUserNearBottom = false;
|
|
return;
|
|
}
|
|
|
|
// Scroll to bottom when re-enabled and user was near bottom
|
|
if (window._isUserNearBottom) {
|
|
scrollToBottom();
|
|
}
|
|
}
|
|
|
|
function updateLogStats() {
|
|
const stats = document.getElementById('log-stats');
|
|
const count = document.getElementById('log-count');
|
|
|
|
if (stats && count) {
|
|
count.textContent = window._filteredLogs.length;
|
|
stats.classList.remove('hidden');
|
|
}
|
|
}
|
|
|
|
function showLoading() {
|
|
document.getElementById('logs-loading').classList.remove('hidden');
|
|
document.getElementById('logs-display').classList.add('hidden');
|
|
document.getElementById('logs-empty').classList.add('hidden');
|
|
}
|
|
|
|
function showLogs() {
|
|
document.getElementById('logs-loading').classList.add('hidden');
|
|
document.getElementById('logs-display').classList.remove('hidden');
|
|
document.getElementById('logs-empty').classList.add('hidden');
|
|
}
|
|
|
|
function hideLoading() {
|
|
document.getElementById('logs-loading').classList.add('hidden');
|
|
}
|
|
|
|
function showEmptyState() {
|
|
document.getElementById('logs-loading').classList.add('hidden');
|
|
document.getElementById('logs-display').classList.add('hidden');
|
|
document.getElementById('logs-empty').classList.remove('hidden');
|
|
document.getElementById('log-stats').classList.add('hidden');
|
|
}
|
|
|
|
function showError(message) {
|
|
if (window._logsContent) {
|
|
window._logsContent.innerHTML = `<div class="text-red-400 p-4">${escapeHtml(message)}</div>`;
|
|
window._logsContent.classList.remove('hidden');
|
|
}
|
|
}
|
|
|
|
// Utility function to escape HTML. Quotes too: the result is interpolated into
|
|
// quoted attribute values (option value=, title=), and the
|
|
// textContent/innerHTML round-trip only escapes &, < and >.
|
|
function escapeHtml(text) {
|
|
const div = document.createElement('div');
|
|
div.textContent = text;
|
|
return div.innerHTML
|
|
.replace(/"/g, '"')
|
|
.replace(/'/g, ''');
|
|
}
|
|
|
|
function refreshCurrentPluginStatus() {
|
|
fetch('/api/v3/display/current-status')
|
|
.then(response => response.json())
|
|
.then(data => {
|
|
if (data.status !== 'success' || !data.data) return;
|
|
const state = data.data;
|
|
const banner = document.getElementById('current-plugin-banner');
|
|
const modeEl = document.getElementById('current-plugin-mode');
|
|
const idWrap = document.getElementById('current-plugin-id-wrap');
|
|
const idEl = document.getElementById('current-plugin-id');
|
|
const filterBtn = document.getElementById('current-plugin-filter-btn');
|
|
if (!banner || !modeEl) return;
|
|
|
|
window._currentPluginId = state.plugin_id || null;
|
|
|
|
modeEl.textContent = state.mode || 'unknown';
|
|
if (state.plugin_id) {
|
|
idEl.textContent = state.plugin_id;
|
|
idWrap.classList.remove('hidden');
|
|
if (filterBtn) filterBtn.classList.remove('hidden');
|
|
} else {
|
|
idWrap.classList.add('hidden');
|
|
if (filterBtn) filterBtn.classList.add('hidden');
|
|
}
|
|
banner.classList.remove('hidden');
|
|
})
|
|
.catch(() => {
|
|
// Silently ignore - banner just stays hidden/stale
|
|
});
|
|
}
|
|
|
|
// Cleanup on page unload
|
|
window.addEventListener('beforeunload', function() {
|
|
if (window._logsEventSource) {
|
|
window._logsEventSource.close();
|
|
}
|
|
if (window._currentPluginPollTimer) {
|
|
clearInterval(window._currentPluginPollTimer);
|
|
window._currentPluginPollTimer = null;
|
|
}
|
|
});
|
|
</script>
|