mirror of
https://github.com/myronblair/novacpx
synced 2026-06-30 17:50:41 -05:00
Nginx proxy: remote VM support via SSH
- ProxyManager: all ops (start/stop/reload, config push) work over SSH when proxy_mode=remote; sysctl/reload/writeHostConfig/deleteHost all route to remoteExec/remotePush helpers - proxy.php: add GET/POST /api/proxy/settings and POST /api/proxy/test-remote - admin.js: Settings modal with mode selector + remote fields + Test Connection; page header always shows Settings button; status card shows mode + remote host; 'not installed' state directs to Configure Remote Proxy VM Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
This commit is contained in:
+190
-89
@@ -2,6 +2,13 @@
|
||||
/**
|
||||
* ProxyManager — manages Nginx reverse proxy for NovaCPX hosted accounts.
|
||||
* Supports local nginx (on same VM) or remote nginx (separate proxy VM via SSH).
|
||||
*
|
||||
* Settings keys:
|
||||
* proxy_mode — 'disabled' | 'local' | 'remote'
|
||||
* proxy_remote_host — IP/hostname of remote nginx VM
|
||||
* proxy_remote_user — SSH user (default: root)
|
||||
* proxy_remote_pass — SSH password
|
||||
* proxy_backend_ip — IP of NovaCPX Apache server (used when syncing proxy hosts)
|
||||
*/
|
||||
class ProxyManager {
|
||||
|
||||
@@ -9,60 +16,107 @@ class ProxyManager {
|
||||
private static string $enabledDir = '/etc/nginx/sites-enabled';
|
||||
private static string $confPrefix = 'novacpx-proxy-';
|
||||
|
||||
// --- Remote helpers ---
|
||||
|
||||
private static function isRemote(): bool {
|
||||
$db = DB::getInstance();
|
||||
return ($db->fetchOne("SELECT value FROM settings WHERE `key`='proxy_mode'")['value'] ?? '') === 'remote';
|
||||
}
|
||||
|
||||
private static function getRemote(): array {
|
||||
$db = DB::getInstance();
|
||||
$get = fn(string $k, string $d = '') => $db->fetchOne("SELECT value FROM settings WHERE `key`=?", [$k])['value'] ?? $d;
|
||||
return [
|
||||
'host' => $get('proxy_remote_host'),
|
||||
'user' => $get('proxy_remote_user', 'root'),
|
||||
'pass' => $get('proxy_remote_pass'),
|
||||
];
|
||||
}
|
||||
|
||||
private static function remoteExec(string $cmd): string {
|
||||
$r = self::getRemote();
|
||||
if (!$r['host']) return 'no remote host configured';
|
||||
return shell_exec(
|
||||
'sshpass -p ' . escapeshellarg($r['pass']) .
|
||||
' ssh -o StrictHostKeyChecking=no -o ConnectTimeout=5 ' .
|
||||
escapeshellarg($r['user'] . '@' . $r['host']) . ' ' .
|
||||
escapeshellarg($cmd) . ' 2>&1'
|
||||
) ?? '';
|
||||
}
|
||||
|
||||
private static function remotePush(string $content, string $remotePath): void {
|
||||
$encoded = base64_encode($content);
|
||||
self::remoteExec('echo ' . escapeshellarg($encoded) . ' | base64 -d > ' . escapeshellarg($remotePath));
|
||||
}
|
||||
|
||||
// --- Status & Control ---
|
||||
|
||||
public static function isInstalled(): bool {
|
||||
if (self::isRemote()) {
|
||||
return trim(self::remoteExec('which nginx')) !== '';
|
||||
}
|
||||
return file_exists('/usr/sbin/nginx') || !empty(shell_exec('which nginx 2>/dev/null'));
|
||||
}
|
||||
|
||||
public static function isRunning(): bool {
|
||||
$out = shell_exec('systemctl is-active nginx 2>/dev/null');
|
||||
return trim($out ?? '') === 'active';
|
||||
if (self::isRemote()) {
|
||||
return trim(self::remoteExec('systemctl is-active nginx')) === 'active';
|
||||
}
|
||||
return trim(shell_exec('systemctl is-active nginx 2>/dev/null') ?? '') === 'active';
|
||||
}
|
||||
|
||||
public static function status(): array {
|
||||
$db = DB::getInstance();
|
||||
$get = fn(string $k, string $d = '') => $db->fetchOne("SELECT value FROM settings WHERE `key`=?", [$k])['value'] ?? $d;
|
||||
$mode = $get('proxy_mode', 'disabled');
|
||||
$remote = self::isRemote();
|
||||
|
||||
$installed = self::isInstalled();
|
||||
$running = $installed && self::isRunning();
|
||||
$version = $installed ? trim(shell_exec('nginx -v 2>&1') ?: '') : '';
|
||||
$db = DB::getInstance();
|
||||
$row = $db->fetchOne("SELECT value FROM settings WHERE `key` = 'proxy_mode'");
|
||||
$mode = $row['value'] ?? 'disabled';
|
||||
return [
|
||||
'installed' => $installed,
|
||||
'running' => $running,
|
||||
'version' => $version,
|
||||
'mode' => $mode,
|
||||
$version = '';
|
||||
if ($installed) {
|
||||
$raw = $remote ? self::remoteExec('nginx -v') : (shell_exec('nginx -v 2>&1') ?: '');
|
||||
$version = trim($raw);
|
||||
}
|
||||
|
||||
$data = [
|
||||
'installed' => $installed,
|
||||
'running' => $running,
|
||||
'version' => $version,
|
||||
'mode' => $mode,
|
||||
];
|
||||
if ($remote) {
|
||||
$data['remote_host'] = $get('proxy_remote_host');
|
||||
$data['remote_user'] = $get('proxy_remote_user', 'root');
|
||||
}
|
||||
return $data;
|
||||
}
|
||||
|
||||
public static function start(): string {
|
||||
return self::sysctl('start');
|
||||
}
|
||||
|
||||
public static function stop(): string {
|
||||
return self::sysctl('stop');
|
||||
}
|
||||
|
||||
public static function restart(): string {
|
||||
return self::sysctl('restart');
|
||||
}
|
||||
public static function start(): string { return self::sysctl('start'); }
|
||||
public static function stop(): string { return self::sysctl('stop'); }
|
||||
public static function restart(): string { return self::sysctl('restart'); }
|
||||
|
||||
public static function reload(): string {
|
||||
if (!self::isInstalled()) return 'nginx not installed';
|
||||
$test = shell_exec('sudo nginx -t 2>&1');
|
||||
if (self::isRemote()) {
|
||||
$test = self::remoteExec('nginx -t');
|
||||
if (strpos($test, 'successful') === false) return 'Config test failed: ' . $test;
|
||||
self::remoteExec('systemctl reload nginx');
|
||||
return 'reloaded';
|
||||
}
|
||||
$test = shell_exec('nginx -t 2>&1');
|
||||
if (strpos($test ?? '', 'successful') === false) return 'Config test failed: ' . $test;
|
||||
shell_exec('sudo systemctl reload nginx 2>/dev/null');
|
||||
shell_exec('systemctl reload nginx 2>/dev/null');
|
||||
return 'reloaded';
|
||||
}
|
||||
|
||||
public static function install(): string {
|
||||
if (self::isRemote()) return 'Use the setup script to install nginx on the remote proxy VM';
|
||||
if (self::isInstalled()) return 'already installed';
|
||||
shell_exec('sudo apt-get update -qq 2>/dev/null && sudo apt-get install -y nginx 2>&1');
|
||||
shell_exec('apt-get update -qq 2>/dev/null && apt-get install -y nginx 2>&1');
|
||||
if (!self::isInstalled()) return 'install failed';
|
||||
// Disable default site
|
||||
@unlink('/etc/nginx/sites-enabled/default');
|
||||
shell_exec('sudo systemctl enable nginx 2>/dev/null');
|
||||
shell_exec('sudo systemctl start nginx 2>/dev/null');
|
||||
shell_exec('systemctl enable nginx 2>/dev/null');
|
||||
shell_exec('systemctl start nginx 2>/dev/null');
|
||||
return 'installed';
|
||||
}
|
||||
|
||||
@@ -74,15 +128,17 @@ class ProxyManager {
|
||||
}
|
||||
|
||||
public static function syncFromAccounts(): int {
|
||||
$db = DB::getInstance();
|
||||
$accounts = $db->fetchAll("SELECT a.*, d.domain FROM accounts a JOIN domains d ON d.account_id=a.id AND d.type='main' WHERE a.status='active'") ?: [];
|
||||
$count = 0;
|
||||
$db = DB::getInstance();
|
||||
$backendIp = $db->fetchOne("SELECT value FROM settings WHERE `key`='proxy_backend_ip'")['value'] ?? '127.0.0.1';
|
||||
$accounts = $db->fetchAll(
|
||||
"SELECT a.*, d.domain FROM accounts a JOIN domains d ON d.account_id=a.id AND d.type='main' WHERE a.status='active'"
|
||||
) ?: [];
|
||||
$count = 0;
|
||||
foreach ($accounts as $acct) {
|
||||
$existing = $db->fetchOne("SELECT id FROM proxy_hosts WHERE domain=?", [$acct['domain']]);
|
||||
if (!$existing) {
|
||||
if (!$db->fetchOne("SELECT id FROM proxy_hosts WHERE domain=?", [$acct['domain']])) {
|
||||
$db->insert(
|
||||
"INSERT INTO proxy_hosts (account_id, domain, upstream, ssl_enabled, enabled, created_at) VALUES (?,?,?,0,1,NOW())",
|
||||
[$acct['id'], $acct['domain'], 'http://127.0.0.1:80']
|
||||
[$acct['id'], $acct['domain'], "http://{$backendIp}:80"]
|
||||
);
|
||||
$count++;
|
||||
}
|
||||
@@ -92,8 +148,8 @@ class ProxyManager {
|
||||
}
|
||||
|
||||
public static function addHost(array $data): int {
|
||||
$db = DB::getInstance();
|
||||
$id = (int)$db->insert(
|
||||
$db = DB::getInstance();
|
||||
$id = (int)$db->insert(
|
||||
"INSERT INTO proxy_hosts (account_id, domain, upstream, ssl_enabled, enabled, custom_config, created_at) VALUES (?,?,?,?,1,?,NOW())",
|
||||
[
|
||||
$data['account_id'] ?? null,
|
||||
@@ -121,8 +177,16 @@ class ProxyManager {
|
||||
$host = $db->fetchOne("SELECT domain FROM proxy_hosts WHERE id=?", [$id]);
|
||||
$db->execute("DELETE FROM proxy_hosts WHERE id=?", [$id]);
|
||||
if ($host) {
|
||||
@unlink(self::$confDir . '/' . self::$confPrefix . $host['domain'] . '.conf');
|
||||
@unlink(self::$enabledDir . '/' . self::$confPrefix . $host['domain'] . '.conf');
|
||||
$safe = preg_replace('/[^a-z0-9._-]/', '', strtolower($host['domain']));
|
||||
if (self::isRemote()) {
|
||||
self::remoteExec('rm -f ' .
|
||||
escapeshellarg(self::$confDir . '/' . self::$confPrefix . $safe . '.conf') . ' ' .
|
||||
escapeshellarg(self::$enabledDir . '/' . self::$confPrefix . $safe . '.conf')
|
||||
);
|
||||
} else {
|
||||
@unlink(self::$confDir . '/' . self::$confPrefix . $safe . '.conf');
|
||||
@unlink(self::$enabledDir . '/' . self::$confPrefix . $safe . '.conf');
|
||||
}
|
||||
}
|
||||
self::reload();
|
||||
}
|
||||
@@ -139,9 +203,21 @@ class ProxyManager {
|
||||
if (!self::isInstalled()) return;
|
||||
$db = DB::getInstance();
|
||||
$hosts = $db->fetchAll("SELECT * FROM proxy_hosts") ?: [];
|
||||
// Remove old novacpx proxy configs
|
||||
foreach (glob(self::$confDir . '/' . self::$confPrefix . '*.conf') ?: [] as $f) @unlink($f);
|
||||
foreach (glob(self::$enabledDir . '/' . self::$confPrefix . '*.conf') ?: [] as $f) @unlink($f);
|
||||
|
||||
if (self::isRemote()) {
|
||||
// Remove old proxy configs on remote
|
||||
self::remoteExec('rm -f ' .
|
||||
escapeshellarg(self::$confDir . '/' . self::$confPrefix . '*.conf') . ' ' .
|
||||
escapeshellarg(self::$enabledDir . '/' . self::$confPrefix . '*.conf')
|
||||
);
|
||||
// Use glob expansion via shell, not escaped
|
||||
self::remoteExec('rm -f ' . self::$confDir . '/' . self::$confPrefix . '*.conf ' .
|
||||
self::$enabledDir . '/' . self::$confPrefix . '*.conf');
|
||||
} else {
|
||||
foreach (glob(self::$confDir . '/' . self::$confPrefix . '*.conf') ?: [] as $f) @unlink($f);
|
||||
foreach (glob(self::$enabledDir . '/' . self::$confPrefix . '*.conf') ?: [] as $f) @unlink($f);
|
||||
}
|
||||
|
||||
foreach ($hosts as $host) {
|
||||
if (!$host['enabled']) continue;
|
||||
self::writeHostConfig($host);
|
||||
@@ -151,65 +227,84 @@ class ProxyManager {
|
||||
|
||||
private static function writeHostConfig(array $host): void {
|
||||
$safe = preg_replace('/[^a-z0-9._-]/', '', strtolower($host['domain']));
|
||||
$confPath = self::$confDir . '/' . self::$confPrefix . $safe . '.conf';
|
||||
$confPath = self::$confDir . '/' . self::$confPrefix . $safe . '.conf';
|
||||
$linkPath = self::$enabledDir . '/' . self::$confPrefix . $safe . '.conf';
|
||||
|
||||
if ($host['custom_config']) {
|
||||
file_put_contents($confPath, $host['custom_config']);
|
||||
} else {
|
||||
$upstream = rtrim($host['upstream'], '/');
|
||||
$ssl = !empty($host['ssl_enabled']);
|
||||
$certDir = "/etc/novacpx/ssl/accounts/" . preg_replace('/[^a-z0-9._-]/', '', $host['domain']);
|
||||
$content = $host['custom_config'] ?: self::buildConf($host);
|
||||
|
||||
$conf = "server {\n";
|
||||
$conf .= " listen 80;\n";
|
||||
if ($ssl) $conf .= " listen 443 ssl http2;\n";
|
||||
$conf .= " server_name {$host['domain']} www.{$host['domain']};\n";
|
||||
if ($ssl) {
|
||||
$conf .= " ssl_certificate {$certDir}/cert.pem;\n";
|
||||
$conf .= " ssl_certificate_key {$certDir}/key.pem;\n";
|
||||
$conf .= " ssl_protocols TLSv1.2 TLSv1.3;\n";
|
||||
$conf .= " ssl_ciphers HIGH:!aNULL:!MD5;\n";
|
||||
}
|
||||
$conf .= " location / {\n";
|
||||
$conf .= " proxy_pass {$upstream};\n";
|
||||
$conf .= " proxy_http_version 1.1;\n";
|
||||
$conf .= " proxy_set_header Host \$host;\n";
|
||||
$conf .= " proxy_set_header X-Real-IP \$remote_addr;\n";
|
||||
$conf .= " proxy_set_header X-Forwarded-For \$proxy_add_x_forwarded_for;\n";
|
||||
$conf .= " proxy_set_header X-Forwarded-Proto \$scheme;\n";
|
||||
$conf .= " proxy_set_header Upgrade \$http_upgrade;\n";
|
||||
$conf .= " proxy_set_header Connection 'upgrade';\n";
|
||||
$conf .= " proxy_cache_bypass \$http_upgrade;\n";
|
||||
$conf .= " proxy_read_timeout 86400;\n";
|
||||
$conf .= " }\n";
|
||||
$conf .= "}\n";
|
||||
file_put_contents($confPath, $conf);
|
||||
if (self::isRemote()) {
|
||||
self::remotePush($content, $confPath);
|
||||
self::remoteExec('ln -sf ' . escapeshellarg($confPath) . ' ' . escapeshellarg($linkPath));
|
||||
} else {
|
||||
file_put_contents($confPath, $content);
|
||||
@symlink($confPath, $linkPath);
|
||||
}
|
||||
@symlink($confPath, $linkPath);
|
||||
}
|
||||
|
||||
private static function buildConf(array $host): string {
|
||||
$upstream = rtrim($host['upstream'], '/');
|
||||
$ssl = !empty($host['ssl_enabled']);
|
||||
$certDir = '/etc/novacpx/ssl/accounts/' . preg_replace('/[^a-z0-9._-]/', '', $host['domain']);
|
||||
|
||||
$c = "server {\n";
|
||||
$c .= " listen 80;\n";
|
||||
if ($ssl) $c .= " listen 443 ssl http2;\n";
|
||||
$c .= " server_name {$host['domain']} www.{$host['domain']};\n";
|
||||
if ($ssl) {
|
||||
$c .= " ssl_certificate {$certDir}/cert.pem;\n";
|
||||
$c .= " ssl_certificate_key {$certDir}/key.pem;\n";
|
||||
$c .= " ssl_protocols TLSv1.2 TLSv1.3;\n";
|
||||
$c .= " ssl_ciphers HIGH:!aNULL:!MD5;\n";
|
||||
}
|
||||
$c .= " location / {\n";
|
||||
$c .= " proxy_pass {$upstream};\n";
|
||||
$c .= " proxy_http_version 1.1;\n";
|
||||
$c .= " proxy_set_header Host \$host;\n";
|
||||
$c .= " proxy_set_header X-Real-IP \$remote_addr;\n";
|
||||
$c .= " proxy_set_header X-Forwarded-For \$proxy_add_x_forwarded_for;\n";
|
||||
$c .= " proxy_set_header X-Forwarded-Proto \$scheme;\n";
|
||||
$c .= " proxy_set_header Upgrade \$http_upgrade;\n";
|
||||
$c .= " proxy_set_header Connection 'upgrade';\n";
|
||||
$c .= " proxy_cache_bypass \$http_upgrade;\n";
|
||||
$c .= " proxy_read_timeout 86400;\n";
|
||||
$c .= " }\n";
|
||||
$c .= "}\n";
|
||||
return $c;
|
||||
}
|
||||
|
||||
// --- Remote connectivity test ---
|
||||
|
||||
public static function testRemote(): array {
|
||||
$r = self::getRemote();
|
||||
if (!$r['host']) return ['ok' => false, 'message' => 'No remote host configured'];
|
||||
$out = self::remoteExec('nginx -v');
|
||||
if (strpos($out, 'nginx') === false) {
|
||||
return ['ok' => false, 'message' => 'Connected but nginx not found: ' . trim($out)];
|
||||
}
|
||||
return ['ok' => true, 'message' => 'Connected — ' . trim($out)];
|
||||
}
|
||||
|
||||
// --- Setup Script ---
|
||||
|
||||
public static function setupScript(): string {
|
||||
$serverIp = trim(shell_exec("hostname -I | awk '{print $1}'") ?: '127.0.0.1');
|
||||
$serverIp = trim(shell_exec("hostname -I | awk '{print \$1}'") ?: '127.0.0.1');
|
||||
return <<<BASH
|
||||
#!/bin/bash
|
||||
# NovaCPX Nginx Reverse Proxy Setup Script
|
||||
# Run as root on the proxy VM (or this VM for local proxy)
|
||||
# Run as root on the dedicated proxy VM
|
||||
set -e
|
||||
|
||||
echo "[NovaCPX] Installing Nginx reverse proxy..."
|
||||
apt-get update -qq
|
||||
apt-get install -y nginx certbot python3-certbot-nginx
|
||||
apt-get install -y nginx openssh-server
|
||||
|
||||
# Disable default site
|
||||
rm -f /etc/nginx/sites-enabled/default
|
||||
|
||||
# Create NovaCPX proxy conf directory
|
||||
# Create NovaCPX proxy conf directories
|
||||
mkdir -p /etc/nginx/sites-available /etc/nginx/sites-enabled
|
||||
|
||||
# Main nginx.conf tuning
|
||||
# Tune nginx for proxying
|
||||
cat > /etc/nginx/conf.d/novacpx-proxy.conf << 'EOF'
|
||||
client_max_body_size 256M;
|
||||
proxy_buffers 16 16k;
|
||||
@@ -218,11 +313,8 @@ gzip on;
|
||||
gzip_types text/plain text/css application/json application/javascript text/xml application/xml;
|
||||
EOF
|
||||
|
||||
# Point proxy back to NovaCPX Apache backend (update SERVER_IP below)
|
||||
BACKEND_IP={$serverIp}
|
||||
|
||||
# Generic catch-all for testing
|
||||
cat > /etc/nginx/sites-available/novacpx-default.conf << EOF
|
||||
# Catch-all that drops unrecognised hosts
|
||||
cat > /etc/nginx/sites-available/novacpx-default.conf << 'EOF'
|
||||
server {
|
||||
listen 80 default_server;
|
||||
server_name _;
|
||||
@@ -231,21 +323,30 @@ server {
|
||||
EOF
|
||||
ln -sf /etc/nginx/sites-available/novacpx-default.conf /etc/nginx/sites-enabled/
|
||||
|
||||
# Test and reload
|
||||
nginx -t && systemctl reload nginx
|
||||
systemctl enable nginx
|
||||
|
||||
echo "[NovaCPX] Nginx proxy installed and running."
|
||||
echo " Backend IP: \$BACKEND_IP"
|
||||
echo " Add proxy hosts from the NovaCPX admin panel → Nginx Proxy"
|
||||
echo " NovaCPX backend (Apache): {$serverIp}"
|
||||
echo ""
|
||||
echo " Now go to NovaCPX Admin -> Nginx Proxy -> Settings and set:"
|
||||
echo " Mode: remote"
|
||||
echo " Remote host: <this VM's IP>"
|
||||
echo " Remote user: root"
|
||||
echo " Remote pass: <this VM's root password>"
|
||||
echo " Backend IP: {$serverIp}"
|
||||
BASH;
|
||||
}
|
||||
|
||||
// --- Helpers ---
|
||||
|
||||
private static function sysctl(string $action): string {
|
||||
if (!self::isInstalled()) return 'nginx not installed';
|
||||
shell_exec("sudo systemctl {$action} nginx 2>/dev/null");
|
||||
if (self::isRemote()) {
|
||||
self::remoteExec("systemctl {$action} nginx");
|
||||
sleep(1);
|
||||
return self::isRunning() ? 'running' : 'stopped';
|
||||
}
|
||||
shell_exec("systemctl {$action} nginx 2>/dev/null");
|
||||
sleep(1);
|
||||
return self::isRunning() ? 'running' : 'stopped';
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user