Adds the server/app half of a remote-diagnostics system so Claude (via a local MCP gateway, added separately) can read a server's full state to diagnose problems: logs, errors, queue/app state, redacted config, system health. All read-only; security review folded in as hard requirements. Architecture (design-verified): - A SECOND, independent RemoteServer instance (diagnosticMode) on its own port (default 9110, bind 127.0.0.1) with NO capture/input callbacks, so screen capture and sendInputEvent are structurally unreachable from the diagnostic path. The existing screen-share server (port 9100) is byte-for-byte unchanged. - lib/remote-server.js: a `host` bind option, a post-auth `diag-request` branch that delegates to onDiagnosticRequest and replies with a reqId-correlated `diag-response`, a `diagnosticMode` guard (capture never spawns), a timing-safe token compare (length-guarded), and getLastAccess(). - lib/diagnostics-agent.js: handle(op,args) enforces a HARDCODED read-only op whitelist as the sole authority — no write/exec op, no run_health_check. - lib/diagnostics-collectors.js: pure, dependency-injected collectors (server_health one-shot hub, read_log, list_errors, get_queue_state, get_history, get_config_redacted, get_system_info, list_logs, get_app_events, get_rotation_state, get_health) reusing support-bundle + stats. Security (all mandatory, implemented): - Redaction gates every off-box payload. support-bundle now adds webhookUrl + diagToken to CRED_KEYS, and exports redactLogText (value-scrub of live secret strings + pattern-scrub of Discord webhooks / Bearer / api_key= / cookies / sess ids) + valueScrub + collectSecretValues. read_log takes a logical NAME (no path traversal); doodstream-debug.log is excluded from the readable set (it logs live api-key-bearing HTML). grep is length-capped (ReDoS guard). - diagnostics config subtree (enabled/port/token/label/codeIssuedAt/bindAddress) defaults OFF, bind 127.0.0.1; deep-merge makes it migration-free. The server-owned token is preserved against renderer clobber in both save-global-settings handlers; the diagnostics:* IPC is the only mutator. - app.requestSingleInstanceLock() (also the approved fix #6) so a relaunch can't EADDRINUSE-kill the agent and two instances can't clobber the config. main.js: buildDiagnosticCode (mhu1_ base64url, no host embedded), start/stop + auto-start-on-launch + stop-on-quit, the four diagnostics:* IPC handlers. renderer: a "Diagnose-Zugriff" settings subtab (toggle, port, bind-address, copyable connection code + regenerate, status, read-only security note). 382 tests pass (incl. 11 new: collectors+redaction, agent whitelist, and a live RemoteServer protocol test proving auth->diag-response correlation, that a diagnostic client never triggers the capture window, and brute-force lockout). Lint clean (0 errors). Smoke boots identically to baseline. The standalone MCP gateway package + operator setup docs land in a follow-up commit. Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
110 lines
4.0 KiB
JavaScript
110 lines
4.0 KiB
JavaScript
const fs = require('fs');
|
|
|
|
const CRED_KEYS = new Set(['password', 'apiKey', 'token', 'cookie', 'sessionId', 'webhookUrl', 'diagToken']);
|
|
const REDACTED = '<redacted>';
|
|
|
|
function sanitizeConfig(config) {
|
|
if (!config || typeof config !== 'object') return config;
|
|
const clone = JSON.parse(JSON.stringify(config));
|
|
(function walk(o) {
|
|
if (!o) return;
|
|
if (Array.isArray(o)) { for (const e of o) walk(e); return; }
|
|
if (typeof o !== 'object') return;
|
|
for (const k of Object.keys(o)) {
|
|
if (CRED_KEYS.has(k) && typeof o[k] === 'string' && o[k]) o[k] = REDACTED;
|
|
else walk(o[k]);
|
|
}
|
|
})(clone);
|
|
return clone;
|
|
}
|
|
|
|
function collectSecretValues(config) {
|
|
const out = new Set();
|
|
(function walk(o) {
|
|
if (!o) return;
|
|
if (Array.isArray(o)) { for (const e of o) walk(e); return; }
|
|
if (typeof o !== 'object') return;
|
|
for (const k of Object.keys(o)) {
|
|
const v = o[k];
|
|
if (CRED_KEYS.has(k) && typeof v === 'string' && v.length >= 6) out.add(v);
|
|
else walk(v);
|
|
}
|
|
})(config);
|
|
return Array.from(out);
|
|
}
|
|
|
|
function redactLogText(text, secrets) {
|
|
if (typeof text !== 'string' || !text) return text;
|
|
let out = text;
|
|
if (Array.isArray(secrets)) {
|
|
for (const s of secrets) {
|
|
if (typeof s === 'string' && s.length >= 6) out = out.split(s).join(REDACTED);
|
|
}
|
|
}
|
|
out = out
|
|
.replace(/https?:\/\/(?:ptb\.|canary\.)?discord(?:app)?\.com\/api\/webhooks\/\d+\/[\w-]+/gi, 'https://discord.com/api/webhooks/' + REDACTED)
|
|
.replace(/(authorization:\s*bearer\s+)\S+/gi, '$1' + REDACTED)
|
|
.replace(/([?&](?:api_?key|key|token|access_token|password|pass)=)[^\s&"'`]+/gi, '$1' + REDACTED)
|
|
.replace(/("?\b(?:api[_-]?key|apikey|password|secret|access_token)"?\s*[:=]\s*"?)[A-Za-z0-9._\-/+]{8,}/gi, '$1' + REDACTED)
|
|
.replace(/(\bset-cookie:|\bcookie:)\s*\S[^\n]*/gi, '$1 ' + REDACTED)
|
|
.replace(/(\bsess(?:_?id)?\b["'=:\s]+)[A-Za-z0-9._\-]{8,}/gi, '$1' + REDACTED);
|
|
return out;
|
|
}
|
|
|
|
function valueScrub(value, secrets) {
|
|
if (value == null) return value;
|
|
const json = JSON.stringify(value);
|
|
let scrubbed = json;
|
|
if (Array.isArray(secrets)) {
|
|
for (const s of secrets) {
|
|
if (typeof s === 'string' && s.length >= 6) scrubbed = scrubbed.split(s).join(REDACTED);
|
|
}
|
|
}
|
|
return JSON.parse(scrubbed);
|
|
}
|
|
|
|
function collectFile(filePath, label, maxBytes) {
|
|
if (!filePath) return `=== ${label} ===\n<no path configured>\n\n`;
|
|
let stat;
|
|
try { stat = fs.statSync(filePath); }
|
|
catch (err) {
|
|
if (err && err.code === 'ENOENT') return `=== ${label} (${filePath}) ===\n<file does not exist yet>\n\n`;
|
|
return `=== ${label} (${filePath}) ===\n<stat error: ${err.message}>\n\n`;
|
|
}
|
|
const cap = Number.isFinite(maxBytes) && maxBytes > 0 ? maxBytes : 5 * 1024 * 1024;
|
|
let content;
|
|
try {
|
|
if (stat.size > cap) {
|
|
const fd = fs.openSync(filePath, 'r');
|
|
const buf = Buffer.alloc(cap);
|
|
fs.readSync(fd, buf, 0, cap, stat.size - cap);
|
|
fs.closeSync(fd);
|
|
const skipped = stat.size - cap;
|
|
content = `<truncated: skipped first ${skipped} bytes; showing last ${cap} bytes of ${stat.size}>\n` + buf.toString('utf-8');
|
|
} else {
|
|
content = fs.readFileSync(filePath, 'utf-8');
|
|
}
|
|
} catch (err) {
|
|
content = `<read error: ${err.message}>`;
|
|
}
|
|
return `=== ${label} (${filePath}, size=${stat.size} bytes) ===\n${content}\n\n`;
|
|
}
|
|
|
|
function buildSupportBundleText({ header, sanitizedConfig, files }) {
|
|
const parts = [];
|
|
parts.push('=== Multi-Hoster-Upload Support Bundle ===\n');
|
|
if (header && typeof header === 'object') {
|
|
for (const [k, v] of Object.entries(header)) parts.push(`${k}: ${v}\n`);
|
|
}
|
|
parts.push('\n');
|
|
parts.push('=== Config (sanitized — password/apiKey/token/cookie/sessionId redacted) ===\n');
|
|
parts.push(JSON.stringify(sanitizedConfig, null, 2));
|
|
parts.push('\n\n');
|
|
for (const f of (files || [])) {
|
|
parts.push(collectFile(f.path, f.label || f.path, f.maxBytes));
|
|
}
|
|
return parts.join('');
|
|
}
|
|
|
|
module.exports = { sanitizeConfig, collectSecretValues, redactLogText, valueScrub, collectFile, buildSupportBundleText, CRED_KEYS, REDACTED };
|