import crypto from 'node:crypto'; import http from 'node:http'; import https from 'node:https'; const panelURL = process.env.SEA_PANEL_URL?.trim(); const panelAPIKey = process.env.SEA_PANEL_API_KEY?.trim(); const insecureTLS = process.env.SEA_PANEL_TLS_INSECURE === 'true'; if (!panelURL || !panelAPIKey) process.exit(2); const panelBase = new URL(panelURL); const panelClient = panelBase.protocol === 'https:' ? https : http; const panelAgent = panelBase.protocol === 'https:' ? new https.Agent({ rejectUnauthorized: !insecureTLS }) : undefined; const md5 = (value) => crypto.createHash('md5').update(value).digest('hex'); const q = (value) => `'${value.replaceAll("'", "'\\''")}'`; const suffix = crypto.randomBytes(6).toString('hex'); const databaseName = `svhr${suffix.slice(0, 8)}`; const databasePassword = `Sv-${crypto.randomBytes(18).toString('base64url')}5b`; function authFields() { const requestTime = Math.floor(Date.now() / 1000).toString(); return { request_time: requestTime, request_token: md5(requestTime + md5(panelAPIKey)) }; } function panelForm(pathname, values) { const body = Buffer.from(new URLSearchParams({ ...values, ...authFields() }).toString()); return new Promise((resolve, reject) => { const request = panelClient.request(new URL(pathname, panelBase), { method: 'POST', agent: panelAgent, timeout: 60_000, headers: { 'content-type': 'application/x-www-form-urlencoded', 'content-length': body.length }, }, (response) => { let data = ''; response.setEncoding('utf8'); response.on('data', (chunk) => { data += chunk; }); response.on('end', () => { if (response.statusCode < 200 || response.statusCode > 299) return reject(new Error(`panel returned HTTP ${response.statusCode}`)); try { resolve(JSON.parse(data)); } catch { reject(new Error('panel returned non-JSON data')); } }); }); request.on('timeout', () => request.destroy(new Error('panel request timed out'))); request.on('error', reject); request.end(body); }); } function requirePanelSuccess(payload, operation) { if (!payload || (payload.status !== true && payload.status !== 'true')) throw new Error(`${operation} was rejected by the panel`); return payload; } async function panelDatabaseRows(search) { const response = await panelForm('/data', { action: 'getData', table: 'databases', search, limit: '100', p: '1' }); const rows = Array.isArray(response?.data) ? response.data : Array.isArray(response) ? response : undefined; if (!rows) throw new Error('panel database listing failed'); return rows; } async function resolveDatabaseID(name) { const matches = (await panelDatabaseRows(name)).filter((row) => row?.name === name || row?.username === name); if (matches.length !== 1) throw new Error(`panel database lookup returned ${matches.length} exact matches`); const id = Number(matches[0].id); if (!Number.isSafeInteger(id) || id <= 0) throw new Error('panel returned invalid database id'); return id; } async function runShell(name, shell, marker, attempts = 180) { const task = await panelForm('/crontab', { action: 'AddCrontab', name, type: 'month', where1: String((new Date().getUTCDate() + 6) % 28 + 1), where_hour: '0', where_minute: '0', user: 'root', urladdress: 'http://', save_local: '0', sType: 'toShell', sBody: shell, sName: 'Temporary Sea vHost backup restore verification', save: '0', backupTo: 'localhost', }); if (!task || (task.status !== true && task.status !== 'true')) throw new Error('panel rejected temporary task'); const taskID = Number(task.id); try { await panelForm('/crontab', { action: 'StartTask', id: String(taskID) }); let log = ''; for (let attempt = 0; attempt < attempts; attempt += 1) { await new Promise((resolve) => setTimeout(resolve, 1000)); const result = await panelForm('/crontab', { action: 'GetLogs', id: String(taskID) }); log = typeof result?.msg === 'string' ? result.msg : typeof result === 'string' ? result : log; if (log.includes(marker)) return log; } throw new Error(`temporary task failed: ${log.trim()}`); } finally { try { await panelForm('/crontab', { action: 'DelCrontab', id: String(taskID) }); } catch { /* best effort */ } } } let databaseID; try { const created = requirePanelSuccess(await panelForm('/database', { action: 'AddDatabase', sid: '0', name: databaseName, db_user: databaseName, password: databasePassword, address: '127.0.0.1', codeing: 'utf8mb4', pid: '0', ps: 'Sea vHost restore verification', }), 'temporary restore database creation'); databaseID = Number(created.id); if (!Number.isSafeInteger(databaseID) || databaseID <= 0) databaseID = await resolveDatabaseID(databaseName); const marker = `backup-restore-verified-${suffix}`; const shell = [ 'set -Eeuo pipefail', `test_id=${q(suffix)}`, `restore_db=${q(databaseName)}`, `restore_password=${q(databasePassword)}`, 'work="/var/lib/sea-vhost/restore-verify-$test_id"; case "$work" in /var/lib/sea-vhost/restore-verify-????????????) ;; *) exit 1 ;; esac; test ! -e "$work"; install -d -o root -g root -m 0700 "$work" "$work/state" "$work/hosts"', 'cleanup() { rm -rf -- "$work"; }; trap cleanup EXIT', 'mapfile -t control_db < <(python3 -c \'import json,re; d=json.load(open("/var/lib/sea-vhost/config.json", encoding="utf-8"))["database_dsn"]; m=re.fullmatch(r"([^:]+):([^@]+)@tcp\\(([^:]+):(\\d+)\\)/([^?]+)(?:\\?.*)?", d); assert m; print("\\n".join(m.groups()))\')', 'control_user="${control_db[0]}"; control_password="${control_db[1]}"; control_host="${control_db[2]}"; control_port="${control_db[3]}"; control_name="${control_db[4]}"', 'mysql_bin="$(command -v mysql || true)"; dump_bin="$(command -v mysqldump || true)"; if [[ -z "$mysql_bin" && -x /www/server/mysql/bin/mysql ]]; then mysql_bin=/www/server/mysql/bin/mysql; fi; if [[ -z "$dump_bin" && -x /www/server/mysql/bin/mysqldump ]]; then dump_bin=/www/server/mysql/bin/mysqldump; fi; test -x "$mysql_bin"; test -x "$dump_bin"', 'host_name="$(MYSQL_PWD="$control_password" "$mysql_bin" --protocol=TCP --host="$control_host" --port="$control_port" --user="$control_user" --database="$control_name" --batch --skip-column-names --execute="SELECT host_name FROM projects WHERE host_name REGEXP \'^sv[0-9a-f]{10}$\' ORDER BY id LIMIT 1")"; test -n "$host_name"; test -d "/www/wwwroot/seavHost/vHost/$host_name"', 'source_counts="$(MYSQL_PWD="$control_password" "$mysql_bin" --protocol=TCP --host="$control_host" --port="$control_port" --user="$control_user" --database="$control_name" --batch --skip-column-names --execute="SELECT CONCAT((SELECT COUNT(*) FROM tenants),\':\',(SELECT COUNT(*) FROM users),\':\',(SELECT COUNT(*) FROM projects),\':\',(SELECT COUNT(*) FROM sites),\':\',(SELECT COUNT(*) FROM ftp_accounts),\':\',(SELECT COUNT(*) FROM \\`databases\\`),\':\',(SELECT COUNT(*) FROM schema_migrations));")"', 'MYSQL_PWD="$control_password" "$dump_bin" --protocol=TCP --host="$control_host" --port="$control_port" --user="$control_user" --single-transaction --skip-lock-tables --default-character-set=utf8mb4 "$control_name" >"$work/control.sql"; test -s "$work/control.sql"; chmod 0600 "$work/control.sql"', 'MYSQL_PWD="$restore_password" "$mysql_bin" --protocol=TCP --host=127.0.0.1 --user="$restore_db" --database="$restore_db" <"$work/control.sql"', 'restored_counts="$(MYSQL_PWD="$restore_password" "$mysql_bin" --protocol=TCP --host=127.0.0.1 --user="$restore_db" --database="$restore_db" --batch --skip-column-names --execute="SELECT CONCAT((SELECT COUNT(*) FROM tenants),\':\',(SELECT COUNT(*) FROM users),\':\',(SELECT COUNT(*) FROM projects),\':\',(SELECT COUNT(*) FROM sites),\':\',(SELECT COUNT(*) FROM ftp_accounts),\':\',(SELECT COUNT(*) FROM \\`databases\\`),\':\',(SELECT COUNT(*) FROM schema_migrations));")"; test "$source_counts" = "$restored_counts"', 'tar --acls --xattrs --numeric-owner -cpf "$work/host.tar" -C /www/wwwroot/seavHost/vHost "$host_name"; test -s "$work/host.tar"; chmod 0600 "$work/host.tar"; tar --acls --xattrs --numeric-owner -xpf "$work/host.tar" -C "$work/hosts"; tar --acls --xattrs --numeric-owner --compare -f "$work/host.tar" -C "$work/hosts"', 'tar --acls --xattrs --numeric-owner -cpf "$work/state.tar" -C / etc/sea-vhost/sea-vhost.env var/lib/sea-vhost/config.json var/lib/sea-vhost-panel/credentials.json var/lib/sea-vhost-panel/resources.json; chmod 0600 "$work/state.tar"; tar --acls --xattrs --numeric-owner -xpf "$work/state.tar" -C "$work/state"', 'for relative in etc/sea-vhost/sea-vhost.env var/lib/sea-vhost/config.json var/lib/sea-vhost-panel/credentials.json var/lib/sea-vhost-panel/resources.json; do test "$(sha256sum "/$relative" | awk \'{print $1}\')" = "$(sha256sum "$work/state/$relative" | awk \'{print $1}\')"; done', 'test "$(stat -c %a "$work/state/etc/sea-vhost/sea-vhost.env")" = 640; test "$(stat -c %a "$work/state/var/lib/sea-vhost/config.json")" = 600; test "$(stat -c %a "$work/state/var/lib/sea-vhost-panel/credentials.json")" = 600', 'printf "database_counts=%s\\nhost_name=%s\\nstate_files=4\\n" "$restored_counts" "$host_name"', `printf '%s\n' ${q(marker)}`, ].join('\n'); const log = await runShell(`Sea vHost restore verify ${suffix}`, shell, marker); const databaseCounts = log.match(/(?:^|\n)database_counts=([^\r\n]+)/)?.[1]; if (!databaseCounts) throw new Error('restore verification output was incomplete'); console.log(JSON.stringify({ status: 'passed', checks: { controlDatabaseDumpCreated: true, controlDatabaseImportedIntoIsolatedDatabase: true, restoredDatabaseObjectCountsMatch: true, managedHostArchiveCreated: true, managedHostArchiveMetadataAndContentMatch: true, criticalStateArchiveCreated: true, restoredStateChecksumsMatch: true, restoredSecretFileModesMatch: true, liveDataWasNotOverwritten: true, }, restoredDatabaseObjectCounts: databaseCounts }, null, 2)); } finally { if (databaseID) { try { await panelForm('/database', { action: 'DeleteDatabase', id: String(databaseID), sid: '0', name: databaseName, db_user: databaseName }); } catch { process.exitCode = 1; } } }