mirror of
https://github.com/myronblair/novacpx
synced 2026-06-30 17:50:41 -05:00
Streaming terminals for PHP extensions, SSL certificates; UFW logging state fix
- php.php: install-extension and remove-extension now stream via SSE (real-time progress, proper error detection, sudo) - ssl.php: issue action now streams certbot output via SSE - admin.js: phpExtInstall/Remove use streaming terminal modal - admin.js: adminIssueBulkSSL uses streaming modal with per-domain progress - admin.js: adminRenewCert now confirms before renewing - admin.js: adminIssueSingleSSL helper for per-domain streaming SSL - admin.js: firewall page pre-selects current UFW logging level from API response - admin.js: fwSetLogging reloads firewall page on success - firewall.php: ufw_status() now parses and returns logging level Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
This commit is contained in:
@@ -100,10 +100,17 @@ function ufw_status(): array {
|
||||
|
||||
// Default policy
|
||||
preg_match('/Default:\s+(\w+) \(incoming\),\s+(\w+) \(outgoing\)/', $raw, $pol);
|
||||
// Logging level
|
||||
preg_match('/Logging:\s+(\S+)/i', $raw, $logm);
|
||||
$logging = strtolower($logm[1] ?? 'off');
|
||||
if ($logging === 'on (low)') $logging = 'low';
|
||||
// Normalise: strip parentheses if present e.g. "on (low)" → "low"
|
||||
if (preg_match('/\((\w+)\)/', $logging, $lm)) $logging = $lm[1];
|
||||
return [
|
||||
'active' => $active,
|
||||
'default_incoming' => $pol[1] ?? 'deny',
|
||||
'default_outgoing' => $pol[2] ?? 'allow',
|
||||
'logging' => $logging,
|
||||
'rules' => $rules,
|
||||
'raw' => $raw,
|
||||
];
|
||||
|
||||
+52
-10
@@ -83,16 +83,40 @@ match ($action) {
|
||||
$ver = $body['version'] ?? '';
|
||||
$ext = preg_replace('/[^a-z0-9\-]/', '', strtolower($body['extension'] ?? ''));
|
||||
if (!preg_match('/^[78]\.\d$/', $ver) || !$ext) Response::error("Invalid input");
|
||||
|
||||
header('Content-Type: text/event-stream');
|
||||
header('Cache-Control: no-cache');
|
||||
header('X-Accel-Buffering: no');
|
||||
while (ob_get_level()) ob_end_clean();
|
||||
$sse = function(string $line) { echo 'data: ' . json_encode(['line' => $line]) . "\n\n"; flush(); };
|
||||
$run = function(string $cmd) use ($sse): int {
|
||||
$proc = proc_open($cmd, [1 => ['pipe','w'], 2 => ['pipe','w']], $pipes);
|
||||
if (!$proc) { $sse(" [failed to start]\n"); return 1; }
|
||||
while (!feof($pipes[1])) { $l = fgets($pipes[1]); if ($l !== false && $l !== '') $sse($l); }
|
||||
while (!feof($pipes[2])) { $l = fgets($pipes[2]); if ($l !== false && $l !== '') $sse(" " . $l); }
|
||||
fclose($pipes[1]); fclose($pipes[2]);
|
||||
return proc_close($proc);
|
||||
};
|
||||
|
||||
$pkg = "php{$ver}-{$ext}";
|
||||
$out = shell_exec("apt-get install -y $pkg 2>&1");
|
||||
if (str_contains($out ?: '', 'Unable to locate') || str_contains($out ?: '', 'E:')) {
|
||||
// Try pecl fallback
|
||||
$out2 = shell_exec("php{$ver} /usr/bin/pecl install {$ext} 2>&1");
|
||||
$out .= "\n[pecl] " . $out2;
|
||||
$sse("▶ Installing {$pkg}…\n");
|
||||
$rc = $run("sudo apt-get install -y $pkg 2>&1");
|
||||
|
||||
if ($rc !== 0) {
|
||||
// Try PECL fallback
|
||||
$sse("\n apt package not found — trying PECL…\n");
|
||||
$rc2 = $run("sudo php{$ver} /usr/bin/pecl install {$ext} 2>&1");
|
||||
if ($rc2 !== 0) {
|
||||
$sse(" ✗ Could not install {$ext} via apt or PECL\n");
|
||||
echo 'data: ' . json_encode(['done' => true, 'success' => false]) . "\n\n"; flush(); exit;
|
||||
}
|
||||
}
|
||||
shell_exec("systemctl reload php{$ver}-fpm 2>/dev/null || true");
|
||||
|
||||
$sse("\n▶ Reloading PHP {$ver} FPM…\n");
|
||||
$run("sudo systemctl reload php{$ver}-fpm 2>&1 || sudo systemctl restart php{$ver}-fpm 2>&1");
|
||||
$sse(" ✓ php{$ver}-{$ext} installed\n");
|
||||
audit('php.install-extension', "$ver/$ext");
|
||||
Response::success(['output' => substr($out ?: '', -1000)], "Extension $ext installed for PHP $ver");
|
||||
echo 'data: ' . json_encode(['done' => true, 'success' => true]) . "\n\n"; flush(); exit;
|
||||
})(),
|
||||
|
||||
'remove-extension' => (function() use ($body) {
|
||||
@@ -100,11 +124,29 @@ match ($action) {
|
||||
$ver = $body['version'] ?? '';
|
||||
$ext = preg_replace('/[^a-z0-9\-]/', '', strtolower($body['extension'] ?? ''));
|
||||
if (!preg_match('/^[78]\.\d$/', $ver) || !$ext) Response::error("Invalid input");
|
||||
|
||||
header('Content-Type: text/event-stream');
|
||||
header('Cache-Control: no-cache');
|
||||
header('X-Accel-Buffering: no');
|
||||
while (ob_get_level()) ob_end_clean();
|
||||
$sse = function(string $line) { echo 'data: ' . json_encode(['line' => $line]) . "\n\n"; flush(); };
|
||||
$run = function(string $cmd) use ($sse): int {
|
||||
$proc = proc_open($cmd, [1 => ['pipe','w'], 2 => ['pipe','w']], $pipes);
|
||||
if (!$proc) { $sse(" [failed to start]\n"); return 1; }
|
||||
while (!feof($pipes[1])) { $l = fgets($pipes[1]); if ($l !== false && $l !== '') $sse($l); }
|
||||
while (!feof($pipes[2])) { $l = fgets($pipes[2]); if ($l !== false && $l !== '') $sse(" " . $l); }
|
||||
fclose($pipes[1]); fclose($pipes[2]);
|
||||
return proc_close($proc);
|
||||
};
|
||||
|
||||
$pkg = "php{$ver}-{$ext}";
|
||||
$out = shell_exec("apt-get remove -y $pkg 2>&1");
|
||||
shell_exec("systemctl reload php{$ver}-fpm 2>/dev/null || true");
|
||||
$sse("▶ Removing {$pkg}…\n");
|
||||
$run("sudo apt-get remove -y $pkg 2>&1");
|
||||
$sse("\n▶ Reloading PHP {$ver} FPM…\n");
|
||||
$run("sudo systemctl reload php{$ver}-fpm 2>&1 || sudo systemctl restart php{$ver}-fpm 2>&1");
|
||||
$sse(" ✓ php{$ver}-{$ext} removed\n");
|
||||
audit('php.remove-extension', "$ver/$ext");
|
||||
Response::success(['output' => substr($out ?: '', -1000)], "Extension $ext removed from PHP $ver");
|
||||
echo 'data: ' . json_encode(['done' => true, 'success' => true]) . "\n\n"; flush(); exit;
|
||||
})(),
|
||||
|
||||
'fpm-action' => (function() use ($body) {
|
||||
|
||||
@@ -21,14 +21,55 @@ match ($action) {
|
||||
Response::success($rows);
|
||||
})(),
|
||||
|
||||
'issue' => (function() use ($body, $accountId) {
|
||||
'issue' => (function() use ($body, $accountId, $db) {
|
||||
$domain = trim($body['domain'] ?? '');
|
||||
$email = trim($body['email'] ?? '');
|
||||
if (!$domain) Response::error("domain required");
|
||||
if (!$accountId) Response::error("account_id required");
|
||||
$result = SSLManager::issueLetsEncrypt($accountId, $domain, $email);
|
||||
audit('ssl.issue', $domain);
|
||||
Response::success($result, "SSL certificate issued for $domain");
|
||||
|
||||
header('Content-Type: text/event-stream');
|
||||
header('Cache-Control: no-cache');
|
||||
header('X-Accel-Buffering: no');
|
||||
while (ob_get_level()) ob_end_clean();
|
||||
$sse = function(string $line) { echo 'data: ' . json_encode(['line' => $line]) . "\n\n"; flush(); };
|
||||
|
||||
$sse("▶ Requesting Let's Encrypt certificate for {$domain}…\n");
|
||||
$sse(" (This may take 30–60 seconds)\n\n");
|
||||
|
||||
try {
|
||||
$webRoot = $db->fetchOne("SELECT document_root FROM domains WHERE domain = ? AND account_id = ?", [$domain, $accountId]);
|
||||
if (!$webRoot) { $sse(" ✗ Domain not found for this account\n"); echo 'data: '.json_encode(['done'=>true,'success'=>false])."\n\n"; flush(); exit; }
|
||||
|
||||
$docRoot = $webRoot['document_root'];
|
||||
$mail = $email ?: "ssl@{$domain}";
|
||||
$cmd = "certbot certonly --webroot -w " . escapeshellarg($docRoot)
|
||||
. " -d " . escapeshellarg($domain) . " -d " . escapeshellarg("www.{$domain}")
|
||||
. " --email " . escapeshellarg($mail)
|
||||
. " --agree-tos --non-interactive 2>&1";
|
||||
|
||||
$proc = proc_open($cmd, [1 => ['pipe','w'], 2 => ['pipe','w']], $pipes);
|
||||
if ($proc) {
|
||||
while (!feof($pipes[1])) { $l = fgets($pipes[1]); if ($l !== false && $l !== '') $sse($l); }
|
||||
fclose($pipes[1]); fclose($pipes[2]);
|
||||
proc_close($proc);
|
||||
}
|
||||
|
||||
$certPath = "/etc/letsencrypt/live/{$domain}/fullchain.pem";
|
||||
if (!file_exists($certPath)) {
|
||||
$sse("\n ✗ Certificate not created — check DNS is pointed to this server\n");
|
||||
echo 'data: '.json_encode(['done'=>true,'success'=>false])."\n\n"; flush(); exit;
|
||||
}
|
||||
|
||||
$sse("\n▶ Installing certificate on vhost…\n");
|
||||
$result = SSLManager::issueLetsEncrypt($accountId, $domain, $email);
|
||||
audit('ssl.issue', $domain);
|
||||
$sse(" ✓ SSL certificate installed (expires {$result['expires']})\n");
|
||||
echo 'data: '.json_encode(['done'=>true,'success'=>true,'cert_id'=>$result['cert_id']])."\n\n";
|
||||
} catch (Exception $e) {
|
||||
$sse(" ✗ Error: " . $e->getMessage() . "\n");
|
||||
echo 'data: '.json_encode(['done'=>true,'success'=>false])."\n\n";
|
||||
}
|
||||
flush(); exit;
|
||||
})(),
|
||||
|
||||
'generate-csr' => (function() use ($body, $accountId) {
|
||||
|
||||
+137
-23
@@ -636,22 +636,65 @@
|
||||
});
|
||||
};
|
||||
|
||||
window.phpExtInstall = async (ver) => {
|
||||
const _phpExtStream = (ver, ext, action) => {
|
||||
const termId = 'phpext-term-' + Date.now();
|
||||
const verb = action === 'install-extension' ? 'Installing' : 'Removing';
|
||||
Nova.modal(`${verb} ${ext} (PHP ${ver})`, `
|
||||
<div id="${termId}" style="background:#1a1a2e;color:#e0e0e0;font-family:monospace;font-size:.82rem;
|
||||
padding:1rem;border-radius:6px;height:240px;overflow-y:auto;white-space:pre-wrap;line-height:1.5">
|
||||
<span style="color:#7ec8e3">Starting…</span>\n
|
||||
</div>`,
|
||||
`<button class="btn btn-ghost" id="phpext-close" onclick="this.closest('.modal-overlay').remove()">Close</button>`);
|
||||
const term = document.getElementById(termId);
|
||||
const append = t => { term.textContent += t; term.scrollTop = term.scrollHeight; };
|
||||
fetch(`/api/php/${action}`, {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ version: ver, extension: ext }),
|
||||
credentials: 'same-origin',
|
||||
}).then(resp => {
|
||||
if (!resp.ok) { append(`\nHTTP error ${resp.status}`); return; }
|
||||
const reader = resp.body.getReader();
|
||||
const dec = new TextDecoder();
|
||||
let buf = '';
|
||||
const read = () => reader.read().then(({ done, value }) => {
|
||||
if (done) { append('\n[done]'); return; }
|
||||
buf += dec.decode(value, { stream: true });
|
||||
const parts = buf.split('\n\n');
|
||||
buf = parts.pop();
|
||||
for (const part of parts) {
|
||||
const m = part.match(/^data: (.+)$/m);
|
||||
if (!m) continue;
|
||||
try {
|
||||
const obj = JSON.parse(m[1]);
|
||||
if (obj.line) { append(obj.line); }
|
||||
else if (obj.done) {
|
||||
const btn = document.getElementById('phpext-close');
|
||||
if (btn) {
|
||||
btn.textContent = obj.success ? 'Done ✓' : 'Close';
|
||||
btn.className = obj.success ? 'btn btn-primary' : 'btn btn-ghost';
|
||||
btn.onclick = () => { document.querySelector('.modal-overlay')?.remove(); phpExtModal(ver); };
|
||||
}
|
||||
}
|
||||
} catch(e) {}
|
||||
}
|
||||
read();
|
||||
}).catch(err => append(`\n[error: ${err.message}]`));
|
||||
read();
|
||||
}).catch(err => append(`\nFetch error: ${err.message}`));
|
||||
};
|
||||
|
||||
window.phpExtInstall = (ver) => {
|
||||
const sel = document.getElementById('php-ext-add-sel')?.value;
|
||||
const custom = document.getElementById('php-ext-add-custom')?.value?.trim();
|
||||
const ext = custom || sel;
|
||||
if (!ext) { Nova.toast('Choose or type an extension name', 'error'); return; }
|
||||
Nova.toast(`Installing ${ext} for PHP ${ver}…`, 'info', 15000);
|
||||
const r = await Nova.api('php', 'install-extension', { method: 'POST', body: { version: ver, extension: ext } });
|
||||
if (r?.success) { Nova.toast(r.message, 'success'); phpExtModal(ver); }
|
||||
else Nova.toast(r?.message || 'Install failed', 'error');
|
||||
_phpExtStream(ver, ext, 'install-extension');
|
||||
};
|
||||
|
||||
window.phpExtRemove = (ver, ext) => {
|
||||
Nova.confirm(`Remove extension ${ext} from PHP ${ver}?`, async () => {
|
||||
const r = await Nova.api('php', 'remove-extension', { method: 'POST', body: { version: ver, extension: ext } });
|
||||
if (r?.success) { Nova.toast(r.message, 'success'); phpExtModal(ver); }
|
||||
else Nova.toast(r?.message || 'Remove failed', 'error');
|
||||
Nova.confirm(`Remove extension ${ext} from PHP ${ver}?`, () => {
|
||||
_phpExtStream(ver, ext, 'remove-extension');
|
||||
}, true);
|
||||
};
|
||||
|
||||
@@ -1330,23 +1373,88 @@
|
||||
</div>
|
||||
</div>`;
|
||||
}
|
||||
const _sslStream = (domain, accountId, label) => {
|
||||
const termId = 'ssl-term-' + Date.now();
|
||||
Nova.modal(`SSL: ${label || domain}`, `
|
||||
<div id="${termId}" style="background:#1a1a2e;color:#e0e0e0;font-family:monospace;font-size:.82rem;
|
||||
padding:1rem;border-radius:6px;height:260px;overflow-y:auto;white-space:pre-wrap;line-height:1.5">
|
||||
<span style="color:#7ec8e3">Requesting certificate…</span>\n
|
||||
</div>`,
|
||||
`<button class="btn btn-ghost" id="ssl-term-close" onclick="this.closest('.modal-overlay').remove()">Close</button>`);
|
||||
const term = document.getElementById(termId);
|
||||
const append = t => { term.textContent += t; term.scrollTop = term.scrollHeight; };
|
||||
fetch('/api/ssl/issue', {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ domain, account_id: accountId }),
|
||||
credentials: 'same-origin',
|
||||
}).then(resp => {
|
||||
if (!resp.ok) { append(`\nHTTP error ${resp.status}`); return; }
|
||||
const reader = resp.body.getReader();
|
||||
const dec = new TextDecoder();
|
||||
let buf = '';
|
||||
const read = () => reader.read().then(({ done, value }) => {
|
||||
if (done) { append('\n[done]'); return; }
|
||||
buf += dec.decode(value, { stream: true });
|
||||
const parts = buf.split('\n\n');
|
||||
buf = parts.pop();
|
||||
for (const part of parts) {
|
||||
const m = part.match(/^data: (.+)$/m);
|
||||
if (!m) continue;
|
||||
try {
|
||||
const obj = JSON.parse(m[1]);
|
||||
if (obj.line) { append(obj.line); }
|
||||
else if (obj.done) {
|
||||
const btn = document.getElementById('ssl-term-close');
|
||||
if (btn) {
|
||||
btn.textContent = obj.success ? 'Done ✓' : 'Close';
|
||||
btn.className = obj.success ? 'btn btn-primary' : 'btn btn-ghost';
|
||||
btn.onclick = () => { document.querySelector('.modal-overlay')?.remove(); adminPage('ssl-manager'); };
|
||||
}
|
||||
}
|
||||
} catch(e) {}
|
||||
}
|
||||
read();
|
||||
}).catch(err => append(`\n[error: ${err.message}]`));
|
||||
read();
|
||||
}).catch(err => append(`\nFetch error: ${err.message}`));
|
||||
};
|
||||
|
||||
window.adminIssueBulkSSL = async () => {
|
||||
Nova.toast('Queuing SSL for all domains without certificates…','info',6000);
|
||||
const accts = await Nova.api('accounts','list',{params:{limit:1000}});
|
||||
let count = 0;
|
||||
for (const a of (accts?.data || [])) {
|
||||
await Nova.api('ssl','issue',{method:'POST',body:{domain:a.domain}});
|
||||
count++;
|
||||
const domains = (accts?.data || []).map(a => ({domain: a.domain, id: a.id}));
|
||||
if (!domains.length) { Nova.toast('No accounts found','error'); return; }
|
||||
const termId = 'ssl-bulk-' + Date.now();
|
||||
Nova.modal('Bulk SSL Issuance', `
|
||||
<div id="${termId}" style="background:#1a1a2e;color:#e0e0e0;font-family:monospace;font-size:.82rem;
|
||||
padding:1rem;border-radius:6px;height:300px;overflow-y:auto;white-space:pre-wrap;line-height:1.5">
|
||||
<span style="color:#7ec8e3">Starting bulk SSL for ${domains.length} domains…</span>\n
|
||||
</div>`,
|
||||
`<button class="btn btn-ghost" id="ssl-bulk-close" onclick="this.closest('.modal-overlay').remove()">Close</button>`);
|
||||
const term = document.getElementById(termId);
|
||||
const append = t => { term.textContent += t; term.scrollTop = term.scrollHeight; };
|
||||
let done = 0;
|
||||
for (const a of domains) {
|
||||
append(`\n[${++done}/${domains.length}] ${a.domain}…\n`);
|
||||
try {
|
||||
const r = await Nova.api('ssl','issue',{method:'POST',body:{domain:a.domain,account_id:a.id}});
|
||||
append(r?.success ? ` ✓ Issued\n` : ` ✗ ${r?.message || 'failed'}\n`);
|
||||
} catch(e) { append(` ✗ ${e.message}\n`); }
|
||||
}
|
||||
Nova.toast(`SSL issued for ${count} domains`,'success');
|
||||
adminPage('ssl-manager');
|
||||
append(`\nDone. ${done} domains processed.\n`);
|
||||
const btn = document.getElementById('ssl-bulk-close');
|
||||
if (btn) { btn.textContent = 'Done'; btn.className = 'btn btn-primary'; btn.onclick = () => { document.querySelector('.modal-overlay')?.remove(); adminPage('ssl-manager'); }; }
|
||||
};
|
||||
window.adminRenewCert = async (id) => {
|
||||
Nova.toast('Renewing…','info');
|
||||
const r = await Nova.api('ssl','renew',{method:'POST',body:{cert_id:id}});
|
||||
if (r?.success) { Nova.toast('Renewed','success'); adminPage('ssl-manager'); }
|
||||
else Nova.toast(r?.message,'error');
|
||||
|
||||
window.adminRenewCert = (id) => {
|
||||
Nova.confirm('Renew this SSL certificate now?', async () => {
|
||||
const r = await Nova.api('ssl','renew',{method:'POST',body:{cert_id:id}});
|
||||
if (r?.success) { Nova.toast('Renewed','success'); adminPage('ssl-manager'); }
|
||||
else Nova.toast(r?.message,'error');
|
||||
});
|
||||
};
|
||||
|
||||
window.adminIssueSingleSSL = (domain, accountId) => _sslStream(domain, accountId, domain);
|
||||
window.adminDelCert = (id, domain) => {
|
||||
Nova.confirm(`Delete SSL cert for ${domain}?`, async () => {
|
||||
const r = await Nova.api('ssl','delete',{method:'POST',body:{cert_id:id}});
|
||||
@@ -1425,6 +1533,7 @@
|
||||
const fwIgnoreips = ignoreipRes?.data?.ignoreip || ignoreipRes?.data?.detected || [];
|
||||
const rules = fw.rules || [];
|
||||
const active = fw.active;
|
||||
const curLogging = fw.logging || 'off';
|
||||
|
||||
const totalBanned = jails.reduce((s,j) => s + (j.currently_banned||0), 0);
|
||||
|
||||
@@ -1654,7 +1763,7 @@
|
||||
<div class="form-group mb-0">
|
||||
<label class="form-label text-sm">Log Level</label>
|
||||
<select id="fw-log-level" class="form-control form-control-sm">
|
||||
${['off','on','low','medium','high','full'].map(l=>`<option value="${l}">${l.charAt(0).toUpperCase()+l.slice(1)}</option>`).join('')}
|
||||
${['off','on','low','medium','high','full'].map(l=>`<option value="${l}" ${l===curLogging?'selected':''}>${l.charAt(0).toUpperCase()+l.slice(1)}</option>`).join('')}
|
||||
</select>
|
||||
</div>
|
||||
<button class="btn btn-sm btn-primary" onclick="fwSetLogging()">Apply</button>
|
||||
@@ -2079,7 +2188,12 @@ ${ips.length ? `
|
||||
window.fwSetLogging = async () => {
|
||||
const level = document.getElementById('fw-log-level')?.value;
|
||||
const r = await Nova.api('firewall','set-logging',{method:'POST',body:{level}});
|
||||
Nova.toast(r?.message || 'Logging updated', r?.success ? 'success' : 'error');
|
||||
if (r?.success) {
|
||||
Nova.toast(`UFW logging set to ${level}`, 'success');
|
||||
adminPage('firewall');
|
||||
} else {
|
||||
Nova.toast(r?.message || 'Logging update failed — UFW may need to be enabled first', 'error');
|
||||
}
|
||||
};
|
||||
|
||||
function fwIgnoreipChip(ip) {
|
||||
|
||||
Reference in New Issue
Block a user