Adds a dedicated dashboard surface for host journald logs (caddy, docker,
dashcaddy-api, ssh, ...) via a read-only bind-mount of /var/log/journal +
journalctl. Closes queue item #2: the only way to see the recurring
'100.120.159.34:5000 i/o timeout' spam in Caddy's health_checker logs was
SSH into DNS2.
Backend (dashcaddy-api/):
- src/monitoring/journald-reader.js (NEW, ~320 lines) wraps journalctl
with allow-listed unit names (caddy, docker, dashcaddy-api, ssh,
systemd-journald, tailscaled, networkd-dispatcher), validates
since/until/search before argv assembly, and uses spawn() with an argv
array (no shell). Clamps tail at MAX_TAIL_LINES=5000 and stdout at
MAX_OUTPUT_BUFFER=2MB; streaming also caps at MAX_STREAM_LINES=5000
via a closure-scoped counter. Maps ENOENT cleanly to 'journalctl
unavailable'.
- routes/logs.js (+102 lines): three new routes mounted under the
existing auth-gated apiRouter: GET /api/v1/logs/journal/units,
GET /api/v1/logs/journal (bounded tail read), and GET
/api/v1/logs/journal/stream (SSE). Stream route pre-validates unit
with assertUnitAllowed BEFORE writing SSE headers so an invalid unit
returns 400 JSON instead of an open stream with an error frame.
- 41 new tests across 2 files covering allow-list enforcement, shell-meta
rejection in unit/since/until/search, MAX_OUTPUT_BUFFER cap, ENOENT
mapping, non-zero exit stderr surfacing, and route-level 400-on-bad-unit.
Full local suite 1831/1831 (+41 net).
Container plumbing (start.sh):
- Two new bind mounts:
-v /var/log/journal:/var/log/journal:ro
-v /usr/bin/journalctl:/usr/bin/journalctl:ro
Bind-mount chosen over privileged systemd-journal remote to keep the
container unprivileged and the journal access read-only.
Frontend (status/js/):
- journald.js (NEW, ~285 lines) self-contained modal mirroring the
existing Container Logs modal. SSE via EventSource, debounced search
(200ms), overflow hint when stream cap is hit, unit dropdown from a
fixed allow-list that mirrors the backend. Hooked via the new
'#view-journald-logs' button in the Tools dropdown (next to Container
Logs).
- build.js (+4 lines) adds journald.js to the features bundle. Bundle
rebuild succeeded (features.js 27 files, 466 KB raw / 1229 KB min).
CSP hash unchanged (no inline script changes).
GLM judge (round 1, 178s, 14 tool calls, cold diff + 8 file reads):
GRADE=B. Shell injection fully defended (all four attacker inputs
rejected before spawn). Route-level allow-list holds (streamEntries not
called for bad unit). SSE cleanup correct. Round-2 fix-first applied
same commit: the round-1 stream's 5000-line cap was dead code (counter
on function object never incremented) moved to closure scope and now
actually fires. Also dropped deprecated req.on('aborted') listener
(Node 18+ fires 'close' for both clean and abort).
Container live HEAD 901df86 [glm-grade=B]; deploy via start.sh atomic
swap. Live verify: status.sami=200, container Up + healthy, the new
bundle and index.html served.
233 lines
8.4 KiB
JavaScript
233 lines
8.4 KiB
JavaScript
const fs = require('fs');
|
|
const path = require('path');
|
|
const crypto = require('crypto');
|
|
const esbuild = require('esbuild');
|
|
|
|
const JS = (...parts) => path.join(__dirname, 'js', ...parts);
|
|
const DIST = path.join(__dirname, 'dist');
|
|
const INDEX_HTML = path.join(__dirname, 'index.html');
|
|
const SW_JS = path.join(__dirname, 'sw.js');
|
|
|
|
// Bundle definitions — files are concatenated in order, then minified
|
|
const bundles = {
|
|
'core.js': [
|
|
// error-handler.js MUST be first — globals.js below does
|
|
// `const errorHandler = new ErrorHandler()` at top level, which throws
|
|
// ReferenceError if the ErrorHandler class isn't already on `window`.
|
|
JS('error-handler.js'),
|
|
JS('globals.js'),
|
|
JS('skeleton-loader.js'),
|
|
JS('theme.js'),
|
|
// DC-049: pluggable auth gate — claims ownership of the
|
|
// ?auth=required flow by setting window.__dc_049_handled BEFORE
|
|
// totp-auth.js runs, so the legacy TOTP-only overlay doesn't flicker
|
|
// in for multi-provider installs. Single-provider TOTP-only installs
|
|
// work because this module delegates back to window._showTotpOverlay().
|
|
JS('auth-gate.js'),
|
|
JS('totp-auth.js'),
|
|
// totp-recovery.js registers window._refreshRecoveryLink which totp-auth.js
|
|
// calls from showTotpOverlay(). Must come after totp-auth.js.
|
|
JS('totp-recovery.js'),
|
|
JS('service-credentials.js'),
|
|
JS('totp-settings.js'),
|
|
// DC-048 admin panel — modal-overlay UI for user/invite management.
|
|
// Renders the "Admin" trigger button into the top bar; only visible
|
|
// when /api/v1/auth/me returns isAdmin=true.
|
|
JS('admin.js'),
|
|
JS('core', 'credentials.js'),
|
|
JS('core', 'grid.js'),
|
|
JS('core', 'dns.js'),
|
|
JS('core', 'logs.js'),
|
|
JS('core', 'service-modals.js'),
|
|
JS('core', 'service-infrastructure.js'),
|
|
JS('core', 'service-crud.js'),
|
|
JS('core', 'service-create.js'),
|
|
JS('live-events.js'),
|
|
JS('service-filter.js'),
|
|
JS('batch-operations.js'),
|
|
],
|
|
'features.js': [
|
|
JS('logo-customization.js'),
|
|
JS('setup-wizard.js'),
|
|
JS('app-selector.js'),
|
|
JS('recipes.js'),
|
|
JS('import-export.js'),
|
|
JS('error-logs.js'),
|
|
JS('container-logs.js'),
|
|
// DC-055: Host journald log viewer — reads /var/log/journal via the
|
|
// bind-mount added in start.sh. Self-contained modal with SSE stream
|
|
// + bounded tail read. Exposes window.openJournaldModal().
|
|
JS('journald.js'),
|
|
JS('snapshot.js'),
|
|
JS('smart-arr-connect.js'),
|
|
JS('notification-settings.js'),
|
|
JS('panel-tabs.js'),
|
|
JS('backup-restore.js'),
|
|
JS('resource-monitor.js'),
|
|
JS('health-check.js'),
|
|
JS('update-management.js'),
|
|
JS('docker-resources.js'),
|
|
JS('compose-import.js'),
|
|
JS('container-exec.js'),
|
|
JS('audit-log.js'),
|
|
JS('security-center.js'),
|
|
JS('weather.js'),
|
|
JS('clock.js'),
|
|
JS('card-badges.js'),
|
|
JS('theme-builder.js'),
|
|
JS('license.js'),
|
|
// DC-058: Share modal — opened from the share button on each service card.
|
|
// Must come after license.js because it uses window.openShareModal and
|
|
// window.wireModal + window.injectModal + window.escapeHtml helpers
|
|
// defined in globals.js (already in core.js).
|
|
JS('share-modal.js'),
|
|
],
|
|
'onboarding.js': [
|
|
JS('driver.min.js'),
|
|
// error-handler.js moved to core.js bundle; window.ErrorHandler is already
|
|
// set before this bundle runs.
|
|
JS('progress-tracker.js'),
|
|
JS('theme-adapter.js'),
|
|
JS('tooltip-definitions.js'),
|
|
JS('dns-template-selector.js'),
|
|
JS('tour-manager.js'),
|
|
JS('onboarding.js'),
|
|
],
|
|
'init.js': [
|
|
JS('core', 'init.js'),
|
|
JS('monitoring-widgets.js'),
|
|
JS('keyboard-shortcuts.js'),
|
|
],
|
|
};
|
|
|
|
function updateInlineScriptCspHash() {
|
|
const html = fs.readFileSync(INDEX_HTML, 'utf8');
|
|
// The hash MUST match what the browser computes from the served bytes.
|
|
// git's text normalization + tar transport strip CRLF on the Linux side,
|
|
// so the deployed file is always LF-only — even when the dev copy is CRLF
|
|
// (e.g. cloned on Windows). Normalize before hashing so a Windows-built
|
|
// index.html produces a CSP allowlist that matches the served LF version.
|
|
const normalized = html.replace(/\r\n/g, '\n');
|
|
const scripts = [...normalized.matchAll(/<script>([\s\S]*?)<\/script>/g)];
|
|
const target = scripts.find(match => {
|
|
const block = match[1] || '';
|
|
return block.includes("license-topbar-version") || block.includes("openVersionInfo") || block.includes("widget-");
|
|
});
|
|
|
|
if (!target) {
|
|
throw new Error('Could not find inline dashboard bootstrap script in index.html');
|
|
}
|
|
|
|
const scriptContent = target[1];
|
|
const hash = crypto.createHash('sha256').update(scriptContent).digest('base64');
|
|
// Write the CSP update back into the original (possibly CRLF) file so we
|
|
// don't churn the working copy's line endings just because we read it.
|
|
const updatedHtml = html.replace(
|
|
/script-src 'self' 'sha256-[^']+';/,
|
|
`script-src 'self' 'sha256-${hash}';`
|
|
);
|
|
|
|
if (updatedHtml !== html) {
|
|
fs.writeFileSync(INDEX_HTML, updatedHtml);
|
|
}
|
|
|
|
return hash;
|
|
}
|
|
|
|
async function build() {
|
|
// Ensure dist/ exists
|
|
if (!fs.existsSync(DIST)) fs.mkdirSync(DIST);
|
|
|
|
const results = {};
|
|
|
|
for (const [outName, files] of Object.entries(bundles)) {
|
|
// Read and concatenate
|
|
const parts = [];
|
|
for (const file of files) {
|
|
if (!fs.existsSync(file)) {
|
|
console.warn(` WARN: ${path.relative(__dirname, file)} not found, skipping`);
|
|
continue;
|
|
}
|
|
parts.push(fs.readFileSync(file, 'utf8'));
|
|
}
|
|
const concatenated = parts.join(';\n');
|
|
|
|
// Minify with esbuild (safe to re-minify already-minified code like driver.min.js)
|
|
// DC-072: sourcemap='both' emits inline + external .map for production debugging
|
|
const { code, map } = await esbuild.transform(concatenated, {
|
|
minify: true,
|
|
target: 'es2020',
|
|
sourcemap: 'both',
|
|
});
|
|
|
|
const outPath = path.join(DIST, outName);
|
|
fs.writeFileSync(outPath, code);
|
|
if (map) {
|
|
fs.writeFileSync(outPath + '.map', map);
|
|
}
|
|
|
|
const rawSize = (Buffer.byteLength(concatenated) / 1024).toFixed(1);
|
|
const minSize = (Buffer.byteLength(code) / 1024).toFixed(1);
|
|
results[outName] = { rawSize, minSize, fileCount: files.length };
|
|
}
|
|
|
|
const cspHash = updateInlineScriptCspHash();
|
|
const cacheTag = updateServiceWorkerCache();
|
|
|
|
// Summary
|
|
console.log('\n DashCaddy Frontend Build\n');
|
|
console.log(' Bundle Files Raw Min');
|
|
console.log(' ─────────────────────────────────────────');
|
|
let totalRaw = 0, totalMin = 0;
|
|
for (const [name, r] of Object.entries(results)) {
|
|
console.log(` ${name.padEnd(18)} ${String(r.fileCount).padStart(3)} ${r.rawSize.padStart(6)} KB ${r.minSize.padStart(6)} KB`);
|
|
totalRaw += parseFloat(r.rawSize);
|
|
totalMin += parseFloat(r.minSize);
|
|
}
|
|
console.log(' ─────────────────────────────────────────');
|
|
console.log(` ${'Total'.padEnd(18)} ${totalRaw.toFixed(1).padStart(6)} KB ${totalMin.toFixed(1).padStart(6)} KB`);
|
|
console.log(`\n Output: ${DIST}`);
|
|
console.log(` CSP Hash: sha256-${cspHash}`);
|
|
console.log(` SW Cache: dashcaddy-shell-${cacheTag}\n`);
|
|
}
|
|
|
|
// Rewrites the CACHE constant in sw.js to a tag derived from the bundle
|
|
// contents. Every change in dist/ produces a new cache name; on next load
|
|
// the SW's activate handler wipes all older caches, so users never get
|
|
// stuck on stale precached bundles after a release.
|
|
function updateServiceWorkerCache() {
|
|
const sw = fs.readFileSync(SW_JS, 'utf8');
|
|
const hash = crypto.createHash('sha256');
|
|
for (const name of Object.keys(bundles)) {
|
|
hash.update(fs.readFileSync(path.join(DIST, name)));
|
|
}
|
|
const tag = hash.digest('hex').slice(0, 10);
|
|
const updated = sw.replace(
|
|
/const CACHE = 'dashcaddy-shell-[^']+';/,
|
|
`const CACHE = 'dashcaddy-shell-${tag}';`
|
|
);
|
|
if (updated !== sw) {
|
|
fs.writeFileSync(SW_JS, updated);
|
|
}
|
|
return tag;
|
|
}
|
|
|
|
// Watch mode
|
|
if (process.argv.includes('--watch')) {
|
|
console.log(' Watching for changes...\n');
|
|
build();
|
|
|
|
const jsDir = path.join(__dirname, 'js');
|
|
let debounce = null;
|
|
fs.watch(jsDir, { recursive: true }, (event, filename) => {
|
|
if (!filename || !filename.endsWith('.js')) return;
|
|
clearTimeout(debounce);
|
|
debounce = setTimeout(() => {
|
|
console.log(` Changed: ${filename}`);
|
|
build();
|
|
}, 200);
|
|
});
|
|
} else {
|
|
build();
|
|
}
|