mirror of
https://github.com/ChuckBuilds/LEDMatrix.git
synced 2026-08-01 16:58:06 +00:00
fix(web): address CodeRabbit review — validation, a11y, perf, and privacy fixes
Verified each finding against current code. Fixed: - api_v3: plugin_rotation_order is now strictly validated (JSON list of strings, 400 with a descriptive message otherwise) and popped from the payload before any further handling. - display_controller: _apply_plugin_rotation_order defensively ignores a non-list value (keeps the existing rotation, logs a warning) and drops non-string entries; new logs carry the [DisplayController] prefix. Unit-tested both defensive paths. - app.py: snapshot-read handler narrowed to OSError with debug logging; flask-compress ImportError now emits one structured warning with the install remedy. - htmx-config: the response-error logger prints form FIELD NAMES only - values (API keys, passwords) never reach the console. - plugin-order-list: saved order/exclusions normalized with Array.isArray (a saved "null" previously crashed .forEach); each row gained keyboard/touch-accessible move-up/move-down buttons (HTML5 drag events don't fire on most mobile browsers) that reorder and syncInputs() immediately alongside native drag. - app-shell: window.installedPlugins setter always takes the new list (same-ID metadata/enabled updates were silently dropped); tab rebuild stays gated on ID changes. LED dot renderer reads the frame with ONE getImageData call instead of one per pixel (~9,200/frame at 192x48). - plugins_manager: togglePlugin returns its request promise resolving the API outcome; the install flow now shows the "installed and enabled" toast (with Restart Now) only after enablement succeeds, and a warning without a restart offer when it fails. - a11y: hamburger aria-label flips Open/Close with drawer state; both Advanced-section toggle buttons declare aria-controls/aria-expanded and the shared toggleSection() keeps aria-expanded in sync; move buttons have per-plugin aria-labels. - Rotation/Vegas order-list bootstraps cap their retries (~5s) and show a reload hint instead of spinning forever; Alpine app-state lookups prefer [x-data="app()"] with a generic fallback. Skipped, with reasons: - executePluginAction arg order: caller (plugin_config.html) already passes (actionId, index, pluginId) matching the signature exactly. - generateFieldHtml XSS, entity-unescape blocks, dotToNested pollution, and "app.loadInstalledPlugins" in app-shell: all inside the legacy client-side config cluster whose entry points are shadowed by plugins_manager.js / replaced by server-rendered forms (zero live callers, verified) - queued for wholesale deletion in the follow-up rather than patching dead code. - custom-feeds-helpers.js findings (3): file was deleted in a prior commit. - console.error/warn override removal and afterSwap script re-execution removal: deliberate pre-existing workarounds every partial's inline init currently depends on; reworking them safely needs isolated testing (follow-up), and the error suppression is already double-gated (insertBefore AND htmx match). - "move durations bootstrap into a bundle": inline partial-scoped init is the established pattern for HTMX partials in this codebase. Validation: all 40 web tests pass; py_compile on all touched Python; all touched templates parse; rotation-order defensive paths unit-tested. Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01KEZK1P1Q1fu5pcuVrkrCFZ
This commit is contained in:
co-authored by
Claude Sonnet 5
parent
aec1368d63
commit
8044084280
@@ -395,7 +395,7 @@ window.updateFloatingPreviewVisibility = function(tab) {
|
||||
if (!panel || !toggle) return;
|
||||
let active = tab;
|
||||
if (!active) {
|
||||
const el = document.querySelector('[x-data]');
|
||||
const el = document.querySelector('[x-data="app()"]') || document.querySelector('[x-data]');
|
||||
const data = el && el._x_dataStack && el._x_dataStack[0];
|
||||
active = data && data.activeTab;
|
||||
}
|
||||
@@ -449,7 +449,7 @@ window.updateNavAriaCurrent = function(tab) {
|
||||
// opening the drawer moves focus to its first tab.
|
||||
(function() {
|
||||
function appData() {
|
||||
const el = document.querySelector('[x-data]');
|
||||
const el = document.querySelector('[x-data="app()"]') || document.querySelector('[x-data]');
|
||||
return el && el._x_dataStack && el._x_dataStack[0];
|
||||
}
|
||||
document.addEventListener('keydown', function(e) {
|
||||
|
||||
@@ -361,12 +361,15 @@
|
||||
const newPlugins = value || [];
|
||||
const oldIds = (_installedPluginsValue || []).map(p => p.id).sort().join(',');
|
||||
const newIds = newPlugins.map(p => p.id).sort().join(',');
|
||||
|
||||
// Only update if plugin list actually changed
|
||||
|
||||
// Always take the new list — same-ID updates
|
||||
// still carry changed metadata/enabled state.
|
||||
_installedPluginsValue = newPlugins;
|
||||
this.installedPlugins = newPlugins;
|
||||
// Only rebuild the tab row when the ID set
|
||||
// actually changed.
|
||||
if (oldIds !== newIds) {
|
||||
debugLog('window.installedPlugins changed:', newPlugins.length, 'plugins');
|
||||
_installedPluginsValue = newPlugins;
|
||||
this.installedPlugins = newPlugins;
|
||||
this.updatePluginTabs();
|
||||
}
|
||||
},
|
||||
@@ -1983,12 +1986,23 @@
|
||||
ctx.fillStyle = 'rgb(0, 0, 0)';
|
||||
ctx.fillRect(0, 0, ledCanvas.width, ledCanvas.height);
|
||||
|
||||
// Read the whole frame once instead of one getImageData call per
|
||||
// pixel (a 192x48 panel would otherwise issue ~9,200 calls per
|
||||
// frame — noticeably heavy on phones).
|
||||
let frame;
|
||||
try {
|
||||
frame = offCtx.getImageData(0, 0, logicalWidth, logicalHeight).data;
|
||||
} catch (e) {
|
||||
console.error('Failed to read offscreen canvas pixels:', e);
|
||||
return;
|
||||
}
|
||||
|
||||
// Draw circular dots for each LED pixel
|
||||
let drawn = 0;
|
||||
for (let y = 0; y < logicalHeight; y++) {
|
||||
for (let x = 0; x < logicalWidth; x++) {
|
||||
const pixel = offCtx.getImageData(x, y, 1, 1).data;
|
||||
const r = pixel[0], g = pixel[1], b = pixel[2], a = pixel[3];
|
||||
const i = (y * logicalWidth + x) * 4;
|
||||
const r = frame[i], g = frame[i + 1], b = frame[i + 2], a = frame[i + 3];
|
||||
|
||||
// Skip fully transparent or black pixels to reduce overdraw
|
||||
if (a === 0 || (r|g|b) === 0) continue;
|
||||
|
||||
@@ -130,14 +130,16 @@
|
||||
responseText: xhr?.responseText
|
||||
});
|
||||
|
||||
// For form submissions, log the form data
|
||||
// For form submissions, log field names only — values
|
||||
// may contain API keys, passwords, or other secrets
|
||||
// that must never reach the console.
|
||||
if (target && target.tagName === 'FORM') {
|
||||
const formData = new FormData(target);
|
||||
const formPayload = Object.create(null);
|
||||
for (const [key, value] of formData.entries()) {
|
||||
formPayload[key] = value;
|
||||
const fieldNames = [];
|
||||
for (const [key] of formData.entries()) {
|
||||
fieldNames.push(key);
|
||||
}
|
||||
console.error('Form payload:', formPayload);
|
||||
console.error('Form fields (values redacted):', fieldNames);
|
||||
|
||||
// Try to parse error response for validation details
|
||||
if (xhr?.responseText) {
|
||||
@@ -243,5 +245,12 @@
|
||||
icon.classList.remove('fa-chevron-down');
|
||||
icon.classList.add('fa-chevron-right');
|
||||
}
|
||||
|
||||
// Keep assistive tech in sync: any toggle button that declares
|
||||
// aria-controls for this section mirrors the expanded state.
|
||||
const controlBtn = document.querySelector(`[aria-controls="${sectionId}"]`);
|
||||
if (controlBtn) {
|
||||
controlBtn.setAttribute('aria-expanded', String(isHidden));
|
||||
}
|
||||
};
|
||||
})();
|
||||
|
||||
@@ -115,6 +115,10 @@
|
||||
} catch (e) {
|
||||
console.error('Error parsing saved plugin order:', e);
|
||||
}
|
||||
// JSON.parse can succeed and still return null/objects
|
||||
// (e.g. a saved value of "null"); normalize to arrays.
|
||||
if (!Array.isArray(currentOrder)) currentOrder = [];
|
||||
if (!Array.isArray(excluded)) excluded = [];
|
||||
|
||||
// Saved order first, then any newly enabled plugins.
|
||||
const orderedPlugins = [];
|
||||
@@ -173,6 +177,31 @@
|
||||
row.appendChild(badge);
|
||||
}
|
||||
|
||||
// Up/down buttons: touch- and keyboard-accessible
|
||||
// reordering alongside native drag-and-drop (HTML5 drag
|
||||
// events don't fire on most mobile browsers).
|
||||
const pluginLabel = plugin.name || plugin.id;
|
||||
[['up', 'fa-chevron-up', `Move ${pluginLabel} up`],
|
||||
['down', 'fa-chevron-down', `Move ${pluginLabel} down`]].forEach(([dir, iconCls, ariaLabel]) => {
|
||||
const moveBtn = document.createElement('button');
|
||||
moveBtn.type = 'button';
|
||||
moveBtn.className = 'plugin-order-move text-gray-400 hover:text-gray-700 px-2 py-1';
|
||||
moveBtn.setAttribute('aria-label', ariaLabel);
|
||||
const moveIcon = document.createElement('i');
|
||||
moveIcon.className = `fas ${iconCls} text-xs`;
|
||||
moveBtn.appendChild(moveIcon);
|
||||
moveBtn.addEventListener('click', function() {
|
||||
if (dir === 'up' && row.previousElementSibling) {
|
||||
container.insertBefore(row, row.previousElementSibling);
|
||||
} else if (dir === 'down' && row.nextElementSibling) {
|
||||
container.insertBefore(row.nextElementSibling, row);
|
||||
}
|
||||
syncInputs();
|
||||
moveBtn.focus();
|
||||
});
|
||||
row.appendChild(moveBtn);
|
||||
});
|
||||
|
||||
container.appendChild(row);
|
||||
});
|
||||
|
||||
|
||||
@@ -317,7 +317,7 @@ window.togglePlugin = window.togglePlugin || function(pluginId, enabled) {
|
||||
showNotification(`${action.charAt(0).toUpperCase() + action.slice(1)} ${pluginName}...`, 'info');
|
||||
}
|
||||
|
||||
fetch('/api/v3/plugins/toggle', {
|
||||
return fetch('/api/v3/plugins/toggle', {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ plugin_id: pluginId, enabled: enabled })
|
||||
@@ -361,6 +361,9 @@ window.togglePlugin = window.togglePlugin || function(pluginId, enabled) {
|
||||
if (wrapperDiv) {
|
||||
wrapperDiv.classList.remove('opacity-50', 'pointer-events-none');
|
||||
}
|
||||
// Resolve the outcome so callers (e.g. the install flow) can chain
|
||||
// on whether enabling actually succeeded.
|
||||
return data;
|
||||
})
|
||||
.catch(error => {
|
||||
// Verify this error is for the latest request (prevent race conditions)
|
||||
@@ -3889,19 +3892,27 @@ window.installPlugin = function(pluginId, branch = null) {
|
||||
.then(data => {
|
||||
showNotification(data.message, data.status);
|
||||
if (data.status === 'success') {
|
||||
// Enable immediately so install -> enable is one step, then nudge
|
||||
// for the display restart that's needed before it shows on the
|
||||
// matrix (persistent toast; duration 0 = stays until dismissed).
|
||||
window.togglePlugin(pluginId, true);
|
||||
showNotification(
|
||||
`${pluginId} installed and enabled — restart the display to show it`,
|
||||
{
|
||||
type: 'success',
|
||||
duration: 0,
|
||||
actionLabel: 'Restart Now',
|
||||
onAction: () => restartDisplay()
|
||||
// Enable immediately so install -> enable is one step; only nudge
|
||||
// for a restart once enablement actually succeeded (persistent
|
||||
// toast; duration 0 = stays until dismissed).
|
||||
Promise.resolve(window.togglePlugin(pluginId, true)).then(toggleResult => {
|
||||
if (toggleResult && toggleResult.status === 'success') {
|
||||
showNotification(
|
||||
`${pluginId} installed and enabled — restart the display to show it`,
|
||||
{
|
||||
type: 'success',
|
||||
duration: 0,
|
||||
actionLabel: 'Restart Now',
|
||||
onAction: () => restartDisplay()
|
||||
}
|
||||
);
|
||||
} else {
|
||||
showNotification(
|
||||
`${pluginId} installed, but enabling it failed — use its toggle in the plugin list`,
|
||||
'warning'
|
||||
);
|
||||
}
|
||||
);
|
||||
});
|
||||
// Refresh installed plugins list, then re-render store to update badges
|
||||
loadInstalledPlugins();
|
||||
setTimeout(() => applyStoreFiltersAndSort(true), 500);
|
||||
|
||||
Reference in New Issue
Block a user