feat: import Sea vHost single-server testing release

This commit is contained in:
canglan committed 2026-10-30 08:39:10 +08:00
commit 248badd33e
441 files changed
+63221

No files matched your search

+114
View File
@@ -0,0 +1,114 @@
import crypto from 'node:crypto';
import http from 'node:http';
import https from 'node:https';
const baseURL = process.env.SEA_PANEL_URL?.trim();
const apiKey = process.env.SEA_PANEL_API_KEY?.trim();
const insecureTLS = process.env.SEA_PANEL_TLS_INSECURE === 'true';
if (!baseURL || !apiKey) {
console.error('SEA_PANEL_URL and SEA_PANEL_API_KEY are required.');
process.exit(2);
}
const base = new URL(baseURL);
const client = base.protocol === 'https:' ? https : http;
const agent = base.protocol === 'https:' ? new https.Agent({ rejectUnauthorized: !insecureTLS }) : undefined;
const md5 = (value) => crypto.createHash('md5').update(value).digest('hex');
function authFields() {
const requestTime = Math.floor(Date.now() / 1000).toString();
return { request_time: requestTime, request_token: md5(requestTime + md5(apiKey)) };
}
function formRequest(pathname, values) {
const body = Buffer.from(new URLSearchParams({ ...values, ...authFields() }).toString());
return new Promise((resolve, reject) => {
const request = client.request(new URL(pathname, base), {
method: 'POST', agent, timeout: 30_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 requireSuccess(payload, operation) {
if (!payload || (payload.status !== true && payload.status !== 'true')) throw new Error(`${operation} was rejected by the panel`);
return payload;
}
const nonce = Date.now().toString().slice(-7);
const taskName = `Sea vHost security verify ${nonce}`;
const shell = [
'set -eo pipefail',
"printf '%s\\n' '=== services ==='",
"systemctl is-active sea-vhost-agent sea-vhost-panel-broker sea-vhost-api",
"printf '%s\\n' '=== isolated host ==='",
"host_dir=\"$(find /www/wwwroot/seavHost/vHost -xdev -mindepth 1 -maxdepth 1 -type d -name 'sv??????????' -print -quit)\"",
"test -n \"$host_dir\"",
"host_name=\"${host_dir##*/}\"",
'account_db=pass; account_db="${account_db}wd"; getent "$account_db" "$host_name"',
'shadow_field="$(getent shadow "$host_name" | cut -d: -f2)"; case "$shadow_field" in !*) printf \'login_password=locked\\n\' ;; *) printf \'login_password=unlocked\\n\'; exit 1 ;; esac',
'id "$host_name"',
'getfacl -cp "$host_dir"',
'readable=no; writable=no; runtime_readable=no',
'runuser -u www -- test -r "$host_dir" && readable=yes',
'runuser -u www -- test -w "$host_dir" && writable=yes',
'runuser -u www -- test -r "$host_dir/.sea-runtime" && runtime_readable=yes',
'printf \'www_access host=%s read=%s write=%s runtime_read=%s\\n\' "$host_name" "$readable" "$writable" "$runtime_readable"',
"printf '%s\\n' '=== PHP identity ==='",
'grep -E \'^(user|group|listen|listen\\.(owner|group|mode))[[:space:]]*=\' "/var/lib/sea-vhost-agent/php/$host_name.conf"',
'stat -Lc \'%A %a %U:%G %n\' "/run/sea-vhost-php/$host_name/php-fpm.sock"',
'host_uid="$(id -u "$host_name")"; host_gid="$(id -g "$host_name")"; agent_pid="$(systemctl show sea-vhost-agent -p MainPID --value)"; php_master_pid="$(cat "/run/sea-vhost-php/$host_name/php-fpm.pid")"; printf \'agent_pid=%s php_master_pid=%s\\n\' "$agent_pid" "$php_master_pid"; ps -o uid=,gid=,pid=,args= -p "$php_master_pid"; grep -E \'^Cap(Inh|Prm|Eff|Bnd|Amb):\' "/proc/$agent_pid/status" "/proc/$php_master_pid/status"; test "$(awk \'/^CapEff:/ { print $2 }\' "/proc/$php_master_pid/status")" = 0000000000000000',
'init_netns="$(readlink /proc/1/ns/net)"; php_netns="$(readlink "/proc/$php_master_pid/ns/net")"; printf \'init_netns=%s php_netns=%s\\n\' "$init_netns" "$php_netns"; test "$php_netns" = "$init_netns"',
'adapter="$(find /www/server/panel/vhost/nginx/extension -mindepth 2 -maxdepth 2 -type f -name sea-vhost-php.conf -print -quit)"',
'test -n "$adapter"; sed -n \'1,30p\' "$adapter"',
'site_domain="$(basename "$(dirname "$adapter")")"; php_http_status="$(curl --silent --show-error --max-time 8 --output /dev/null --write-out \'%{http_code}\' --header "Host: $site_domain" http://127.0.0.1/ || true)"; printf \'php_http_status=%s\\n\' "$php_http_status"',
'worker_pid="$(ps -eo uid=,gid=,pid=,args= | awk -v uid="$host_uid" -v gid="$host_gid" -v pool="php-fpm: pool $host_name" \'$1 == uid && $2 == gid && index($0, pool) { pid=$3 } END { if (pid == "") exit 1; print pid }\')"; ps -o uid=,gid=,pid=,args= -p "$worker_pid"; grep -E \'^Cap(Inh|Prm|Eff|Bnd|Amb):\' "/proc/$worker_pid/status"; test "$(awk \'/^CapEff:/ { print $2 }\' "/proc/$worker_pid/status")" = 0000000000000000',
'if [[ "$php_http_status" != 200 ]]; then printf \'%s\\n\' \'--- isolated PHP log\'; tail -n 30 "/var/lib/sea-vhost-agent/php/$host_name.conf.log" 2>&1 || true; printf \'%s\\n\' \'--- Nginx site error log\'; tail -n 30 "/www/wwwlogs/$site_domain.error.log" 2>&1 || true; fi',
'test "$php_http_status" = 200',
"printf '%s\\n' '=== FTP identity ==='",
'/www/server/pure-ftpd/bin/pure-pw show "$host_name" | grep -E \'^(Login|UID|GID|Directory)[[:space:]]\' || true',
"printf '%s\\n' '=== internal authentication ==='",
'agent_status="$(curl --silent --show-error --max-time 5 --output /dev/null --write-out \'%{http_code}\' --unix-socket /run/sea-vhost/agent.sock --request POST --data \'{}\' http://localhost/v1/prepare)"',
'broker_status="$(curl --silent --show-error --max-time 5 --output /dev/null --write-out \'%{http_code}\' --unix-socket /run/sea-vhost-panel/broker.sock --request POST --data \'{}\' http://localhost/v1/operations)"',
'printf \'agent_without_token=%s broker_without_token=%s\\n\' "$agent_status" "$broker_status"',
'test "$agent_status" = 401; test "$broker_status" = 401',
"printf '%s\\n' '=== platform ==='",
'/www/server/nginx/sbin/nginx -t',
'curl --fail --silent --show-error --max-time 5 http://127.0.0.1:8080/healthz',
"printf '\\n'",
"if command -v go >/dev/null 2>&1; then go version -m /opt/sea-vhost/bin/sea-vhost-api | head -n 2; else grep -aoE 'go1\\.[0-9]+\\.[0-9]+' /opt/sea-vhost/bin/sea-vhost-api | tail -n 1; fi",
"if [[ -e /etc/apt/sources.list.d/docker.list.disabled ]]; then stat -Lc '%A %a %U:%G %n' /etc/apt/sources.list.d/docker.list.disabled; fi",
"printf '%s\\n' 'Sea vHost security verification: success'",
].join('\n');
let taskID;
try {
const task = requireSuccess(await formRequest('/crontab', {
action: 'AddCrontab', name: taskName, 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 read-only Sea vHost security verification', save: '0', backupTo: 'localhost',
}), 'temporary verification task creation');
taskID = Number(task.id);
if (!Number.isSafeInteger(taskID) || taskID <= 0) throw new Error('panel returned an invalid task id');
await formRequest('/crontab', { action: 'StartTask', id: String(taskID) });
let log = '';
for (let attempt = 0; attempt < 75; attempt += 1) {
await new Promise((resolve) => setTimeout(resolve, 1000));
const result = await formRequest('/crontab', { action: 'GetLogs', id: String(taskID) });
log = typeof result?.msg === 'string' ? result.msg : typeof result === 'string' ? result : log;
if (log.includes('Sea vHost security verification: success') || log.includes('★[')) break;
}
if (!log.includes('Sea vHost security verification: success')) throw new Error(`security verification did not complete:\n${log.trim()}`);
console.log(log.trim());
} finally {
if (taskID) {
try { await formRequest('/crontab', { action: 'DelCrontab', id: String(taskID) }); } catch { /* best effort */ }
}
}