diff --git a/db/migrations/002_features_14_17.sql b/db/migrations/002_features_14_17.sql new file mode 100644 index 0000000..d01c183 --- /dev/null +++ b/db/migrations/002_features_14_17.sql @@ -0,0 +1,29 @@ +-- Migration 002: Features #14-17 (WordPress, Backup, Cloudflare, TOTP) +ALTER TABLE users ADD COLUMN totp_secret VARCHAR(64) DEFAULT NULL; +ALTER TABLE users ADD COLUMN totp_enabled TINYINT(1) DEFAULT 0; +ALTER TABLE users ADD COLUMN totp_backup_codes TEXT DEFAULT NULL; +ALTER TABLE accounts ADD COLUMN cf_api_key VARCHAR(255) DEFAULT NULL; +ALTER TABLE accounts ADD COLUMN cf_api_email VARCHAR(255) DEFAULT NULL; +ALTER TABLE accounts ADD COLUMN cf_zone_id VARCHAR(64) DEFAULT NULL; +ALTER TABLE dns_zones ADD COLUMN cf_zone_id VARCHAR(64) DEFAULT NULL; +CREATE TABLE IF NOT EXISTS wordpress_installs ( + id INT AUTO_INCREMENT PRIMARY KEY,account_id INT NOT NULL,domain VARCHAR(255) NOT NULL, + path VARCHAR(255) DEFAULT '/',db_name VARCHAR(64) DEFAULT NULL,db_user VARCHAR(64) DEFAULT NULL, + db_pass VARCHAR(128) DEFAULT NULL,wp_version VARCHAR(20) DEFAULT NULL,admin_user VARCHAR(64) DEFAULT NULL, + admin_email VARCHAR(255) DEFAULT NULL,status ENUM('active','updating','suspended') DEFAULT 'active', + staging_of INT DEFAULT NULL,created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP, + updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,INDEX (account_id) +) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci; +CREATE TABLE IF NOT EXISTS backups ( + id INT AUTO_INCREMENT PRIMARY KEY,account_id INT NOT NULL,filename VARCHAR(255) NOT NULL, + size BIGINT DEFAULT 0,type ENUM('full','files','database') DEFAULT 'full', + status ENUM('pending','running','complete','failed') DEFAULT 'pending', + storage VARCHAR(50) DEFAULT 'local',remote_path VARCHAR(500) DEFAULT NULL, + created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,INDEX (account_id),INDEX (status) +) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci; +CREATE TABLE IF NOT EXISTS backup_schedules ( + id INT AUTO_INCREMENT PRIMARY KEY,account_id INT NOT NULL UNIQUE, + frequency ENUM('hourly','daily','weekly','monthly') DEFAULT 'daily', + type ENUM('full','files','database') DEFAULT 'full',retain_count INT DEFAULT 7, + last_run TIMESTAMP NULL,created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,INDEX (account_id) +) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci; diff --git a/panel/api/endpoints/auth.php b/panel/api/endpoints/auth.php index 981dd5d..9fa9414 100644 --- a/panel/api/endpoints/auth.php +++ b/panel/api/endpoints/auth.php @@ -4,11 +4,15 @@ $body = json_decode(file_get_contents('php://input'), true) ?? []; match ($action) { 'login' => (function() use ($body) { - $username = trim($body['username'] ?? ''); - $password = $body['password'] ?? ''; + $username = trim($body['username'] ?? ''); + $password = $body['password'] ?? ''; + $totpCode = isset($body['totp_code']) ? trim($body['totp_code']) : null; if (!$username || !$password) Response::error('Username and password required'); $auth = Auth::getInstance(); - $token = $auth->attempt($username, $password); + $token = $auth->attempt($username, $password, $totpCode); + if ($token === Auth::TOTP_REQUIRED) { + Response::json(['success' => false, 'totp_required' => true, 'message' => 'Enter your 2FA code'], 200); + } if (!$token) { // Log failure for Fail2Ban to detect $ip = $_SERVER['REMOTE_ADDR'] ?? 'unknown'; diff --git a/panel/api/endpoints/backup.php b/panel/api/endpoints/backup.php new file mode 100644 index 0000000..a3df798 --- /dev/null +++ b/panel/api/endpoints/backup.php @@ -0,0 +1,82 @@ + (function() use ($bm, $accountId, $isAdmin) { + $list = $bm->list($isAdmin ? $accountId : $accountId); + Response::success(['backups' => $list, 'disk_used' => $bm->diskUsage($accountId)]); + })(), + + 'create' => (function() use ($bm, $body, $accountId) { + if (!$accountId) Response::error('account_id required'); + $type = in_array($body['type'] ?? 'full', ['full','files','database']) ? $body['type'] : 'full'; + $result = $bm->create($accountId, $type); + audit('backup_create', 'backup', ['account_id' => $accountId, 'type' => $type]); + Response::success($result, 'Backup created successfully'); + })(), + + 'restore' => (function() use ($bm, $body, $isAdmin) { + if (!$isAdmin) Response::error('Admin only', 403); + $id = (int)($body['id'] ?? 0); + if (!$id) Response::error('id required'); + $bm->restore($id); + audit('backup_restore', 'backup', ['id' => $id]); + Response::success(null, 'Backup restored successfully'); + })(), + + 'download' => (function() use ($bm, $body) { + $id = (int)($body['id'] ?? $_GET['id'] ?? 0); + if (!$id) Response::error('id required'); + $path = $bm->getDownloadPath($id); + $name = basename($path); + header('Content-Type: application/gzip'); + header("Content-Disposition: attachment; filename=\"{$name}\""); + header('Content-Length: ' . filesize($path)); + ob_end_clean(); + readfile($path); + exit; + })(), + + 'delete' => (function() use ($bm, $body, $isAdmin) { + if (!$isAdmin) Response::error('Admin only', 403); + $id = (int)($body['id'] ?? 0); + if (!$id) Response::error('id required'); + $bm->delete($id); + audit('backup_delete', 'backup', ['id' => $id]); + Response::success(null, 'Backup deleted'); + })(), + + 'schedule' => (function() use ($bm, $body, $accountId, $isAdmin) { + if (!$isAdmin) Response::error('Admin only', 403); + if (!$accountId) Response::error('account_id required'); + $freq = $body['frequency'] ?? 'daily'; + $type = $body['type'] ?? 'full'; + $retain = (int)($body['retain'] ?? 7); + $bm->setSchedule($accountId, $freq, $type, $retain); + Response::success(null, 'Backup schedule saved'); + })(), + + 'get-schedule' => (function() use ($bm, $accountId) { + if (!$accountId) Response::error('account_id required'); + Response::success($bm->getSchedule($accountId)); + })(), + + 'upload-remote' => (function() use ($bm, $body, $isAdmin) { + if (!$isAdmin) Response::error('Admin only', 403); + $id = (int)($body['id'] ?? 0); + $remote = trim($body['remote'] ?? ''); + if (!$id || !$remote) Response::error('id and remote required'); + $out = $bm->uploadRemote($id, $remote); + Response::success(['output' => $out], 'Upload complete'); + })(), + + default => Response::error('Unknown action', 404), +}; diff --git a/panel/api/endpoints/cloudflare.php b/panel/api/endpoints/cloudflare.php new file mode 100644 index 0000000..eb99783 --- /dev/null +++ b/panel/api/endpoints/cloudflare.php @@ -0,0 +1,99 @@ +getCredentials($accountId); + $apiKey = $creds['cf_api_key'] ?? null; + $email = $creds['cf_api_email'] ?? null; +} + +match ($action) { + 'test-key' => (function() use ($cf, $body) { + $key = trim($body['api_key'] ?? ''); + $email = trim($body['email'] ?? ''); + if (!$key || !$email) Response::error('api_key and email required'); + $ok = $cf->testCredentials($key, $email); + Response::success(['valid' => $ok], $ok ? 'API key is valid' : 'Invalid API key'); + })(), + + 'save-credentials' => (function() use ($cf, $body, $accountId) { + if (!$accountId) Response::error('account_id required'); + $key = trim($body['api_key'] ?? ''); + $email = trim($body['email'] ?? ''); + if (!$key || !$email) Response::error('api_key and email required'); + $cf->saveCredentials($accountId, $key, $email); + audit('cf_credentials_saved', 'cloudflare', ['account_id' => $accountId]); + Response::success(null, 'Cloudflare credentials saved'); + })(), + + 'get-credentials' => (function() use ($cf, $accountId) { + if (!$accountId) Response::error('account_id required'); + $creds = $cf->getCredentials($accountId); + // Mask the key in the response + if ($creds) $creds['cf_api_key'] = substr($creds['cf_api_key'], 0, 6) . str_repeat('*', 30); + Response::success($creds); + })(), + + 'list-zones' => (function() use ($cf, $apiKey, $email) { + if (!$apiKey || !$email) Response::error('No Cloudflare credentials configured'); + Response::success($cf->listZones($apiKey, $email)); + })(), + + 'list-records' => (function() use ($cf, $body, $apiKey, $email) { + $zoneId = trim($body['zone_id'] ?? ''); + if (!$zoneId) Response::error('zone_id required'); + if (!$apiKey || !$email) Response::error('No Cloudflare credentials configured'); + Response::success($cf->listRecords($zoneId, $apiKey, $email)); + })(), + + 'toggle-proxy' => (function() use ($cf, $body, $apiKey, $email) { + $zoneId = trim($body['zone_id'] ?? ''); + $recordId = trim($body['record_id'] ?? ''); + $proxied = (bool)($body['proxied'] ?? false); + if (!$zoneId || !$recordId) Response::error('zone_id and record_id required'); + if (!$apiKey || !$email) Response::error('No credentials'); + $result = $cf->toggleProxy($zoneId, $recordId, $proxied, $apiKey, $email); + Response::success($result, 'Proxy status updated'); + })(), + + 'sync-to-cf' => (function() use ($cf, $body, $apiKey, $email) { + $domain = trim($body['domain'] ?? ''); + $zoneId = trim($body['zone_id'] ?? ''); + if (!$domain || !$zoneId) Response::error('domain and zone_id required'); + if (!$apiKey || !$email) Response::error('No credentials'); + $result = $cf->syncToCloudflare($domain, $zoneId, $apiKey, $email); + audit('cf_sync_to', 'cloudflare', ['domain' => $domain]); + Response::success($result, "Pushed to Cloudflare: {$result['created']} created, {$result['updated']} updated"); + })(), + + 'sync-from-cf' => (function() use ($cf, $body, $apiKey, $email) { + $domain = trim($body['domain'] ?? ''); + $zoneId = trim($body['zone_id'] ?? ''); + if (!$domain || !$zoneId) Response::error('domain and zone_id required'); + if (!$apiKey || !$email) Response::error('No credentials'); + $count = $cf->syncFromCloudflare($domain, $zoneId, $apiKey, $email); + audit('cf_sync_from', 'cloudflare', ['domain' => $domain, 'records' => $count]); + Response::success(['count' => $count], "Pulled {$count} records from Cloudflare"); + })(), + + 'purge-cache' => (function() use ($cf, $body, $apiKey, $email) { + $zoneId = trim($body['zone_id'] ?? ''); + if (!$zoneId) Response::error('zone_id required'); + if (!$apiKey || !$email) Response::error('No credentials'); + $ok = $cf->purgeCache($zoneId, $apiKey, $email); + Response::success(['success' => $ok], $ok ? 'Cache purged' : 'Purge failed'); + })(), + + default => Response::error('Unknown action', 404), +}; diff --git a/panel/api/endpoints/totp.php b/panel/api/endpoints/totp.php new file mode 100644 index 0000000..4704d39 --- /dev/null +++ b/panel/api/endpoints/totp.php @@ -0,0 +1,90 @@ +getPDO(); + +match ($action) { + // Begin setup: generate secret + return QR URL (not yet enabled) + 'setup' => (function() use ($db, $uid, $currentUser) { + $secret = TOTP::generateSecret(); + // Store pending secret (not enabled yet until verified) + $db->prepare("UPDATE users SET totp_secret=? WHERE id=?")->execute([$secret, $uid]); + Response::success([ + 'secret' => $secret, + 'qr_url' => TOTP::qrUrl($secret, $currentUser['username']), + ], 'Scan QR code in your authenticator app, then confirm with a code'); + })(), + + // Confirm setup: verify first code, then enable TOTP and return backup codes + 'enable' => (function() use ($db, $uid, $body) { + $code = trim($body['code'] ?? ''); + if (strlen($code) !== 6) Response::error('Enter the 6-digit code from your authenticator'); + $stmt = $db->prepare("SELECT totp_secret FROM users WHERE id=?"); + $stmt->execute([$uid]); + $secret = $stmt->fetchColumn(); + if (!$secret) Response::error('Run setup first'); + if (!TOTP::verify($secret, $code)) Response::error('Code incorrect — try again'); + $backupCodes = TOTP::generateBackupCodes(); + $hashedCodes = TOTP::hashBackupCodes($backupCodes); + $db->prepare("UPDATE users SET totp_enabled=1, totp_backup_codes=? WHERE id=?")->execute([$hashedCodes, $uid]); + audit('totp_enabled', 'security'); + Response::success(['backup_codes' => $backupCodes], '2FA enabled. Save your backup codes — they will not be shown again.'); + })(), + + // Disable TOTP (requires current password confirmation) + 'disable' => (function() use ($db, $uid, $body) { + $pass = $body['password'] ?? ''; + $stmt = $db->prepare("SELECT password FROM users WHERE id=?"); + $stmt->execute([$uid]); + $hash = $stmt->fetchColumn(); + if (!password_verify($pass, $hash)) Response::error('Password incorrect'); + $db->prepare("UPDATE users SET totp_enabled=0, totp_secret=NULL, totp_backup_codes=NULL WHERE id=?")->execute([$uid]); + audit('totp_disabled', 'security'); + Response::success(null, '2FA disabled'); + })(), + + // Get status (is 2FA on?) + 'status' => (function() use ($db, $uid) { + $stmt = $db->prepare("SELECT totp_enabled FROM users WHERE id=?"); + $stmt->execute([$uid]); + $enabled = (bool)$stmt->fetchColumn(); + Response::success(['enabled' => $enabled]); + })(), + + // Regenerate backup codes + 'regen-backup-codes' => (function() use ($db, $uid, $body) { + $code = trim($body['code'] ?? ''); + $stmt = $db->prepare("SELECT totp_secret, totp_enabled FROM users WHERE id=?"); + $stmt->execute([$uid]); + $row = $stmt->fetch(PDO::FETCH_ASSOC); + if (!$row['totp_enabled']) Response::error('2FA not enabled'); + if (!TOTP::verify($row['totp_secret'], $code)) Response::error('Code incorrect'); + $backupCodes = TOTP::generateBackupCodes(); + $db->prepare("UPDATE users SET totp_backup_codes=? WHERE id=?")->execute([TOTP::hashBackupCodes($backupCodes), $uid]); + Response::success(['backup_codes' => $backupCodes], 'Backup codes regenerated'); + })(), + + // Admin: get 2FA status for any user + 'admin-status' => (function() use ($db, $body, $currentUser) { + if ($currentUser['role'] !== 'admin') Response::error('Admin only', 403); + $userId = (int)($body['user_id'] ?? 0); + if (!$userId) Response::error('user_id required'); + $stmt = $db->prepare("SELECT id, username, totp_enabled FROM users WHERE id=?"); + $stmt->execute([$userId]); + Response::success($stmt->fetch(PDO::FETCH_ASSOC)); + })(), + + // Admin: force-disable 2FA for a user (account recovery) + 'admin-disable' => (function() use ($db, $body, $currentUser) { + if ($currentUser['role'] !== 'admin') Response::error('Admin only', 403); + $userId = (int)($body['user_id'] ?? 0); + if (!$userId) Response::error('user_id required'); + $db->prepare("UPDATE users SET totp_enabled=0, totp_secret=NULL, totp_backup_codes=NULL WHERE id=?")->execute([$userId]); + audit('totp_admin_disabled', 'security', ['user_id' => $userId]); + Response::success(null, '2FA disabled for user'); + })(), + + default => Response::error('Unknown action', 404), +}; diff --git a/panel/api/endpoints/wordpress.php b/panel/api/endpoints/wordpress.php new file mode 100644 index 0000000..6bd3f32 --- /dev/null +++ b/panel/api/endpoints/wordpress.php @@ -0,0 +1,72 @@ + (function() use ($wp, $accountId, $isAdmin) { + Response::success($wp->list($isAdmin ? $accountId : $accountId)); + })(), + + 'install' => (function() use ($wp, $body, $accountId, $currentUser) { + $required = ['domain','path','admin_user','admin_email','admin_pass','site_title']; + foreach ($required as $f) if (empty($body[$f])) Response::error("Missing: {$f}"); + if (!$accountId) Response::error('account_id required'); + $result = $wp->install($accountId, $body['domain'], $body['path'], + $body['admin_user'], $body['admin_email'], $body['admin_pass'], $body['site_title']); + audit('wordpress_install', 'wordpress', ['domain' => $body['domain']]); + Response::success($result, 'WordPress installed successfully'); + })(), + + 'update-core' => (function() use ($wp, $body) { + $id = (int)($body['id'] ?? 0); + if (!$id) Response::error('id required'); + Response::success(['output' => $wp->updateCore($id)], 'Core updated'); + })(), + + 'update-plugins' => (function() use ($wp, $body) { + $id = (int)($body['id'] ?? 0); + if (!$id) Response::error('id required'); + Response::success(['output' => $wp->updatePlugins($id)], 'Plugins updated'); + })(), + + 'update-themes' => (function() use ($wp, $body) { + $id = (int)($body['id'] ?? 0); + if (!$id) Response::error('id required'); + Response::success(['output' => $wp->updateThemes($id)], 'Themes updated'); + })(), + + 'clone-staging' => (function() use ($wp, $body) { + $id = (int)($body['id'] ?? 0); + if (!$id) Response::error('id required'); + $result = $wp->cloneStaging($id); + audit('wordpress_staging', 'wordpress', ['id' => $id]); + Response::success($result, 'Staging clone created'); + })(), + + 'info' => (function() use ($wp, $body) { + $id = (int)($body['id'] ?? $_GET['id'] ?? 0); + if (!$id) Response::error('id required'); + Response::success($wp->info($id)); + })(), + + 'delete' => (function() use ($wp, $body, $isAdmin) { + if (!$isAdmin) Response::error('Admin only', 403); + $id = (int)($body['id'] ?? 0); + if (!$id) Response::error('id required'); + $wp->delete($id); + audit('wordpress_delete', 'wordpress', ['id' => $id]); + Response::success(null, 'WordPress installation deleted'); + })(), + + default => Response::error('Unknown action', 404), +}; diff --git a/panel/lib/Auth.php b/panel/lib/Auth.php index 76614eb..5c4769a 100644 --- a/panel/lib/Auth.php +++ b/panel/lib/Auth.php @@ -1,8 +1,13 @@ fetchOne( "SELECT * FROM users WHERE (username = ? OR email = ?) AND status = 'active'", [$username, $username] ); if (!$user || !password_verify($password, $user['password'])) return null; + // TOTP check + if (!empty($user['totp_enabled'])) { + if ($totpCode === null) { + $this->user = $user; + return self::TOTP_REQUIRED; + } + $verified = TOTP::verify($user['totp_secret'] ?? '', $totpCode); + if (!$verified && !empty($user['totp_backup_codes'])) { + $verified = TOTP::verifyBackupCode($totpCode, $user['totp_backup_codes']); + if ($verified) { + // Consume used backup code + $hashes = json_decode($user['totp_backup_codes'], true) ?? []; + $hashes = array_values(array_filter($hashes, fn($h) => !password_verify(strtoupper($totpCode), $h))); + $db->execute("UPDATE users SET totp_backup_codes=? WHERE id=?", [json_encode($hashes), $user['id']]); + } + } + if (!$verified) return null; + } + // Create session $token = bin2hex(random_bytes(32)); $sessionId = hash('sha256', $token); diff --git a/panel/lib/BackupManager.php b/panel/lib/BackupManager.php new file mode 100644 index 0000000..22f31de --- /dev/null +++ b/panel/lib/BackupManager.php @@ -0,0 +1,165 @@ +db = Database::getInstance()->getPDO(); + if (!is_dir($this->backupRoot)) mkdir($this->backupRoot, 0750, true); + } + + // ── Create full backup ──────────────────────────────────────────────────── + public function create(int $accountId, string $type = 'full'): array { + $account = $this->getAccount($accountId); + $dir = $this->backupRoot . '/' . $account['username']; + if (!is_dir($dir)) mkdir($dir, 0750, true); + + $ts = date('Ymd_His'); + $filename = "{$account['username']}_{$type}_{$ts}.tar.gz"; + $filepath = "{$dir}/{$filename}"; + + // Record as pending + $stmt = $this->db->prepare("INSERT INTO backups (account_id, filename, type, status, storage) VALUES (?,?,?,'running','local')"); + $stmt->execute([$accountId, $filename, $type]); + $backupId = $this->db->lastInsertId(); + + try { + if ($type === 'full' || $type === 'files') { + $docRoot = escapeshellarg($account['document_root']); + exec("tar -czf " . escapeshellarg($filepath) . " -C / " . ltrim($docRoot, '/') . " 2>&1", $out, $rc); + if ($rc !== 0) throw new RuntimeException("tar failed: " . implode("\n", $out)); + } + + if ($type === 'full' || $type === 'database') { + // Dump all databases belonging to this account + $dbs = $this->db->prepare("SELECT db_name FROM account_databases WHERE account_id=?"); + $dbs->execute([$accountId]); + foreach ($dbs->fetchAll(PDO::FETCH_COLUMN) as $dbName) { + $dumpFile = escapeshellarg("{$dir}/{$account['username']}_{$dbName}_{$ts}.sql.gz"); + exec("mysqldump " . escapeshellarg($dbName) . " | gzip > {$dumpFile} 2>&1"); + } + + if ($type === 'database') { + // Pack all sql.gz files into the tar + exec("tar -czf " . escapeshellarg($filepath) . " -C {$dir} " . + escapeshellarg("{$account['username']}_{$ts}") . "*.sql.gz 2>/dev/null"); + } + } + + $size = file_exists($filepath) ? filesize($filepath) : 0; + $this->db->prepare("UPDATE backups SET status='complete', size=? WHERE id=?")->execute([$size, $backupId]); + return ['id' => $backupId, 'filename' => $filename, 'size' => $size]; + + } catch (RuntimeException $e) { + $this->db->prepare("UPDATE backups SET status='failed' WHERE id=?")->execute([$backupId]); + throw $e; + } + } + + // ── List ────────────────────────────────────────────────────────────────── + public function list(int $accountId = 0): array { + if ($accountId) { + $stmt = $this->db->prepare("SELECT b.*, a.username FROM backups b JOIN accounts a ON b.account_id=a.id WHERE b.account_id=? ORDER BY b.created_at DESC"); + $stmt->execute([$accountId]); + } else { + $stmt = $this->db->query("SELECT b.*, a.username FROM backups b JOIN accounts a ON b.account_id=a.id ORDER BY b.created_at DESC"); + } + return $stmt->fetchAll(PDO::FETCH_ASSOC); + } + + // ── Download ────────────────────────────────────────────────────────────── + public function getDownloadPath(int $backupId): string { + $stmt = $this->db->prepare("SELECT b.*, a.username FROM backups b JOIN accounts a ON b.account_id=a.id WHERE b.id=?"); + $stmt->execute([$backupId]); + $backup = $stmt->fetch(PDO::FETCH_ASSOC); + if (!$backup) throw new RuntimeException("Backup not found"); + $path = $this->backupRoot . '/' . $backup['username'] . '/' . $backup['filename']; + if (!file_exists($path)) throw new RuntimeException("Backup file missing from disk"); + return $path; + } + + // ── Restore ─────────────────────────────────────────────────────────────── + public function restore(int $backupId): bool { + $stmt = $this->db->prepare("SELECT b.*, a.document_root, a.username FROM backups b JOIN accounts a ON b.account_id=a.id WHERE b.id=?"); + $stmt->execute([$backupId]); + $backup = $stmt->fetch(PDO::FETCH_ASSOC); + if (!$backup) throw new RuntimeException("Backup not found"); + + $path = $this->backupRoot . '/' . $backup['username'] . '/' . $backup['filename']; + if (!file_exists($path)) throw new RuntimeException("Backup file not found on disk"); + + exec("tar -xzf " . escapeshellarg($path) . " -C / 2>&1", $out, $rc); + if ($rc !== 0) throw new RuntimeException("Restore failed: " . implode("\n", $out)); + return true; + } + + // ── Delete ──────────────────────────────────────────────────────────────── + public function delete(int $backupId): bool { + $stmt = $this->db->prepare("SELECT b.*, a.username FROM backups b JOIN accounts a ON b.account_id=a.id WHERE b.id=?"); + $stmt->execute([$backupId]); + $backup = $stmt->fetch(PDO::FETCH_ASSOC); + if ($backup) { + $path = $this->backupRoot . '/' . $backup['username'] . '/' . $backup['filename']; + if (file_exists($path)) unlink($path); + $this->db->prepare("DELETE FROM backups WHERE id=?")->execute([$backupId]); + } + return true; + } + + // ── Schedule ────────────────────────────────────────────────────────────── + public function setSchedule(int $accountId, string $frequency, string $type = 'full', int $retain = 7): bool { + $stmt = $this->db->prepare("INSERT INTO backup_schedules (account_id, frequency, type, retain_count) + VALUES (?,?,?,?) ON DUPLICATE KEY UPDATE frequency=VALUES(frequency), type=VALUES(type), retain_count=VALUES(retain_count)"); + $stmt->execute([$accountId, $frequency, $type, $retain]); + return true; + } + + public function getSchedule(int $accountId): ?array { + $stmt = $this->db->prepare("SELECT * FROM backup_schedules WHERE account_id=?"); + $stmt->execute([$accountId]); + return $stmt->fetch(PDO::FETCH_ASSOC) ?: null; + } + + // ── Prune old backups per retention policy ──────────────────────────────── + public function prune(int $accountId): int { + $schedule = $this->getSchedule($accountId); + if (!$schedule) return 0; + $retain = (int)$schedule['retain_count']; + $stmt = $this->db->prepare("SELECT * FROM backups WHERE account_id=? AND status='complete' ORDER BY created_at DESC"); + $stmt->execute([$accountId]); + $all = $stmt->fetchAll(PDO::FETCH_ASSOC); + $pruned = 0; + foreach (array_slice($all, $retain) as $old) { + $this->delete($old['id']); + $pruned++; + } + return $pruned; + } + + // ── rclone remote upload ────────────────────────────────────────────────── + public function uploadRemote(int $backupId, string $remote): string { + $path = $this->getDownloadPath($backupId); + $out = []; exec("rclone copy " . escapeshellarg($path) . " " . escapeshellarg($remote) . " 2>&1", $out, $rc); + if ($rc === 0) { + $this->db->prepare("UPDATE backups SET storage='remote', remote_path=? WHERE id=?")->execute([$remote, $backupId]); + } + return implode("\n", $out); + } + + // ── Disk usage ──────────────────────────────────────────────────────────── + public function diskUsage(int $accountId = 0): int { + if ($accountId) { + $stmt = $this->db->prepare("SELECT COALESCE(SUM(size),0) FROM backups WHERE account_id=? AND status='complete'"); + $stmt->execute([$accountId]); + } else { + $stmt = $this->db->query("SELECT COALESCE(SUM(size),0) FROM backups WHERE status='complete'"); + } + return (int)$stmt->fetchColumn(); + } + + private function getAccount(int $id): array { + $stmt = $this->db->prepare("SELECT * FROM accounts WHERE id=?"); + $stmt->execute([$id]); + return $stmt->fetch(PDO::FETCH_ASSOC) ?: throw new RuntimeException("Account not found"); + } +} diff --git a/panel/lib/CloudflareManager.php b/panel/lib/CloudflareManager.php new file mode 100644 index 0000000..5e91152 --- /dev/null +++ b/panel/lib/CloudflareManager.php @@ -0,0 +1,150 @@ +db = Database::getInstance()->getPDO(); + } + + // ── Credential management ───────────────────────────────────────────────── + public function saveCredentials(int $accountId, string $apiKey, string $email): bool { + $stmt = $this->db->prepare("UPDATE accounts SET cf_api_key=?, cf_api_email=? WHERE id=?"); + return $stmt->execute([$apiKey, $email, $accountId]); + } + + public function testCredentials(string $apiKey, string $email): bool { + $r = $this->req('GET', 'user/tokens/verify', [], $apiKey, $email); + return $r['success'] ?? false; + } + + public function getCredentials(int $accountId): ?array { + $stmt = $this->db->prepare("SELECT cf_api_key, cf_api_email, cf_zone_id FROM accounts WHERE id=?"); + $stmt->execute([$accountId]); + $row = $stmt->fetch(PDO::FETCH_ASSOC); + return ($row && $row['cf_api_key']) ? $row : null; + } + + // ── Zones ───────────────────────────────────────────────────────────────── + public function listZones(string $apiKey, string $email): array { + $r = $this->req('GET', 'zones?per_page=200&status=active', [], $apiKey, $email); + return $r['result'] ?? []; + } + + public function getZoneId(string $domain, string $apiKey, string $email): ?string { + $r = $this->req('GET', 'zones?name=' . urlencode($domain), [], $apiKey, $email); + return $r['result'][0]['id'] ?? null; + } + + // ── DNS records ─────────────────────────────────────────────────────────── + public function listRecords(string $zoneId, string $apiKey, string $email): array { + $r = $this->req('GET', "zones/{$zoneId}/dns_records?per_page=200", [], $apiKey, $email); + return $r['result'] ?? []; + } + + public function createRecord(string $zoneId, array $record, string $apiKey, string $email): array { + return $this->req('POST', "zones/{$zoneId}/dns_records", $record, $apiKey, $email); + } + + public function updateRecord(string $zoneId, string $recordId, array $record, string $apiKey, string $email): array { + return $this->req('PUT', "zones/{$zoneId}/dns_records/{$recordId}", $record, $apiKey, $email); + } + + public function deleteRecord(string $zoneId, string $recordId, string $apiKey, string $email): bool { + $r = $this->req('DELETE', "zones/{$zoneId}/dns_records/{$recordId}", [], $apiKey, $email); + return $r['success'] ?? false; + } + + public function toggleProxy(string $zoneId, string $recordId, bool $proxied, string $apiKey, string $email): array { + // Fetch existing record first + $r = $this->req('GET', "zones/{$zoneId}/dns_records/{$recordId}", [], $apiKey, $email); + $rec = $r['result'] ?? []; + $rec['proxied'] = $proxied; + unset($rec['id'], $rec['zone_id'], $rec['zone_name'], $rec['created_on'], $rec['modified_on'], $rec['meta']); + return $this->req('PUT', "zones/{$zoneId}/dns_records/{$recordId}", $rec, $apiKey, $email); + } + + // ── Sync: push local DNS records to Cloudflare ──────────────────────────── + public function syncToCloudflare(string $domain, string $zoneId, string $apiKey, string $email): array { + $localRecords = $this->getLocalRecords($domain); + $cfRecords = $this->listRecords($zoneId, $apiKey, $email); + $cfIndex = []; + foreach ($cfRecords as $r) $cfIndex[$r['type'] . '_' . $r['name']] = $r; + + $created = 0; $updated = 0; + foreach ($localRecords as $local) { + $key = $local['type'] . '_' . $local['name'] . '.' . $domain . '.'; + if (isset($cfIndex[$key])) { + $this->updateRecord($zoneId, $cfIndex[$key]['id'], [ + 'type' => $local['type'], + 'name' => $local['name'], + 'content' => $local['content'], + 'ttl' => (int)($local['ttl'] ?? 1), + 'proxied' => in_array($local['type'], ['A','AAAA','CNAME']), + ], $apiKey, $email); + $updated++; + } else { + $this->createRecord($zoneId, [ + 'type' => $local['type'], + 'name' => $local['name'], + 'content' => $local['content'], + 'ttl' => (int)($local['ttl'] ?? 1), + 'proxied' => in_array($local['type'], ['A','AAAA','CNAME']), + ], $apiKey, $email); + $created++; + } + } + return ['created' => $created, 'updated' => $updated]; + } + + // ── Sync: pull Cloudflare records into local DB ─────────────────────────── + public function syncFromCloudflare(string $domain, string $zoneId, string $apiKey, string $email): int { + $cfRecords = $this->listRecords($zoneId, $apiKey, $email); + $count = 0; + foreach ($cfRecords as $rec) { + $name = rtrim(str_replace('.' . $domain, '', $rec['name']), '.'); + $this->db->prepare("INSERT INTO dns_records (domain, name, type, content, ttl, priority) + VALUES (?,?,?,?,?,?) ON DUPLICATE KEY UPDATE content=VALUES(content), ttl=VALUES(ttl)") + ->execute([$domain, $name ?: '@', $rec['type'], $rec['content'], $rec['ttl'] ?? 300, $rec['priority'] ?? 0]); + $count++; + } + // Store zone ID on domain + $this->db->prepare("UPDATE dns_zones SET cf_zone_id=? WHERE domain=?")->execute([$zoneId, $domain]); + return $count; + } + + // ── Purge cache ─────────────────────────────────────────────────────────── + public function purgeCache(string $zoneId, string $apiKey, string $email): bool { + $r = $this->req('POST', "zones/{$zoneId}/purge_cache", ['purge_everything' => true], $apiKey, $email); + return $r['success'] ?? false; + } + + // ── HTTP helper ─────────────────────────────────────────────────────────── + private function req(string $method, string $path, array $body, string $apiKey, string $email): array { + $ch = curl_init(self::API . ltrim($path, '/')); + $headers = [ + "X-Auth-Email: {$email}", + "X-Auth-Key: {$apiKey}", + "Content-Type: application/json", + ]; + curl_setopt_array($ch, [ + CURLOPT_CUSTOMREQUEST => $method, + CURLOPT_HTTPHEADER => $headers, + CURLOPT_RETURNTRANSFER => true, + CURLOPT_TIMEOUT => 15, + CURLOPT_SSL_VERIFYPEER => true, + ]); + if ($body && in_array($method, ['POST','PUT','PATCH'])) { + curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($body)); + } + $result = curl_exec($ch); + curl_close($ch); + return json_decode($result, true) ?? ['success' => false, 'errors' => ['curl failed']]; + } + + private function getLocalRecords(string $domain): array { + $stmt = $this->db->prepare("SELECT * FROM dns_records WHERE domain=?"); + $stmt->execute([$domain]); + return $stmt->fetchAll(PDO::FETCH_ASSOC); + } +} diff --git a/panel/lib/TOTP.php b/panel/lib/TOTP.php new file mode 100644 index 0000000..bc5afa1 --- /dev/null +++ b/panel/lib/TOTP.php @@ -0,0 +1,78 @@ + password_hash($c, PASSWORD_BCRYPT), $codes)); + } + + public static function verifyBackupCode(string $code, string $hashedJson): bool { + $hashes = json_decode($hashedJson, true) ?? []; + foreach ($hashes as $hash) { + if (password_verify(strtoupper($code), $hash)) return true; + } + return false; + } + + private static function base32Decode(string $base32): string { + $base32 = strtoupper(preg_replace('/[^A-Z2-7]/', '', $base32)); + $buf = 0; $bits = 0; $out = ''; + for ($i = 0; $i < strlen($base32); $i++) { + $val = strpos(self::CHARS, $base32[$i]); + $buf = ($buf << 5) | $val; + $bits += 5; + if ($bits >= 8) { $bits -= 8; $out .= chr(($buf >> $bits) & 0xFF); } + } + return $out; + } +} diff --git a/panel/lib/WordPressManager.php b/panel/lib/WordPressManager.php new file mode 100644 index 0000000..ca3d386 --- /dev/null +++ b/panel/lib/WordPressManager.php @@ -0,0 +1,174 @@ +db = Database::getInstance()->getPDO(); + $this->ensureWpCli(); + } + + // ── Install ─────────────────────────────────────────────────────────────── + public function install(int $accountId, string $domain, string $path, + string $adminUser, string $adminEmail, string $adminPass, + string $siteTitle): array { + $account = $this->getAccount($accountId); + $docRoot = $account['document_root'] . rtrim($path, '/'); + $dbName = 'wp_' . preg_replace('/[^a-z0-9]/', '_', strtolower($account['username'])) . '_' . substr(md5($domain), 0, 6); + $dbPass = bin2hex(random_bytes(12)); + $dbUser = substr($dbName, 0, 32); + + // Create DB + $this->db->exec("CREATE DATABASE IF NOT EXISTS `{$dbName}` CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci"); + $this->db->exec("CREATE USER IF NOT EXISTS '{$dbUser}'@'localhost' IDENTIFIED BY '{$dbPass}'"); + $this->db->exec("GRANT ALL ON `{$dbName}`.* TO '{$dbUser}'@'localhost'"); + + // Download WP + install + $sysUser = $account['system_user'] ?? 'www-data'; + $this->wp($docRoot, "core download --locale=en_US", $sysUser); + $this->wp($docRoot, "config create --dbname={$dbName} --dbuser={$dbUser} --dbpass={$dbPass} --dbhost=localhost --skip-check", $sysUser); + $this->wp($docRoot, sprintf( + 'core install --url=https://%s --title="%s" --admin_user=%s --admin_password=%s --admin_email=%s --skip-email', + escapeshellarg($domain . $path), escapeshellarg($siteTitle), + escapeshellarg($adminUser), escapeshellarg($adminPass), escapeshellarg($adminEmail) + ), $sysUser); + + // Store in DB + $stmt = $this->db->prepare("INSERT INTO wordpress_installs + (account_id, domain, path, db_name, db_user, db_pass, admin_user, admin_email, wp_version, status) + VALUES (?,?,?,?,?,?,?,?,?,?)"); + $stmt->execute([$accountId, $domain, $path, $dbName, $dbUser, $dbPass, $adminUser, $adminEmail, + $this->getVersion($docRoot, $sysUser), 'active']); + $id = $this->db->lastInsertId(); + + return ['id' => $id, 'db_name' => $dbName, 'admin_user' => $adminUser, 'admin_pass' => $adminPass]; + } + + // ── List ────────────────────────────────────────────────────────────────── + public function list(int $accountId = 0): array { + $sql = $accountId + ? "SELECT w.*, a.domain as account_domain FROM wordpress_installs w JOIN accounts a ON w.account_id=a.id WHERE w.account_id=? ORDER BY w.created_at DESC" + : "SELECT w.*, a.domain as account_domain FROM wordpress_installs w JOIN accounts a ON w.account_id=a.id ORDER BY w.created_at DESC"; + $stmt = $this->db->prepare($sql); + $accountId ? $stmt->execute([$accountId]) : $stmt->execute(); + return $stmt->fetchAll(PDO::FETCH_ASSOC); + } + + // ── Update ──────────────────────────────────────────────────────────────── + public function updateCore(int $id): string { + [$install, $sysUser, $docRoot] = $this->resolve($id); + $out = $this->wp($docRoot, 'core update', $sysUser); + $ver = $this->getVersion($docRoot, $sysUser); + $this->db->prepare("UPDATE wordpress_installs SET wp_version=? WHERE id=?")->execute([$ver, $id]); + return $out; + } + + public function updatePlugins(int $id): string { + [$install, $sysUser, $docRoot] = $this->resolve($id); + return $this->wp($docRoot, 'plugin update --all', $sysUser); + } + + public function updateThemes(int $id): string { + [$install, $sysUser, $docRoot] = $this->resolve($id); + return $this->wp($docRoot, 'theme update --all', $sysUser); + } + + // ── Staging clone ───────────────────────────────────────────────────────── + public function cloneStaging(int $id): array { + [$install, $sysUser, $docRoot] = $this->resolve($id); + $stagingPath = $install['path'] . '_staging'; + $stagingDomain = 'staging.' . $install['domain']; + $stagingRoot = dirname($docRoot) . rtrim($stagingPath, '/'); + + // Copy files + $this->exec("cp -r {$docRoot} {$stagingRoot}"); + + // Clone DB + $stagingDb = $install['db_name'] . '_staging'; + $stagingDbPw = bin2hex(random_bytes(8)); + $this->db->exec("CREATE DATABASE IF NOT EXISTS `{$stagingDb}`"); + $this->db->exec("CREATE USER IF NOT EXISTS '{$stagingDb}'@'localhost' IDENTIFIED BY '{$stagingDbPw}'"); + $this->db->exec("GRANT ALL ON `{$stagingDb}`.* TO '{$stagingDb}'@'localhost'"); + $this->exec("mysqldump {$install['db_name']} | mysql {$stagingDb}"); + + // Update staging wp-config + $this->wp($stagingRoot, "config set DB_NAME {$stagingDb}", $sysUser); + $this->wp($stagingRoot, "config set DB_USER {$stagingDb}", $sysUser); + $this->wp($stagingRoot, "config set DB_PASSWORD {$stagingDbPw}", $sysUser); + $this->wp($stagingRoot, "search-replace https://{$install['domain']} https://{$stagingDomain} --all-tables", $sysUser); + + // Record staging install + $stmt = $this->db->prepare("INSERT INTO wordpress_installs + (account_id,domain,path,db_name,db_user,db_pass,admin_user,admin_email,wp_version,status,staging_of) + VALUES (?,?,?,?,?,?,?,?,?,?,?)"); + $stmt->execute([$install['account_id'], $stagingDomain, $stagingPath, + $stagingDb, $stagingDb, $stagingDbPw, + $install['admin_user'], $install['admin_email'], $install['wp_version'], 'active', $id]); + + return ['domain' => $stagingDomain, 'path' => $stagingPath]; + } + + // ── Delete ──────────────────────────────────────────────────────────────── + public function delete(int $id): bool { + [$install, $sysUser, $docRoot] = $this->resolve($id); + $this->exec("rm -rf {$docRoot}"); + $this->db->exec("DROP DATABASE IF EXISTS `{$install['db_name']}`"); + $this->db->exec("DROP USER IF EXISTS '{$install['db_user']}'@'localhost'"); + $this->db->prepare("DELETE FROM wordpress_installs WHERE id=?")->execute([$id]); + return true; + } + + // ── Info ────────────────────────────────────────────────────────────────── + public function info(int $id): array { + [$install, $sysUser, $docRoot] = $this->resolve($id); + $plugins = $this->wp($docRoot, 'plugin list --format=json', $sysUser); + $themes = $this->wp($docRoot, 'theme list --format=json', $sysUser); + return [ + 'install' => $install, + 'plugins' => json_decode($plugins, true) ?? [], + 'themes' => json_decode($themes, true) ?? [], + 'version' => $this->getVersion($docRoot, $sysUser), + ]; + } + + // ── Helpers ─────────────────────────────────────────────────────────────── + private function wp(string $path, string $cmd, string $user): string { + $safe = escapeshellarg($path); + $out = []; $rc = 0; + exec("sudo -u {$user} {$this->wpcli} --path={$safe} --allow-root {$cmd} 2>&1", $out, $rc); + return implode("\n", $out); + } + + private function exec(string $cmd): string { + $out = []; exec($cmd . ' 2>&1', $out); return implode("\n", $out); + } + + private function getVersion(string $path, string $user): string { + $v = trim($this->wp($path, 'core version', $user)); + return $v ?: 'unknown'; + } + + private function resolve(int $id): array { + $stmt = $this->db->prepare("SELECT w.*, a.document_root, a.system_user, a.username FROM wordpress_installs w JOIN accounts a ON w.account_id=a.id WHERE w.id=?"); + $stmt->execute([$id]); + $install = $stmt->fetch(PDO::FETCH_ASSOC); + if (!$install) throw new RuntimeException("WordPress install #{$id} not found"); + $docRoot = $install['document_root'] . rtrim($install['path'], '/'); + $sysUser = $install['system_user'] ?? 'www-data'; + return [$install, $sysUser, $docRoot]; + } + + private function getAccount(int $id): array { + $stmt = $this->db->prepare("SELECT * FROM accounts WHERE id=?"); + $stmt->execute([$id]); + return $stmt->fetch(PDO::FETCH_ASSOC) ?: throw new RuntimeException("Account #{$id} not found"); + } + + private function ensureWpCli(): void { + if (!file_exists($this->wpcli)) { + file_put_contents('/tmp/wp-cli.phar', file_get_contents('https://raw.githubusercontent.com/wp-cli/builds/gh-pages/phar/wp-cli.phar')); + rename('/tmp/wp-cli.phar', $this->wpcli); + chmod($this->wpcli, 0755); + } + } +} diff --git a/panel/public/admin/index.php b/panel/public/admin/index.php index b772b3d..202bf99 100644 --- a/panel/public/admin/index.php +++ b/panel/public/admin/index.php @@ -97,6 +97,10 @@ FTP Server + + + WordPress +
`; } - // ── Backups ──────────────────────────────────────────────────────────────── - async function backups() { - const res = await Nova.api('accounts','list',{params:{limit:1000}}); - const accts = res?.data?.accounts || []; - return ` -| Account | Domain | Actions |
|---|---|---|
| ${a.username} | -${a.domain} | -- - | -
Loading…
`; } + async function cloudflare() { return `Loading…
`; } + async function twofa() { return `Loading…
`; } // ── Global action helpers ────────────────────────────────────────────────── window.adminPage = (page) => Nova.loadPage(page, pages); @@ -1406,3 +1409,513 @@ ${ips.length ? ` if (badge && total > 0) { badge.textContent = total; badge.style.display = ''; } } })(); +// ── ADDITIONS: appended by features #14-17 ──────────────────────────────── + +// ── WordPress Manager (#14) ──────────────────────────────────────────────── +async function wordpress() { + const [acctRes, wpRes] = await Promise.all([ + Nova.api('accounts','list',{params:{limit:500}}), + Nova.api('wordpress','list'), + ]); + const accts = acctRes?.data?.accounts || []; + const installs = wpRes?.data?.installs || []; + window._adminAcctsWP = accts; + + return ` +| Domain | Path | Account | Version | Status | Actions |
|---|---|---|---|---|---|
| ${Nova.escHtml(w.domain)} | +${Nova.escHtml(w.path||'/')} |
+ ${Nova.escHtml(w.username||'—')} | +${w.wp_version ? `${Nova.escHtml(w.wp_version)}` : '—'} |
+ ${Nova.badge(w.status||'active', w.status==='active'?'green':w.status==='updating'?'yellow':'red')} | ++ + + + + ${!w.staging_of ? `` : `staging`} + + | +
wp-cli will be downloaded automatically if not installed. This may take 1-2 minutes.
`, + ` + `); +}; + +window.wpSubmitInstall = async () => { + const btn = document.getElementById('wp-install-btn'); + if (btn) { btn.disabled = true; btn.textContent = 'Installing…'; } + Nova.toast('Installing WordPress — this may take 1-2 minutes…', 'info', 90000); + const res = await Nova.api('wordpress','install',{method:'POST',body:{ + account_id: +document.getElementById('wp-acct')?.value, + domain: document.getElementById('wp-domain')?.value, + path: document.getElementById('wp-path')?.value || '/', + site_title: document.getElementById('wp-title')?.value, + admin_user: document.getElementById('wp-admin')?.value, + admin_pass: document.getElementById('wp-adminpass')?.value, + admin_email:document.getElementById('wp-email')?.value, + }}); + document.querySelector('.modal-overlay')?.remove(); + if (res?.success) { Nova.toast('WordPress installed!','success'); adminPage('wordpress'); } + else Nova.toast(res?.message || 'Install failed','error'); +}; + +window.wpUpdate = async (id, type) => { + const action = type === 'core' ? 'update-core' : type === 'plugins' ? 'update-plugins' : 'update-themes'; + Nova.toast(`Updating ${type}…`,'info',15000); + const r = await Nova.api('wordpress', action, {method:'POST',body:{install_id:id}}); + Nova.toast(r?.message || (r?.success ? 'Updated' : 'Failed'), r?.success ? 'success' : 'error'); + if (r?.success) adminPage('wordpress'); +}; + +window.wpInfo = async (id, domain) => { + Nova.toast('Loading info…','info',5000); + const r = await Nova.api('wordpress','info',{params:{install_id:id}}); + if (!r?.success) { Nova.toast(r?.message,'error'); return; } + const d = r.data || {}; + const plugins = (d.plugins||[]).map(p => `Core Version
${Nova.escHtml(d.version||'—')}
Site URL
${Nova.escHtml(d.siteurl||'—')}
| Plugin | Version | Status |
|---|
None
'} +| Theme | Version | Status |
|---|
None
'}`); +}; + +window.wpCloneStaging = (id, domain) => { + Nova.confirm(`Clone ${domain} to a staging environment? This copies all files and the database.`, async () => { + Nova.toast('Cloning to staging…','info',30000); + const r = await Nova.api('wordpress','clone-staging',{method:'POST',body:{install_id:id}}); + Nova.toast(r?.message || (r?.success ? 'Staging created' : 'Failed'), r?.success ? 'success' : 'error'); + if (r?.success) adminPage('wordpress'); + }); +}; + +window.wpDelete = (id, domain) => { + Nova.confirm(`DELETE WordPress install on ${domain}? This removes all files AND drops the database. IRREVERSIBLE.`, async () => { + const r = await Nova.api('wordpress','delete',{method:'POST',body:{install_id:id}}); + Nova.toast(r?.message || (r?.success ? 'Deleted' : 'Failed'), r?.success ? 'success' : 'error'); + if (r?.success) adminPage('wordpress'); + }, true); +}; + +// ── Backup Manager — full implementation (#15) ───────────────────────────── +async function backupsFull() { + const [acctRes, bkRes] = await Promise.all([ + Nova.api('accounts','list',{params:{limit:500}}), + Nova.api('backup','list'), + ]); + const accts = acctRes?.data?.accounts || []; + const backupList = bkRes?.data?.backups || []; + const diskUsed = bkRes?.data?.disk_used || 0; + window._adminAcctsBK = accts; + + return ` +Set per-account backup schedules. Cron runs backups automatically based on the configured frequency.
+| Account | Type | Size | Status | Storage | Created | Actions |
|---|---|---|---|---|---|---|
| ${Nova.escHtml(b.username||b.account_id||'—')} | +${Nova.badge(b.type,'default')} | +${Nova.bytes(b.size||0)} | +${Nova.badge(b.status, b.status==='complete'?'green':b.status==='failed'?'red':'yellow')} | +${b.remote_path ? Nova.badge('remote','blue') : Nova.badge('local','muted')} | +${Nova.relTime(b.created_at)} | ++ ${b.status==='complete'?`Download`:''} + + + | +
Manage Cloudflare API credentials and DNS sync per account.
+Select an account to configure or view its Cloudflare API key.
+Key on file: ${Nova.escHtml(c.cf_api_key)}
${Nova.escHtml(r?.message||'Failed to load zones')}
`; return; } + if (!zones.length) { body.innerHTML='No zones found for these credentials.
'; return; } + body.innerHTML = ` +| Zone | Status | Plan | Actions |
|---|---|---|---|
${Nova.escHtml(z.name)}${Nova.escHtml(z.id)} |
+ ${Nova.badge(z.status,z.status==='active'?'green':'yellow')} | +${Nova.escHtml(z.plan?.name||'—')} | ++ + + + + | +
No records.
' : ` +| Name | Type | Value | Proxy |
|---|---|---|---|
| ${Nova.escHtml(rec.name)} | +${Nova.badge(rec.type,'default')} | + ++ + | +
View 2FA status for all users. Force-disable for account recovery.
+| Username | Role | 2FA Status | Actions | |
|---|---|---|---|---|
| ${Nova.escHtml(u.username)} | +${Nova.escHtml(u.email||'—')} | +${Nova.badge(u.role||'user','default')} | ++ — + | ++ + + | +