#!/usr/bin/env node // Controlled static deployment for the PDEV-WEB VM. // Credentials are read inside this MCP process from Bitwarden and never become tool output. "use strict"; const { execFileSync } = require("node:child_process"); const fs = require("node:fs"); const os = require("node:os"); const path = require("node:path"); const crypto = require("node:crypto"); const BW_DATA_DIR = process.env.BW_DATA_DIR || "/home/node/.openclaw/bw-data"; const BW_CLI = process.env.BW_CLI || "/home/node/.openclaw/bw-cli/node_modules/@bitwarden/cli/build/bw.js"; const BW_MP_FILE = process.env.BW_MP_FILE || "/home/node/.openclaw/mcp/.bw-masterpass"; const PROJECT_ROOT = "/home/node/.openclaw/workspaces/jarvis/projects"; const HOST = "YOUR_WEBHOST_IP"; const CLOUDFLARE_TOKEN_FILE = process.env.CLOUDFLARE_TOKEN_FILE || "/home/node/.openclaw/mcp/.cloudflare-api-token"; const KEYHELP_TOKEN_FILE = process.env.KEYHELP_TOKEN_FILE || "/home/node/.openclaw/mcp/.keyhelp-api-key"; const TIMEOUT = 90_000; let bwSession; let cachedKeyHelpAuth; function runBw(args, input, withSession = true) { const env = { ...process.env, BITWARDENCLI_APPDATA_DIR: BW_DATA_DIR }; if (withSession && bwSession) env.BW_SESSION = bwSession; return execFileSync(BW_CLI, args, { env, input, timeout: 20_000, maxBuffer: 8 * 1024 * 1024, stdio: ["pipe", "pipe", "pipe"] }).toString("utf8"); } function ensureBitwarden() { try { const master = fs.readFileSync(BW_MP_FILE, "utf8").trim(); if (!master) return "Das Bitwarden-Masterpasswort-File ist leer."; let lastError = "unbekannter Fehler"; for (let attempt = 0; attempt < 3; attempt += 1) { try { bwSession = runBw(["unlock", "--raw", "--passwordfile", BW_MP_FILE], undefined, false).trim(); if (bwSession) return null; lastError = "kein Session-Schlüssel zurückgegeben"; } catch (error) { const stderr = error?.stderr ? String(error.stderr).trim() : ""; lastError = stderr || String(error?.message || error); } } return `Bitwarden konnte nicht entsperrt werden: ${lastError}`; } catch (error) { return `Bitwarden konnte nicht entsperrt werden: ${String(error?.message || error)}`; } } function readBwJson(args) { let lastError; for (let attempt = 0; attempt < 3; attempt += 1) { try { const output = runBw(args).trim(); if (!output) throw new Error("Bitwarden lieferte eine leere Antwort."); return JSON.parse(output); } catch (error) { lastError = error; bwSession = undefined; const unlockError = ensureBitwarden(); if (unlockError) lastError = new Error(unlockError); } } throw lastError; } function credential() { const problem = ensureBitwarden(); if (problem) return { error: problem }; try { // Shared organization items may not exist in the local CLI cache after a fresh login. try { runBw(["sync"]); } catch {} const items = readBwJson(["list", "items"]); const hit = items.find((item) => { const login = item.login || {}; const uris = (login.uris || []).map((u) => String(u.uri || "").toLowerCase()); const hay = `${item.name || ""} ${login.username || ""} ${uris.join(" ")}`.toLowerCase(); return hay.includes("webhost.your-domain.com") || hay.includes("pdev - webhost") || hay.includes("pdev-web") || hay.includes("webhost ssh"); }); if (!hit?.id) return { error: "Kein dedizierter Webhost-Eintrag gefunden. Bitte einen Bitwarden-Eintrag mit webhost.your-domain.com oder PDEV-WEB anlegen." }; const full = readBwJson(["get", "item", hit.id]); const login = full.login || {}; if (!login.password) return { error: "Der Webhost-Eintrag enthält kein Passwort." }; // The vault item is the shared PDEV credential; the VM account is deliberately // fixed to the confirmed deployment user, not the Bitwarden/SSO email field. return { user: "administrator", password: String(login.password) }; } catch (error) { return { error: `Webhost-Eintrag konnte nicht gelesen werden: ${String(error.stderr || error.message || error)}` }; } } function keyHelpApiKey() { if (cachedKeyHelpAuth) return cachedKeyHelpAuth; try { const key = fs.readFileSync(KEYHELP_TOKEN_FILE, "utf8").trim(); if (key) return cachedKeyHelpAuth = { key, source: `Datei ${KEYHELP_TOKEN_FILE}`, length: key.length }; } catch {} const problem = ensureBitwarden(); if (!problem) { try { try { runBw(["sync"]); } catch {} const items = readBwJson(["list", "items"]); const hit = items.find((item) => /keyhelp.*api|api.*keyhelp/i.test(String(item.name || ""))); if (hit?.id) { const full = readBwJson(["get", "item", hit.id]); const fields = full.fields || []; const field = fields.find((candidate) => /api.?key|token/i.test(String(candidate.name || ""))); const key = field?.value || full.login?.password || full.notes; const normalized = key ? String(key).trim() : ""; const location = field ? `Feld ${field.name}` : full.login?.password ? "Login-Passwort" : "Notiz"; if (normalized) return cachedKeyHelpAuth = { key: normalized, source: `Bitwarden-Eintrag ${hit.name}, ${location}`, length: normalized.length }; } } catch {} } return { error: problem || `Kein KeyHelp-API-Key gefunden. Lege ihn in ${KEYHELP_TOKEN_FILE} oder als Bitwarden-Eintrag mit \"KeyHelp API\" im Namen ab.` }; } async function keyHelpRequest(endpoint, init = {}) { const auth = keyHelpApiKey(); if (auth.error) throw new Error(auth.error); const c = credential(); if (c.error) throw new Error(c.error); if (!/^\/[A-Za-z0-9_?&=/%.-]+$/.test(endpoint) || /[\r\n]/.test(endpoint)) throw new Error("Ungueltiger KeyHelp-API-Endpunkt."); const escapeConfig = (value) => String(value).replace(/\\/g, "\\\\").replace(/"/g, '\\"').replace(/[\r\n]+/g, " "); const method = String(init.method || "GET").toUpperCase(); if (!["GET", "POST", "PUT", "DELETE"].includes(method)) throw new Error("Ungueltige KeyHelp-API-Methode."); const makeConfig = (host) => [ `url = "https://${host}/api/v2${escapeConfig(endpoint)}"`, 'header = "Host: webhost.your-domain.com"', `header = "X-API-Key: ${escapeConfig(auth.key)}"`, 'header = "Accept: application/json"', 'header = "Content-Type: application/json"', `request = "${method}"`, "insecure", "silent", "show-error", ...(init.body ? [`data = "${escapeConfig(init.body)}"`] : []), ].join("\n") + "\n"; const parse = (output) => { const match = output.match(/\n(\d{3})\s*$/); if (!match) throw new Error("KeyHelp-API lieferte keinen HTTP-Status."); const status = Number(match[1]); const text = output.slice(0, match.index); let body; try { body = text ? JSON.parse(text) : null; } catch { body = text; } return { status, body }; }; let response = parse(execFileSync("curl", ["--config", "-", "--write-out", "\n%{http_code}"], { input: makeConfig(HOST), timeout: TIMEOUT, stdio: ["pipe", "pipe", "pipe"], maxBuffer: 4 * 1024 * 1024, }).toString("utf8")); if (response.status === 401) { response = parse(withAskpass(c.password, (env, common) => execFileSync( "ssh", [...common, `${c.user}@${HOST}`, "curl --config - --write-out '\\n%{http_code}'"], { env, input: makeConfig("127.0.0.1"), timeout: TIMEOUT, stdio: ["pipe", "pipe", "pipe"], maxBuffer: 4 * 1024 * 1024 }, ).toString("utf8"))); } if (response.status < 200 || response.status >= 300) throw new Error(`KeyHelp HTTP ${response.status}: ${typeof response.body === "string" ? response.body : response.body?.message || response.body?.code || "unbekannter Fehler"}`); return response.body; } async function keyHelpApiProbe() { const auth = keyHelpApiKey(); if (auth.error) return { error: true, text: `KeyHelp-API nicht bereit: ${auth.error}` }; try { const clients = await keyHelpRequest("/clients"); const domains = await keyHelpRequest("/domains"); const safeClients = (Array.isArray(clients) ? clients : []).map(({ id, username, document_root, status }) => ({ id, username, document_root, status })); const safeDomains = (Array.isArray(domains) ? domains : []).map(({ id, id_user, domain, target, status }) => ({ id, id_user, domain, target, status })); return { error: false, text: JSON.stringify({ api: "ready", clients: safeClients, domains: safeDomains }, null, 2) }; } catch (error) { return { error: true, text: `KeyHelp-API nicht bereit: ${String(error.message || error).replace(/password|secret|token/gi, "[redacted]").slice(0, 1600)}\nKey-Quelle: ${auth.source}; Laenge: ${auth.length} Zeichen.` }; } } function withAskpass(password, fn) { const dir = fs.mkdtempSync(path.join(os.tmpdir(), "jarvis-web-deploy-")); const askpass = path.join(dir, "askpass.sh"); const knownHosts = path.join(dir, "known_hosts"); fs.writeFileSync(askpass, "#!/bin/sh\nprintf '%s\\n' \"$JARVIS_WEBHOST_PASSWORD\"\n", { mode: 0o700 }); const env = { ...process.env, DISPLAY: ":99", SSH_ASKPASS: askpass, SSH_ASKPASS_REQUIRE: "force", JARVIS_WEBHOST_PASSWORD: password }; const common = ["-o", "StrictHostKeyChecking=accept-new", "-o", `UserKnownHostsFile=${knownHosts}`, "-o", "ConnectTimeout=12", "-o", "NumberOfPasswordPrompts=1", "-o", "PreferredAuthentications=password", "-o", "PubkeyAuthentication=no"]; try { return fn(env, common); } finally { try { fs.rmSync(dir, { recursive: true, force: true }); } catch {} } } function sourcePath(raw) { const full = path.resolve(PROJECT_ROOT, raw || ""); if (!raw || (full !== PROJECT_ROOT && !full.startsWith(`${PROJECT_ROOT}${path.sep}`))) return null; try { if (!fs.statSync(full).isDirectory()) return null; } catch { return null; } return full; } function shellQuote(value) { return `'${String(value).replace(/'/g, `'"'"'`)}'`; } function loadDeployManifest(source) { const manifestPath = path.join(source, "jarvis.deploy.json"); if (!fs.existsSync(manifestPath)) throw new Error("jarvis.deploy.json fehlt im Projektverzeichnis."); const manifest = JSON.parse(fs.readFileSync(manifestPath, "utf8")); const domain = String(manifest.domain || "").toLowerCase(); const client = String(manifest.client || ""); const runtime = String(manifest.runtime || "static"); const webRoot = String(manifest.web_root || (runtime === "php" ? "public" : ".")); const healthPath = String(manifest.health_path || "/"); if (!/^(?:[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?\.)+your_username44\.dev$/.test(domain)) throw new Error("Manifest-Domain muss eine gueltige Subdomain unter your-domain.com sein."); if (!/^[a-z][a-z0-9_-]{0,31}$/.test(client)) throw new Error("Ungueltiger KeyHelp-Client im Manifest."); if (!["static", "php"].includes(runtime)) throw new Error("runtime muss static oder php sein."); if (webRoot !== "." && !/^[A-Za-z0-9_.-]+(?:\/[A-Za-z0-9_.-]+)*$/.test(webRoot)) throw new Error("Ungueltiges web_root im Manifest."); if (!/^\/[A-Za-z0-9_./?=&%-]*$/.test(healthPath) || healthPath.includes("..")) throw new Error("Ungueltiger health_path im Manifest."); if (manifest.migration && manifest.migration !== "laravel") throw new Error("Unterstuetzt wird nur migration=laravel."); return { ...manifest, domain, client, runtime, webRoot, healthPath }; } function prepareArtifact(source, manifest) { const workspace = fs.mkdtempSync(path.join(os.tmpdir(), "jarvis-release-")); const project = path.join(workspace, "project"); fs.cpSync(source, project, { recursive: true, filter: (entry) => ![".git", "node_modules", ".next"].includes(path.basename(entry)) }); if (manifest.runtime === "static" && fs.existsSync(path.join(project, "package.json"))) { const pkg = JSON.parse(fs.readFileSync(path.join(project, "package.json"), "utf8")); if (pkg.scripts?.build) { const installArgs = fs.existsSync(path.join(project, "package-lock.json")) ? ["ci", "--ignore-scripts"] : ["install", "--ignore-scripts"]; execFileSync("npm", installArgs, { cwd: project, timeout: 5 * 60_000, stdio: ["ignore", "pipe", "pipe"] }); execFileSync("npm", ["run", "build"], { cwd: project, timeout: 10 * 60_000, stdio: ["ignore", "pipe", "pipe"] }); } } const configured = manifest.artifact_dir ? path.resolve(project, String(manifest.artifact_dir)) : null; if (configured && (!configured.startsWith(`${project}${path.sep}`) || !fs.existsSync(configured))) { fs.rmSync(workspace, { recursive: true, force: true }); throw new Error("Das konfigurierte artifact_dir fehlt oder liegt ausserhalb des Projekts."); } const candidates = [configured, path.join(project, "dist"), path.join(project, "build"), path.join(project, "out"), project].filter(Boolean); const artifact = manifest.runtime === "php" ? project : candidates.find((candidate) => candidate === project || fs.existsSync(candidate)); if (!artifact || (artifact !== project && !artifact.startsWith(`${project}${path.sep}`)) || !fs.statSync(artifact).isDirectory()) { fs.rmSync(workspace, { recursive: true, force: true }); throw new Error("Build-Artefakt fehlt oder liegt ausserhalb des Projekts."); } return { workspace, artifact }; } async function ensureKeyHelpDomain(manifest, target) { const client = await keyHelpRequest(`/clients/name/${encodeURIComponent(manifest.client)}`); if (!client?.id) throw new Error(`KeyHelp-Client ${manifest.client} wurde nicht gefunden.`); const payload = { id_user: client.id, domain: manifest.domain, is_email_domain: false, is_dns_disabled: true, target: { target }, security: { lets_encrypt: manifest.lets_encrypt === true, is_prefer_https: manifest.prefer_https !== false }, }; try { const domain = await keyHelpRequest(`/domains/name/${encodeURIComponent(manifest.domain)}`); await keyHelpRequest(`/domains/${domain.id}`, { method: "PUT", body: JSON.stringify(payload) }); return { created: false, id: domain.id, client, previousTarget: domain.target?.target, payload }; } catch (error) { if (!String(error.message || error).includes("HTTP 404")) throw error; const created = await keyHelpRequest("/domains", { method: "POST", body: JSON.stringify({ ...payload, create_www_subdomain: false }) }); return { created: true, id: created?.id, client, payload }; } } async function deployRelease(args) { if (args.confirm !== true) return { error: true, text: "Produktiv-Deploy benoetigt confirm=true." }; const source = sourcePath(String(args.source_dir || "")); if (!source) return { error: true, text: `Quellverzeichnis muss unter ${PROJECT_ROOT} liegen und existieren.` }; let prepared; try { const manifest = loadDeployManifest(source); if (manifest.migration && args.confirm_migration !== true) return { error: true, text: "Datenbankmigration benoetigt zusaetzlich confirm_migration=true." }; prepared = prepareArtifact(source, manifest); const c = credential(); if (c.error) throw new Error(c.error); const releaseId = `${new Date().toISOString().replace(/[-:.TZ]/g, "").slice(0, 14)}-${crypto.randomBytes(4).toString("hex")}`; const root = `/home/users/${manifest.client}/www/.jarvis-deploy/${manifest.domain}`; const release = `${root}/releases/${releaseId}`; const stage = `/tmp/jarvis-release-${crypto.randomUUID()}`; const target = `/.jarvis-deploy/${manifest.domain}/releases/${releaseId}${manifest.webRoot === "." ? "" : `/${manifest.webRoot}`}/`; await withAskpass(c.password, async (env, common) => { execFileSync("ssh", [...common, `${c.user}@${HOST}`, `mkdir -p ${shellQuote(stage)}`], { env, timeout: TIMEOUT, stdio: ["ignore", "pipe", "pipe"] }); execFileSync("scp", [...common, "-r", `${prepared.artifact}${path.sep}.`, `${c.user}@${HOST}:${stage}`], { env, timeout: 10 * 60_000, stdio: ["ignore", "pipe", "pipe"] }); const envFile = `/home/users/${manifest.client}/files/jarvis-env/${manifest.domain}.env`; const setup = [ "set -eu", "sudo -S -p '' -v", `sudo install -d -o ${manifest.client} -g ${manifest.client} ${shellQuote(root)} ${shellQuote(`${root}/releases`)}`, `sudo rm -rf ${shellQuote(release)}`, `sudo mv ${shellQuote(stage)} ${shellQuote(release)}`, `sudo chown -R ${manifest.client}:${manifest.client} ${shellQuote(release)}`, manifest.shared_env === true ? `sudo test -f ${shellQuote(envFile)} && sudo -u ${manifest.client} ln -s ${shellQuote(envFile)} ${shellQuote(`${release}/.env`)}` : "true", manifest.runtime === "php" && manifest.composer !== false ? `sudo -u ${manifest.client} composer install --no-dev --no-interaction --prefer-dist --optimize-autoloader --working-dir=${shellQuote(release)}` : "true", ].join("; "); execFileSync("ssh", [...common, `${c.user}@${HOST}`, setup], { env, input: `${c.password}\n`, timeout: 10 * 60_000, stdio: ["pipe", "pipe", "pipe"], maxBuffer: 2 * 1024 * 1024 }); }); let domainResult; let migrationApplied = false; try { if (manifest.migration === "laravel") { await withAskpass(c.password, (env, common) => { const migrate = `sudo -S -p '' -v; sudo -u ${manifest.client} php ${shellQuote(`${release}/artisan`)} migrate --force`; execFileSync("ssh", [...common, `${c.user}@${HOST}`, migrate], { env, input: `${c.password}\n`, timeout: 10 * 60_000, stdio: ["pipe", "pipe", "pipe"] }); }); migrationApplied = true; } domainResult = await ensureKeyHelpDomain(manifest, target); await withAskpass(c.password, (env, common) => { const health = `for attempt in $(seq 1 12); do curl -kfsS --max-time 20 --resolve ${shellQuote(`${manifest.domain}:443:127.0.0.1`)} ${shellQuote(`https://${manifest.domain}${manifest.healthPath}`)} >/dev/null && exit 0; sleep 5; done; exit 1`; execFileSync("ssh", [...common, `${c.user}@${HOST}`, health], { env, timeout: 30_000, stdio: ["ignore", "pipe", "pipe"] }); }); } catch (activationError) { if (domainResult) { try { if (domainResult.created) await keyHelpRequest(`/domains/${domainResult.id}`, { method: "DELETE" }); else if (domainResult.previousTarget) await keyHelpRequest(`/domains/${domainResult.id}`, { method: "PUT", body: JSON.stringify({ ...domainResult.payload, target: { target: domainResult.previousTarget } }) }); } catch {} } await withAskpass(c.password, (env, common) => { const rollback = `sudo -S -p '' -v; ${migrationApplied ? `sudo -u ${manifest.client} php ${shellQuote(`${release}/artisan`)} migrate:rollback --force || true;` : ""} sudo rm -rf ${shellQuote(release)}`; execFileSync("ssh", [...common, `${c.user}@${HOST}`, rollback], { env, input: `${c.password}\n`, timeout: TIMEOUT, stdio: ["pipe", "pipe", "pipe"] }); }); throw new Error(`KeyHelp-Aktivierung oder Healthcheck fehlgeschlagen; Release wurde zurueckgerollt: ${String(activationError.stderr || activationError.message || activationError).slice(0, 1000)}`); } await withAskpass(c.password, (env, common) => { const cleanup = `sudo -S -p '' -v; sudo find ${shellQuote(`${root}/releases`)} -mindepth 1 -maxdepth 1 -type d -printf '%T@ %p\\n' | sort -rn | tail -n +6 | cut -d' ' -f2- | xargs -r sudo rm -rf --`; execFileSync("ssh", [...common, `${c.user}@${HOST}`, cleanup], { env, input: `${c.password}\n`, timeout: TIMEOUT, stdio: ["pipe", "pipe", "pipe"] }); }); return { error: false, text: `Release ${releaseId} erfolgreich fuer ${manifest.domain} deployt. KeyHelp-Domain ${domainResult.created ? "angelegt" : "aktualisiert"}; Healthcheck erfolgreich.` }; } catch (error) { return { error: true, text: `Release-Deploy fehlgeschlagen: ${String(error.stderr || error.message || error).replace(/password|secret|token/gi, "[redacted]").slice(0, 2000)}` }; } finally { if (prepared?.workspace) try { fs.rmSync(prepared.workspace, { recursive: true, force: true }); } catch {} } } function probeHost() { const c = credential(); if (c.error) return { error: true, text: c.error }; return withAskpass(c.password, (env, common) => { try { const result = execFileSync("ssh", [...common, `${c.user}@${HOST}`, "printf 'USER='; id -un; printf 'HOME_DIRS\\n'; find /home/users -maxdepth 4 -type d -path '*/www/*' -print 2>/dev/null | head -30"], { env, timeout: TIMEOUT, stdio: ["ignore", "pipe", "pipe"] }).toString("utf8").trim(); return { error: false, text: result || "SSH erreichbar, aber keine KeyHelp-Webroot gefunden." }; } catch (error) { return { error: true, text: `SSH erreichbar? Nein oder kein Zugriff: ${String(error.stderr || error.message || error).replace(/password|secret|token/gi, "[redacted]").slice(0, 1000)}` }; } }); } function discoverKeyHelp() { const c = credential(); if (c.error) return { error: true, text: c.error }; return withAskpass(c.password, (env, common) => { const command = [ "printf '%s\\n' '== IDENTITY =='", "id", "getent passwd $(id -un) || true", "printf '%s\\n' '== SUDO =='", "sudo -S -p '' -v >/dev/null 2>&1 && sudo -n -l || echo SUDO_UNAVAILABLE", "printf '%s\\n' '== KEYHELP PATHS =='", "sudo -n ls -la /home/keyhelp/www 2>/dev/null || true", "sudo -n find /home/keyhelp/www/keyhelp /etc/keyhelp /usr/local/keyhelp -maxdepth 4 -type f 2>/dev/null | grep -Ei 'api|route|console|command|config|domain' | head -160 || true", "printf '%s\\n' '== APACHE VHOSTS =='", "sudo -n apache2ctl -S 2>/dev/null | head -120 || true", "printf '%s\\n' '== WEBROOTS =='", "sudo -n find /home/users -maxdepth 5 -type d -path '*/www/*' -printf '%u:%g %m %p\\n' 2>/dev/null | head -120 || true", "printf '%s\\n' '== COMMANDS =='", "for x in keyhelp keyhelp-cli kh php composer node npm apache2ctl nginx; do command -v $x 2>/dev/null || true; done", "printf '%s\\n' '== SERVICES =='", "sudo -n systemctl list-unit-files --type=service 2>/dev/null | grep -Ei 'keyhelp|apache|nginx|php.*fpm|mariadb|mysql' | head -80 || true", "printf '%s\\n' '== OS =='", "cat /etc/os-release 2>/dev/null || true", ].join("; "); try { const output = execFileSync("ssh", [...common, `${c.user}@${HOST}`, command], { env, input: `${c.password}\n`, timeout: TIMEOUT, stdio: ["pipe", "pipe", "pipe"], maxBuffer: 2 * 1024 * 1024 }).toString("utf8").trim(); return { error: false, text: output || "Keine KeyHelp-Metadaten gefunden." }; } catch (error) { return { error: true, text: `KeyHelp-Erkennung fehlgeschlagen: ${String(error.stderr || error.message || error).replace(/password|secret|token/gi, "[redacted]").slice(0, 2000)}` }; } }); } function keyHelpApiSchema() { const c = credential(); if (c.error) return { error: true, text: c.error }; return withAskpass(c.password, (env, common) => { try { const output = execFileSync("ssh", [...common, `${c.user}@${HOST}`, "sudo -S -p '' cat /home/keyhelp/www/keyhelp/api/openapi.json"], { env, input: `${c.password}\n`, timeout: TIMEOUT, stdio: ["pipe", "pipe", "pipe"], maxBuffer: 8 * 1024 * 1024 }).toString("utf8"); const schema = JSON.parse(output); const paths = Object.fromEntries(Object.entries(schema.paths || {}).filter(([name]) => /domain|client|certificate/i.test(name)).map(([name, operations]) => [name, Object.fromEntries(Object.entries(operations).map(([method, operation]) => [method, { summary: operation.summary, parameters: operation.parameters, requestBody: operation.requestBody, responses: operation.responses, security: operation.security }]))])); const schemas = schema.components?.schemas || {}; const selectedSchemas = Object.fromEntries(Object.entries(schemas).filter(([name]) => /^(domain|client|certificate|created|error)$/i.test(name))); return { error: false, text: JSON.stringify({ info: schema.info, servers: schema.servers, security: schema.security, securitySchemes: schema.components?.securitySchemes, paths, schemas: selectedSchemas }, null, 2).slice(0, 60000) }; } catch (error) { return { error: true, text: `KeyHelp-API-Schema konnte nicht gelesen werden: ${String(error.stderr || error.message || error).replace(/password|secret|token/gi, "[redacted]").slice(0, 2000)}` }; } }); } function keyHelpApiDiagnose() { const c = credential(); if (c.error) return { error: true, text: c.error }; return withAskpass(c.password, (env, common) => { const command = [ "sudo -S -p '' -v", "printf '%s\\n' '== RECENT API ACCESS =='", "sudo grep -h '/api/v2/' /var/log/apache2/keyhelp/access.log /var/log/apache2/*access*.log 2>/dev/null | tail -20 || true", "printf '%s\\n' '== KEYHELP LOG TARGETS =='", "sudo grep -R -n -E 'CustomLog|ErrorLog' /etc/apache2/keyhelp 2>/dev/null | head -80 || true", "printf '%s\\n' '== API IMPLEMENTATION REFERENCES =='", "sudo grep -R -n -E 'ip.?restriction|allowed.?ip|api.?key' /home/keyhelp/www/keyhelp/core/Api /home/keyhelp/www/keyhelp/pages/admin_api.php 2>/dev/null | head -80 || true", "printf '%s\\n' '== API DATABASE TABLES =='", "sudo mariadb --batch --skip-column-names -e \"SELECT TABLE_SCHEMA, TABLE_NAME FROM information_schema.TABLES WHERE LOWER(TABLE_NAME) LIKE '%api%' OR LOWER(TABLE_NAME) LIKE '%key%';\" 2>/dev/null | head -80 || true", "printf '%s\\n' '== KEYHELP API COLUMNS =='", "sudo mariadb --batch --skip-column-names -e \"SELECT COLUMN_NAME, DATA_TYPE FROM information_schema.COLUMNS WHERE TABLE_SCHEMA='keyhelp' AND TABLE_NAME='api_keys' ORDER BY ORDINAL_POSITION;\" 2>/dev/null || true", "printf '%s\\n' '== KEYHELP API KEY METADATA =='", "sudo mariadb --batch --skip-column-names -e \"SELECT id, name, ips, created_at, COALESCE(last_access, 'never'), CHAR_LENGTH(api_key) FROM keyhelp.api_keys ORDER BY id;\" 2>/dev/null || true", "printf '%s\\n' '== KEYHELP ACCOUNT TABLES =='", "sudo mariadb --batch --skip-column-names -e \"SELECT TABLE_NAME FROM information_schema.TABLES WHERE TABLE_SCHEMA='keyhelp' AND (LOWER(TABLE_NAME) LIKE '%user%' OR LOWER(TABLE_NAME) LIKE '%admin%');\" 2>/dev/null || true", "printf '%s\\n' '== KEYHELP ACCOUNT COLUMNS =='", "sudo mariadb --batch --skip-column-names -e \"SELECT TABLE_NAME, COLUMN_NAME, DATA_TYPE FROM information_schema.COLUMNS WHERE TABLE_SCHEMA='keyhelp' AND (LOWER(TABLE_NAME) LIKE '%user%' OR LOWER(TABLE_NAME) LIKE '%admin%') AND (LOWER(COLUMN_NAME) LIKE '%name%' OR LOWER(COLUMN_NAME) LIKE '%admin%' OR LOWER(COLUMN_NAME) LIKE '%role%' OR LOWER(COLUMN_NAME)='id') ORDER BY TABLE_NAME, ORDINAL_POSITION;\" 2>/dev/null | head -120 || true", "printf '%s\\n' '== KEYHELP ADMIN ACCOUNTS =='", "sudo mariadb --batch --skip-column-names -e \"SELECT id, username, is_admin, is_main_admin FROM keyhelp.users WHERE is_admin=1 OR is_main_admin=1 ORDER BY id;\" 2>/dev/null || true", ].join("; "); try { const output = execFileSync("ssh", [...common, `${c.user}@${HOST}`, command], { env, input: `${c.password}\n`, timeout: TIMEOUT, stdio: ["pipe", "pipe", "pipe"], maxBuffer: 2 * 1024 * 1024 }).toString("utf8").trim(); return { error: false, text: output || "Keine API-Diagnosedaten gefunden." }; } catch (error) { return { error: true, text: `KeyHelp-API-Diagnose fehlgeschlagen: ${String(error.stderr || error.message || error).replace(/password|secret|token/gi, "[redacted]").slice(0, 2000)}` }; } }); } function compareKeyHelpApiKey() { const c = credential(); if (c.error) return { error: true, text: c.error }; return withAskpass(c.password, (env, common) => { try { const problem = ensureBitwarden(); if (problem) return { error: true, text: problem }; const items = readBwJson(["list", "items"]); const hit = items.find((item) => /keyhelp.*api|api.*keyhelp/i.test(String(item.name || ""))); if (!hit?.id) return { error: true, text: "Kein KeyHelp-API-Eintrag in Bitwarden gefunden." }; const full = readBwJson(["get", "item", hit.id]); const field = (full.fields || []).find((candidate) => /api.?key|token/i.test(String(candidate.name || ""))); const vaultKey = String(field?.value || full.login?.password || full.notes || "").trim(); const command = "sudo -S -p '' mariadb --batch --skip-column-names -e \"SELECT api_key FROM keyhelp.api_keys WHERE name='Jarvis' ORDER BY id DESC LIMIT 1;\""; const stored = execFileSync("ssh", [...common, `${c.user}@${HOST}`, command], { env, input: `${c.password}\n`, timeout: TIMEOUT, stdio: ["pipe", "pipe", "pipe"], maxBuffer: 64 * 1024 }).toString("utf8").trim(); const sha256 = crypto.createHash("sha256").update(vaultKey).digest("hex"); const result = { vaultLength: vaultKey.length, storedLength: stored.length, exactMatch: crypto.timingSafeEqual(Buffer.from(crypto.createHash("sha256").update(vaultKey).digest()), Buffer.from(crypto.createHash("sha256").update(stored).digest())), sha256Match: stored === sha256 || stored.endsWith(sha256), vaultContainsWhitespace: /\s/.test(vaultKey), }; return { error: false, text: JSON.stringify(result, null, 2) }; } catch (error) { return { error: true, text: `KeyHelp-API-Key-Vergleich fehlgeschlagen: ${String(error.stderr || error.message || error).replace(/password|secret|token|api[_ -]?key/gi, "[redacted]").slice(0, 1200)}` }; } }); } function keyHelpVaultMetadata() { const problem = ensureBitwarden(); if (problem) return { error: true, text: problem }; try { try { runBw(["sync"]); } catch {} const items = readBwJson(["list", "items"]); const hit = items.find((item) => /keyhelp.*api|api.*keyhelp/i.test(String(item.name || ""))); if (!hit?.id) return { error: true, text: "Kein KeyHelp-API-Eintrag in Bitwarden gefunden." }; const full = readBwJson(["get", "item", hit.id]); const metadata = { name: hit.name, loginUsernameLength: String(full.login?.username || "").length, loginPasswordLength: String(full.login?.password || "").trim().length, notesLength: String(full.notes || "").trim().length, fields: (full.fields || []).map((field) => ({ name: String(field.name || ""), length: String(field.value || "").trim().length })), }; return { error: false, text: JSON.stringify(metadata, null, 2) }; } catch (error) { return { error: true, text: `Bitwarden-Metadaten konnten nicht gelesen werden: ${String(error.stderr || error.message || error).replace(/password|secret|token/gi, "[redacted]").slice(0, 1200)}` }; } } function inspectKeyHelpApiPanel() { const c = credential(); if (c.error) return { error: true, text: c.error }; const dir = fs.mkdtempSync(path.join(os.tmpdir(), "jarvis-keyhelp-panel-")); const cookies = path.join(dir, "cookies.txt"); const escapeConfig = (value) => String(value).replace(/\\/g, "\\\\").replace(/"/g, '\\"').replace(/[\r\n]+/g, " "); const common = (url) => [ `url = "https://${HOST}/${url}"`, 'header = "Host: webhost.your-domain.com"', `cookie = "${escapeConfig(cookies)}"`, `cookie-jar = "${escapeConfig(cookies)}"`, "insecure", "silent", "show-error", "location", ]; try { const loginConfig = [ ...common("index.php"), 'header = "Content-Type: application/x-www-form-urlencoded"', `data = "submit=1&username=keyadmin&password=${escapeConfig(encodeURIComponent(c.password))}"`, ].join("\n") + "\n"; execFileSync("curl", ["--config", "-"], { input: loginConfig, timeout: TIMEOUT, stdio: ["pipe", "pipe", "pipe"], maxBuffer: 4 * 1024 * 1024 }); const fetchPage = (url) => execFileSync("curl", ["--config", "-"], { input: common(url).join("\n") + "\n", timeout: TIMEOUT, stdio: ["pipe", "pipe", "pipe"], maxBuffer: 8 * 1024 * 1024 }).toString("utf8"); const describe = (html) => ({ page: html.match(/"app\.page"\s*:\s*"([^"]*)"/)?.[1] || "unknown", forms: [...html.matchAll(/