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

+22
View File
@@ -0,0 +1,22 @@
# 安装与维护工具
交付后的 36 机器已运行最新版应用,直接访问控制台开展业务测试,不需要重新安装或初始化数据库。
## 安装包内的工具
- `install.sh`、`install-controller.sh`、`install-node.sh`、`install-wizard.py`:交互或自动化安装;默认入口为 `bash deploy/install.sh`。
- `preflight.sh`、`diagnose.sh`:只读安装预检与运行诊断。
- `prepare-runtime-roots.sh`:由安装器调用,准备受管目录。
- `activate-production.sh`、`activate-production-ftps.sh`、`update-production-ftp-mode.sh`:配置管理站点或 FTP 的运维工具,会修改系统配置;仅在相应操作说明要求时执行。
- `pureftp-certificate-probe.sh`、`production-health.sh`:证书与运行状态检查。
- `nginx/`、`systemd/`:配置模板。
## 仅在源码包内的开发工具
`build.ps1` / `build.sh` 构建应用,`package-release.mjs` 按 `release-files.json` 生成安装包和源码包及逐文件校验清单。
其余 `panel-*.mjs`、`*-verify.*`、`*-smoke.*`、`activate-test.sh`、`reset-*.sh/mjs`、`repair-test-*.mjs` 和 `fixtures/` 是开发联调、安全探针、历史部署或故障恢复工具。部分会创建、停用、清理资源或改变密码,源码中保留用于追溯,安装包不会携带它们;不要按文件顺序批量执行。
这些工具使用 `SEA_PANEL_URL`、`SEA_PANEL_API_KEY` 等进程环境变量取得目标信息。项目真实配置、口令、证书私钥、数据库备份、`build/smoke/` 和本地缓存不进入交付包。历史验收命令可能指向旧测试环境,应先阅读对应日期及脚本参数。
完整操作顺序见 `docs/handover-2026-10-30.md`、`docs/deployment.md` 与 `docs/hosting-operations.md`。源码包中的 `reset-production-admin.sh` 只用于明确需要的管理员恢复,交付不自动执行。
+115
View File
@@ -0,0 +1,115 @@
#!/usr/bin/env bash
set -euo pipefail
certificate_domain="${SEA_FTP_CERTIFICATE_DOMAIN:-}"
test_host="${SEA_FTP_TEST_HOST:-}"
for domain in "${certificate_domain}" "${test_host}"; do
if [[ ! "${domain}" =~ ^[A-Za-z0-9.-]+$ ]] || [[ "${domain}" == .* ]] || [[ "${domain}" == *..* ]]; then
echo "The FTP certificate domain or test host is invalid." >&2
exit 1
fi
done
certificate_directory="/www/server/panel/vhost/cert/${certificate_domain}"
certificate_file="${certificate_directory}/fullchain.pem"
private_key_file="${certificate_directory}/privkey.pem"
for regular_file in "${certificate_file}" "${private_key_file}" /etc/sea-vhost/sea-vhost.env; do
if [[ ! -f "${regular_file}" || -L "${regular_file}" ]]; then
printf 'Required regular file is missing or unsafe: %s\n' "${regular_file}" >&2
exit 1
fi
done
openssl x509 -in "${certificate_file}" -noout -checkhost "${certificate_domain}" >/dev/null
openssl x509 -in "${certificate_file}" -noout -checkhost "${test_host}" >/dev/null
openssl pkey -in "${private_key_file}" -noout -check >/dev/null 2>&1
sync_script=/opt/sea-vhost/bin/sea-vhost-ftps-sync
temporary_sync="$(mktemp /opt/sea-vhost/bin/.sea-vhost-ftps-sync-XXXXXX.tmp)"
cat >"${temporary_sync}" <<'EOF'
#!/usr/bin/env bash
set -euo pipefail
domain="${1:-}"
[[ "${domain}" =~ ^[A-Za-z0-9.-]+$ ]]
token="$(sed -n 's/^SEA_INTERNAL_AUTH_TOKEN=//p' /etc/sea-vhost/sea-vhost.env | head -n 1)"
[[ "${#token}" -ge 32 ]]
response="$(curl --silent --show-error --fail --max-time 45 \
--unix-socket /run/sea-vhost/agent.sock \
--header "Authorization: Bearer ${token}" \
--header 'Content-Type: application/json' \
--request POST \
--data "{\"domain\":\"${domain}\"}" \
http://localhost/v1/ftp/tls)"
grep -Fq '"policy":"explicit_tls_required"' <<<"${response}"
systemctl stop pure-ftpd.service >/dev/null 2>&1 || true
ftp_binary="$(readlink -f /www/server/pure-ftpd/sbin/pure-ftpd)"
for proc_exe in /proc/[0-9]*/exe; do
[[ "$(readlink -f "${proc_exe}" 2>/dev/null || true)" == "${ftp_binary}" ]] || continue
proc_pid="${proc_exe#/proc/}"
proc_pid="${proc_pid%/exe}"
kill -TERM "${proc_pid}" 2>/dev/null || true
done
sleep 1
for proc_exe in /proc/[0-9]*/exe; do
[[ "$(readlink -f "${proc_exe}" 2>/dev/null || true)" == "${ftp_binary}" ]] || continue
proc_pid="${proc_exe#/proc/}"
proc_pid="${proc_pid%/exe}"
kill -KILL "${proc_pid}" 2>/dev/null || true
done
systemctl start pure-ftpd.service
EOF
chown root:root "${temporary_sync}"
chmod 0750 "${temporary_sync}"
mv -f -- "${temporary_sync}" "${sync_script}"
cat >/etc/systemd/system/sea-vhost-ftps-sync.service <<EOF
[Unit]
Description=Synchronize the Sea vHost Pure-FTPd certificate
After=sea-vhost-agent.service pure-ftpd.service
Requires=sea-vhost-agent.service
[Service]
Type=oneshot
User=root
Group=root
ExecStart=${sync_script} ${certificate_domain}
NoNewPrivileges=true
PrivateTmp=true
PrivateDevices=true
PrivateNetwork=true
ProtectSystem=strict
ProtectHome=true
ProtectKernelTunables=true
ProtectKernelModules=true
ProtectKernelLogs=true
ProtectControlGroups=true
RestrictSUIDSGID=true
LockPersonality=true
ReadOnlyPaths=/etc/sea-vhost /www/server/panel/vhost/cert/${certificate_domain}
RestrictAddressFamilies=AF_UNIX
CapabilityBoundingSet=CAP_KILL
LimitCORE=0
EOF
cat >/etc/systemd/system/sea-vhost-ftps-sync.timer <<'EOF'
[Unit]
Description=Daily Sea vHost Pure-FTPd certificate synchronization
[Timer]
OnCalendar=daily
Persistent=true
RandomizedDelaySec=30m
Unit=sea-vhost-ftps-sync.service
[Install]
WantedBy=timers.target
EOF
chown root:root /etc/systemd/system/sea-vhost-ftps-sync.service /etc/systemd/system/sea-vhost-ftps-sync.timer
chmod 0644 /etc/systemd/system/sea-vhost-ftps-sync.service /etc/systemd/system/sea-vhost-ftps-sync.timer
systemctl daemon-reload
systemctl enable --now sea-vhost-ftps-sync.timer
systemctl start sea-vhost-ftps-sync.service
grep -Eq '^[[:space:]]*TLS[[:space:]]+2[[:space:]]*$' /www/server/pure-ftpd/etc/pure-ftpd.conf
test "$(stat -Lc '%a' /www/server/pure-ftpd/etc/pure-ftpd.pem)" = 600
timeout 20 openssl s_client -connect 127.0.0.1:21 -starttls ftp -servername "${test_host}" \
-verify_hostname "${test_host}" -verify_return_error </dev/null 2>&1 | grep -Fq 'Verify return code: 0 (ok)'
echo "Sea vHost production FTPS activation result: success"
+205
View File
@@ -0,0 +1,205 @@
#!/usr/bin/env bash
set -euo pipefail
management_host="${SEA_MANAGEMENT_DOMAIN:-}"
panel_local_port="${SEA_PANEL_LOCAL_PORT:-}"
panel_bridge_port="${SEA_PANEL_BRIDGE_PORT:-7813}"
if [[ ! "${management_host}" =~ ^[A-Za-z0-9.-]+$ ]] || [[ "${management_host}" == .* ]] || [[ "${management_host}" == *..* ]]; then
echo "SEA_MANAGEMENT_DOMAIN is invalid." >&2
exit 1
fi
for port in "${panel_local_port}" "${panel_bridge_port}"; do
if [[ ! "${port}" =~ ^[0-9]+$ ]] || (( port < 1 || port > 65535 )); then
echo "The panel and bridge ports must be valid TCP ports." >&2
exit 1
fi
done
if [[ "${panel_local_port}" == "${panel_bridge_port}" ]]; then
echo "The local aaPanel and bridge ports must differ." >&2
exit 1
fi
nginx_binary=/www/server/nginx/sbin/nginx
environment_file=/etc/sea-vhost/sea-vhost.env
nginx_config="/www/server/panel/vhost/nginx/${management_host}.conf"
certificate_directory="/www/server/panel/vhost/cert/${management_host}"
certificate_file="${certificate_directory}/fullchain.pem"
private_key_file="${certificate_directory}/privkey.pem"
for regular_file in "${environment_file}" "${certificate_file}" "${private_key_file}"; do
if [[ ! -f "${regular_file}" || -L "${regular_file}" ]]; then
printf 'Required regular file is missing or unsafe: %s\n' "${regular_file}" >&2
exit 1
fi
done
if [[ ! -x "${nginx_binary}" ]]; then
echo "aaPanel Nginx is unavailable." >&2
exit 1
fi
if ! openssl x509 -in "${certificate_file}" -noout -checkhost "${management_host}" >/dev/null; then
echo "The installed certificate does not cover the management domain." >&2
exit 1
fi
if ! openssl pkey -in "${private_key_file}" -noout -check >/dev/null 2>&1; then
echo "The installed certificate private key is invalid." >&2
exit 1
fi
had_config=false
config_backup="$(mktemp)"
environment_backup="$(mktemp)"
temporary_config=""
if [[ -e "${nginx_config}" ]]; then
if [[ ! -f "${nginx_config}" || -L "${nginx_config}" ]]; then
echo "The existing Nginx vhost is not a safe regular file." >&2
exit 1
fi
had_config=true
cp --preserve=mode,ownership,timestamps -- "${nginx_config}" "${config_backup}"
fi
cp --preserve=mode,ownership,timestamps -- "${environment_file}" "${environment_backup}"
rollback() {
cp --preserve=mode,ownership,timestamps -- "${environment_backup}" "${environment_file}" || true
if [[ "${had_config}" == true ]]; then
cp --preserve=mode,ownership,timestamps -- "${config_backup}" "${nginx_config}" || true
else
rm -f -- "${nginx_config}"
fi
"${nginx_binary}" -t >/dev/null 2>&1 && "${nginx_binary}" -s reload >/dev/null 2>&1 || true
}
cleanup() {
[[ -z "${temporary_config}" ]] || rm -f -- "${temporary_config}"
rm -f -- "${config_backup}" "${environment_backup}"
}
trap 'rollback; cleanup' ERR
if grep -q '^SEA_COOKIE_SECURE=' "${environment_file}"; then
sed -i 's/^SEA_COOKIE_SECURE=.*/SEA_COOKIE_SECURE=true/' "${environment_file}"
else
echo 'SEA_COOKIE_SECURE=true' >>"${environment_file}"
fi
chown root:sea-vhost-control "${environment_file}"
chmod 0640 "${environment_file}"
temporary_config="$(mktemp /www/server/panel/vhost/nginx/.sea-vhost-production-XXXXXX.tmp)"
cat >"${temporary_config}" <<EOF
# Managed by Sea vHost. The certificate files are maintained by aaPanel.
# Local-only aaPanel API bridge. aaPanel itself uses a self-signed certificate
# on its loopback listener; the broker talks to this private HTTP endpoint and
# never exposes the panel API key to the Web process.
map \$upstream_http_content_security_policy \$sea_vhost_csp {
"" "default-src 'self'; base-uri 'self'; object-src 'none'; frame-ancestors 'none'; form-action 'self'; connect-src 'self'; img-src 'self' data:; font-src 'self'; style-src 'self' 'unsafe-inline'; script-src 'self'";
default \$upstream_http_content_security_policy;
}
server {
listen 127.0.0.1:${panel_bridge_port};
server_name _;
access_log off;
location / {
proxy_pass https://127.0.0.1:${panel_local_port};
proxy_ssl_verify off;
proxy_set_header Host 127.0.0.1:${panel_local_port};
proxy_set_header X-Real-IP 127.0.0.1;
proxy_connect_timeout 3s;
proxy_read_timeout 300s;
}
}
server {
listen 80;
server_name ${management_host};
server_tokens off;
location ^~ /.well-known/acme-challenge/ {
root /opt/sea-vhost/web;
try_files \$uri =404;
}
location / {
return 301 https://\$host\$request_uri;
}
}
server {
listen 443 ssl;
http2 on;
server_name ${management_host};
server_tokens off;
ssl_certificate ${certificate_file};
ssl_certificate_key ${private_key_file};
ssl_protocols TLSv1.2 TLSv1.3;
ssl_session_cache shared:SeaVHostSSL:10m;
ssl_session_timeout 10m;
root /opt/sea-vhost/web;
index index.html;
client_max_body_size 21m;
add_header Strict-Transport-Security "max-age=31536000; includeSubDomains" always;
add_header X-Content-Type-Options "nosniff" always;
add_header X-Frame-Options "DENY" always;
add_header Referrer-Policy "same-origin" always;
add_header Permissions-Policy "camera=(), microphone=(), geolocation=()" always;
add_header Content-Security-Policy \$sea_vhost_csp always;
proxy_hide_header Content-Security-Policy;
location /api/ {
proxy_pass http://127.0.0.1:8080;
proxy_http_version 1.1;
proxy_cache off;
proxy_set_header Range \$http_range;
proxy_set_header If-Range \$http_if_range;
proxy_set_header Host \$http_host;
proxy_set_header X-Real-IP \$remote_addr;
proxy_set_header X-Forwarded-For \$proxy_add_x_forwarded_for;
proxy_set_header X-Forwarded-Proto https;
proxy_connect_timeout 3s;
proxy_read_timeout 300s;
}
location = /healthz {
proxy_pass http://127.0.0.1:8080;
proxy_set_header Host \$http_host;
proxy_set_header X-Forwarded-Proto https;
access_log off;
}
location / {
try_files \$uri \$uri/ /index.html;
}
location ~ /\. {
deny all;
}
}
EOF
chown root:root "${temporary_config}"
chmod 0644 "${temporary_config}"
mv -f -- "${temporary_config}" "${nginx_config}"
temporary_config=""
"${nginx_binary}" -t
systemctl enable sea-vhost-agent sea-vhost-panel-broker sea-vhost-api
systemctl restart sea-vhost-agent sea-vhost-panel-broker sea-vhost-api
for _ in {1..30}; do
if curl --fail --silent --show-error --max-time 3 --header "Host: ${management_host}" http://127.0.0.1:8080/healthz >/dev/null; then
break
fi
sleep 1
done
curl --fail --silent --show-error --max-time 3 --header "Host: ${management_host}" http://127.0.0.1:8080/healthz >/dev/null
"${nginx_binary}" -s reload
for _ in {1..20}; do
if curl --fail --silent --show-error --max-time 5 --resolve "${management_host}:443:127.0.0.1" "https://${management_host}/healthz" >/dev/null; then
break
fi
sleep 1
done
curl --fail --silent --show-error --max-time 5 --resolve "${management_host}:443:127.0.0.1" "https://${management_host}/healthz" >/dev/null
trap - ERR
cleanup
echo "Sea vHost production activation result: success"
+132
View File
@@ -0,0 +1,132 @@
#!/usr/bin/env bash
set -euo pipefail
if [[ "${EUID}" -ne 0 ]]; then
echo "Run this test activator as root." >&2
exit 1
fi
console_host="${1:-}"
if [[ ! "${console_host}" =~ ^[A-Za-z0-9.-]+$ ]] || [[ "${console_host}" == .* ]] || [[ "${console_host}" == *..* ]]; then
echo "Invalid console host." >&2
exit 1
fi
env_file=/etc/sea-vhost/sea-vhost.env
nginx_binary=/www/server/nginx/sbin/nginx
nginx_config=/www/server/panel/vhost/nginx/sea-vhost-console.conf
if [[ ! -f "${env_file}" || -L "${env_file}" ]]; then
echo "Sea vHost environment file is missing or unsafe." >&2
exit 1
fi
if [[ ! -x "${nginx_binary}" ]]; then
echo "aaPanel Nginx binary is unavailable." >&2
exit 1
fi
had_config=false
if [[ -e "${nginx_config}" ]]; then
if [[ ! -f "${nginx_config}" || -L "${nginx_config}" ]]; then
echo "Existing console Nginx configuration is unsafe." >&2
exit 1
fi
had_config=true
fi
env_backup="$(mktemp)"
config_backup="$(mktemp)"
temporary_config=""
cp --preserve=mode,ownership,timestamps -- "${env_file}" "${env_backup}"
if [[ "${had_config}" == true ]]; then
cp --preserve=mode,ownership,timestamps -- "${nginx_config}" "${config_backup}"
fi
rollback() {
cp --preserve=mode,ownership,timestamps -- "${env_backup}" "${env_file}" || true
if [[ "${had_config}" == true ]]; then
cp --preserve=mode,ownership,timestamps -- "${config_backup}" "${nginx_config}" || true
else
rm -f -- "${nginx_config}"
fi
"${nginx_binary}" -t >/dev/null 2>&1 && "${nginx_binary}" -s reload >/dev/null 2>&1 || true
}
trap 'rollback; [[ -z "${temporary_config}" ]] || rm -f -- "${temporary_config}"; rm -f -- "${env_backup}" "${config_backup}"' ERR
if grep -q '^SEA_COOKIE_SECURE=' "${env_file}"; then
sed -i 's/^SEA_COOKIE_SECURE=.*/SEA_COOKIE_SECURE=false/' "${env_file}"
else
echo 'SEA_COOKIE_SECURE=false' >> "${env_file}"
fi
chown root:sea-vhost-control "${env_file}"
chmod 0640 "${env_file}"
temporary_config="$(mktemp /www/server/panel/vhost/nginx/.sea-vhost-console-XXXXXX.tmp)"
cat > "${temporary_config}" <<EOF
# Managed by Sea vHost test activation. Replace with TLS for production.
map \$upstream_http_content_security_policy \$sea_vhost_csp {
"" "default-src 'self'; base-uri 'self'; object-src 'none'; frame-ancestors 'none'; form-action 'self'; connect-src 'self'; img-src 'self' data:; font-src 'self'; style-src 'self' 'unsafe-inline'; script-src 'self'";
default \$upstream_http_content_security_policy;
}
server {
listen 80;
server_name ${console_host};
server_tokens off;
root /opt/sea-vhost/web;
index index.html;
client_max_body_size 21m;
add_header X-Content-Type-Options "nosniff" always;
add_header X-Frame-Options "DENY" always;
add_header Referrer-Policy "same-origin" always;
add_header Permissions-Policy "camera=(), microphone=(), geolocation=()" always;
add_header Content-Security-Policy \$sea_vhost_csp always;
proxy_hide_header Content-Security-Policy;
location /api/ {
proxy_pass http://127.0.0.1:8080;
proxy_http_version 1.1;
# Preserve an externally forwarded non-standard port so the API can
# compare the browser Origin to the original Host without weakening
# its CSRF same-origin policy.
proxy_set_header Host \$http_host;
proxy_set_header X-Real-IP \$remote_addr;
proxy_set_header X-Forwarded-For \$proxy_add_x_forwarded_for;
proxy_set_header X-Forwarded-Proto http;
proxy_connect_timeout 3s;
proxy_read_timeout 300s;
}
location = /healthz {
proxy_pass http://127.0.0.1:8080;
access_log off;
}
location / {
try_files \$uri \$uri/ /index.html;
}
location ~ /\. {
deny all;
}
}
EOF
chown root:root "${temporary_config}"
chmod 0644 "${temporary_config}"
mv -f -- "${temporary_config}" "${nginx_config}"
"${nginx_binary}" -t
systemctl enable sea-vhost-agent sea-vhost-panel-broker sea-vhost-api
systemctl restart sea-vhost-agent sea-vhost-panel-broker sea-vhost-api
for _ in {1..20}; do
if curl --fail --silent --show-error http://127.0.0.1:8080/healthz >/dev/null; then
break
fi
sleep 1
done
curl --fail --silent --show-error http://127.0.0.1:8080/healthz
"${nginx_binary}" -s reload
trap - ERR
rm -f -- "${env_backup}" "${config_backup}"
echo "Sea vHost test activation result: success"
+81
View File
@@ -0,0 +1,81 @@
$ErrorActionPreference = 'Stop'
Set-StrictMode -Version Latest
$repoRoot = [IO.Path]::GetFullPath((Join-Path $PSScriptRoot '..'))
$buildRoot = [IO.Path]::GetFullPath((Join-Path $repoRoot 'build'))
$binaryRoot = Join-Path $buildRoot 'bin'
$webRoot = Join-Path $buildRoot 'web'
$archive = Join-Path $buildRoot 'sea-vhost-linux-amd64.tar.gz'
foreach ($script in Get-ChildItem -LiteralPath (Join-Path $repoRoot 'deploy') -Filter '*.sh' -File) {
if ([IO.File]::ReadAllText($script.FullName).Contains("`r")) {
throw "Linux shell script must use LF line endings: $($script.Name)"
}
}
function Assert-BuildPath([string]$path) {
$absolute = [IO.Path]::GetFullPath($path)
$prefix = $buildRoot.TrimEnd([IO.Path]::DirectorySeparatorChar) + [IO.Path]::DirectorySeparatorChar
if (-not $absolute.StartsWith($prefix, [StringComparison]::OrdinalIgnoreCase)) {
throw "Refusing to modify a path outside the build directory: $absolute"
}
}
foreach ($path in @($binaryRoot, $webRoot)) {
Assert-BuildPath $path
if (Test-Path -LiteralPath $path) {
Remove-Item -LiteralPath $path -Recurse -Force
}
New-Item -ItemType Directory -Path $path | Out-Null
}
Push-Location (Join-Path $repoRoot 'backend')
try {
$goCommand = if ([string]::IsNullOrWhiteSpace($env:SEA_GO_BINARY)) { 'go' } else { [IO.Path]::GetFullPath($env:SEA_GO_BINARY) }
if ($goCommand -ne 'go' -and -not (Test-Path -LiteralPath $goCommand -PathType Leaf)) { throw "Configured Go binary does not exist: $goCommand" }
$env:CGO_ENABLED = '0'
$env:GOOS = 'linux'
$env:GOARCH = 'amd64'
$goVersion = (& $goCommand env GOVERSION).Trim()
if ($LASTEXITCODE -ne 0 -or [string]::IsNullOrWhiteSpace($goVersion)) { throw 'Cannot determine the Go toolchain version' }
$env:GOCACHE = Join-Path $repoRoot ".cache\go-build-linux-amd64-$goVersion"
New-Item -ItemType Directory -Path $env:GOCACHE -Force | Out-Null
& $goCommand build -trimpath -ldflags '-s -w' -o (Join-Path $binaryRoot 'sea-vhost-api') ./cmd/server
& $goCommand build -trimpath -ldflags '-s -w' -o (Join-Path $binaryRoot 'sea-vhost-agent') ./cmd/agent
& $goCommand build -trimpath -ldflags '-s -w' -o (Join-Path $binaryRoot 'sea-vhost-panel-broker') ./cmd/panel-broker
& $goCommand build -trimpath -ldflags '-s -w' -o (Join-Path $binaryRoot 'sea-vhost-node') ./cmd/node
& $goCommand build -trimpath -ldflags '-s -w' -o (Join-Path $binaryRoot 'sea-vhost-run') ./cmd/runner
& $goCommand build -trimpath -ldflags '-s -w' -o (Join-Path $binaryRoot 'sea-vhost-scheduler') ./cmd/scheduler
if ($LASTEXITCODE -ne 0) { throw 'Go cross compilation failed' }
foreach ($binary in @('sea-vhost-api', 'sea-vhost-agent', 'sea-vhost-panel-broker','sea-vhost-node','sea-vhost-run','sea-vhost-scheduler')) {
$metadata = @(& $goCommand version -m (Join-Path $binaryRoot $binary))
if ($LASTEXITCODE -ne 0 -or $metadata.Count -eq 0 -or -not $metadata[0].EndsWith(": $goVersion", [StringComparison]::Ordinal)) {
throw "$binary was not linked by the requested $goVersion toolchain"
}
}
} finally {
Pop-Location
}
Push-Location (Join-Path $repoRoot 'frontend')
try {
# Local Windows development can keep node_modules open briefly (for
# example after browser tests). The opt-out is only for an already
# restored lockfile-compatible dependency tree; CI remains the default.
if ($env:SEA_BUILD_SKIP_NPM_CI -ne 'true') {
& npm ci
if ($LASTEXITCODE -ne 0) { throw 'npm ci failed' }
}
$env:VITE_API_MODE = 'true'
& npm run build
if ($LASTEXITCODE -ne 0) { throw 'Frontend build failed' }
Copy-Item -Path (Join-Path $PWD 'dist\*') -Destination $webRoot -Recurse -Force
} finally {
Pop-Location
}
Assert-BuildPath $archive
& node (Join-Path $PSScriptRoot 'package-release.mjs')
if ($LASTEXITCODE -ne 0) { throw 'Curated release packaging failed' }
Write-Host "Build completed: $archive"
Write-Host 'Runtime/source archives, SHA-256 files and manifests are in build/.'
+26
View File
@@ -0,0 +1,26 @@
#!/usr/bin/env bash
set -euo pipefail
repo_root="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)"
output_dir="${repo_root}/build"
mkdir -p "${output_dir}/bin" "${output_dir}/web"
cd "${repo_root}/backend"
CGO_ENABLED=0 GOOS=linux GOARCH=amd64 go build -trimpath -ldflags='-s -w' -o "${output_dir}/bin/sea-vhost-scheduler" ./cmd/scheduler
CGO_ENABLED=0 GOOS=linux GOARCH=amd64 go build -trimpath -ldflags='-s -w' -o "${output_dir}/bin/sea-vhost-run" ./cmd/runner
CGO_ENABLED=0 GOOS=linux GOARCH=amd64 go build -trimpath -ldflags='-s -w' -o "${output_dir}/bin/sea-vhost-api" ./cmd/server
CGO_ENABLED=0 GOOS=linux GOARCH=amd64 go build -trimpath -ldflags='-s -w' -o "${output_dir}/bin/sea-vhost-agent" ./cmd/agent
CGO_ENABLED=0 GOOS=linux GOARCH=amd64 go build -trimpath -ldflags='-s -w' -o "${output_dir}/bin/sea-vhost-panel-broker" ./cmd/panel-broker
CGO_ENABLED=0 GOOS=linux GOARCH=amd64 go build -trimpath -ldflags='-s -w' -o "${output_dir}/bin/sea-vhost-node" ./cmd/node
cd "${repo_root}/frontend"
npm ci
VITE_API_MODE=true npm run build
[[ "${output_dir}" == "${repo_root}/build" && ! -L "${output_dir}/web" ]] || { echo 'Unsafe web output directory' >&2; exit 1; }
rm -rf -- "${output_dir}/web"
mkdir -p "${output_dir}/web"
cp -a dist/. "${output_dir}/web/"
node "${repo_root}/deploy/package-release.mjs"
echo "Build completed: ${output_dir}"
+208
View File
@@ -0,0 +1,208 @@
#!/usr/bin/env bash
set -uo pipefail
failures=0
warnings=0
agent_socket="${SEA_AGENT_SOCKET:-/run/sea-vhost/agent.sock}"
panel_broker_socket="${SEA_PANEL_BROKER_SOCKET:-/run/sea-vhost-panel/broker.sock}"
panel_broker_state="${SEA_PANEL_BROKER_STATE:-/var/lib/sea-vhost-panel}"
config_file="${SEA_CONFIG_FILE:-/var/lib/sea-vhost/config.json}"
environment_file="/etc/sea-vhost/sea-vhost.env"
nginx_vhost_root="${SEA_NGINX_VHOST_ROOT:-/www/server/panel/vhost/nginx}"
nginx_security_global="${nginx_vhost_root}/sea-vhost-security-global.conf"
backup_root="${SEA_BACKUP_ROOT:-/www/backup/sea-vhost}"
production_mode="${SEA_DIAGNOSE_PRODUCTION:-false}"
pass() { printf '[PASS] %s\n' "$1"; }
warn() { printf '[WARN] %s\n' "$1"; warnings=$((warnings + 1)); }
fail() { printf '[FAIL] %s\n' "$1"; failures=$((failures + 1)); }
security_finding() {
if [[ "${production_mode}" == "true" ]]; then fail "$1"; else warn "$1"; fi
}
check_service() {
local service="$1"
if systemctl is-active --quiet "${service}"; then
pass "${service} is active"
else
fail "${service} is not active"
fi
}
check_mode() {
local path="$1" expected="$2" label="$3" actual
if [[ ! -e "${path}" ]]; then
warn "${label} does not exist: ${path}"
return
fi
actual="$(stat -c '%a' "${path}" 2>/dev/null || true)"
if [[ "${actual}" == "${expected}" ]]; then
pass "${label} permissions are ${actual}"
else
fail "${label} permissions are ${actual:-unknown}; expected ${expected}"
fi
}
check_owner() {
local path="$1" expected="$2" label="$3" actual
if [[ ! -e "${path}" ]]; then
warn "${label} does not exist: ${path}"
return
fi
actual="$(stat -c '%U:%G' "${path}" 2>/dev/null || true)"
if [[ "${actual}" == "${expected}" ]]; then
pass "${label} owner is ${actual}"
else
fail "${label} owner is ${actual:-unknown}; expected ${expected}"
fi
}
printf 'Sea vHost deployment diagnostics\n'
printf '================================\n'
if [[ "${production_mode}" == "true" ]]; then
pass 'production security gate is enabled'
else
warn 'production security gate is disabled; set SEA_DIAGNOSE_PRODUCTION=true for release acceptance'
fi
for command in systemctl stat curl; do
if command -v "${command}" >/dev/null 2>&1; then
pass "command available: ${command}"
else
fail "missing command: ${command}"
fi
done
if command -v systemctl >/dev/null 2>&1; then
check_service sea-vhost-agent.service
check_service sea-vhost-panel-broker.service
check_service sea-vhost-api.service
fi
if id www >/dev/null 2>&1 && id -nG www | tr ' ' '\n' | grep -Eq '^sea-vhost-(control|agent-control|panel-control)$'; then
fail 'www user must not belong to a Sea vHost control group'
else
pass 'www user is excluded from all Sea vHost control groups'
fi
if id sea-vhost-panel >/dev/null 2>&1 && id -nG sea-vhost-panel | tr ' ' '\n' | grep -qx 'sea-vhost-agent-control'; then
fail 'panel broker user must not belong to the root-agent control group'
else
pass 'panel broker is excluded from the root-agent control group'
fi
for required_group in sea-vhost-agent-control sea-vhost-panel-control; do
if id sea-vhost >/dev/null 2>&1 && id -nG sea-vhost | tr ' ' '\n' | grep -qx "${required_group}"; then
pass "API user belongs to ${required_group}"
else
fail "API user is missing required group: ${required_group}"
fi
done
check_mode "${environment_file}" 640 'environment file'
check_owner "${environment_file}" 'root:sea-vhost-control' 'environment file'
check_mode "${nginx_security_global}" 644 'Nginx security baseline'
check_owner "${nginx_security_global}" 'root:root' 'Nginx security baseline'
check_mode "${backup_root}" 700 'lifecycle backup root'
check_owner "${backup_root}" 'root:root' 'lifecycle backup root'
if [[ -e "${config_file}" ]]; then
check_mode "${config_file}" 600 'installed configuration'
check_owner "${config_file}" 'sea-vhost:sea-vhost-control' 'installed configuration'
else
warn "installed configuration is absent; Web setup should be active"
fi
if [[ -S "${agent_socket}" ]]; then
socket_metadata="$(stat -c '%U:%G:%a' "${agent_socket}" 2>/dev/null || true)"
if [[ "${socket_metadata}" == "root:sea-vhost-agent-control:660" ]]; then
pass "isolation socket ownership is ${socket_metadata}"
else
fail "isolation socket ownership is ${socket_metadata:-unknown}; expected root:sea-vhost-agent-control:660"
fi
if curl --silent --show-error --fail --max-time 5 --unix-socket "${agent_socket}" http://localhost/healthz >/dev/null; then
pass 'isolation agent health check succeeded'
else
fail 'isolation agent health check failed'
fi
else
fail "isolation socket is missing: ${agent_socket}"
fi
if [[ -S "${panel_broker_socket}" ]]; then
broker_metadata="$(stat -c '%U:%G:%a' "${panel_broker_socket}" 2>/dev/null || true)"
if [[ "${broker_metadata}" == "sea-vhost-panel:sea-vhost-panel-control:660" ]]; then
pass "panel broker socket ownership is ${broker_metadata}"
else
fail "panel broker socket ownership is ${broker_metadata:-unknown}; expected sea-vhost-panel:sea-vhost-panel-control:660"
fi
broker_health="$(curl --silent --show-error --fail --max-time 5 --unix-socket "${panel_broker_socket}" http://localhost/healthz 2>/dev/null || true)"
if [[ "${broker_health}" == *'"status":"ok"'* || "${broker_health}" == *'"status":"unconfigured"'* ]]; then
pass 'panel broker health check succeeded'
else
fail 'panel broker health check failed'
fi
else
fail "panel broker socket is missing: ${panel_broker_socket}"
fi
if [[ -f "${panel_broker_state}/credentials.json" ]]; then
check_mode "${panel_broker_state}/credentials.json" 600 'panel broker credentials'
check_owner "${panel_broker_state}/credentials.json" 'sea-vhost-panel:sea-vhost-panel-control' 'panel broker credentials'
panel_url="$(sed -nE 's/^[[:space:]]*"url"[[:space:]]*:[[:space:]]*"([^"]+)".*/\1/p' "${panel_broker_state}/credentials.json" | head -n 1)"
if [[ "${panel_url}" =~ ^https?://(127\.0\.0\.1|localhost)(:[0-9]{1,5})?/?$ || "${panel_url}" =~ ^https?://\[::1\](:[0-9]{1,5})?/?$ ]]; then
pass 'panel broker target is loopback-only'
else
security_finding 'panel broker target is missing or is not a loopback URL'
fi
if grep -Eq '"tlsInsecure"[[:space:]]*:[[:space:]]*true' "${panel_broker_state}/credentials.json"; then
security_finding 'panel broker accepts an untrusted aaPanel TLS certificate'
else
pass 'panel broker requires a trusted aaPanel TLS certificate'
fi
panel_port="$(printf '%s\n' "${panel_url}" | sed -nE 's#^https?://(127\.0\.0\.1|localhost|\[::1\]):([0-9]{1,5})/?$#\2#p')"
if [[ -n "${panel_port}" ]] && command -v ss >/dev/null 2>&1; then
if ss -ltnH 2>/dev/null | awk '{print $4}' | grep -Eq "(^|0\\.0\\.0\\.0:|\\[::\\]:|\\*:)${panel_port}$"; then
security_finding "aaPanel port ${panel_port} listens on a wildcard address; firewall/VPN exposure must be checked externally"
else
pass "aaPanel port ${panel_port} is not bound to a wildcard address"
fi
fi
fi
if [[ -f "${config_file}" ]] && grep -q 'panel_api_key' "${config_file}"; then
fail 'Web API configuration still contains a legacy panel API key'
else
pass 'Web API configuration does not contain the panel API key'
fi
if grep -Eq '^SEA_COOKIE_SECURE=false([[:space:]]*)$' "${environment_file}" 2>/dev/null; then
security_finding 'session cookies are allowed over plain HTTP'
else
pass 'session cookies require HTTPS'
fi
api_health="$(curl --silent --show-error --fail --max-time 5 http://127.0.0.1:8080/healthz 2>/dev/null || true)"
if [[ "${api_health}" == *'"status":"ok"'* ]]; then
pass 'Sea vHost API is running normally'
elif [[ "${api_health}" == *'"status":"setup_required"'* ]]; then
pass 'Sea vHost API is waiting for Web setup'
else
fail 'Sea vHost API health check failed'
fi
nginx_binary=""
if command -v nginx >/dev/null 2>&1; then
nginx_binary="$(command -v nginx)"
elif [[ -x /www/server/nginx/sbin/nginx ]]; then
nginx_binary="/www/server/nginx/sbin/nginx"
fi
if [[ -n "${nginx_binary}" ]]; then
if "${nginx_binary}" -t >/dev/null 2>&1; then
pass 'Nginx configuration test succeeded'
else
fail 'Nginx configuration test failed'
fi
else
warn 'Nginx executable was not found in PATH or the standard aaPanel location'
fi
printf '\nResult: %d failure(s), %d warning(s)\n' "${failures}" "${warnings}"
if (( failures > 0 )); then
exit 1
fi
+39
View File
@@ -0,0 +1,39 @@
//go:build linux && amd64
// This deliberately small HTTP server is the real Go artifact used by the
// aaPanel lifecycle smoke test. It avoids third-party dependencies so the
// binary can fit into even the smallest development quota.
package main
import (
"os"
"strconv"
"syscall"
)
func main() {
port, err := strconv.Atoi(os.Getenv("PORT"))
if err != nil || port < 1 || port > 65535 {
os.Exit(2)
}
listener, err := syscall.Socket(syscall.AF_INET, syscall.SOCK_STREAM, 0)
if err != nil {
os.Exit(3)
}
defer syscall.Close(listener)
_ = syscall.SetsockoptInt(listener, syscall.SOL_SOCKET, syscall.SO_REUSEADDR, 1)
if syscall.Bind(listener, &syscall.SockaddrInet4{Port: port, Addr: [4]byte{127, 0, 0, 1}}) != nil || syscall.Listen(listener, 16) != nil {
os.Exit(4)
}
response := []byte("HTTP/1.1 200 OK\r\nContent-Length: 21\r\nConnection: close\r\n\r\nsea-vhost-go-artifact")
for {
connection, _, acceptErr := syscall.Accept(listener)
if acceptErr != nil {
continue
}
var request [1024]byte
_, _ = syscall.Read(connection, request[:])
_, _ = syscall.Write(connection, response)
_ = syscall.Close(connection)
}
}
@@ -0,0 +1,41 @@
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.InetAddress;
import java.net.ServerSocket;
import java.net.Socket;
import java.nio.charset.StandardCharsets;
public final class SeaVHostSmoke {
private SeaVHostSmoke() {}
public static void main(String[] args) throws Exception {
String portValue = System.getenv("PORT");
if (portValue == null || portValue.isEmpty()) {
for (String argument : args) {
if (argument.startsWith("--server.port=")) {
portValue = argument.substring("--server.port=".length());
}
}
}
if (portValue == null || portValue.isEmpty()) {
throw new IllegalArgumentException("missing runtime port");
}
int port = Integer.parseInt(portValue);
byte[] body = "sea-vhost-java-artifact".getBytes(StandardCharsets.UTF_8);
try (ServerSocket server = new ServerSocket(port, 50, InetAddress.getLoopbackAddress())) {
while (true) {
try (Socket socket = server.accept()) {
BufferedReader reader = new BufferedReader(new InputStreamReader(socket.getInputStream(), StandardCharsets.US_ASCII));
for (String line; (line = reader.readLine()) != null && !line.isEmpty();) {
// Consume one HTTP request before returning the fixed marker.
}
OutputStream output = socket.getOutputStream();
output.write(("HTTP/1.1 200 OK\r\nContent-Type: text/plain\r\nContent-Length: " + body.length + "\r\nConnection: close\r\n\r\n").getBytes(StandardCharsets.US_ASCII));
output.write(body);
output.flush();
}
}
}
}
}
+32
View File
@@ -0,0 +1,32 @@
#!/usr/bin/env bash
set -euo pipefail
if [[ ${1:-} == --help ]]; then
echo '独立主控:bash deploy/install.sh --interactive --role controller;自动化:bash deploy/install-controller.sh --non-interactive'
exit 0
fi
if [[ $# -eq 0 && -t 0 && -t 1 ]]; then exec python3 "$(dirname "${BASH_SOURCE[0]}")/install-wizard.py" --role controller; fi
if [[ ${1:-} == --non-interactive ]]; then shift; fi
[[ $# -eq 0 ]] || { echo '未知参数。' >&2; exit 1; }
[[ ${EUID} -eq 0 ]] || { echo 'Run as root.' >&2; exit 1; }
source_dir="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)"
[[ -f "$source_dir/build/bin/sea-vhost-api" && -f "$source_dir/build/web/index.html" ]] || { echo 'Build output missing.' >&2; exit 1; }
[[ ! -e /var/lib/sea-vhost-panel/credentials.json ]] || { echo 'Existing combined installation detected; use the documented migration procedure.' >&2; exit 1; }
getent group sea-vhost-control >/dev/null || groupadd --system sea-vhost-control
id sea-vhost >/dev/null 2>&1 || useradd --system --gid sea-vhost-control --no-create-home --home-dir /var/lib/sea-vhost --shell /usr/sbin/nologin sea-vhost
install -d -o root -g root -m 0755 /opt/sea-vhost /opt/sea-vhost/bin /opt/sea-vhost/web
install -d -o root -g sea-vhost-control -m 0750 /etc/sea-vhost
install -d -o sea-vhost -g sea-vhost-control -m 0700 /var/lib/sea-vhost
install -o root -g root -m 0755 "$source_dir/build/bin/sea-vhost-api" /opt/sea-vhost/bin/sea-vhost-api
cp -a "$source_dir/build/web/." /opt/sea-vhost/web/
chmod -R a+rX /opt/sea-vhost/web
if [[ ! -e /etc/sea-vhost/sea-vhost.env ]]; then
umask 077
token="$(openssl rand -hex 32)"
printf 'SEA_CONTROLLER_ONLY=true\nSEA_SETUP_TOKEN=%s\nSEA_ADDR=127.0.0.1:8080\nSEA_CONFIG_FILE=/var/lib/sea-vhost/config.json\n' "$token" > /etc/sea-vhost/sea-vhost.env
echo 'Created installation token in /etc/sea-vhost/sea-vhost.env.'
fi
grep -qx 'SEA_CONTROLLER_ONLY=true' /etc/sea-vhost/sea-vhost.env || { echo 'Existing environment is not controller-only.' >&2; exit 1; }
install -o root -g root -m 0644 "$source_dir/deploy/systemd/sea-vhost-controller.service" /etc/systemd/system/sea-vhost-api.service
systemctl daemon-reload
systemctl enable --now sea-vhost-api.service
echo 'Controller listening on 127.0.0.1:8080. Serve /opt/sea-vhost/web and proxy /api to this address using your management domain. Complete the Web installation with the local MySQL account.'
+101
View File
@@ -0,0 +1,101 @@
#!/usr/bin/env bash
set -euo pipefail
if [[ ${1:-} == --help ]]; then
echo '被控向导:bash deploy/install.sh --interactive --role node;自动化:bash deploy/install-node.sh 配对文件 凭据文件'
exit 0
fi
if [[ $# -eq 0 && -t 0 && -t 1 ]]; then exec python3 "$(dirname "${BASH_SOURCE[0]}")/install-wizard.py" --role node; fi
[[ ${EUID} -eq 0 ]] || { echo 'Run as root.' >&2; exit 1; }
[[ $# -eq 2 ]] || { echo 'Usage: install-node.sh /root/sea-node-ID.json /root/local-panel-credentials.json' >&2; exit 1; }
source_dir="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)"
for binary in sea-vhost-node sea-vhost-agent sea-vhost-panel-broker sea-vhost-scheduler sea-vhost-run; do [[ -f "$source_dir/build/bin/$binary" && ! -L "$source_dir/build/bin/$binary" ]] || { echo "Missing $binary" >&2; exit 1; }; done
[[ ! -e /var/lib/sea-vhost/config.json ]] || { echo 'Controller configuration exists. Do not convert a combined installation in place.' >&2; exit 1; }
[[ ! -e /var/lib/sea-vhost-panel/resources.json ]] || { echo 'A local platform registry exists; reconcile it before installing a stateless node.' >&2; exit 1; }
[[ -d /www/server/panel && -x /www/server/nginx/sbin/nginx ]] || { echo 'Debian aaPanel/Nginx is required.' >&2; exit 1; }
[[ -x /www/server/pure-ftpd/bin/pure-pw && -d /www/server/pure-ftpd/etc ]] || { echo 'Install the free Pure-FTPd service in aaPanel first.' >&2; exit 1; }
command -v python3 >/dev/null
# Validation runs before creating accounts, changing services or copying keys.
tenant_root="$(python3 - "$1" "$2" <<'PY'
import json,os,re,stat,sys,urllib.parse
for file in sys.argv[1:]:
s=os.lstat(file)
if not stat.S_ISREG(s.st_mode) or s.st_uid!=0 or s.st_mode&0o077: raise SystemExit('Configuration files must be root-owned regular files with mode 0600.')
c=json.load(open(sys.argv[1]));p=json.load(open(sys.argv[2]));root=c['tenantRoot']
if os.path.exists('/etc/sea-vhost-node/config.json'):
old=json.load(open('/etc/sea-vhost-node/config.json'))
if old['identity']['nodeId']!=c['identity']['nodeId'] or old['tenantRoot']!=root: raise SystemExit('Existing node identity/root differs; cross-node migration is not automatic.')
if not re.fullmatch(r'/www/wwwroot/[A-Za-z0-9_/-]+',root) or os.path.normpath(root)!=root or '..' in root.split('/'): raise SystemExit('Invalid tenant root.')
if c['identity']['nodeId']<2 or c['agentSocket']!='/run/sea-vhost/agent.sock' or c['brokerSocket']!='/run/sea-vhost-panel/broker.sock': raise SystemExit('Invalid node pairing configuration.')
u=urllib.parse.urlparse(p['url'])
if u.scheme not in ('http','https') or u.hostname not in ('127.0.0.1','localhost','::1') or u.username or u.password or len(p.get('api_key',''))<16 or p.get('version')!=1: raise SystemExit('Panel credentials must use the loopback interface.')
current='/'
for part in root.strip('/').split('/'):
current=os.path.join(current,part)
if os.path.lexists(current) and (os.path.islink(current) or not os.path.isdir(current)): raise SystemExit('Tenant root contains an unsafe component.')
print(root)
PY
)"
packages=(acl build-essential ca-certificates xz-utils libssl-dev zlib1g-dev libncurses-dev libreadline-dev libsqlite3-dev libgdbm-dev libdb-dev libbz2-dev libexpat1-dev liblzma-dev tk-dev libffi-dev uuid-dev)
missing_packages=()
for package in "${packages[@]}"; do
dpkg-query -W -f='${Status}' "$package" 2>/dev/null | grep -q 'ok installed' || missing_packages+=("$package")
done
if (( ${#missing_packages[@]} > 0 )); then
export DEBIAN_FRONTEND=noninteractive
apt-get update
apt-get install -y --no-install-recommends "${missing_packages[@]}"
fi
bash "$source_dir/deploy/prepare-runtime-roots.sh"
for group in sea-vhost-control sea-vhost-agent-control sea-vhost-panel-control; do getent group "$group" >/dev/null || groupadd --system "$group"; done
id sea-vhost >/dev/null 2>&1 || useradd --system --gid sea-vhost-control --no-create-home --home-dir /nonexistent --shell /usr/sbin/nologin sea-vhost
usermod -g sea-vhost-control -aG sea-vhost-agent-control,sea-vhost-panel-control sea-vhost
id sea-vhost-panel >/dev/null 2>&1 || useradd --system --gid sea-vhost-panel-control --no-create-home --home-dir /nonexistent --shell /usr/sbin/nologin sea-vhost-panel
for group in sea-vhost-control sea-vhost-agent-control sea-vhost-panel-control; do gpasswd -d www "$group" >/dev/null 2>&1 || true; done
gpasswd -d sea-vhost-panel sea-vhost-agent-control >/dev/null 2>&1 || true
install -d -o root -g root -m 0755 /opt/sea-vhost /opt/sea-vhost/bin
install -d -o root -g root -m 0755 /usr/local/libexec
install -o root -g root -m 0755 "$source_dir/build/bin/sea-vhost-run" /usr/local/libexec/sea-vhost-run
install -d -o root -g sea-vhost-control -m 0750 /etc/sea-vhost /etc/sea-vhost-node
install -d -o sea-vhost-panel -g sea-vhost-panel-control -m 0700 /var/lib/sea-vhost-panel
install -d -o root -g root -m 0750 /var/lib/sea-vhost
install -d -o root -g root -m 0755 /www/backup/sea-vhost /www/wwwlogs /www/server/panel/vhost/nginx/extension
# The per-site protection snippets reference these zones on fresh nodes too.
security_global=/www/server/panel/vhost/nginx/sea-vhost-security-global.conf
security_backup=''
if [[ -e "$security_global" || -L "$security_global" ]]; then
[[ -f "$security_global" && ! -L "$security_global" ]] || { echo 'Unsafe Nginx security baseline.' >&2; exit 1; }
security_backup="$(mktemp)"
cp --preserve=mode,ownership,timestamps -- "$security_global" "$security_backup"
fi
install -o root -g root -m 0644 "$source_dir/deploy/nginx/sea-vhost-security-global.conf" "$security_global"
if ! /www/server/nginx/sbin/nginx -t; then
if [[ -n "$security_backup" ]]; then cp --preserve=mode,ownership,timestamps -- "$security_backup" "$security_global"; else rm -f -- "$security_global"; fi
[[ -z "$security_backup" ]] || rm -f -- "$security_backup"
echo 'Nginx rejected the security baseline; the previous file was restored.' >&2
exit 1
fi
[[ -z "$security_backup" ]] || rm -f -- "$security_backup"
/www/server/nginx/sbin/nginx -s reload
install -d -o root -g root -m 0755 "$tenant_root"
for default_dir in /www/wwwroot/seavHost /www/wwwroot/seavHost/vHost; do
[[ ! -L "$default_dir" && ( ! -e "$default_dir" || -d "$default_dir" ) ]] || { echo 'Unsafe default managed root.' >&2; exit 1; }
[[ -d "$default_dir" ]] || install -d -o root -g root -m 0755 "$default_dir"
done
install -o root -g sea-vhost-control -m 0640 "$1" /etc/sea-vhost-node/config.json
install -o sea-vhost-panel -g sea-vhost-panel-control -m 0600 "$2" /var/lib/sea-vhost-panel/credentials.json
if [[ -e /var/lib/sea-vhost-panel/resources.json ]]; then echo 'A node-side platform registry exists; reconcile it before enabling stateless mode.' >&2; exit 1; fi
if [[ ! -e /etc/sea-vhost/sea-vhost.env ]]; then
umask 077
printf 'SEA_INTERNAL_AUTH_TOKEN=%s\nSEA_NODE_STATELESS=true\nSEA_TENANT_ROOT=%s\nSEA_AGENT_SOCKET=/run/sea-vhost/agent.sock\nSEA_PANEL_BROKER_SOCKET=/run/sea-vhost-panel/broker.sock\n' "$(openssl rand -hex 32)" "$tenant_root" > /etc/sea-vhost/sea-vhost.env
fi
grep -qx 'SEA_NODE_STATELESS=true' /etc/sea-vhost/sea-vhost.env || { echo 'Existing environment is not a stateless node.' >&2; exit 1; }
grep -qx "SEA_TENANT_ROOT=$tenant_root" /etc/sea-vhost/sea-vhost.env || { echo 'Existing node root differs from paired configuration.' >&2; exit 1; }
for binary in sea-vhost-node sea-vhost-agent sea-vhost-panel-broker sea-vhost-scheduler; do install -o root -g root -m 0755 "$source_dir/build/bin/$binary" "/opt/sea-vhost/bin/$binary"; done
for unit in sea-vhost-agent sea-vhost-panel-broker sea-vhost-node; do install -m 0644 "$source_dir/deploy/systemd/$unit.service" "/etc/systemd/system/$unit.service"; done
install -d -m 0755 /etc/systemd/system/sea-vhost-node.service.d /etc/systemd/system/sea-vhost-agent.service.d
printf '[Service]\nReadWritePaths=%s\n' "$tenant_root" > /etc/systemd/system/sea-vhost-node.service.d/paths.conf
printf '[Service]\nReadWritePaths=%s\n' "$tenant_root" > /etc/systemd/system/sea-vhost-agent.service.d/node-paths.conf
systemctl daemon-reload
systemctl enable sea-vhost-agent sea-vhost-panel-broker sea-vhost-node
systemctl restart sea-vhost-agent sea-vhost-panel-broker sea-vhost-node
echo 'Node installed. No controller database or scheduler was installed. Enable this node from the controller to probe and connect.'
+458
View File
@@ -0,0 +1,458 @@
#!/usr/bin/env python3
"""Interactive front end for the existing Debian installers (stdlib only)."""
import argparse
import getpass
import json
import os
import platform
import posixpath
import re
import shutil
import stat
import subprocess
import sys
import tempfile
import time
import urllib.parse
import urllib.error
import urllib.request
from pathlib import Path
SOURCE = Path(__file__).resolve().parent.parent
ENVIRONMENT = Path('/etc/sea-vhost/sea-vhost.env')
CONFIG = Path('/var/lib/sea-vhost/config.json')
NODE_CONFIG = Path('/etc/sea-vhost-node/config.json')
PANEL_CREDENTIALS = Path('/var/lib/sea-vhost-panel/credentials.json')
PANEL_REGISTRY = Path('/var/lib/sea-vhost-panel/resources.json')
ROLES = {'combined': '主控兼本机托管', 'controller': '独立主控', 'node': '被控节点'}
class InstallError(Exception):
pass
def run(args, **kwargs):
return subprocess.run([str(a) for a in args], check=True, **kwargs)
class Console:
def ask(self, label, default=''):
value = input(f'{label}' + (f' [{default}]' if default else '') + ':').strip()
return value or default
def confirm(self, label, default=True):
while True:
value = self.ask(label + (' [Y/n]' if default else ' [y/N]')).lower()
if not value:
return default
if value in ('y', 'yes', '是'):
return True
if value in ('n', 'no', '否'):
return False
print('请输入 y 或 n。')
def secret(self, label):
return getpass.getpass(label + ':').strip()
def read_json(file, protect=False):
# No following links, unbounded reads or accepting a writable borrowed key file.
fd = os.open(file, os.O_RDONLY | getattr(os, 'O_NOFOLLOW', 0))
try:
info = os.fstat(fd)
if not stat.S_ISREG(info.st_mode) or info.st_size > 1024 * 1024:
raise InstallError('配置必须是小于 1 MiB 的普通文件。')
if protect:
if info.st_uid != 0:
raise InstallError('配对文件须由 root 所有,请先复制到 /root。')
os.fchmod(fd, 0o600)
with os.fdopen(fd, 'r', encoding='utf-8') as stream:
fd = -1
value = json.load(stream)
if not isinstance(value, dict):
raise InstallError('配置内容必须是 JSON 对象。')
return value
finally:
if fd != -1:
os.close(fd)
def private_json(file, value):
fd = os.open(file, os.O_WRONLY | os.O_CREAT | os.O_EXCL, 0o600)
with os.fdopen(fd, 'w', encoding='utf-8') as stream:
json.dump(value, stream, ensure_ascii=False)
stream.write('\n')
def environment():
if not ENVIRONMENT.exists():
return {}
if ENVIRONMENT.is_symlink() or not ENVIRONMENT.is_file():
raise InstallError('现有环境文件不是安全的普通文件。')
info = ENVIRONMENT.stat()
if info.st_uid != 0 or info.st_mode & 0o022:
raise InstallError('现有环境文件须由 root 所有且不可被组或其他用户修改。')
# Deliberately do not source shell text from this file.
return dict(line.split('=', 1) for line in ENVIRONMENT.read_text().splitlines()
if line and not line.startswith('#') and '=' in line)
def check_role(role, values):
if role == 'node':
if CONFIG.exists() or values and values.get('SEA_NODE_STATELESS') != 'true':
raise InstallError('检测到主控或单机配置,不能原地转换为被控。')
if PANEL_REGISTRY.exists():
raise InstallError('检测到本机资源登记表,请先完成现有主机迁移。')
elif NODE_CONFIG.exists() or values.get('SEA_NODE_STATELESS') == 'true':
raise InstallError('检测到被控配置,不能原地转换为主控。')
elif values and (values.get('SEA_CONTROLLER_ONLY') == 'true') != (role == 'controller'):
raise InstallError('已有安装角色不同;请在另一台服务器安装该角色。')
elif role == 'controller' and PANEL_CREDENTIALS.exists():
raise InstallError('检测到本机宝塔代理凭据,不能直接转换为独立主控。')
def check_build(role):
binaries = ['sea-vhost-node', 'sea-vhost-agent', 'sea-vhost-panel-broker'] if role == 'node' else ['sea-vhost-api']
if role == 'combined':
binaries += ['sea-vhost-agent', 'sea-vhost-panel-broker']
files = [SOURCE / 'build/bin' / name for name in binaries]
if role != 'node':
files.append(SOURCE / 'build/web/index.html')
for file in files:
if file.is_symlink() or not file.is_file():
raise InstallError('安装包不完整,请解压完整的 sea-vhost-linux-amd64.tar.gz 后再运行。')
def panel_url(value):
try:
parsed = urllib.parse.urlsplit(value)
port = parsed.port
except ValueError:
raise InstallError('宝塔地址或端口无效。') from None
if (parsed.scheme not in ('http', 'https') or parsed.hostname not in ('127.0.0.1', 'localhost', '::1')
or parsed.username or parsed.password or parsed.query or parsed.fragment
or parsed.path not in ('', '/') or port is not None and not 1 <= port <= 65535):
raise InstallError('宝塔地址只能是本机回环 HTTP/HTTPS 地址,不包含安全入口路径。')
return value.rstrip('/')
def detect_panel_url():
data = Path('/www/server/panel/data')
try:
port = int((data / 'port.pl').read_text().strip())
if not 1 <= port <= 65535:
raise ValueError()
except (OSError, ValueError):
port = 8888
return ('https' if (data / 'ssl.pl').exists() else 'http') + f'://127.0.0.1:{port}'
def credentials(ui):
saved = read_json(PANEL_CREDENTIALS) if PANEL_CREDENTIALS.exists() else {}
if saved and ui.confirm('复用本机已保存的宝塔凭据'):
panel_url(saved.get('url', ''))
if saved.get('version') != 1 or len(saved.get('api_key', '')) < 16:
raise InstallError('已有宝塔凭据不完整,请重新填写。')
return saved
while True:
try:
url = panel_url(ui.ask('本机宝塔 API 地址', detect_panel_url()))
break
except InstallError as error:
print(error)
while True:
key = ui.secret('宝塔 API 密钥(输入隐藏)')
if len(key) >= 16 and not any(c.isspace() for c in key):
break
print('密钥格式无效,请重新输入。')
insecure = url.startswith('https:') and ui.confirm('本机宝塔使用自签名证书,跳过其证书校验')
return {'version': 1, 'url': url, 'api_key': key, 'tls_insecure': insecure}
def validate_pair(config):
identity = config.get('identity', {})
root = config.get('tenantRoot', '')
if (not isinstance(identity, dict) or type(identity.get('nodeId')) is not int or identity['nodeId'] < 2
or not re.fullmatch(r'/www/wwwroot/[A-Za-z0-9_/-]+', root)
or posixpath.normpath(root) != root or '..' in root.split('/')
or config.get('brokerSocket') != '/run/sea-vhost-panel/broker.sock'
or config.get('agentSocket') != '/run/sea-vhost/agent.sock'):
raise InstallError('配对文件的节点、目录或 Socket 配置无效。')
if not re.fullmatch(r'(?:\[[0-9a-fA-F:]+\]|[0-9.]*):([0-9]{1,5})', config.get('address', '')):
raise InstallError('配对文件的监听地址无效。')
port = int(config['address'].rsplit(':', 1)[1])
if not 1024 <= port <= 65535:
raise InstallError('被控监听端口须为 1024–65535。')
if not all(isinstance(identity.get(k), str) and identity[k] for k in ('caPem', 'certificate', 'privateKey', 'clientSpki')):
raise InstallError('配对文件缺少身份材料。')
return identity['nodeId'], root
def wait_services(units, attempts=20):
consecutive = 0
for _ in range(attempts):
if all(subprocess.run(['systemctl', 'is-active', '--quiet', unit], check=False).returncode == 0 for unit in units):
consecutive += 1
if consecutive >= 2:
return
else:
consecutive = 0
time.sleep(1)
raise InstallError('服务未全部就绪。检查命令:journalctl -u ' + ' -u '.join(units) + ' -n 60 --no-pager')
class NoRedirect(urllib.request.HTTPRedirectHandler):
def redirect_request(self, req, fp, code, msg, headers, newurl):
raise InstallError('本机健康检查意外返回重定向,拒绝继续。')
def wait_api(values, timeout=660):
address = values.get('SEA_ADDR', '127.0.0.1:8080')
if not re.fullmatch(r'127\.0\.0\.1:[0-9]{1,5}', address) or not 1 <= int(address.split(':')[1]) <= 65535:
raise InstallError('无法自动核验现有 API 地址,请使用 127.0.0.1 的监听地址。')
opener = urllib.request.build_opener(urllib.request.ProxyHandler({}), NoRedirect())
deadline = time.monotonic() + timeout
print('正在等待 API 完成数据库迁移与主机身份核验……')
while time.monotonic() < deadline:
try:
with opener.open('http://' + address + '/healthz', timeout=3) as response:
if response.status == 200 and json.loads(response.read(4096)).get('status') in ('ok', 'setup_required'):
return
except (OSError, urllib.error.URLError, ValueError):
pass
time.sleep(1)
raise InstallError('API 健康检查未通过,不能报告安装成功。请执行 journalctl -u sea-vhost-api -n 60 --no-pager;修复后重跑向导。')
def install_node(ui):
if not Path('/www/server/panel').is_dir() or not Path('/www/server/nginx/sbin/nginx').is_file():
raise InstallError('被控需要本机宝塔和 Nginx。')
if not Path('/www/server/pure-ftpd/bin/pure-pw').is_file():
raise InstallError('请先在宝塔安装免费 Pure-FTPd,再运行被控向导。')
candidates = sorted(Path('/root').glob('sea-node-*.json'))
default = str(NODE_CONFIG) if NODE_CONFIG.exists() else str(candidates[0]) if len(candidates) == 1 else ''
pairing = Path(ui.ask('主控下载的配对文件路径', default)).expanduser()
# An installed config is intentionally group-readable by the non-root node.
# Do not chmod it to 0600 while the user is still answering/cancelling prompts.
installed_pair = NODE_CONFIG.exists() and pairing.samefile(NODE_CONFIG)
config = read_json(pairing, protect=not installed_pair)
node, root = validate_pair(config)
if NODE_CONFIG.exists():
old = read_json(NODE_CONFIG)
if old.get('identity', {}).get('nodeId') != node or old.get('tenantRoot') != root:
raise InstallError('配对文件与现有节点编号或根目录不同,不能直接覆盖。')
creds = credentials(ui)
print(f'\n安装角色:被控 #{node}\n主机目录:{root}\n监听地址:{config["address"]}\n宝塔地址:{creds["url"]}')
if not ui.confirm('开始安装并启动被控'):
return False
with tempfile.TemporaryDirectory(prefix='sea-vhost-install-', dir='/run') as directory:
pair_file, panel_file = Path(directory) / 'pair.json', Path(directory) / 'panel.json'
private_json(pair_file, config)
private_json(panel_file, creds)
run(['bash', SOURCE / 'deploy/install-node.sh', pair_file, panel_file])
units = ['sea-vhost-agent', 'sea-vhost-panel-broker', 'sea-vhost-node']
wait_services(units)
print('\n被控安装完成,服务已启动。回到主控「节点管理」,点击「启用」即可自动探测并连接。')
print('被控不保存平台数据库;无需额外填写主控数据库或管理员信息。')
return True
def valid_domain(value):
return len(value) <= 253 and '.' in value and all(
re.fullmatch(r'[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?', label)
for label in value.split('.'))
def certificate_for(domain):
for base in (Path('/www/server/panel/vhost/cert'), Path('/www/server/panel/vhost/ssl'), Path('/etc/letsencrypt/live')):
if not base.is_dir():
continue
ordered = [base / domain] + sorted(p for p in base.iterdir() if p.name != domain)
for directory in ordered:
cert, key = directory / 'fullchain.pem', directory / 'privkey.pem'
if not cert.is_file() or not key.is_file():
continue
if certificate_covers(cert, domain):
return cert, key
return None
def certificate_covers(cert, domain):
return all(subprocess.run(['openssl', 'x509', '-in', str(cert)] + args,
stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL, check=False).returncode == 0
for args in (['-checkhost', domain, '-noout'], ['-checkend', '0', '-noout']))
def nginx_plan(ui, values):
if not ui.confirm('自动配置管理站点 HTTPS 与反向代理(复用已有证书)'):
return None
nginx = Path('/www/server/nginx/sbin/nginx')
if nginx.is_file():
vhosts = Path('/www/server/panel/vhost/nginx')
reload_command = [str(nginx), '-s', 'reload']
else:
binary = shutil.which('nginx')
if not binary:
print('本机未检测到 Nginx,本次仅安装主控程序。配置好管理站点后可再次运行向导。')
return None
nginx, vhosts, reload_command = Path(binary), Path('/etc/nginx/conf.d'), ['systemctl', 'reload', 'nginx']
while True:
domain = ui.ask('管理域名(不含协议和路径)', 'host.ser888.cn').lower()
if valid_domain(domain):
break
print('请输入有效的域名。')
addr = values.get('SEA_ADDR', '127.0.0.1:8080')
if not re.fullmatch(r'127\.0\.0\.1:[0-9]{1,5}', addr) or not 1 <= int(addr.split(':')[1]) <= 65535:
raise InstallError('现有 API 监听地址不是受支持的本机地址,保留现有 Nginx 配置后重试。')
found = certificate_for(domain)
if not found:
print('未检测到覆盖该管理域名的有效证书。可输入证书路径,或留空后自行配置站点。')
cert = ui.ask('完整证书链路径(留空跳过站点配置)')
if not cert:
return None
key = ui.ask('证书私钥路径')
found = (Path(cert), Path(key))
for file in found:
if not file.is_absolute() or not file.is_file() or re.search(r'[\s;{}"\'\\$]', str(file)):
raise InstallError('证书路径须是可读绝对路径且不包含 Nginx 特殊字符。')
if not certificate_covers(found[0], domain):
raise InstallError('证书已过期或未覆盖管理域名,请更换后重试。')
target = vhosts / 'sea-vhost-console.conf'
if target.is_symlink() or target.exists() and not target.is_file():
raise InstallError('管理站点配置路径不是安全的普通文件。')
for file in vhosts.glob('*.conf'):
if file == target:
continue
text = file.read_text(errors='replace')
if any(domain in names.split() for names in re.findall(r'^\s*server_name\s+([^;]+);', text, re.M)):
if 'root /opt/sea-vhost/web;' in text or re.search(r'root\s+/opt/sea-vhost/web\s*;', text):
print(f'检测到已有 Sea vHost 管理站点,保留 {file}。')
run([nginx, '-t'])
return {'domain': domain, 'existing': True}
raise InstallError(f'域名已由其他 Nginx 站点使用:{file}。不会覆盖;可重新运行并跳过自动配置。')
text = (SOURCE / 'deploy/nginx/sea-vhost.conf').read_text()
text = text.replace('host.ser888.cn', domain)
text = text.replace(f'/www/server/panel/vhost/cert/{domain}/fullchain.pem', str(found[0]))
text = text.replace(f'/www/server/panel/vhost/cert/{domain}/privkey.pem', str(found[1]))
text = text.replace('127.0.0.1:8080', addr)
return {'domain': domain, 'existing': False, 'target': target, 'text': text,
'nginx': nginx, 'reload': reload_command}
def apply_nginx(plan):
if not plan or plan['existing']:
return
target = plan['target']
previous = target.read_bytes() if target.exists() else None
if previous is not None:
# Backups live outside the *.conf include namespace, with exclusive creation.
with tempfile.NamedTemporaryFile(prefix=target.name + '.', suffix='.bak', dir=target.parent, delete=False) as backup:
backup.write(previous)
print(f'Nginx 原配置备份:{backup.name}')
try:
atomic_config(target, plan['text'].encode())
run([plan['nginx'], '-t'])
run(plan['reload'])
except (OSError, subprocess.CalledProcessError):
if previous is None:
target.unlink(missing_ok=True)
else:
atomic_config(target, previous)
# Reload again so a partially successful first reload cannot retain new config.
subprocess.run([str(v) for v in plan['reload']], check=False)
raise InstallError('Nginx 检查或重载失败,已恢复配置;主控程序仍保留,可修复后重跑向导。') from None
def atomic_config(target, content):
if target.is_symlink() or target.exists() and not target.is_file():
raise InstallError('拒绝写入非普通 Nginx 配置文件。')
with tempfile.NamedTemporaryFile(dir=target.parent, prefix='.sea-vhost-', delete=False) as stream:
temporary = Path(stream.name)
try:
stream.write(content)
stream.flush()
os.fchmod(stream.fileno(), 0o644)
except BaseException:
temporary.unlink(missing_ok=True)
raise
try:
os.replace(temporary, target)
finally:
temporary.unlink(missing_ok=True)
def install_controller(ui, role, values):
if role == 'combined' and not Path('/www/server/panel').is_dir():
raise InstallError('兼本机托管需要本机宝塔;没有宝塔时请选择独立主控。')
plan = nginx_plan(ui, values)
print(f'\n安装角色:{ROLES[role]}\n平台数据:保留已有配置;首次安装的数据库与管理员信息在 Web 安装页填写')
if plan:
print('管理地址:https://' + plan['domain'])
if not ui.confirm('开始安装/更新并启动服务'):
return False
script = 'install-controller.sh' if role == 'controller' else 'install.sh'
run(['bash', SOURCE / 'deploy' / script, '--non-interactive'])
units = ['sea-vhost-api'] if role == 'controller' else ['sea-vhost-agent', 'sea-vhost-panel-broker', 'sea-vhost-api']
run(['systemctl', 'enable', *units])
run(['systemctl', 'restart', *units])
wait_services(units)
wait_api(values)
apply_nginx(plan)
print('\n主控安装完成,服务已启动。')
if plan:
print('打开 https://' + plan['domain'] + '/ 完成 Web 安装;已安装则直接登录。')
else:
print('管理站点根目录:/opt/sea-vhost/web;/api/ 反代至 http://' + values.get('SEA_ADDR', '127.0.0.1:8080'))
if not CONFIG.exists():
token = environment().get('SEA_SETUP_TOKEN', '')
if token:
print('Web 安装令牌(请保密):' + token)
return True
def main(argv=None):
parser = argparse.ArgumentParser(description='Sea vHost 中文交互式安装向导;保留现有数据,不自动转换安装角色。')
parser.add_argument('--role', choices=ROLES, help='预选安装角色')
options = parser.parse_args(argv)
if platform.system() != 'Linux' or platform.machine() not in ('x86_64', 'amd64'):
raise InstallError('当前安装包仅支持 Debian Linux amd64。')
if os.geteuid() != 0:
raise InstallError('请使用 root 运行安装向导。')
if not sys.stdin.isatty():
raise InstallError('交互向导需要终端;自动化部署请使用原脚本的 --non-interactive 模式。')
os.umask(0o077)
ui = Console()
values = environment()
print('\nSea vHost 安装向导\n回车采用默认值,Ctrl+C 取消;密码输入不会显示。\n')
role = options.role
if not role:
default = '3' if NODE_CONFIG.exists() else '2' if values.get('SEA_CONTROLLER_ONLY') == 'true' else '1'
print('1. 主控兼本机托管(已有宝塔的服务器)\n2. 独立主控(仅管理其他被控)\n3. 被控节点(已有宝塔的服务器)')
while not role:
role = {'1': 'combined', '2': 'controller', '3': 'node'}.get(ui.ask('选择安装角色', default))
if not role:
print('请输入 1、2 或 3。')
check_role(role, values)
check_build(role)
for command in ('bash', 'systemctl', 'openssl'):
if not shutil.which(command):
raise InstallError(f'缺少必要命令 {command},请安装后重试。')
completed = install_node(ui) if role == 'node' else install_controller(ui, role, values)
if not completed:
print('安装已取消。')
return 0
if __name__ == '__main__':
try:
sys.exit(main())
except (KeyboardInterrupt, EOFError):
print('\n安装已取消;已完成的安装步骤会保留,可再次运行向导继续。', file=sys.stderr)
sys.exit(130)
except subprocess.CalledProcessError as error:
print(f'\n安装命令失败(退出码 {error.returncode}),请检查上方输出;修复后可重新运行向导。', file=sys.stderr)
sys.exit(1)
except (InstallError, OSError, ValueError, TypeError, KeyError) as error:
# Never print config contents, subprocess input or stored credentials.
print(f'\n安装未完成:{error}', file=sys.stderr)
sys.exit(1)
+242
View File
@@ -0,0 +1,242 @@
#!/usr/bin/env bash
set -euo pipefail
if [[ ${1:-} == --help ]]; then
echo '用法:bash deploy/install.sh [--interactive [--role combined|controller|node] | --non-interactive]'
echo '终端运行默认进入中文交互向导;--non-interactive 保留原本机安装行为。'
exit 0
fi
if [[ ${1:-} == --interactive || ( $# -eq 0 && -t 0 && -t 1 ) ]]; then
[[ ${1:-} != --interactive ]] || shift
exec python3 "$(dirname "${BASH_SOURCE[0]}")/install-wizard.py" "$@"
fi
if [[ ${1:-} == --non-interactive ]]; then shift; fi
[[ $# -eq 0 ]] || { echo '未知参数,使用 --help 查看安装方式。' >&2; exit 1; }
if [[ "${EUID}" -ne 0 ]]; then
echo "Run this installer as root." >&2
exit 1
fi
source_dir="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)"
build_dir="${source_dir}/build"
for binary in sea-vhost-api sea-vhost-agent sea-vhost-panel-broker sea-vhost-run sea-vhost-scheduler; do
[[ -f "${build_dir}/bin/$binary" && ! -L "${build_dir}/bin/$binary" ]] || { echo "Missing $binary" >&2; exit 1; }
done
if [[ ! -f "${build_dir}/bin/sea-vhost-api" || -L "${build_dir}/bin/sea-vhost-api" || ! -f "${build_dir}/bin/sea-vhost-agent" || -L "${build_dir}/bin/sea-vhost-agent" || ! -f "${build_dir}/bin/sea-vhost-panel-broker" || -L "${build_dir}/bin/sea-vhost-panel-broker" || ! -f "${build_dir}/web/index.html" || -L "${build_dir}/web/index.html" ]]; then
echo "Missing build output. Run deploy/build.sh first." >&2
exit 1
fi
if ! command -v setfacl >/dev/null 2>&1 || ! command -v getfacl >/dev/null 2>&1; then
export DEBIAN_FRONTEND=noninteractive
apt-get update
apt-get install -y --no-install-recommends acl
fi
# Current security releases for older Python branches are source-only. Keep the
# compiler and standard-library headers available so the privileged installer
# can build the latest patch of each supported branch from verified CPython
# sources instead of relying on aaPanel's stale prebuilt-version list.
python_build_packages=(build-essential ca-certificates xz-utils libssl-dev zlib1g-dev libncurses-dev libreadline-dev libsqlite3-dev libgdbm-dev libdb-dev libbz2-dev libexpat1-dev liblzma-dev tk-dev libffi-dev uuid-dev)
missing_python_build_packages=()
for package in "${python_build_packages[@]}"; do
dpkg-query -W -f='${Status}' "${package}" 2>/dev/null | grep -q 'ok installed' || missing_python_build_packages+=("${package}")
done
if (( ${#missing_python_build_packages[@]} > 0 )); then
export DEBIAN_FRONTEND=noninteractive
apt-get update
apt-get install -y --no-install-recommends "${missing_python_build_packages[@]}"
fi
bash "$source_dir/deploy/prepare-runtime-roots.sh"
for required in chattr systemctl openssl mktemp setfacl getfacl useradd usermod passwd make tar xz; do
command -v "${required}" >/dev/null || { echo "Missing required command: ${required}" >&2; exit 1; }
done
legacy_config="/var/lib/sea-vhost/config.json"
if [[ -f "${legacy_config}" ]] && grep -q '"panel_api_key"' "${legacy_config}"; then
echo "Legacy Web API configuration still contains a root-equivalent panel API key." >&2
echo "Refusing an automatic migration. Back up the file, move the key into the panel broker through a root-controlled maintenance procedure, then remove it from ${legacy_config}." >&2
exit 1
fi
getent group sea-vhost-control >/dev/null || groupadd --system sea-vhost-control
getent group sea-vhost-agent-control >/dev/null || groupadd --system sea-vhost-agent-control
getent group sea-vhost-panel-control >/dev/null || groupadd --system sea-vhost-panel-control
id sea-vhost >/dev/null 2>&1 || useradd --system --gid sea-vhost-control --groups sea-vhost-agent-control,sea-vhost-panel-control --home-dir /var/lib/sea-vhost --shell /usr/sbin/nologin sea-vhost
usermod -g sea-vhost-control -aG sea-vhost-agent-control,sea-vhost-panel-control sea-vhost
id sea-vhost-panel >/dev/null 2>&1 || useradd --system --gid sea-vhost-panel-control --groups sea-vhost-control --home-dir /var/lib/sea-vhost-panel --shell /usr/sbin/nologin sea-vhost-panel
usermod -g sea-vhost-panel-control -aG sea-vhost-control sea-vhost-panel
gpasswd -d sea-vhost-panel sea-vhost-agent-control >/dev/null 2>&1 || true
gpasswd -d sea-vhost-panel sea-vhost-files >/dev/null 2>&1 || true
gpasswd -d sea-vhost sea-vhost-files >/dev/null 2>&1 || true
if ! id www >/dev/null 2>&1; then
echo "Missing Nginx/PHP service user: www" >&2
exit 1
fi
if getent group sea-vhost >/dev/null 2>&1 && id www >/dev/null 2>&1; then
gpasswd -d www sea-vhost >/dev/null 2>&1 || true
fi
if id www >/dev/null 2>&1; then
gpasswd -d www sea-vhost-control >/dev/null 2>&1 || true
gpasswd -d www sea-vhost-agent-control >/dev/null 2>&1 || true
gpasswd -d www sea-vhost-panel-control >/dev/null 2>&1 || true
gpasswd -d www sea-vhost-files >/dev/null 2>&1 || true
if id -nG www | tr ' ' '\n' | grep -Eq '^sea-vhost-(control|agent-control|panel-control)$'; then
echo "The www user still belongs to a Sea vHost control group; refusing to expose privileged sockets." >&2
exit 1
fi
fi
install -d -o root -g sea-vhost-control -m 0750 /etc/sea-vhost
install -d -o root -g root -m 0755 /opt/sea-vhost
if [[ -L /www/wwwroot || ( -e /www/wwwroot && ! -d /www/wwwroot ) ]]; then
echo "The aaPanel site root /www/wwwroot is not a physical directory." >&2
exit 1
fi
if [[ ! -d /www/wwwroot ]]; then
install -d -o root -g root -m 0755 /www/wwwroot
fi
tenant_root="/www/wwwroot/seavHost/vHost"
for managed_dir in /www/wwwroot/seavHost "${tenant_root}"; do
if [[ -L "${managed_dir}" || ( -e "${managed_dir}" && ! -d "${managed_dir}" ) ]]; then
echo "Unsafe Sea vHost managed directory: ${managed_dir}" >&2
exit 1
fi
if [[ ! -d "${managed_dir}" ]]; then
install -d -o root -g root -m 0755 "${managed_dir}"
fi
done
nginx_vhost_root="/www/server/panel/vhost/nginx"
nginx_binary="/www/server/nginx/sbin/nginx"
if [[ -L "${nginx_vhost_root}" || ! -d "${nginx_vhost_root}" ]]; then
echo "The aaPanel Nginx vhost root is missing or not a physical directory: ${nginx_vhost_root}" >&2
exit 1
fi
if [[ ! -x "${nginx_binary}" ]]; then
echo "The aaPanel Nginx binary is unavailable: ${nginx_binary}" >&2
exit 1
fi
install -d -o root -g root -m 0755 "${nginx_vhost_root}/extension"
security_global="${nginx_vhost_root}/sea-vhost-security-global.conf"
security_backup=""
if [[ -e "${security_global}" ]]; then
if [[ -L "${security_global}" || ! -f "${security_global}" ]]; then
echo "Unsafe existing Sea vHost Nginx security file: ${security_global}" >&2
exit 1
fi
security_backup="$(mktemp)"
cp --preserve=mode,ownership,timestamps -- "${security_global}" "${security_backup}"
fi
install -o root -g root -m 0644 "${source_dir}/deploy/nginx/sea-vhost-security-global.conf" "${security_global}"
if ! "${nginx_binary}" -t; then
if [[ -n "${security_backup}" ]]; then
cp --preserve=mode,ownership,timestamps -- "${security_backup}" "${security_global}"
else
rm -f -- "${security_global}"
fi
[[ -z "${security_backup}" ]] || rm -f -- "${security_backup}"
echo "Nginx rejected the Sea vHost security baseline; the previous configuration was restored." >&2
exit 1
fi
[[ -z "${security_backup}" ]] || rm -f -- "${security_backup}"
install -d -o root -g root -m 0755 /usr/local/libexec
install -o root -g root -m 0755 "${build_dir}/bin/sea-vhost-run" /usr/local/libexec/sea-vhost-run
install -o root -g root -m 0750 "${build_dir}/bin/sea-vhost-scheduler" /opt/sea-vhost/bin/sea-vhost-scheduler
install -d -o root -g sea-vhost-control -m 0750 /opt/sea-vhost/bin
install -d -o root -g root -m 0755 /opt/sea-vhost/web
install -d -o sea-vhost -g sea-vhost-control -m 0700 /var/lib/sea-vhost
install -d -o sea-vhost-panel -g sea-vhost-panel-control -m 0700 /var/lib/sea-vhost-panel
install -d -o root -g root -m 0700 /www/backup/sea-vhost
install -o root -g sea-vhost-control -m 0750 "${build_dir}/bin/sea-vhost-api" /opt/sea-vhost/bin/
install -o root -g sea-vhost-control -m 0750 "${build_dir}/bin/sea-vhost-agent" /opt/sea-vhost/bin/
install -o root -g sea-vhost-control -m 0750 "${build_dir}/bin/sea-vhost-panel-broker" /opt/sea-vhost/bin/
# aaPanel adds an immutable PHP .user.ini when a directory is registered as a
# site, even for Sea vHost's static console. This directory is fully managed by
# the installer and does not execute PHP, so remove that panel artifact before
# normalizing ownership during upgrades.
if [[ -e /opt/sea-vhost/web/.user.ini ]]; then
if [[ -L /opt/sea-vhost/web/.user.ini || ! -f /opt/sea-vhost/web/.user.ini ]]; then
echo "Unsafe aaPanel .user.ini artifact in the managed Web directory." >&2
exit 1
fi
chattr -i -a -- /opt/sea-vhost/web/.user.ini 2>/dev/null || true
rm -f -- /opt/sea-vhost/web/.user.ini
fi
cp -a "${build_dir}/web/." /opt/sea-vhost/web/
chown -R root:root /opt/sea-vhost/web
find /opt/sea-vhost/web -type d -exec chmod 0755 {} +
find /opt/sea-vhost/web -type f -exec chmod 0644 {} +
if [[ ! -f /etc/sea-vhost/sea-vhost.env ]]; then
setup_token="$(openssl rand -hex 32)"
internal_auth_token="$(openssl rand -hex 32)"
install -o root -g sea-vhost-control -m 0640 /dev/null /etc/sea-vhost/sea-vhost.env
{
echo "SEA_ADDR=127.0.0.1:8080"
echo "SEA_CONFIG_FILE=/var/lib/sea-vhost/config.json"
echo "SEA_SETUP_TOKEN=${setup_token}"
echo "SEA_INTERNAL_AUTH_TOKEN=${internal_auth_token}"
echo "SEA_COOKIE_SECURE=true"
echo "SEA_TENANT_ROOT=${tenant_root}"
echo "SEA_BACKUP_ROOT=/www/backup/sea-vhost"
echo "SEA_UPLOAD_LIMIT=20971520"
echo "SEA_AGENT_SOCKET=/run/sea-vhost/agent.sock"
echo "SEA_PANEL_BROKER_SOCKET=/run/sea-vhost-panel/broker.sock"
echo "SEA_PANEL_BROKER_STATE=/var/lib/sea-vhost-panel"
echo "SEA_FILE_OWNER=sea-vhost"
echo "SEA_NODE_PID_ROOT=/www/server/nodejs/vhost/pids"
echo "SEA_NGINX_VHOST_ROOT=${nginx_vhost_root}"
echo "SEA_NGINX_BINARY=${nginx_binary}"
echo "SEA_PURE_PW_BINARY=/www/server/pure-ftpd/bin/pure-pw"
echo "SEA_PHP_IDENTITY_STATE=/var/lib/sea-vhost-agent/php"
echo "SEA_PHP_IDENTITY_RUN=/run/sea-vhost-php"
echo "SEA_USAGE_STATE=/var/lib/sea-vhost-agent/traffic.json"
echo "SEA_NGINX_LOG_ROOT=/www/wwwlogs"
echo "SEA_CERT_ROOT=/www/server/panel/vhost/cert"
echo "SEA_PURE_FTP_CONFIG=/www/server/pure-ftpd/etc/pure-ftpd.conf"
echo "SEA_PURE_FTP_PEM=/www/server/pure-ftpd/etc/pure-ftpd.pem"
} > /etc/sea-vhost/sea-vhost.env
chown root:sea-vhost-control /etc/sea-vhost/sea-vhost.env
chmod 0640 /etc/sea-vhost/sea-vhost.env
echo "Created /etc/sea-vhost/sea-vhost.env."
echo "A one-time setup token was created. Retrieve it locally as root from /etc/sea-vhost/sea-vhost.env."
else
echo "Keeping existing /etc/sea-vhost/sea-vhost.env and setup token."
fi
chown root:sea-vhost-control /etc/sea-vhost/sea-vhost.env
chmod 0640 /etc/sea-vhost/sea-vhost.env
grep -q '^SEA_PANEL_BROKER_SOCKET=' /etc/sea-vhost/sea-vhost.env || echo 'SEA_PANEL_BROKER_SOCKET=/run/sea-vhost-panel/broker.sock' >> /etc/sea-vhost/sea-vhost.env
if ! grep -q '^SEA_INTERNAL_AUTH_TOKEN=' /etc/sea-vhost/sea-vhost.env; then
internal_auth_token="$(openssl rand -hex 32)"
echo "SEA_INTERNAL_AUTH_TOKEN=${internal_auth_token}" >> /etc/sea-vhost/sea-vhost.env
fi
grep -q '^SEA_PANEL_BROKER_STATE=' /etc/sea-vhost/sea-vhost.env || echo 'SEA_PANEL_BROKER_STATE=/var/lib/sea-vhost-panel' >> /etc/sea-vhost/sea-vhost.env
grep -q '^SEA_TENANT_ROOT=' /etc/sea-vhost/sea-vhost.env || echo "SEA_TENANT_ROOT=${tenant_root}" >> /etc/sea-vhost/sea-vhost.env
grep -q '^SEA_BACKUP_ROOT=' /etc/sea-vhost/sea-vhost.env || echo 'SEA_BACKUP_ROOT=/www/backup/sea-vhost' >> /etc/sea-vhost/sea-vhost.env
grep -q '^SEA_NGINX_VHOST_ROOT=' /etc/sea-vhost/sea-vhost.env || echo "SEA_NGINX_VHOST_ROOT=${nginx_vhost_root}" >> /etc/sea-vhost/sea-vhost.env
grep -q '^SEA_NGINX_BINARY=' /etc/sea-vhost/sea-vhost.env || echo "SEA_NGINX_BINARY=${nginx_binary}" >> /etc/sea-vhost/sea-vhost.env
grep -q '^SEA_PURE_PW_BINARY=' /etc/sea-vhost/sea-vhost.env || echo 'SEA_PURE_PW_BINARY=/www/server/pure-ftpd/bin/pure-pw' >> /etc/sea-vhost/sea-vhost.env
grep -q '^SEA_PHP_IDENTITY_STATE=' /etc/sea-vhost/sea-vhost.env || echo 'SEA_PHP_IDENTITY_STATE=/var/lib/sea-vhost-agent/php' >> /etc/sea-vhost/sea-vhost.env
grep -q '^SEA_PHP_IDENTITY_RUN=' /etc/sea-vhost/sea-vhost.env || echo 'SEA_PHP_IDENTITY_RUN=/run/sea-vhost-php' >> /etc/sea-vhost/sea-vhost.env
grep -q '^SEA_USAGE_STATE=' /etc/sea-vhost/sea-vhost.env || echo 'SEA_USAGE_STATE=/var/lib/sea-vhost-agent/traffic.json' >> /etc/sea-vhost/sea-vhost.env
grep -q '^SEA_NGINX_LOG_ROOT=' /etc/sea-vhost/sea-vhost.env || echo 'SEA_NGINX_LOG_ROOT=/www/wwwlogs' >> /etc/sea-vhost/sea-vhost.env
grep -q '^SEA_CERT_ROOT=' /etc/sea-vhost/sea-vhost.env || echo 'SEA_CERT_ROOT=/www/server/panel/vhost/cert' >> /etc/sea-vhost/sea-vhost.env
grep -q '^SEA_PURE_FTP_CONFIG=' /etc/sea-vhost/sea-vhost.env || echo 'SEA_PURE_FTP_CONFIG=/www/server/pure-ftpd/etc/pure-ftpd.conf' >> /etc/sea-vhost/sea-vhost.env
grep -q '^SEA_PURE_FTP_PEM=' /etc/sea-vhost/sea-vhost.env || echo 'SEA_PURE_FTP_PEM=/www/server/pure-ftpd/etc/pure-ftpd.pem' >> /etc/sea-vhost/sea-vhost.env
grep -q '^SEA_FILE_OWNER=' /etc/sea-vhost/sea-vhost.env || echo 'SEA_FILE_OWNER=sea-vhost' >> /etc/sea-vhost/sea-vhost.env
grep -q '^SEA_NODE_PID_ROOT=' /etc/sea-vhost/sea-vhost.env || echo 'SEA_NODE_PID_ROOT=/www/server/nodejs/vhost/pids' >> /etc/sea-vhost/sea-vhost.env
sed -i '/^SEA_RUNTIME_USER=/d' /etc/sea-vhost/sea-vhost.env
sed -i '/^SEA_RUNTIME_GROUP=/d' /etc/sea-vhost/sea-vhost.env
sed -i '/^SEA_AGENT_GROUP=/d' /etc/sea-vhost/sea-vhost.env
sed -i '/^SEA_QUOTA_MOUNT=/d' /etc/sea-vhost/sea-vhost.env
install -o root -g root -m 0644 "${source_dir}/deploy/systemd/sea-vhost-agent.service" /etc/systemd/system/
install -o root -g root -m 0644 "${source_dir}/deploy/systemd/sea-vhost-panel-broker.service" /etc/systemd/system/
install -o root -g root -m 0644 "${source_dir}/deploy/systemd/sea-vhost-api.service" /etc/systemd/system/
systemctl daemon-reload
echo "Files installed. Services were not started. Configure the Nginx vhost, create an empty MySQL database and user, then run:"
echo " systemctl enable --now sea-vhost-agent sea-vhost-panel-broker sea-vhost-api"
echo "Open the Sea vHost console and complete the Web installation wizard."
@@ -0,0 +1,20 @@
# Defense-in-depth for an aaPanel reverse-proxy server block.
# Include this file inside the public aaPanel `server {}` block, before the
# catch-all proxy location. It intentionally disables browser terminal and
# other privileged WebSocket features; normal signed HTTP API calls continue.
#
# This is not sufficient while the aaPanel backend port remains reachable
# from untrusted networks. Bind/restrict that port with a firewall, security
# group, VPN, or SSH tunnel as the primary control.
location = /sock_shell { return 403; }
location = /webssh { return 403; }
location = /ws_panel { return 403; }
location = /ws_home { return 403; }
location = /ws_project { return 403; }
location = /ws_model { return 403; }
location = /workorder_client { return 403; }
location ~ ^/v2/(?:sock_shell|webssh|ws_panel|ws_home|ws_project|ws_model|workorder_client)$ {
return 403;
}
@@ -0,0 +1,3 @@
# Managed by Sea vHost. Local changes will be replaced.
limit_req_zone $binary_remote_addr$server_name zone=sea_vhost_per_ip:10m rate=20r/s;
limit_conn_zone $binary_remote_addr$server_name zone=sea_vhost_per_ip_conn:10m;
+61
View File
@@ -0,0 +1,61 @@
map $upstream_http_content_security_policy $sea_vhost_csp {
"" "default-src 'self'; base-uri 'self'; object-src 'none'; frame-ancestors 'none'; form-action 'self'; connect-src 'self'; img-src 'self' data:; font-src 'self'; style-src 'self' 'unsafe-inline'; script-src 'self'";
default $upstream_http_content_security_policy;
}
server {
listen 80;
server_name host.ser888.cn;
return 301 https://$host$request_uri;
}
server {
listen 443 ssl http2;
server_name host.ser888.cn;
server_tokens off;
# 证书可由宝塔站点设置生成;部署前替换路径。
ssl_certificate /www/server/panel/vhost/cert/host.ser888.cn/fullchain.pem;
ssl_certificate_key /www/server/panel/vhost/cert/host.ser888.cn/privkey.pem;
ssl_protocols TLSv1.2 TLSv1.3;
add_header Strict-Transport-Security "max-age=31536000; includeSubDomains" always;
add_header X-Content-Type-Options "nosniff" always;
add_header X-Frame-Options "DENY" always;
add_header Referrer-Policy "same-origin" always;
add_header Permissions-Policy "camera=(), microphone=(), geolocation=()" always;
add_header Content-Security-Policy $sea_vhost_csp always;
root /opt/sea-vhost/web;
index index.html;
client_max_body_size 21m;
proxy_hide_header Content-Security-Policy;
location /api/ {
proxy_pass http://127.0.0.1:8080;
proxy_http_version 1.1;
# Management responses are private; override any server-wide proxy cache.
proxy_cache off;
proxy_set_header Range $http_range;
proxy_set_header If-Range $http_if_range;
# Keep an explicit public port (when present) for strict Origin checks.
proxy_set_header Host $http_host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Forwarded-Proto https;
proxy_connect_timeout 3s;
proxy_read_timeout 300s;
}
location = /healthz {
proxy_pass http://127.0.0.1:8080;
access_log off;
}
location / {
try_files $uri $uri/ /index.html;
}
location ~ /\. {
deny all;
}
}
+34
View File
@@ -0,0 +1,34 @@
#!/usr/bin/env bash
set -euo pipefail
config=/var/lib/sea-vhost/config.json
management_domain="${SEA_MANAGEMENT_DOMAIN:-host.ser888.cn}"
mysql_bin="$(command -v mysql || true)"
if [[ -z "${mysql_bin}" && -x /www/server/mysql/bin/mysql ]]; then
mysql_bin=/www/server/mysql/bin/mysql
fi
[[ -x "${mysql_bin}" ]]
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]}"
sql() {
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="$1"
}
[[ "$(sql "SELECT COUNT(*) FROM schema_migrations WHERE version='010_operational_completion.sql';")" == 1 ]]
[[ "$(sql "SELECT COUNT(*) FROM information_schema.columns WHERE table_schema=DATABASE() AND table_name='domains' AND column_name IN ('dns_credential_id','dns_record_id','dns_record_type','dns_last_error');")" == 4 ]]
[[ "$(sql "SELECT COUNT(*) FROM information_schema.tables WHERE table_schema=DATABASE() AND table_name IN ('tenant_backups','oidc_states');")" == 2 ]]
[[ "$(sql "SELECT COUNT(*) FROM information_schema.columns WHERE table_schema=DATABASE() AND table_name='admin_notifications' AND column_name IN ('attempts','last_error','next_attempt_at');")" == 3 ]]
oidc_status="$(curl --silent --show-error --fail --max-time 10 --header "Host: ${management_domain}" http://127.0.0.1:8080/api/v1/auth/oidc/status)"
python3 -c 'import json,sys; d=json.loads(sys.argv[1]); assert isinstance(d.get("enabled"), bool)' "${oidc_status}"
unauthorized="$(curl --silent --show-error --output /dev/null --write-out '%{http_code}' --max-time 10 --header "Host: ${management_domain}" http://127.0.0.1:8080/api/v1/admin/panel-sites)"
[[ "${unauthorized}" == 401 ]]
systemctl show sea-vhost-agent.service -p ReadWritePaths --value | tr ' ' '\n' | grep -qx '/www/backup/sea-vhost'
[[ -d /www/backup/sea-vhost && ! -L /www/backup/sea-vhost ]]
printf '%s\n' 'Operational completion verification: passed'
printf 'migration=010 dns_columns=4 lifecycle_tables=2 notification_retry_columns=3 oidc_status=valid admin_boundary=401 backup_root=allowed\n'
+60
View File
@@ -0,0 +1,60 @@
// Package only declared project inputs. Never recursively copy the workspace.
import fs from 'node:fs';
import path from 'node:path';
import crypto from 'node:crypto';
import {fileURLToPath} from 'node:url';
import {execFileSync} from 'node:child_process';
const root=path.resolve(path.dirname(fileURLToPath(import.meta.url)),'..');
const build=path.join(root,'build');
const config=JSON.parse(fs.readFileSync(path.join(root,'deploy/release-files.json'),'utf8'));
const requiredBinaries=['sea-vhost-api','sea-vhost-agent','sea-vhost-panel-broker','sea-vhost-node','sea-vhost-run','sea-vhost-scheduler'];
const skip=new Set(['node_modules','__pycache__','.git','.cache','.npm-cache']);
const hash=b=>crypto.createHash('sha256').update(b).digest('hex');
const slash=p=>p.split(path.sep).join('/');
function inside(base,name){const target=path.resolve(base,name),relative=path.relative(base,target);if(!relative||relative.startsWith('..')||path.isAbsolute(relative))throw Error('Path outside allowed output directory');return target}
function validateName(name){if(!name||name.includes('\\')||name.includes('\n')||path.posix.isAbsolute(name)||name.split('/').some(v=>v==='..'||v===''))throw Error('Unsafe package path');return name}
function collect(files,dirs){
const found=new Set();
function visit(name){validateName(name);const full=inside(root,name),s=fs.lstatSync(full);if(s.isSymbolicLink())throw Error('Refusing package symlink: '+name);if(s.isDirectory()){for(const item of fs.readdirSync(full).sort()){if(skip.has(item)||item.startsWith('.tmp')||item.endsWith('.pyc')||item.endsWith('.tsbuildinfo'))continue;visit(name+'/'+item)}}else if(s.isFile()){if(path.basename(name)==='.env')throw Error('Live environment file in package');found.add(name)}else throw Error('Non-regular package input: '+name)}
for(const name of [...files,...dirs])visit(name);
return [...found].sort();
}
function scanSecrets(files){
// Certificate forms contain PEM header placeholders. Reject actual key
// material, including escaped newlines, rather than the header text alone.
const patterns=[[/-----BEGIN (?:RSA |EC |OPENSSH |ENCRYPTED )?PRIVATE KEY-----(?:\s|\\[rn])*(?:[A-Za-z0-9+/=](?:\s|\\[rn])*){80,}/,'private-key'],[/\b(?:AKIA|ASIA)[A-Z0-9]{16}\b/,'aws-access-key'],[/\bgh[pousr]_[A-Za-z0-9]{30,}\b/,'github-token']];
const actualSecret=process.env.SEA_PANEL_API_KEY;
for(const name of files){const data=fs.readFileSync(path.join(root,name));if(actualSecret&&data.includes(Buffer.from(actualSecret)))throw Error('Live panel credential detected in '+name);if(!/\.(?:go|mjs|js|ts|tsx|py|sh|md|json|example|conf|service|sql)$/.test(name)||name.endsWith('_test.go')||/\.test\.(?:ts|tsx|mjs)$/.test(name)||name==='deploy/package-release.mjs')continue;const value=data.toString('utf8');for(const [pattern,kind] of patterns)if(pattern.test(value))throw Error('Potential '+kind+' in '+name)}
}
function checkBuild(){
for(const name of requiredBinaries){const file=path.join(build,'bin',name),s=fs.lstatSync(file);if(!s.isFile()||s.isSymbolicLink()||!fs.readFileSync(file).subarray(0,4).equals(Buffer.from([127,69,76,70])))throw Error('Missing Linux ELF: '+name)}
if(!fs.statSync(path.join(build,'web/index.html')).isFile())throw Error('Frontend build missing');
const actual=fs.readdirSync(path.join(build,'bin')).sort();if(JSON.stringify(actual)!==JSON.stringify([...requiredBinaries].sort()))throw Error('Unexpected file in build/bin');
}
function writePackage(kind,files){
const archiveName=kind==='runtime'?'sea-vhost-linux-amd64.tar.gz':'sea-vhost-source.tar.gz';
const output=inside(build,archiveName),stage=fs.mkdtempSync(path.join(build,'release-stage-'));
try{
const entries=files.map(name=>{const source=path.join(root,name),target=inside(stage,name);fs.mkdirSync(path.dirname(target),{recursive:true});fs.copyFileSync(source,target);const executable=name.startsWith('build/bin/')||name.endsWith('.sh');fs.chmodSync(target,executable?0o755:0o644);return {path:name,bytes:fs.statSync(source).size,sha256:hash(fs.readFileSync(source))}});
const manifest={format:'sea-vhost.release',version:1,kind,createdAt:new Date().toISOString(),platform:'linux/amd64',databaseMigrations:fs.readdirSync(path.join(root,'backend/internal/migrations')).filter(n=>/^\d{3}_.+\.sql$/.test(n)).length,files:entries};
fs.writeFileSync(path.join(stage,'RELEASE-MANIFEST.json'),JSON.stringify(manifest,null,2)+'\n');
const names=[...files,'RELEASE-MANIFEST.json'].sort();
const listing=path.join(stage,'package-list.txt');fs.writeFileSync(listing,names.join('\n')+'\n');
const temporary=inside(build,archiveName+'.pending');
execFileSync('tar',['-czf',temporary,'-C',stage,'-T',listing],{stdio:'pipe'});
const actual=execFileSync('tar',['-tzf',temporary],{encoding:'utf8'}).split(/\r?\n/).filter(Boolean).sort();
if(JSON.stringify(actual)!==JSON.stringify(names))throw Error('Archive content verification failed');
if(fs.existsSync(output)){const prior=hash(fs.readFileSync(output)),history=inside(build,'archive');fs.mkdirSync(history,{recursive:true});const archived=inside(history,archiveName.replace('.tar.gz','-'+prior.slice(0,12)+'.tar.gz'));if(!fs.existsSync(archived))fs.copyFileSync(output,archived)}
fs.renameSync(temporary,output);
const digest=hash(fs.readFileSync(output));fs.writeFileSync(output+'.sha256',digest+' '+archiveName+'\n');
fs.writeFileSync(inside(build,kind+'-manifest.json'),JSON.stringify(manifest,null,2)+'\n');
return {name:archiveName,sha256:digest,bytes:fs.statSync(output).size,files:entries.length};
}finally{const safe=inside(build,path.basename(stage));if(safe!==stage||!path.basename(safe).startsWith('release-stage-'))throw Error('Unsafe staging cleanup');fs.rmSync(safe,{recursive:true,force:true})}
}
checkBuild();fs.mkdirSync(build,{recursive:true});
const runtime=collect(config.runtimeFiles,config.runtimeDirectories),source=collect(config.sourceFiles,config.sourceDirectories);
scanSecrets([...new Set([...runtime,...source])]);
const report={format:'sea-vhost.package-verification',createdAt:new Date().toISOString(),curatedInputs:true,knownLivePanelCredentialChecked:Boolean(process.env.SEA_PANEL_API_KEY),secretScan:'passed (private keys, common token patterns, and supplied live credential; not a complete secret audit)',packages:[writePackage('runtime',runtime),writePackage('source',source)]};
fs.writeFileSync(inside(build,'release-verification.json'),JSON.stringify(report,null,2)+'\n');
console.log(JSON.stringify(report));
+408
View File
@@ -0,0 +1,408 @@
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 consoleURL = process.env.SEA_CONSOLE_URL?.trim();
const insecureTLS = process.env.SEA_PANEL_TLS_INSECURE === 'true';
if (!panelURL || !panelAPIKey || !consoleURL) {
console.error('SEA_PANEL_URL, SEA_PANEL_API_KEY and SEA_CONSOLE_URL are required.');
process.exit(2);
}
const panelBase = new URL(panelURL);
const consoleBase = new URL(consoleURL);
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 suffix = crypto.randomBytes(6).toString('hex');
const email = `security-${suffix}@seavhost.test`;
const tenantEmail = `tenant-security-${suffix}@seavhost.test`;
const initialPassword = `Sv-${crypto.randomBytes(18).toString('base64url')}9a`;
const changedPassword = `Sv-${crypto.randomBytes(18).toString('base64url')}8B`;
const tenantPassword = `Sv-${crypto.randomBytes(18).toString('base64url')}7c`;
const marker = `Sea-vHost-account-security-${suffix}`;
const planName = `File verification ${suffix}`;
const planStatePath = `/var/lib/sea-vhost/account-verify-${suffix}.state`;
const domainRunDirectory = `domain-${suffix}`;
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: 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);
});
}
async function runShell(name, shell, successMarker) {
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 account verification', save: '0', backupTo: 'localhost',
});
if (!task || (task.status !== true && task.status !== 'true')) throw new Error('panel rejected temporary verification task');
const taskID = Number(task.id);
if (!Number.isSafeInteger(taskID) || taskID <= 0) throw new Error('panel returned invalid task id');
try {
await panelForm('/crontab', { action: 'StartTask', id: String(taskID) });
let log = '';
for (let attempt = 0; attempt < 90; 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(successMarker) || log.includes('★[')) break;
}
if (!log.includes(successMarker)) throw new Error(`temporary verification task failed:\n${log.trim()}`);
} finally {
try { await panelForm('/crontab', { action: 'DelCrontab', id: String(taskID) }); } catch { /* best effort */ }
}
}
const q = (value) => `'${value.replaceAll("'", "'\\''")}'`;
const seedMarker = `${marker}-seeded`;
const seedShell = [
'set -Eeuo pipefail',
'stage=initial; trap \'printf "account_seed_failed_stage=%s\\n" "$stage" >&2\' ERR',
`email=${q(email)}`,
`tenant_email=${q(tenantEmail)}`,
`password=${q(initialPassword)}`,
`tenant_password=${q(tenantPassword)}`,
`plan_name=${q(planName)}`,
`state_path=${q(planStatePath)}`,
'stage=php; php_bin="$(find /www/server/php -mindepth 3 -maxdepth 4 -type f -path \'*/bin/php\' -print -quit)"; test -x "$php_bin"',
'password_hash="$(TEST_PASSWORD="$password" "$php_bin" -r \'echo password_hash(getenv("TEST_PASSWORD"), PASSWORD_BCRYPT);\')"; test "${#password_hash}" -gt 50',
'tenant_password_hash="$(TEST_PASSWORD="$tenant_password" "$php_bin" -r \'echo password_hash(getenv("TEST_PASSWORD"), PASSWORD_BCRYPT);\')"; test "${#tenant_password_hash}" -gt 50',
'stage=config',
'mapfile -t db_parts < <(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()))\')',
'test "${#db_parts[@]}" -eq 5; db_user="${db_parts[0]}"; db_password="${db_parts[1]}"; db_host="${db_parts[2]}"; db_port="${db_parts[3]}"; db_name="${db_parts[4]}"',
'mysql_bin="$(command -v mysql || true)"; if [[ -z "$mysql_bin" && -x /www/server/mysql/bin/mysql ]]; then mysql_bin=/www/server/mysql/bin/mysql; fi; test -x "$mysql_bin"',
'stage=database',
'sql="DELETE FROM users WHERE email IN (\'$email\',\'$tenant_email\'); INSERT INTO users(email,login_name,display_name,password_hash,role,status) VALUES (\'$email\',\'$email\',\'Security verification\',\'$password_hash\',\'admin\',\'active\'); INSERT INTO users(tenant_id,email,login_name,display_name,password_hash,role,status) SELECT tenant_id,\'$tenant_email\',\'$tenant_email\',\'Tenant security verification\',\'$tenant_password_hash\',\'tenant\',\'active\' FROM projects ORDER BY id LIMIT 1;"',
'MYSQL_PWD="$db_password" "$mysql_bin" --protocol=TCP --host="$db_host" --port="$db_port" --user="$db_user" --database="$db_name" --execute="$sql"',
'read -r tenant_id original_plan_id project_root < <(MYSQL_PWD="$db_password" "$mysql_bin" --protocol=TCP --host="$db_host" --port="$db_port" --user="$db_user" --database="$db_name" --batch --skip-column-names --execute="SELECT p.tenant_id,t.plan_id,p.root_path FROM projects p JOIN tenants t ON t.id=p.tenant_id ORDER BY p.id LIMIT 1")',
'case "$project_root" in /www/wwwroot/seavHost/vHost/sv??????????) ;; *) exit 1 ;; esac; if [[ -d "$project_root/.sea-trash" ]] && find "$project_root/.sea-trash" -mindepth 1 -print -quit | grep -q .; then printf "test project trash is not empty\\n" >&2; exit 1; fi',
'MYSQL_PWD="$db_password" "$mysql_bin" --protocol=TCP --host="$db_host" --port="$db_port" --user="$db_user" --database="$db_name" --execute="INSERT INTO plans(name,storage_bytes,database_bytes,monthly_bandwidth_bytes,process_limit,ftp_limit,database_limit,project_limit) SELECT \'$plan_name\',67108864,database_bytes,monthly_bandwidth_bytes,process_limit,ftp_limit,database_limit,project_limit FROM plans WHERE id=$original_plan_id; SET @test_plan_id=LAST_INSERT_ID(); UPDATE tenants SET plan_id=@test_plan_id WHERE id=$tenant_id;"',
'temp_plan_id="$(MYSQL_PWD="$db_password" "$mysql_bin" --protocol=TCP --host="$db_host" --port="$db_port" --user="$db_user" --database="$db_name" --batch --skip-column-names --execute="SELECT id FROM plans WHERE name=\'$plan_name\'")"; test -n "$temp_plan_id"; printf "%s %s %s\\n" "$tenant_id" "$original_plan_id" "$temp_plan_id" | install -o root -g root -m 0600 /dev/stdin "$state_path"',
`printf '%s\\n' ${q(seedMarker)}`,
].join('\n');
const cleanupMarker = `${marker}-cleaned`;
const cleanupShell = [
'set -euo pipefail',
`email=${q(email)}`,
`tenant_email=${q(tenantEmail)}`,
`state_path=${q(planStatePath)}`,
`file_prefix=${q(`verify-${suffix}-`)}`,
`test_run_directory=${q(domainRunDirectory)}`,
'mapfile -t db_parts < <(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()))\')',
'test "${#db_parts[@]}" -eq 5; db_user="${db_parts[0]}"; db_password="${db_parts[1]}"; db_host="${db_parts[2]}"; db_port="${db_parts[3]}"; db_name="${db_parts[4]}"',
'mysql_bin="$(command -v mysql || true)"; if [[ -z "$mysql_bin" && -x /www/server/mysql/bin/mysql ]]; then mysql_bin=/www/server/mysql/bin/mysql; fi; test -x "$mysql_bin"',
'if [[ -f "$state_path" ]]; then read -r tenant_id original_plan_id temp_plan_id <"$state_path"; project_root="$(MYSQL_PWD="$db_password" "$mysql_bin" --protocol=TCP --host="$db_host" --port="$db_port" --user="$db_user" --database="$db_name" --batch --skip-column-names --execute="SELECT root_path FROM projects WHERE tenant_id=$tenant_id ORDER BY id LIMIT 1")"; case "$project_root" in /www/wwwroot/seavHost/vHost/sv??????????) find "$project_root" -xdev -maxdepth 1 -type f -name "$file_prefix*" -delete; if [[ -d "$project_root/.sea-trash" ]]; then find "$project_root/.sea-trash" -xdev -maxdepth 1 -type f -name "*$file_prefix*" -delete; fi; rmdir -- "$project_root/$test_run_directory" 2>/dev/null || true ;; *) exit 1 ;; esac; MYSQL_PWD="$db_password" "$mysql_bin" --protocol=TCP --host="$db_host" --port="$db_port" --user="$db_user" --database="$db_name" --execute="UPDATE tenants SET plan_id=$original_plan_id WHERE id=$tenant_id AND plan_id=$temp_plan_id; DELETE FROM plans WHERE id=$temp_plan_id;"; rm -f -- "$state_path"; fi',
'MYSQL_PWD="$db_password" "$mysql_bin" --protocol=TCP --host="$db_host" --port="$db_port" --user="$db_user" --database="$db_name" --execute="DELETE FROM users WHERE email IN (\'$email\',\'$tenant_email\');"',
`printf '%s\\n' ${q(cleanupMarker)}`,
].join('\n');
async function api(pathname, { method = 'GET', body, cookie, expected = [200] } = {}) {
const started = performance.now();
const response = await fetch(new URL(pathname, consoleBase), {
method, redirect: 'manual', signal: AbortSignal.timeout(15_000),
headers: {
Accept: 'application/json',
...(body === undefined ? {} : { 'Content-Type': 'application/json' }),
...(cookie ? { Cookie: cookie } : {}),
},
body: body === undefined ? undefined : JSON.stringify(body),
});
const elapsedMs = performance.now() - started;
const text = await response.text();
let payload;
try { payload = text ? JSON.parse(text) : undefined; } catch { payload = undefined; }
if (!expected.includes(response.status)) throw new Error(`${method} ${pathname} returned HTTP ${response.status}`);
return { response, payload, elapsedMs };
}
async function upload(projectID, cookie, name, bytes, overwrite, expected) {
const form = new FormData();
form.set('path', '');
form.set('overwrite', overwrite ? 'true' : 'false');
form.set('file', new Blob([bytes]), name);
const response = await fetch(new URL(`/api/v1/projects/${projectID}/files`, consoleBase), {
method: 'POST', headers: { Cookie: cookie }, body: form, redirect: 'manual', signal: AbortSignal.timeout(60_000),
});
const text = await response.text();
if (!expected.includes(response.status)) throw new Error(`file upload ${name} returned HTTP ${response.status}: ${text.slice(0, 160)}`);
return response;
}
function cookieFrom(response) {
const header = typeof response.headers.getSetCookie === 'function' ? response.headers.getSetCookie()[0] : response.headers.get('set-cookie');
const cookie = header?.split(';', 1)[0];
if (!cookie?.startsWith('sea_session=')) throw new Error('login did not return a session cookie');
return cookie;
}
async function login(password, totpCode, expected = [200]) {
return loginIdentifier(email, password, totpCode, expected);
}
async function loginIdentifier(identifier, password, totpCode, expected = [200]) {
return api('/api/v1/auth/login', { method: 'POST', expected, body: { identifier, password, ...(totpCode ? { totpCode } : {}) } });
}
function decodeBase32(value) {
const alphabet = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ234567';
let bits = '';
for (const character of value.replaceAll('=', '').toUpperCase()) {
const index = alphabet.indexOf(character);
if (index < 0) throw new Error('invalid TOTP secret');
bits += index.toString(2).padStart(5, '0');
}
const bytes = [];
for (let offset = 0; offset + 8 <= bits.length; offset += 8) bytes.push(Number.parseInt(bits.slice(offset, offset + 8), 2));
return Buffer.from(bytes);
}
function totp(secret) {
const counter = BigInt(Math.floor(Date.now() / 30_000));
const buffer = Buffer.alloc(8);
buffer.writeBigUInt64BE(counter);
const digest = crypto.createHmac('sha1', decodeBase32(secret)).update(buffer).digest();
const offset = digest[digest.length - 1] & 0x0f;
const value = (digest.readUInt32BE(offset) & 0x7fffffff) % 1_000_000;
return value.toString().padStart(6, '0');
}
let seeded = false;
let adminCookieForCleanup;
let tenantCookieForCleanup;
let projectIDForCleanup;
let siteIDForCleanup;
let originalDomainApproval;
try {
await runShell(`Sea vHost account seed ${suffix}`, seedShell, seedMarker);
seeded = true;
const knownTimings = [];
const missingTimings = [];
for (let index = 0; index < 5; index += 1) {
knownTimings.push((await login('definitely-wrong-password', undefined, [401])).elapsedMs);
missingTimings.push((await api('/api/v1/auth/login', { method: 'POST', expected: [401], body: { identifier: `missing-${suffix}@seavhost.test`, password: 'definitely-wrong-password' } })).elapsedMs);
}
const knownAverage = knownTimings.reduce((sum, value) => sum + value, 0) / knownTimings.length;
const missingAverage = missingTimings.reduce((sum, value) => sum + value, 0) / missingTimings.length;
if (knownAverage < 300 || missingAverage < 300 || Math.abs(knownAverage - missingAverage) > 150) throw new Error('login timing equalization is outside the accepted envelope');
let rateLimited;
for (let attempt = 1; attempt <= 21; attempt += 1) {
rateLimited = await api('/api/v1/auth/login', {
method: 'POST', expected: attempt === 21 ? [429] : [401],
body: { identifier: `limited-${suffix}@seavhost.test`, password: 'definitely-wrong-password' },
});
}
if (!rateLimited.response.headers.get('retry-after')) throw new Error('rate limit response omitted Retry-After');
const first = await login(initialPassword);
const second = await login(initialPassword);
const firstCookie = cookieFrom(first.response);
const secondCookie = cookieFrom(second.response);
await api('/api/v1/account/password', {
method: 'PUT', cookie: firstCookie, expected: [204],
body: { currentPassword: initialPassword, newPassword: changedPassword },
});
await api('/api/v1/me', { cookie: firstCookie });
await api('/api/v1/me', { cookie: secondCookie, expected: [401] });
await login(initialPassword, undefined, [401]);
const changedLogin = await login(changedPassword);
const changedCookie = cookieFrom(changedLogin.response);
const setup = await api('/api/v1/account/mfa/setup', {
method: 'POST', cookie: changedCookie, body: { currentPassword: changedPassword },
});
const secret = setup.payload?.secret;
if (typeof secret !== 'string' || secret.length < 16 || !setup.payload?.otpauthURI?.startsWith('otpauth://')) throw new Error('MFA setup returned invalid data');
const enabled = await api('/api/v1/account/mfa/enable', {
method: 'POST', cookie: changedCookie, body: { code: totp(secret) },
});
const recoveryCodes = enabled.payload?.recoveryCodes;
if (!Array.isArray(recoveryCodes) || recoveryCodes.length !== 10) throw new Error('MFA did not return ten recovery codes');
await login(changedPassword, undefined, [401]);
await login(changedPassword, '000000', [401]);
const mfaLogin = await login(changedPassword, totp(secret));
const mfaCookie = cookieFrom(mfaLogin.response);
await login(changedPassword, recoveryCodes[0]);
await login(changedPassword, recoveryCodes[0], [401]);
await api('/api/v1/account/mfa/disable', {
method: 'POST', cookie: mfaCookie, expected: [204],
body: { currentPassword: changedPassword, code: recoveryCodes[1] },
});
await api('/api/v1/me', { cookie: mfaCookie, expected: [401] });
const finalAdminLogin = await login(changedPassword);
const adminCookie = cookieFrom(finalAdminLogin.response);
adminCookieForCleanup = adminCookie;
const tenantLogin = await loginIdentifier(tenantEmail, tenantPassword);
const tenantCookie = cookieFrom(tenantLogin.response);
tenantCookieForCleanup = tenantCookie;
const projects = await api('/api/v1/projects', { cookie: tenantCookie });
const project = projects.payload?.projects?.[0];
if (!project?.id || !/^sv[0-9a-f]{10}$/.test(project.hostName)) throw new Error('temporary tenant could not read its managed host');
projectIDForCleanup = project.id;
const firstReset = await api(`/api/v1/projects/${project.id}/host-password/reset`, { method: 'POST', cookie: tenantCookie, body: {} });
const firstHostPassword = firstReset.payload?.password;
if (typeof firstHostPassword !== 'string' || firstHostPassword.length < 16) throw new Error('host password reset returned invalid data');
const hostLoginA = await loginIdentifier(project.hostName, firstHostPassword);
const hostLoginB = await loginIdentifier(project.hostName, firstHostPassword);
const hostCookieA = cookieFrom(hostLoginA.response);
const hostCookieB = cookieFrom(hostLoginB.response);
const hostDashboard = await api('/api/v1/dashboard', { cookie: hostCookieA });
if (hostDashboard.payload?.hostScoped !== true || hostDashboard.payload?.projects?.length !== 1 || hostDashboard.payload.projects[0].id !== project.id) {
throw new Error('host session was not scoped to exactly one project');
}
await api('/api/v1/admin/plans', { cookie: hostCookieA, expected: [403] });
await api(`/api/v1/projects/${project.id}/credentials`, { cookie: hostCookieA });
await api('/api/v1/projects/9223372036854775807/files', { cookie: hostCookieA, expected: [404] });
const secondReset = await api(`/api/v1/projects/${project.id}/host-password/reset`, { method: 'POST', cookie: tenantCookie, body: {} });
const secondHostPassword = secondReset.payload?.password;
await api('/api/v1/me', { cookie: hostCookieA, expected: [401] });
await api('/api/v1/me', { cookie: hostCookieB, expected: [401] });
await loginIdentifier(project.hostName, firstHostPassword, undefined, [401]);
await loginIdentifier(project.hostName, secondHostPassword);
const textName = `verify-${suffix}-text.txt`;
const uploadName = `verify-${suffix}-upload.bin`;
const limitName = `verify-${suffix}-20m.bin`;
const overLimitName = `verify-${suffix}-over.bin`;
const textPath = `/api/v1/projects/${project.id}/files`;
await api(textPath, { method: 'PUT', cookie: tenantCookie, expected: [204], body: { path: textName, content: 'first-value', overwrite: false } });
await api(textPath, { method: 'PUT', cookie: tenantCookie, expected: [409], body: { path: textName, content: 'duplicate', overwrite: false } });
await api(textPath, { method: 'PUT', cookie: tenantCookie, expected: [204], body: { path: textName, content: 'second-value', overwrite: true } });
const downloaded = await fetch(new URL(`${textPath}?path=${encodeURIComponent(textName)}&download=1`, consoleBase), { headers: { Cookie: tenantCookie }, signal: AbortSignal.timeout(15_000) });
if (downloaded.status !== 200 || await downloaded.text() !== 'second-value') throw new Error('downloaded text file did not match overwritten content');
await upload(project.id, tenantCookie, uploadName, Buffer.from('small-upload'), false, [201]);
await upload(project.id, tenantCookie, uploadName, Buffer.from('duplicate'), false, [409]);
await upload(project.id, tenantCookie, uploadName, Buffer.from('overwritten-upload'), true, [201]);
await upload(project.id, tenantCookie, limitName, Buffer.alloc(20 * 1024 * 1024, 0x61), false, [201]);
await upload(project.id, tenantCookie, overLimitName, Buffer.alloc(20 * 1024 * 1024 + 1, 0x62), false, [413]);
const listing = await api(textPath, { cookie: tenantCookie });
const listedNames = new Set((listing.payload?.entries ?? []).map((entry) => entry.name));
for (const required of [textName, uploadName, limitName]) if (!listedNames.has(required)) throw new Error(`file listing omitted ${required}`);
for (const name of [textName, uploadName, limitName]) {
await api(`${textPath}?path=${encodeURIComponent(name)}`, { method: 'DELETE', cookie: tenantCookie, expected: [204] });
await api(`${textPath}?path=${encodeURIComponent(name)}&download=1`, { cookie: tenantCookie, expected: [404] });
}
await api(`${textPath}?emptyTrash=1`, { method: 'DELETE', cookie: tenantCookie, expected: [204] });
const approvalSetting = await api('/api/v1/admin/settings/domain-approval', { cookie: adminCookie });
originalDomainApproval = approvalSetting.payload?.enabled === true;
await api('/api/v1/admin/settings/domain-approval', { method: 'PUT', cookie: adminCookie, expected: [204], body: { enabled: true } });
const siteCreate = await api(`/api/v1/projects/${project.id}/sites`, {
method: 'POST', cookie: tenantCookie, expected: [201],
body: { name: `domain-${suffix}`, runtime: 'PHP', version: project.version, runPath: `/${domainRunDirectory}`, customDomain: '', autoSSL: false },
});
const domainSite = siteCreate.payload?.site;
if (!domainSite?.id || domainSite.status !== 'running') throw new Error('domain verification site was not created');
siteIDForCleanup = domainSite.id;
const bindPath = `/api/v1/projects/${project.id}/sites/${domainSite.id}/domains`;
const dashboardForDomain = await api('/api/v1/dashboard', { cookie: tenantCookie });
const rootDomain = dashboardForDomain.payload?.rootDomain;
if (typeof rootDomain !== 'string' || !rootDomain.includes('.')) throw new Error('dashboard omitted root domain');
await api(bindPath, { method: 'POST', cookie: tenantCookie, expected: [422], body: { domain: rootDomain } });
await api(bindPath, { method: 'POST', cookie: tenantCookie, expected: [422], body: { domain: `blocked.${rootDomain}` } });
const pendingName = `pending-${suffix}.example.invalid`;
const pending = await api(bindPath, { method: 'POST', cookie: tenantCookie, expected: [202], body: { domain: pendingName } });
if (pending.payload?.domain?.status !== 'pending') throw new Error('domain approval did not keep the domain pending');
const pendingList = await api('/api/v1/admin/domains/pending', { cookie: adminCookie });
const pendingItem = pendingList.payload?.domains?.find((item) => item.domain === pendingName && item.siteId === domainSite.id);
if (!pendingItem?.id) throw new Error('pending domain was not visible to the administrator');
const approved = await api(`/api/v1/admin/domains/${pendingItem.id}/review`, { method: 'POST', cookie: adminCookie, body: { approved: true } });
if (approved.payload?.domain?.status !== 'approved') throw new Error('administrator approval did not approve the domain');
const rejectedName = `rejected-${suffix}.example.invalid`;
await api(bindPath, { method: 'POST', cookie: tenantCookie, expected: [202], body: { domain: rejectedName } });
const rejectList = await api('/api/v1/admin/domains/pending', { cookie: adminCookie });
const rejectItem = rejectList.payload?.domains?.find((item) => item.domain === rejectedName && item.siteId === domainSite.id);
if (!rejectItem?.id) throw new Error('second pending domain was not visible to the administrator');
const rejected = await api(`/api/v1/admin/domains/${rejectItem.id}/review`, { method: 'POST', cookie: adminCookie, body: { approved: false } });
if (rejected.payload?.domain?.status !== 'rejected') throw new Error('administrator rejection did not reject the domain');
await api('/api/v1/admin/settings/domain-approval', { method: 'PUT', cookie: adminCookie, expected: [204], body: { enabled: false } });
const directName = `direct-${suffix}.example.invalid`;
const direct = await api(bindPath, { method: 'POST', cookie: tenantCookie, expected: [202], body: { domain: directName } });
if (direct.payload?.domain?.status !== 'approved') throw new Error('approval-disabled domain was not bound immediately');
const duplicateName = `duplicate-${suffix}.example.invalid`;
const duplicateResults = await Promise.all([
api(bindPath, { method: 'POST', cookie: tenantCookie, expected: [202, 422], body: { domain: duplicateName } }),
api(bindPath, { method: 'POST', cookie: tenantCookie, expected: [202, 422], body: { domain: duplicateName } }),
]);
const duplicateStatuses = duplicateResults.map((result) => result.response.status).sort();
if (duplicateStatuses[0] !== 202 || duplicateStatuses[1] !== 422) throw new Error(`concurrent duplicate binding returned ${duplicateStatuses.join(',')}`);
await api('/api/v1/admin/settings/domain-approval', { method: 'PUT', cookie: adminCookie, expected: [204], body: { enabled: true } });
const beforeLimit = await api('/api/v1/resources', { cookie: tenantCookie });
const currentDomainCount = (beforeLimit.payload?.domains ?? []).filter((item) => item.siteId === domainSite.id).length;
const expectedAccepted = 100 - currentDomainCount;
if (expectedAccepted < 1 || expectedAccepted > 100) throw new Error(`unexpected initial domain count ${currentDomainCount}`);
const limitResults = await Promise.all(Array.from({ length: expectedAccepted + 10 }, (_, index) => api(bindPath, {
method: 'POST', cookie: tenantCookie, expected: [202, 422], body: { domain: `limit-${index}-${suffix}.example.invalid` },
})));
const acceptedAtLimit = limitResults.filter((result) => result.response.status === 202).length;
if (acceptedAtLimit !== expectedAccepted) throw new Error(`domain limit accepted ${acceptedAtLimit}, want ${expectedAccepted}`);
const afterLimit = await api('/api/v1/resources', { cookie: tenantCookie });
const finalDomainCount = (afterLimit.payload?.domains ?? []).filter((item) => item.siteId === domainSite.id).length;
if (finalDomainCount !== 100) throw new Error(`site domain count is ${finalDomainCount}, want 100`);
await api(`/api/v1/projects/${project.id}/sites/${domainSite.id}`, { method: 'DELETE', cookie: tenantCookie, expected: [204] });
siteIDForCleanup = undefined;
await api('/api/v1/admin/settings/domain-approval', { method: 'PUT', cookie: adminCookie, expected: [204], body: { enabled: originalDomainApproval } });
originalDomainApproval = undefined;
console.log(JSON.stringify({
status: 'passed',
loginTiming: { knownAverageMs: Math.round(knownAverage), missingAverageMs: Math.round(missingAverage), differenceMs: Math.round(Math.abs(knownAverage - missingAverage)) },
checks: {
rateLimitAndRetryAfter: true, concurrentSessions: true, passwordChangeKeepsCurrentSession: true,
passwordChangeRevokesOtherSessions: true, oldPasswordRejected: true, totpLogin: true,
recoveryCodeSingleUse: true, disableMFARevokesSessions: true, loginWithoutMFAAfterDisable: true,
hostScopedDashboard: true, hostCannotUseAdminAPI: true, hostProjectIDORDenied: true,
hostPasswordResetRevokesAllSessions: true, oldHostPasswordRejected: true,
textCreateConflictOverwriteDownload: true, multipartCreateConflictOverwrite: true,
uploadExactly20MiBAccepted: true, uploadOver20MiBRejected: true,
fileListingTrashAndEmptyTrash: true,
domainReservedZoneRejected: true, domainApprovalAndRejection: true,
approvalDisabledImmediateBinding: true, concurrentDuplicateBinding: true,
concurrentDomainLimitExactly100: true, additionalSiteCleanup: true,
},
}, null, 2));
} finally {
if (tenantCookieForCleanup && projectIDForCleanup && siteIDForCleanup) {
try { await api(`/api/v1/projects/${projectIDForCleanup}/sites/${siteIDForCleanup}`, { method: 'DELETE', cookie: tenantCookieForCleanup, expected: [204, 404, 422] }); } catch { /* remote cleanup below handles the retained directory */ }
}
if (adminCookieForCleanup && typeof originalDomainApproval === 'boolean') {
try { await api('/api/v1/admin/settings/domain-approval', { method: 'PUT', cookie: adminCookieForCleanup, expected: [204], body: { enabled: originalDomainApproval } }); } catch { /* best effort */ }
}
if (seeded) {
try { await runShell(`Sea vHost account cleanup ${suffix}`, cleanupShell, cleanupMarker); } catch (error) {
console.error(`temporary account cleanup failed: ${error instanceof Error ? error.message : 'unknown error'}`);
process.exitCode = 1;
}
}
}
+39
View File
@@ -0,0 +1,39 @@
#!/usr/bin/env bash
set -euo pipefail
/www/server/panel/pyenv/bin/python3 - <<'PY'
import json
import os
import stat
import tempfile
from pathlib import Path
path = Path('/www/server/panel/config/api.json')
if not path.is_file() or path.is_symlink():
raise SystemExit('aaPanel API configuration is missing or unsafe')
metadata = path.stat()
payload = json.loads(path.read_text(encoding='utf-8'))
addresses = payload.get('limit_addr')
if not isinstance(payload, dict) or not isinstance(addresses, list):
raise SystemExit('aaPanel API allowlist has an unexpected format')
if '127.0.0.1' in addresses:
print('aaPanel API loopback allowlist: already present')
raise SystemExit(0)
addresses.append('127.0.0.1')
handle, temporary_name = tempfile.mkstemp(prefix='.sea-vhost-api-', dir=str(path.parent), text=True)
try:
with os.fdopen(handle, 'w', encoding='utf-8') as output:
json.dump(payload, output, ensure_ascii=False, separators=(',', ':'))
output.write('\n')
output.flush()
os.fsync(output.fileno())
os.chmod(temporary_name, stat.S_IMODE(metadata.st_mode))
os.chown(temporary_name, metadata.st_uid, metadata.st_gid)
os.replace(temporary_name, path)
finally:
try:
os.unlink(temporary_name)
except FileNotFoundError:
pass
print('aaPanel API loopback allowlist: added 127.0.0.1')
PY
+25
View File
@@ -0,0 +1,25 @@
#!/usr/bin/env bash
set +e
/www/server/panel/pyenv/bin/python3 - <<'PY'
import json
from pathlib import Path
for candidate in (Path('/www/server/panel/config/api.json'), Path('/www/server/panel/data/api.json')):
if not candidate.is_file() or candidate.is_symlink():
continue
try:
payload = json.loads(candidate.read_text(encoding='utf-8'))
except Exception as exc:
print(f'{candidate}: invalid JSON ({type(exc).__name__})')
continue
print(candidate)
if isinstance(payload, dict):
for key, value in payload.items():
if isinstance(value, list):
print(f' {key}: list[{len(value)}]')
else:
print(f' {key}: {type(value).__name__}')
else:
print(f' root: {type(payload).__name__}')
PY
+133
View File
@@ -0,0 +1,133 @@
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; }
}
}
+188
View File
@@ -0,0 +1,188 @@
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 consoleURL = process.env.SEA_CONSOLE_URL?.trim();
const insecureTLS = process.env.SEA_PANEL_TLS_INSECURE === 'true';
if (!panelURL || !panelAPIKey || !consoleURL) {
console.error('SEA_PANEL_URL, SEA_PANEL_API_KEY and SEA_CONSOLE_URL are required.');
process.exit(2);
}
const panelBase = new URL(panelURL);
const consoleBase = new URL(consoleURL);
if (!['http:', 'https:'].includes(panelBase.protocol) || panelBase.username || panelBase.password ||
!['http:', 'https:'].includes(consoleBase.protocol) || consoleBase.username || consoleBase.password) {
console.error('Panel and console URLs must be HTTP(S) URLs without embedded credentials.');
process.exit(2);
}
const client = panelBase.protocol === 'https:' ? https : http;
const agent = panelBase.protocol === 'https:' ? new https.Agent({ rejectUnauthorized: !insecureTLS }) : undefined;
const md5 = (value) => crypto.createHash('md5').update(value).digest('hex');
const canaryID = crypto.randomBytes(6).toString('hex');
const marker = (scope) => `SEA_VHOST_CANARY_V1:${scope}:${canaryID}:${crypto.randomBytes(16).toString('hex')}`;
const markers = {
control: marker('control'), broker: marker('broker'), agent: marker('agent'), runtime: marker('runtime'),
hidden: marker('hidden-web'), env: marker('extension-web'), manifest: marker('manifest-web'), public: marker('public-baseline'),
};
function authFields() {
const requestTime = Math.floor(Date.now() / 1000).toString();
return { request_time: requestTime, request_token: md5(requestTime + md5(panelAPIKey)) };
}
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, panelBase), {
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;
if (data.length > 2 * 1024 * 1024) request.destroy(new Error('panel response exceeded 2 MB'));
});
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 q = (value) => `'${value.replaceAll("'", "'\\''")}'`;
const shell = [
'set -euo pipefail',
'umask 077',
`canary_id=${q(canaryID)}`,
`control_marker=${q(markers.control)}`,
`broker_marker=${q(markers.broker)}`,
`agent_marker=${q(markers.agent)}`,
`runtime_marker=${q(markers.runtime)}`,
`hidden_marker=${q(markers.hidden)}`,
`env_marker=${q(markers.env)}`,
`manifest_marker=${q(markers.manifest)}`,
`public_marker=${q(markers.public)}`,
"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##*/}"',
'case "$host_name" in sv??????????) ;; *) exit 1 ;; esac',
'site_conf="$(find /www/server/panel/vhost/nginx -maxdepth 1 -type f -name "$host_name*.conf" -print -quit)"',
'test -n "$site_conf"',
'site_domain="$(basename "$site_conf" .conf)"',
'site_root="$(awk \'$1 == "root" { value=$2; sub(/;$/, "", value); print value; exit }\' "$site_conf")"',
'test -n "$site_root"; site_root="$(realpath -e "$site_root")"',
'case "$site_root/" in "$host_dir/"*) ;; *) printf \'site root escaped managed host\\n\'; exit 1 ;; esac',
'control_dir=/var/lib/sea-vhost/security-canaries',
'broker_dir=/var/lib/sea-vhost-panel/security-canaries',
'agent_dir=/var/lib/sea-vhost-agent/security-canaries',
'runtime_dir="$host_dir/.sea-runtime/security-canaries"',
'web_dir="$site_root/.sea-vhost-canaries"',
'install -d -o root -g sea-vhost-control -m 0750 "$control_dir"',
'install -d -o sea-vhost-panel -g sea-vhost-panel-control -m 0700 "$broker_dir"',
'install -d -o root -g root -m 0700 "$agent_dir"',
'install -d -o "$host_name" -g "$host_name" -m 0700 "$runtime_dir"',
'install -d -o "$host_name" -g "$host_name" -m 0750 "$web_dir"',
'control_path="$control_dir/control-$canary_id.txt"',
'broker_path="$broker_dir/broker-$canary_id.txt"',
'agent_path="$agent_dir/agent-$canary_id.txt"',
'runtime_path="$runtime_dir/runtime-$canary_id.txt"',
'hidden_path="$web_dir/hidden-$canary_id.txt"',
'env_path="$site_root/sea-vhost-canary-$canary_id.env"',
'manifest_path="$site_root/requirements-sea-vhost-$canary_id.txt"',
'public_path="$site_root/sea-vhost-canary-public-$canary_id.txt"',
'link_path="$site_root/sea-vhost-canary-link-$canary_id"',
'registry_path="$control_dir/registry-$canary_id.tsv"',
'printf \'%s\\n\' "$control_marker" | install -o root -g sea-vhost-control -m 0640 /dev/stdin "$control_path"',
'printf \'%s\\n\' "$broker_marker" | install -o sea-vhost-panel -g sea-vhost-panel-control -m 0600 /dev/stdin "$broker_path"',
'printf \'%s\\n\' "$agent_marker" | install -o root -g root -m 0600 /dev/stdin "$agent_path"',
'printf \'%s\\n\' "$runtime_marker" | install -o "$host_name" -g "$host_name" -m 0600 /dev/stdin "$runtime_path"',
'printf \'%s\\n\' "$hidden_marker" | install -o "$host_name" -g "$host_name" -m 0640 /dev/stdin "$hidden_path"',
'printf \'%s\\n\' "$env_marker" | install -o "$host_name" -g "$host_name" -m 0640 /dev/stdin "$env_path"',
'printf \'%s\\n\' "$manifest_marker" | install -o "$host_name" -g "$host_name" -m 0640 /dev/stdin "$manifest_path"',
'printf \'%s\\n\' "$public_marker" | install -o "$host_name" -g "$host_name" -m 0640 /dev/stdin "$public_path"',
'ln -s "$runtime_path" "$link_path"',
'setfacl -m u:www:r-x "$web_dir"; setfacl -m u:www:r-- "$hidden_path" "$env_path" "$manifest_path" "$public_path"',
'printf \'scope\\tpath\\tmarker\\ncontrol\\t%s\\t%s\\nbroker\\t%s\\t%s\\nagent\\t%s\\t%s\\nruntime\\t%s\\t%s\\nhidden_web\\t%s\\t%s\\nextension_web\\t%s\\t%s\\nmanifest_web\\t%s\\t%s\\npublic_baseline\\t%s\\t%s\\nsymlink_probe\\t%s\\t%s\\n\' "$control_path" "$control_marker" "$broker_path" "$broker_marker" "$agent_path" "$agent_marker" "$runtime_path" "$runtime_marker" "$hidden_path" "$hidden_marker" "$env_path" "$env_marker" "$manifest_path" "$manifest_marker" "$public_path" "$public_marker" "$link_path" "$runtime_marker" | install -o root -g root -m 0600 /dev/stdin "$registry_path"',
'expect_readable() { runuser -u "$1" -- grep -Fqx -- "$2" "$3" 2>/dev/null; }',
'expect_denied() { if runuser -u "$1" -- grep -Fqx -- "$2" "$3" 2>/dev/null; then printf \'unexpected read: %s -> %s\\n\' "$1" "$3"; exit 1; fi; }',
'expect_readable sea-vhost "$control_marker" "$control_path"',
'expect_readable "$host_name" "$runtime_marker" "$runtime_path"',
'expect_readable www "$public_marker" "$public_path"',
'expect_readable www "$hidden_marker" "$hidden_path"',
'for account in www nobody "$host_name"; do expect_denied "$account" "$control_marker" "$control_path"; expect_denied "$account" "$broker_marker" "$broker_path"; expect_denied "$account" "$agent_marker" "$agent_path"; done',
'expect_denied sea-vhost "$broker_marker" "$broker_path"; expect_denied sea-vhost "$agent_marker" "$agent_path"',
'expect_denied www "$runtime_marker" "$runtime_path"; expect_denied nobody "$runtime_marker" "$runtime_path"',
'response_body="$(mktemp)"; trap \'rm -f "$response_body"\' EXIT',
'public_status="$(curl --silent --show-error --path-as-is --max-time 8 --output "$response_body" --write-out \'%{http_code}\' --header "Host: $site_domain" "http://127.0.0.1/sea-vhost-canary-public-$canary_id.txt")"',
'test "$public_status" = 200; grep -Fqx -- "$public_marker" "$response_body"',
'probe_web_denied() { local path="$1" marker="$2" status; status="$(curl --silent --show-error --path-as-is --max-time 8 --output "$response_body" --write-out \'%{http_code}\' --header "Host: $site_domain" "http://127.0.0.1$path")"; case "$status" in 403|404) ;; *) printf \'unexpected HTTP status %s for %s\\n\' "$status" "$path"; exit 1 ;; esac; if grep -Fq -- "$marker" "$response_body"; then printf \'canary leaked over HTTP: %s\\n\' "$path"; exit 1; fi; }',
'probe_web_denied "/.sea-vhost-canaries/hidden-$canary_id.txt" "$hidden_marker"',
'probe_web_denied "/sea-vhost-canary-$canary_id.env" "$env_marker"',
'probe_web_denied "/requirements-sea-vhost-$canary_id.txt" "$manifest_marker"',
'probe_web_denied "/.sea-runtime/security-canaries/runtime-$canary_id.txt" "$runtime_marker"',
'probe_web_denied "/sea-vhost-canary-link-$canary_id" "$runtime_marker"',
'agent_status="$(curl --silent --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 --output /dev/null --write-out \'%{http_code}\' --unix-socket /run/sea-vhost-panel/broker.sock --request POST --data \'{}\' http://localhost/v1/operations)"',
'test "$agent_status" = 401; test "$broker_status" = 401',
'printf \'canary_id=%s host=%s site=%s public_baseline=%s hidden_http=denied extension_http=denied manifest_http=denied runtime_http=denied symlink_http=denied os_boundaries=denied internal_sockets=401 registry=%s\\n\' "$canary_id" "$host_name" "$site_domain" "$public_status" "$registry_path"',
"printf '%s\\n' 'Sea vHost canary verification: success'",
].join('\n');
const taskName = `Sea vHost canary verify ${canaryID}`;
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 Sea vHost security canary verification', save: '0', backupTo: 'localhost',
}), 'temporary canary 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 < 90; 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 canary verification: success') || log.includes('★[')) break;
}
if (!log.includes('Sea vHost canary verification: success')) throw new Error(`canary verification did not complete:\n${log.trim()}`);
if (Object.values(markers).some((value) => log.includes(value))) throw new Error('canary marker was written to the task log');
const unauthenticated = await fetch(new URL(`/api/v1/projects/1/files?path=.sea-runtime/security-canaries/runtime-${canaryID}.txt`, consoleBase), {
redirect: 'manual', signal: AbortSignal.timeout(10_000),
});
if (unauthenticated.status !== 401 || (await unauthenticated.text()).includes(canaryID)) throw new Error('unauthenticated file API boundary failed');
const crossOrigin = await fetch(new URL('/api/v1/projects/1/domains', consoleBase), {
method: 'POST', redirect: 'manual', signal: AbortSignal.timeout(10_000),
headers: { Origin: 'https://attacker.invalid', 'Content-Type': 'application/json' },
body: JSON.stringify({ domain: 'canary.invalid' }),
});
if (crossOrigin.status !== 403 || (await crossOrigin.text()).includes(canaryID)) throw new Error('cross-origin API boundary failed');
const consoleStatic = await fetch(new URL(`/.sea-vhost-canaries/${canaryID}.txt`, consoleBase), {
redirect: 'manual', signal: AbortSignal.timeout(10_000),
});
if ((await consoleStatic.text()).includes(canaryID)) throw new Error('host canary appeared on the management console');
const summary = log.split(/\r?\n/).find((line) => line.startsWith('canary_id='));
console.log(summary ?? `canary_id=${canaryID}`);
console.log('external_api_unauthenticated=401 external_api_cross_origin=403 console_canary_leak=no');
console.log('Sea VHost canary verification: success');
} finally {
if (taskID) {
try { await formRequest('/crontab', { action: 'DelCrontab', id: String(taskID) }); } catch { /* best effort */ }
}
}
+230
View File
@@ -0,0 +1,230 @@
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 consoleURL = process.env.SEA_CONSOLE_URL?.trim();
const insecureTLS = process.env.SEA_PANEL_TLS_INSECURE === 'true';
if (!panelURL || !panelAPIKey || !consoleURL) process.exit(2);
const panelBase = new URL(panelURL);
const consoleBase = new URL(consoleURL);
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 email = `certificate-${suffix}@seavhost.test`;
const password = `Sv-${crypto.randomBytes(18).toString('base64url')}9c`;
const dnsSecret = `svh-cloudflare-token-${crypto.randomBytes(18).toString('base64url')}`;
const dnsSecretUpdated = `svh-cloudflare-updated-${crypto.randomBytes(18).toString('base64url')}`;
const zoneID = crypto.randomBytes(16).toString('hex');
const runDirectory = `certificate-${suffix}`;
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: 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);
});
}
async function runShell(name, shell, marker, attempts = 120) {
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 certificate 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 {
const execution = await panelForm('/crontab', { action: 'StartTask', id: String(taskID) });
if (execution?.status === false || execution?.status === 'false') throw new Error('panel did not start temporary task');
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) || log.includes('★[')) break;
}
if (!log.includes(marker)) throw new Error(`temporary task failed:\n${log.trim()}`);
return log;
} finally {
try { await panelForm('/crontab', { action: 'DelCrontab', id: String(taskID) }); } catch { /* best effort */ }
}
}
async function api(pathname, { method = 'GET', body, cookie, expected = [200], timeout = 30_000 } = {}) {
const response = await fetch(new URL(pathname, consoleBase), {
method, redirect: 'manual', signal: AbortSignal.timeout(timeout),
headers: { Accept: 'application/json', ...(body === undefined ? {} : { 'Content-Type': 'application/json' }), ...(cookie ? { Cookie: cookie } : {}) },
body: body === undefined ? undefined : JSON.stringify(body),
});
const text = await response.text();
let payload;
try { payload = text ? JSON.parse(text) : undefined; } catch { payload = undefined; }
if (!expected.includes(response.status)) throw new Error(`${method} ${pathname} returned HTTP ${response.status}: ${text.slice(0, 160)}`);
return { response, payload, text };
}
function cookieFrom(response) {
const header = typeof response.headers.getSetCookie === 'function' ? response.headers.getSetCookie()[0] : response.headers.get('set-cookie');
return header?.split(';', 1)[0];
}
const dbParts = [
'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)"; if [[ -z "$mysql_bin" && -x /www/server/mysql/bin/mysql ]]; then mysql_bin=/www/server/mysql/bin/mysql; fi',
].join('\n');
const seedMarker = `certificate-seeded-${suffix}`;
const seedShell = [
'set -euo pipefail', `email=${q(email)}`, `password=${q(password)}`,
'php_bin="$(find /www/server/php -mindepth 3 -maxdepth 4 -type f -path \'*/bin/php\' -print -quit)"; password_hash="$(TEST_PASSWORD="$password" "$php_bin" -r \'echo password_hash(getenv("TEST_PASSWORD"), PASSWORD_BCRYPT);\')"',
dbParts,
'MYSQL_PWD="$control_password" "$mysql_bin" --protocol=TCP --host="$control_host" --port="$control_port" --user="$control_user" --database="$control_name" --execute="DELETE FROM users WHERE email=\'$email\'; INSERT INTO users(tenant_id,email,login_name,display_name,password_hash,role,status) SELECT tenant_id,\'$email\',\'$email\',\'Certificate verification\',\'$password_hash\',\'tenant\',\'active\' FROM projects ORDER BY id LIMIT 1;"',
`printf '%s\n' ${q(seedMarker)}`,
].join('\n');
const cleanupMarker = `certificate-cleaned-${suffix}`;
const cleanupShell = [
'set -euo pipefail', `email=${q(email)}`, `run_directory=${q(runDirectory)}`, dbParts,
'project_root="$(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 root_path FROM projects ORDER BY id LIMIT 1")"; case "$project_root" in /www/wwwroot/seavHost/vHost/sv??????????) rmdir -- "$project_root/$run_directory" 2>/dev/null || true ;; *) exit 1 ;; esac',
'MYSQL_PWD="$control_password" "$mysql_bin" --protocol=TCP --host="$control_host" --port="$control_port" --user="$control_user" --database="$control_name" --execute="DELETE FROM users WHERE email=\'$email\';"',
`printf '%s\n' ${q(cleanupMarker)}`,
].join('\n');
function decodeLogValue(log, name) {
const value = log.match(new RegExp(`(?:^|\\n)${name}=([A-Za-z0-9+/=]+)`))?.[1];
if (!value) throw new Error(`certificate generator omitted ${name}`);
return Buffer.from(value, 'base64').toString('utf8');
}
let seeded = false;
let cookie;
let project;
let site;
let dnsCredentialID;
try {
await runShell(`Sea vHost certificate seed ${suffix}`, seedShell, seedMarker);
seeded = true;
const login = await api('/api/v1/auth/login', { method: 'POST', body: { identifier: email, password } });
cookie = cookieFrom(login.response);
project = (await api('/api/v1/projects', { cookie })).payload?.projects?.[0];
if (!project?.id) throw new Error('temporary tenant has no project');
const created = await api(`/api/v1/projects/${project.id}/sites`, {
method: 'POST', cookie, expected: [201],
body: { name: `certificate-${suffix}`, runtime: 'PHP', version: project.version, runPath: `/${runDirectory}`, customDomain: '', autoSSL: false },
});
site = created.payload?.site;
if (!site?.id || !site?.domain) throw new Error('temporary certificate site was not created');
const generatedMarker = `certificate-generated-${suffix}`;
const generationShell = [
'set -euo pipefail', `domain=${q(site.domain)}`, 'work="$(mktemp -d /tmp/sea-vhost-certificate.XXXXXX)"; trap \'rm -rf -- "$work"\' EXIT',
'openssl ecparam -name prime256v1 -genkey -noout -out "$work/key.pem"; openssl req -x509 -new -key "$work/key.pem" -days 2 -subj "/CN=$domain" -addext "subjectAltName=DNS:$domain" -addext "basicConstraints=critical,CA:FALSE" -addext "keyUsage=critical,digitalSignature" -addext "extendedKeyUsage=serverAuth" -out "$work/cert.pem" >/dev/null 2>&1',
'openssl ecparam -name prime256v1 -genkey -noout -out "$work/wrong-domain-key.pem"; openssl req -x509 -new -key "$work/wrong-domain-key.pem" -days 2 -subj "/CN=wrong.example.invalid" -addext "subjectAltName=DNS:wrong.example.invalid" -addext "basicConstraints=critical,CA:FALSE" -addext "keyUsage=critical,digitalSignature" -addext "extendedKeyUsage=serverAuth" -out "$work/wrong-domain-cert.pem" >/dev/null 2>&1',
'openssl ecparam -name prime256v1 -genkey -noout -out "$work/wrong-key.pem"',
'printf "CERT_B64=%s\\n" "$(base64 -w0 "$work/cert.pem")"; printf "KEY_B64=%s\\n" "$(base64 -w0 "$work/key.pem")"; printf "WRONG_CERT_B64=%s\\n" "$(base64 -w0 "$work/wrong-domain-cert.pem")"; printf "WRONG_DOMAIN_KEY_B64=%s\\n" "$(base64 -w0 "$work/wrong-domain-key.pem")"; printf "WRONG_KEY_B64=%s\\n" "$(base64 -w0 "$work/wrong-key.pem")"',
`printf '%s\n' ${q(generatedMarker)}`,
].join('\n');
const generated = await runShell(`Sea vHost certificate generate ${suffix}`, generationShell, generatedMarker);
const certificate = decodeLogValue(generated, 'CERT_B64');
const privateKey = decodeLogValue(generated, 'KEY_B64');
const wrongCertificate = decodeLogValue(generated, 'WRONG_CERT_B64');
const wrongDomainKey = decodeLogValue(generated, 'WRONG_DOMAIN_KEY_B64');
const wrongKey = decodeLogValue(generated, 'WRONG_KEY_B64');
const manualPath = `/api/v1/projects/${project.id}/sites/${site.id}/certificate/manual`;
await api(manualPath, { method: 'PUT', cookie, expected: [422], body: { certificate: 'not-a-certificate', privateKey } });
await api(manualPath, { method: 'PUT', cookie, expected: [422], body: { certificate: wrongCertificate, privateKey: wrongDomainKey } });
await api(manualPath, { method: 'PUT', cookie, expected: [422], body: { certificate, privateKey: wrongKey } });
await api(manualPath, { method: 'PUT', cookie, expected: [422], body: { certificate, privateKey: '' } });
const installed = await api(manualPath, { method: 'PUT', cookie, body: { certificate, privateKey } });
if (installed.payload?.site?.sslStatus !== 'active') throw new Error('valid manual certificate did not become active');
await api(`/api/v1/projects/${project.id}/sites/${site.id}/certificate`, { method: 'DELETE', cookie });
const autoResult = await api(`/api/v1/projects/${project.id}/sites/${site.id}/certificate/auto`, {
method: 'POST', cookie, expected: [200, 422], timeout: 180_000,
});
const automation = await api(`/api/v1/projects/${project.id}/sites/${site.id}/certificate`, { cookie });
const autoSucceeded = autoResult.response.status === 200;
const http01FailureStatePersisted = autoSucceeded || (automation.payload?.automation?.mode === 'http-01' && Boolean(automation.payload?.automation?.lastError));
if (autoSucceeded) await api(`/api/v1/projects/${project.id}/sites/${site.id}/certificate`, { method: 'DELETE', cookie });
const createdCredential = await api('/api/v1/dns-credentials', {
method: 'POST', cookie, expected: [201], body: {
label: `Cloudflare test ${suffix}`, provider: 'cloudflare', zoneName: 'example.invalid', credential: { apiToken: dnsSecret, zoneId: zoneID },
},
});
dnsCredentialID = createdCredential.payload?.credential?.id;
if (!dnsCredentialID) throw new Error('DNS credential was not created');
const listed = await api('/api/v1/dns-credentials', { cookie });
if (listed.text.includes(dnsSecret) || listed.text.includes(zoneID) || !listed.payload?.credentials?.some((item) => item.id === dnsCredentialID)) {
throw new Error('DNS credential list leaked or omitted credential data');
}
const encryptedMarker = `dns-encrypted-${suffix}`;
const encryptedShell = [
'set -euo pipefail', `credential_id=${dnsCredentialID}`, `secret=${q(dnsSecret)}`, dbParts,
'found="$(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 IF(LOCATE(HEX(\'$secret\'),HEX(credential_ciphertext))=0,0,1) FROM dns_credentials WHERE id=$credential_id")"; test "$found" = 0',
`printf '%s\n' ${q(encryptedMarker)}`,
].join('\n');
await runShell(`Sea vHost DNS encryption ${suffix}`, encryptedShell, encryptedMarker);
const failedTest = await api(`/api/v1/dns-credentials/${dnsCredentialID}/test`, { method: 'POST', cookie, expected: [422], timeout: 60_000 });
if (failedTest.text.includes(dnsSecret) || failedTest.text.includes(zoneID)) throw new Error('DNS test failure leaked credentials');
const cooldown = await api(`/api/v1/dns-credentials/${dnsCredentialID}/test`, { method: 'POST', cookie, expected: [429] });
if (!cooldown.response.headers.get('retry-after')) throw new Error('DNS test cooldown omitted Retry-After');
const updated = await api(`/api/v1/dns-credentials/${dnsCredentialID}`, {
method: 'PUT', cookie, body: {
label: `Cloudflare updated ${suffix}`, provider: 'cloudflare', zoneName: 'example.invalid', credential: { apiToken: dnsSecretUpdated, zoneId: zoneID },
},
});
if (updated.payload?.credential?.testStatus !== 'untested' || updated.text.includes(dnsSecretUpdated)) throw new Error('DNS credential update was not safely reset');
await api(`/api/v1/dns-credentials/${dnsCredentialID}`, { method: 'DELETE', cookie, expected: [204] });
dnsCredentialID = undefined;
console.log(JSON.stringify({ status: http01FailureStatePersisted ? 'passed' : 'failed', checks: {
malformedCertificateRejected: true,
hostnameMismatchRejected: true,
mismatchedPrivateKeyRejected: true,
incompletePairRejected: true,
validManualCertificateInstalled: true,
manualCertificateDisabled: true,
http01AttemptCompleted: true,
http01FailureStatePersisted,
http01Issued: autoSucceeded,
dnsCredentialEncryptedAtRest: true,
dnsCredentialSecretsOmittedFromAPI: true,
dnsCredentialFailureDoesNotLeakSecret: true,
dnsCredentialCooldownEnforced: true,
dnsCredentialUpdateAndDelete: true,
}, http01Result: autoSucceeded ? 'issued' : 'failed_in_current_port_forwarding_environment' }, null, 2));
if (!http01FailureStatePersisted) process.exitCode = 1;
} finally {
if (dnsCredentialID && cookie) {
try { await api(`/api/v1/dns-credentials/${dnsCredentialID}`, { method: 'DELETE', cookie, expected: [204, 404] }); } catch { process.exitCode = 1; }
}
if (site?.id && project?.id && cookie) {
try { await api(`/api/v1/projects/${project.id}/sites/${site.id}`, { method: 'DELETE', cookie, expected: [204] }); } catch { process.exitCode = 1; }
}
if (seeded) {
try { await runShell(`Sea vHost certificate cleanup ${suffix}`, cleanupShell, cleanupMarker, 90); } catch { process.exitCode = 1; }
}
}
+44
View File
@@ -0,0 +1,44 @@
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 prefix = process.env.SEA_PANEL_TASK_PREFIX?.trim();
const insecureTLS = process.env.SEA_PANEL_TLS_INSECURE === 'true';
if (!panelURL || !panelAPIKey || !prefix || prefix.length < 12 || prefix.length > 80 || /[\r\n]/.test(prefix)) process.exit(2);
const base = new URL(panelURL);
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 panelForm(pathname, values) {
const requestTime = Math.floor(Date.now() / 1000).toString();
const body = Buffer.from(new URLSearchParams({ ...values, request_time: requestTime, request_token: md5(requestTime + md5(panelAPIKey)) }).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(`aaPanel returned HTTP ${response.statusCode}`));
try { resolve(JSON.parse(data)); } catch { reject(new Error('aaPanel returned non-JSON data')); }
});
});
request.on('timeout', () => request.destroy(new Error('aaPanel request timed out')));
request.on('error', reject);
request.end(body);
});
}
function rows(payload) {
if (Array.isArray(payload)) return payload;
if (Array.isArray(payload?.data)) return payload.data;
if (Array.isArray(payload?.data?.data)) return payload.data.data;
return [];
}
const listing = await panelForm('/crontab', { action: 'GetCrontab' });
const matches = rows(listing).filter((item) => String(item.name ?? item.sName ?? '').startsWith(prefix));
for (const item of matches) {
const id = Number(item.id);
if (Number.isSafeInteger(id) && id > 0) await panelForm('/crontab', { action: 'DelCrontab', id: String(id) });
}
console.log(JSON.stringify({ removed: matches.length, prefix }));
+117
View File
@@ -0,0 +1,117 @@
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 managementDomain = process.env.SEA_MANAGEMENT_DOMAIN?.trim().toLowerCase();
const insecureTLS = process.env.SEA_PANEL_TLS_INSECURE === 'true';
if (!panelURL || !panelAPIKey || !managementDomain) {
console.error('SEA_PANEL_URL, SEA_PANEL_API_KEY and SEA_MANAGEMENT_DOMAIN are required.');
process.exit(2);
}
if (!/^(?=.{1,253}$)(?:[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?$/.test(managementDomain)) {
console.error('SEA_MANAGEMENT_DOMAIN must be a valid domain name.');
process.exit(2);
}
const base = new URL(panelURL);
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 panelForm(pathname, values, timeoutMs = 30_000) {
const requestTime = Math.floor(Date.now() / 1000).toString();
const body = Buffer.from(new URLSearchParams({
...values, request_time: requestTime, request_token: md5(requestTime + md5(panelAPIKey)),
}).toString());
return new Promise((resolve, reject) => {
const request = client.request(new URL(pathname, base), {
method: 'POST', agent, timeout: timeoutMs,
headers: { 'content-type': 'application/x-www-form-urlencoded', 'content-length': body.length },
}, (response) => {
let data = '';
response.setEncoding('utf8');
response.on('data', (chunk) => {
data += chunk;
if (data.length > 4 * 1024 * 1024) request.destroy(new Error('panel response exceeded 4 MB'));
});
response.on('end', () => {
if (response.statusCode < 200 || response.statusCode > 299) {
reject(new Error(`aaPanel returned HTTP ${response.statusCode}`));
return;
}
try { resolve(JSON.parse(data)); } catch { reject(new Error('aaPanel returned non-JSON data')); }
});
});
request.on('timeout', () => request.destroy(new Error('aaPanel request timed out')));
request.on('error', reject);
request.end(body);
});
}
function rows(payload) {
if (Array.isArray(payload?.data)) return payload.data;
if (Array.isArray(payload?.data?.data)) return payload.data.data;
return [];
}
function message(payload) {
return String(payload?.msg ?? payload?.message ?? 'aaPanel rejected the operation').slice(0, 300);
}
const listing = await panelForm('/data', { action: 'getData', table: 'sites', p: '1', limit: '100', search: managementDomain });
const existing = rows(listing).find((site) => String(site.name ?? '').toLowerCase() === managementDomain);
let siteID = Number(existing?.id ?? 0);
let created = false;
if (!Number.isSafeInteger(siteID) || siteID <= 0) {
const webname = JSON.stringify({ domain: managementDomain, domainlist: [], count: 0 });
const createdSite = await panelForm('/site', {
action: 'AddSite', webname, path: '/opt/sea-vhost/web', type: '', version: '00', port: '80',
ps: 'Sea vHost management console', ftp: 'false', sql: 'false',
});
if (createdSite?.status === false || createdSite?.status === 'false' || createdSite?.siteStatus === false) {
throw new Error(`management site creation failed: ${message(createdSite)}`);
}
siteID = Number(createdSite.siteId ?? createdSite.siteID ?? createdSite.id);
if (!Number.isSafeInteger(siteID) || siteID <= 0) throw new Error('aaPanel did not return the management site id');
created = true;
}
const domains = JSON.stringify([managementDomain]);
const order = await panelForm('/acme', {
action: 'apply_cert_api', id: String(siteID), domains, auth_type: 'http', auth_to: '/opt/sea-vhost/web', ca: 'letsencrypt',
}, 60_000);
if (order?.status === false || order?.status === 'false') throw new Error(`certificate order failed: ${message(order)}`);
const orderIndex = String(order?.index ?? '').trim();
if (!orderIndex) {
if (order?.status === true && typeof order?.cert === 'string' && typeof order?.private_key === 'string') {
const certificateChain = typeof order?.root === 'string' && order.root.includes('BEGIN CERTIFICATE')
? `${order.cert.trim()}\n${order.root.trim()}\n`
: order.cert;
const installed = await panelForm('/site', {
action: 'SetSSL', siteName: managementDomain, key: order.private_key, csr: certificateChain,
});
if (installed?.status === false || installed?.status === 'false') {
throw new Error(`certificate deployment failed: ${message(installed)}`);
}
console.log(JSON.stringify({ result: 'success', managementDomain, siteID, siteCreated: created, certificate: 'valid' }, null, 2));
process.exit(0);
}
const shape = Object.fromEntries(Object.entries(order ?? {}).map(([key, value]) => [key, Array.isArray(value) ? 'array' : typeof value]));
throw new Error(`aaPanel did not return an ACME order index; response shape: ${JSON.stringify(shape).slice(0, 600)}`);
}
let status = String(order?.status ?? '').toLowerCase();
for (let attempt = 0; status !== 'valid'; attempt += 1) {
if (['expired', 'invalid', 'revoked', 'deactivated'].includes(status)) {
throw new Error(`certificate order ended with status ${status}`);
}
if (attempt >= 45) throw new Error('certificate order did not become valid before the timeout');
await new Promise((resolve) => setTimeout(resolve, 2000));
const detail = await panelForm('/acme', { action: 'get_order_find', index: orderIndex });
if (detail?.status === false || detail?.status === 'false') throw new Error(`certificate status check failed: ${message(detail)}`);
status = String(detail?.status ?? '').toLowerCase();
}
const deployed = await panelForm('/acme', { action: 'SetCertToSite', index: orderIndex, siteName: managementDomain });
if (deployed?.status === false || deployed?.status === 'false') {
throw new Error(`certificate deployment failed: ${message(deployed)}`);
}
console.log(JSON.stringify({ result: 'success', managementDomain, siteID, siteCreated: created, certificate: 'valid' }, null, 2));
+323
View File
@@ -0,0 +1,323 @@
import crypto from 'node:crypto';
import http from 'node:http';
import https from 'node:https';
import { spawnSync } from 'node:child_process';
const panelURL = process.env.SEA_PANEL_URL?.trim();
const panelAPIKey = process.env.SEA_PANEL_API_KEY?.trim();
const consoleURL = process.env.SEA_CONSOLE_URL?.trim();
const insecureTLS = process.env.SEA_PANEL_TLS_INSECURE === 'true';
if (!panelURL || !panelAPIKey || !consoleURL) {
console.error('SEA_PANEL_URL, SEA_PANEL_API_KEY and SEA_CONSOLE_URL are required.');
process.exit(2);
}
const panelBase = new URL(panelURL);
const consoleBase = new URL(consoleURL);
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 tenantEmail = `data-${suffix}@seavhost.test`;
const tenantPassword = `Sv-${crypto.randomBytes(18).toString('base64url')}7d`;
const planName = `Data verification ${suffix}`;
const statePath = `/var/lib/sea-vhost/data-verify-${suffix}.state`;
const symlinkName = `ftp-escape-${suffix}`;
const quotaTable = `svh_quota_${suffix}`;
const otherDatabase = `svhx${suffix.slice(0, 10)}`;
const otherPassword = `Sv-${crypto.randomBytes(18).toString('base64url')}6e`;
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: 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);
});
}
async function runShell(name, shell, marker, attempts = 120) {
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 data service verification', save: '0', backupTo: 'localhost',
});
if (!task || (task.status !== true && task.status !== 'true')) throw new Error('panel rejected temporary verification task');
const taskID = Number(task.id);
if (!Number.isSafeInteger(taskID) || taskID <= 0) throw new Error('panel returned invalid 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) || log.includes('★[')) break;
}
if (!log.includes(marker)) throw new Error(`temporary verification task failed:\n${log.trim()}`);
return log;
} finally {
try { await panelForm('/crontab', { action: 'DelCrontab', id: String(taskID) }); } catch { /* best effort */ }
}
}
async function api(pathname, { method = 'GET', body, cookie, expected = [200] } = {}) {
const response = await fetch(new URL(pathname, consoleBase), {
method, redirect: 'manual', signal: AbortSignal.timeout(30_000),
headers: { Accept: 'application/json', ...(body === undefined ? {} : { 'Content-Type': 'application/json' }), ...(cookie ? { Cookie: cookie } : {}) },
body: body === undefined ? undefined : JSON.stringify(body),
});
const text = await response.text();
let payload;
try { payload = text ? JSON.parse(text) : undefined; } catch { payload = undefined; }
if (!expected.includes(response.status)) throw new Error(`${method} ${pathname} returned HTTP ${response.status}: ${text.slice(0, 160)}`);
return { response, payload };
}
function cookieFrom(response) {
const header = typeof response.headers.getSetCookie === 'function' ? response.headers.getSetCookie()[0] : response.headers.get('set-cookie');
const cookie = header?.split(';', 1)[0];
if (!cookie?.startsWith('sea_session=')) throw new Error('login did not return a session cookie');
return cookie;
}
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 cleanupOrphanTestDatabases() {
for (const row of await panelDatabaseRows('svhx')) {
const name = typeof row?.name === 'string' ? row.name : '';
const id = Number(row?.id);
if (!/^svhx[0-9a-f]{10}$/.test(name) || !Number.isSafeInteger(id) || id <= 0) continue;
await panelForm('/database', { action: 'DeleteDatabase', id: String(id), sid: '0', name, db_user: name });
}
}
const dbPartsShell = [
'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()))\')',
'test "${#control_db[@]}" -eq 5; 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)"; if [[ -z "$mysql_bin" && -x /www/server/mysql/bin/mysql ]]; then mysql_bin=/www/server/mysql/bin/mysql; fi; test -x "$mysql_bin"',
].join('\n');
const seedMarker = `data-seeded-${suffix}`;
const seedShell = [
'set -Eeuo pipefail',
`tenant_email=${q(tenantEmail)}`,
`tenant_password=${q(tenantPassword)}`,
`plan_name=${q(planName)}`,
`state_path=${q(statePath)}`,
`symlink_name=${q(symlinkName)}`,
'php_bin="$(find /www/server/php -mindepth 3 -maxdepth 4 -type f -path \'*/bin/php\' -print -quit)"; test -x "$php_bin"',
'tenant_password_hash="$(TEST_PASSWORD="$tenant_password" "$php_bin" -r \'echo password_hash(getenv("TEST_PASSWORD"), PASSWORD_BCRYPT);\')"; test "${#tenant_password_hash}" -gt 50',
dbPartsShell,
'MYSQL_PWD="$control_password" "$mysql_bin" --protocol=TCP --host="$control_host" --port="$control_port" --user="$control_user" --database="$control_name" --execute="DELETE FROM users WHERE email=\'$tenant_email\'; INSERT INTO users(tenant_id,email,login_name,display_name,password_hash,role,status) SELECT tenant_id,\'$tenant_email\',\'$tenant_email\',\'Data verification\',\'$tenant_password_hash\',\'tenant\',\'active\' FROM projects ORDER BY id LIMIT 1;"',
'read -r tenant_id original_plan_id project_root < <(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 p.tenant_id,t.plan_id,p.root_path FROM projects p JOIN tenants t ON t.id=p.tenant_id ORDER BY p.id LIMIT 1")',
'case "$project_root" in /www/wwwroot/seavHost/vHost/sv??????????) ;; *) exit 1 ;; esac; host_name="${project_root##*/}"',
'MYSQL_PWD="$control_password" "$mysql_bin" --protocol=TCP --host="$control_host" --port="$control_port" --user="$control_user" --database="$control_name" --execute="INSERT INTO plans(name,storage_bytes,database_bytes,monthly_bandwidth_bytes,process_limit,ftp_limit,database_limit,project_limit) SELECT \'$plan_name\',67108864,8388608,monthly_bandwidth_bytes,process_limit,ftp_limit,database_limit,project_limit FROM plans WHERE id=$original_plan_id; SET @test_plan_id=LAST_INSERT_ID(); UPDATE tenants SET plan_id=@test_plan_id WHERE id=$tenant_id;"',
'temp_plan_id="$(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 id FROM plans WHERE name=\'$plan_name\'")"; test -n "$temp_plan_id"',
'ln -s /etc/passwd "$project_root/$symlink_name"; chown -h "$host_name:$host_name" "$project_root/$symlink_name"',
'printf "%s %s %s %s\\n" "$tenant_id" "$original_plan_id" "$temp_plan_id" "$project_root" | install -o root -g root -m 0600 /dev/stdin "$state_path"',
`printf '%s\\n' ${q(seedMarker)}`,
].join('\n');
const cleanupMarker = `data-cleaned-${suffix}`;
const cleanupShell = [
'set -euo pipefail',
`tenant_email=${q(tenantEmail)}`,
`state_path=${q(statePath)}`,
`symlink_name=${q(symlinkName)}`,
dbPartsShell,
'if [[ -f "$state_path" ]]; then read -r tenant_id original_plan_id temp_plan_id project_root <"$state_path"; case "$project_root" in /www/wwwroot/seavHost/vHost/sv??????????) rm -f -- "$project_root/$symlink_name" ;; *) exit 1 ;; esac; MYSQL_PWD="$control_password" "$mysql_bin" --protocol=TCP --host="$control_host" --port="$control_port" --user="$control_user" --database="$control_name" --execute="UPDATE tenants SET plan_id=$original_plan_id WHERE id=$tenant_id AND plan_id=$temp_plan_id; DELETE FROM plans WHERE id=$temp_plan_id;"; rm -f -- "$state_path"; fi',
'MYSQL_PWD="$control_password" "$mysql_bin" --protocol=TCP --host="$control_host" --port="$control_port" --user="$control_user" --database="$control_name" --execute="DELETE FROM users WHERE email=\'$tenant_email\';"',
`printf '%s\\n' ${q(cleanupMarker)}`,
].join('\n');
function ftpCurl(credentials, extraArgs, input, expectSuccess = true) {
const host = panelBase.hostname;
const args = ['--silent', '--show-error', '--fail', '--ftp-skip-pasv-ip', '--connect-timeout', '10', '--max-time', '35', '--user', `${credentials.ftpUsername}:${credentials.ftpPassword}`, ...extraArgs];
const result = spawnSync('curl.exe', args, { input, maxBuffer: 4 * 1024 * 1024 });
if (expectSuccess && result.status !== 0) throw new Error(`FTP command failed with exit ${result.status}`);
if (!expectSuccess && result.status === 0) throw new Error('FTP escape probe unexpectedly succeeded');
return result.stdout;
}
function ftpURL(name = '') {
return `ftp://${panelBase.hostname}:21/${name}`;
}
function projectDatabaseShell(credentials, body, marker) {
return [
'set -euo pipefail',
`db_user=${q(credentials.databaseUsername)}`,
`db_password=${q(credentials.databasePassword)}`,
`db_name=${q(credentials.databaseName)}`,
'mysql_bin="$(command -v mysql || true)"; if [[ -z "$mysql_bin" && -x /www/server/mysql/bin/mysql ]]; then mysql_bin=/www/server/mysql/bin/mysql; fi; test -x "$mysql_bin"',
body,
`printf '%s\\n' ${q(marker)}`,
].join('\n');
}
let seeded = false;
let otherDatabaseID;
let credentials;
let tenantCookie;
let project;
let initiallyRunning = false;
try {
await cleanupOrphanTestDatabases();
await runShell(`Sea vHost data seed ${suffix}`, seedShell, seedMarker);
seeded = true;
const login = await api('/api/v1/auth/login', { method: 'POST', body: { identifier: tenantEmail, password: tenantPassword } });
tenantCookie = cookieFrom(login.response);
const projects = await api('/api/v1/projects', { cookie: tenantCookie });
project = projects.payload?.projects?.[0];
if (!project?.id) throw new Error('temporary tenant has no project');
initiallyRunning = project.status === 'running';
const credentialResponse = await api(`/api/v1/projects/${project.id}/credentials`, { cookie: tenantCookie });
credentials = credentialResponse.payload?.credentials;
if (!credentials?.ftpUsername || !credentials?.ftpPassword || !credentials?.databaseName || !credentials?.databaseUsername || !credentials?.databasePassword) {
throw new Error('project credentials are incomplete');
}
const ftpName = `verify-${suffix}.txt`;
const renamedFTPName = `verify-${suffix}-renamed.txt`;
const ftpPayload = Buffer.from(`sea-vhost-ftp-${suffix}`);
let externalFTPPassiveTransfer = false;
try {
ftpCurl(credentials, ['--upload-file', '-', ftpURL(ftpName)], ftpPayload);
const downloaded = ftpCurl(credentials, [ftpURL(ftpName)]);
if (!downloaded.equals(ftpPayload)) throw new Error('FTP download did not match upload');
ftpCurl(credentials, ['--quote', `RNFR ${ftpName}`, '--quote', `RNTO ${renamedFTPName}`, ftpURL()]);
const renamedDownload = ftpCurl(credentials, [ftpURL(renamedFTPName)]);
if (!renamedDownload.equals(ftpPayload)) throw new Error('FTP rename did not preserve data');
ftpCurl(credentials, ['--quote', `DELE ${renamedFTPName}`, ftpURL()]);
ftpCurl(credentials, [ftpURL(symlinkName)], undefined, false);
ftpCurl(credentials, ['--path-as-is', ftpURL('../../etc/passwd')], undefined, false);
externalFTPPassiveTransfer = true;
} catch {
console.log('ftp_external_passive_data_channel=unavailable');
}
const ftpLoopbackMarker = `ftp-loopback-${suffix}`;
const ftpLoopbackShell = [
'set -euo pipefail',
`ftp_user=${q(credentials.ftpUsername)}`,
`ftp_password=${q(credentials.ftpPassword)}`,
`ftp_name=${q(ftpName)}`,
`renamed_name=${q(renamedFTPName)}`,
`symlink_name=${q(symlinkName)}`,
`payload=${q(ftpPayload.toString())}`,
'ftp_base=ftp://127.0.0.1:21',
'printf "%s" "$payload" | curl --silent --show-error --fail --ftp-skip-pasv-ip --max-time 20 --user "$ftp_user:$ftp_password" --upload-file - "$ftp_base/$ftp_name"',
'test "$(curl --silent --show-error --fail --ftp-skip-pasv-ip --max-time 20 --user "$ftp_user:$ftp_password" "$ftp_base/$ftp_name")" = "$payload"',
'curl --silent --show-error --fail --ftp-skip-pasv-ip --max-time 20 --user "$ftp_user:$ftp_password" --quote "RNFR $ftp_name" --quote "RNTO $renamed_name" "$ftp_base/" >/dev/null',
'test "$(curl --silent --show-error --fail --ftp-skip-pasv-ip --max-time 20 --user "$ftp_user:$ftp_password" "$ftp_base/$renamed_name")" = "$payload"',
'curl --silent --show-error --fail --ftp-skip-pasv-ip --max-time 20 --user "$ftp_user:$ftp_password" --quote "DELE $renamed_name" "$ftp_base/" >/dev/null',
'if curl --silent --show-error --fail --ftp-skip-pasv-ip --max-time 20 --user "$ftp_user:$ftp_password" "$ftp_base/$symlink_name" >/dev/null 2>&1; then printf "ftp_symlink_escape=allowed\\n" >&2; exit 1; fi',
'if curl --silent --show-error --fail --ftp-skip-pasv-ip --path-as-is --max-time 20 --user "$ftp_user:$ftp_password" "$ftp_base/../../etc/passwd" >/dev/null 2>&1; then printf "ftp_parent_escape=allowed\\n" >&2; exit 1; fi',
].join('\n');
await runShell(`Sea vHost FTP loopback ${suffix}`, `${ftpLoopbackShell}\nprintf '%s\\n' ${q(ftpLoopbackMarker)}`, ftpLoopbackMarker);
const other = requirePanelSuccess(await panelForm('/database', {
action: 'AddDatabase', sid: '0', name: otherDatabase, db_user: otherDatabase, password: otherPassword,
address: '127.0.0.1', codeing: 'utf8mb4', pid: '0', ps: 'Sea vHost isolation verification',
}), 'temporary cross-database creation');
otherDatabaseID = Number(other.id);
if (!Number.isSafeInteger(otherDatabaseID) || otherDatabaseID <= 0) otherDatabaseID = await resolveDatabaseID(otherDatabase);
const isolationMarker = `database-isolation-${suffix}`;
const ownTable = `svh_own_${suffix}`;
await runShell(`Sea vHost database isolation ${suffix}`, projectDatabaseShell(credentials, [
`MYSQL_PWD="$db_password" "$mysql_bin" --protocol=TCP --host=127.0.0.1 --user="$db_user" --database="$db_name" --execute="CREATE TABLE ${ownTable}(value VARCHAR(80)); INSERT INTO ${ownTable} VALUES (\'${suffix}\'); SELECT value FROM ${ownTable}; DROP TABLE ${ownTable};" >/dev/null`,
`if MYSQL_PWD="$db_password" "$mysql_bin" --protocol=TCP --host=127.0.0.1 --user="$db_user" --database=${q(otherDatabase)} --execute="SELECT 1" >/dev/null 2>&1; then printf 'cross_database_access=allowed\\n' >&2; exit 1; fi`,
].join('\n'), isolationMarker), isolationMarker);
const fillMarker = `database-filled-${suffix}`;
await runShell(`Sea vHost database quota fill ${suffix}`, projectDatabaseShell(credentials, [
`MYSQL_PWD="$db_password" "$mysql_bin" --protocol=TCP --host=127.0.0.1 --user="$db_user" --database="$db_name" --execute="DROP TABLE IF EXISTS ${quotaTable}; CREATE TABLE ${quotaTable}(payload LONGBLOB NOT NULL) ENGINE=InnoDB;"`,
`for index in $(seq 1 12); do MYSQL_PWD="$db_password" "$mysql_bin" --protocol=TCP --host=127.0.0.1 --user="$db_user" --database="$db_name" --execute="INSERT INTO ${quotaTable}(payload) VALUES (REPEAT(\'x\',1048576));"; done`,
].join('\n'), fillMarker), fillMarker);
console.log('database_quota_payload=created');
let suspendedProject;
for (let attempt = 0; attempt < 12; attempt += 1) {
await new Promise((resolve) => setTimeout(resolve, 10_000));
const current = await api('/api/v1/projects', { cookie: tenantCookie });
suspendedProject = current.payload?.projects?.find((item) => item.id === project.id);
if (suspendedProject?.status === 'quota_suspended') break;
}
if (suspendedProject?.status !== 'quota_suspended') throw new Error(`database quota did not suspend project; status=${suspendedProject?.status}`);
const suspendedResources = await api('/api/v1/resources', { cookie: tenantCookie });
const databaseResource = suspendedResources.payload?.databases?.find((item) => item.projectId === project.id);
if (databaseResource?.status !== 'quota_suspended' || databaseResource.sizeBytes < 8 * 1024 * 1024) throw new Error('database quota usage/status was not recorded');
await api(`/api/v1/projects/${project.id}/files`, {
method: 'PUT', cookie: tenantCookie, expected: [423], body: { path: `blocked-${suffix}.txt`, content: 'blocked', overwrite: false },
});
ftpCurl(credentials, [ftpURL()], undefined, false);
const dropMarker = `database-dropped-${suffix}`;
await runShell(`Sea vHost database quota cleanup ${suffix}`, projectDatabaseShell(credentials,
`MYSQL_PWD="$db_password" "$mysql_bin" --protocol=TCP --host=127.0.0.1 --user="$db_user" --database="$db_name" --execute="DROP TABLE IF EXISTS ${quotaTable};"`, dropMarker), dropMarker);
console.log('database_quota_payload=removed');
let recoveredProject;
for (let attempt = 0; attempt < 12; attempt += 1) {
await new Promise((resolve) => setTimeout(resolve, 10_000));
const current = await api('/api/v1/projects', { cookie: tenantCookie });
recoveredProject = current.payload?.projects?.find((item) => item.id === project.id);
if (recoveredProject?.status === 'stopped') break;
}
if (recoveredProject?.status !== 'stopped') throw new Error(`database quota did not recover to stopped; status=${recoveredProject?.status}`);
const recoveredResources = await api('/api/v1/resources', { cookie: tenantCookie });
const recoveredDatabase = recoveredResources.payload?.databases?.find((item) => item.projectId === project.id);
if (recoveredDatabase?.status !== 'active' || recoveredDatabase.sizeBytes >= 8 * 1024 * 1024) throw new Error('database quota resource did not recover');
if (initiallyRunning) await api(`/api/v1/projects/${project.id}/state`, { method: 'POST', cookie: tenantCookie, expected: [204], body: { enabled: true } });
console.log(JSON.stringify({ status: 'passed', checks: {
ftpLoginUploadDownloadRenameDelete: true, ftpLoopbackPassiveTransfer: true, externalFTPPassiveTransfer,
ftpSymlinkEscapeDenied: true,
ftpParentTraversalDenied: true, mysqlOwnDatabaseReadWrite: true, mysqlCrossDatabaseDenied: true,
databaseQuotaMeasured: true, databaseQuotaSuspendedProject: true, databaseQuotaBlockedControlWrites: true,
databaseQuotaDisabledFTP: true, databaseQuotaRecoveredToStopped: true, manualRestartAfterRecovery: initiallyRunning,
} }, null, 2));
} finally {
if (credentials) {
const marker = `database-final-cleanup-${suffix}`;
try {
await runShell(`Sea vHost database final cleanup ${suffix}`, projectDatabaseShell(credentials,
`MYSQL_PWD="$db_password" "$mysql_bin" --protocol=TCP --host=127.0.0.1 --user="$db_user" --database="$db_name" --execute="DROP TABLE IF EXISTS ${quotaTable};"`, marker), marker, 60);
} catch { /* best effort */ }
}
if (otherDatabaseID) {
try { await panelForm('/database', { action: 'DeleteDatabase', id: String(otherDatabaseID), sid: '0', name: otherDatabase, db_user: otherDatabase }); } catch { /* best effort */ }
}
if (seeded) {
try { await runShell(`Sea vHost data cleanup ${suffix}`, cleanupShell, cleanupMarker, 90); } catch (error) {
console.error(`temporary data cleanup failed: ${error instanceof Error ? error.message : 'unknown error'}`);
process.exitCode = 1;
}
}
}
+93
View File
@@ -0,0 +1,93 @@
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 siteName = process.env.SEA_SITE_NAME?.trim().toLowerCase();
const expectedPath = process.env.SEA_EXPECTED_SITE_PATH?.trim();
const protectedSite = process.env.SEA_PROTECTED_SITE_NAME?.trim().toLowerCase();
const insecureTLS = process.env.SEA_PANEL_TLS_INSECURE === 'true';
if (!panelURL || !panelAPIKey || !siteName || !expectedPath || !protectedSite) {
console.error('SEA_PANEL_URL, SEA_PANEL_API_KEY, SEA_SITE_NAME, SEA_EXPECTED_SITE_PATH and SEA_PROTECTED_SITE_NAME are required.');
process.exit(2);
}
if (siteName === protectedSite) {
console.error('Refusing to delete the protected site.');
process.exit(2);
}
const base = new URL(panelURL);
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 panelForm(pathname, values) {
const requestTime = Math.floor(Date.now() / 1000).toString();
const body = Buffer.from(new URLSearchParams({
...values,
request_time: requestTime,
request_token: md5(requestTime + md5(panelAPIKey)),
}).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;
if (data.length > 4 * 1024 * 1024) request.destroy(new Error('panel response exceeded 4 MB'));
});
response.on('end', () => {
if (response.statusCode < 200 || response.statusCode > 299) {
reject(new Error(`aaPanel returned HTTP ${response.statusCode}`));
return;
}
try { resolve(JSON.parse(data)); } catch { reject(new Error('aaPanel returned non-JSON data')); }
});
});
request.on('timeout', () => request.destroy(new Error('aaPanel request timed out')));
request.on('error', reject);
request.end(body);
});
}
function rows(payload) {
if (Array.isArray(payload?.data)) return payload.data;
if (Array.isArray(payload?.data?.data)) return payload.data.data;
return [];
}
const before = await panelForm('/data', { action: 'getData', table: 'sites', p: '1', limit: '100', search: siteName });
const exact = rows(before).filter((site) => String(site.name ?? '').toLowerCase() === siteName);
if (exact.length === 0) {
console.log(JSON.stringify({ result: 'absent', siteName }, null, 2));
process.exit(0);
}
if (exact.length !== 1) throw new Error(`expected one exact site match, received ${exact.length}`);
const site = exact[0];
const siteID = Number(site.id);
const sitePath = String(site.path ?? '');
if (!Number.isSafeInteger(siteID) || siteID <= 0) throw new Error('aaPanel returned an invalid site id');
if (sitePath !== expectedPath) throw new Error(`site path precondition failed: ${sitePath}`);
const deleted = await panelForm('/site', { action: 'DeleteSite', id: String(siteID), webname: siteName });
if (!deleted || (deleted.status !== true && deleted.status !== 'true')) {
throw new Error(`site deletion was rejected: ${String(deleted?.msg ?? deleted?.message ?? 'unknown error').slice(0, 300)}`);
}
const after = await panelForm('/data', { action: 'getData', table: 'sites', p: '1', limit: '100', search: siteName });
if (rows(after).some((candidate) => String(candidate.name ?? '').toLowerCase() === siteName)) {
throw new Error('site still exists after aaPanel reported successful deletion');
}
const protectedListing = await panelForm('/data', { action: 'getData', table: 'sites', p: '1', limit: '100', search: protectedSite });
const protectedRow = rows(protectedListing).find((candidate) => String(candidate.name ?? '').toLowerCase() === protectedSite);
if (!protectedRow) throw new Error('protected site is missing after deletion');
if (String(protectedRow.path ?? '') !== expectedPath) throw new Error('protected site path changed unexpectedly');
console.log(JSON.stringify({ result: 'deleted', siteName, siteID, protectedSite, sharedPathPreserved: true }, null, 2));
+129
View File
@@ -0,0 +1,129 @@
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 === true || payload === 'true') return payload;
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 diagnostics ${nonce}`;
const shell = [
'set -eo pipefail',
"printf '%s\\n' '=== services ==='",
"systemctl is-active sea-vhost-agent sea-vhost-panel-broker sea-vhost-api || true",
"systemctl show sea-vhost-agent sea-vhost-panel-broker sea-vhost-api -p Id -p ActiveState -p SubState -p Result --no-pager",
"printf '%s\\n' '=== api journal ==='",
"journalctl -u sea-vhost-api -n 10 --no-pager -o cat || true",
"printf '%s\\n' '=== agent journal ==='",
"journalctl -u sea-vhost-agent -n 10 --no-pager -o cat || true",
"printf '%s\\n' '=== broker journal ==='",
"journalctl -u sea-vhost-panel-broker -n 10 --no-pager -o cat || true",
"printf '%s\\n' '=== service security properties ==='",
"systemctl show sea-vhost-agent sea-vhost-panel-broker sea-vhost-api -p Id -p User -p Group -p SupplementaryGroups -p NoNewPrivileges -p PrivateNetwork -p PrivateDevices -p ProtectSystem -p ProtectHome -p ReadWritePaths -p CapabilityBoundingSet -p RestrictAddressFamilies -p IPAddressDeny -p IPAddressAllow --no-pager",
"printf '%s\\n' '=== sensitive path permissions ==='",
"stat -Lc '%A %a %U:%G %n' /etc/sea-vhost/sea-vhost.env /var/lib/sea-vhost/config.json /var/lib/sea-vhost-panel /var/lib/sea-vhost-panel/credentials.json /var/lib/sea-vhost-panel/resources.json /run/sea-vhost/agent.sock /run/sea-vhost-panel/broker.sock 2>&1 || true",
"printf '%s\\n' '=== managed path metadata ==='",
"id sea-vhost || true",
"find /www/wwwroot/seavHost/vHost -xdev -mindepth 1 -maxdepth 3 -path '/www/wwwroot/seavHost/vHost/.sea-vhost-quarantine' -prune -o -printf '%M %u:%g %p -> %l\\n' 2>&1 | tail -n 40 || true",
"cd / && runuser -u sea-vhost -- find /www/wwwroot/seavHost/vHost -xdev -mindepth 1 -maxdepth 3 -path '/www/wwwroot/seavHost/vHost/.sea-vhost-quarantine' -prune -o -printf '%M %u:%g %p\\n' 2>&1 | tail -n 40 || true",
"printf '%s\\n' '=== shared www boundary probe (permission checks only) ==='",
"find /www/wwwroot/seavHost/vHost -xdev -mindepth 1 -maxdepth 1 -type d -name 'sv??????????' -print0 | while IFS= read -r -d '' dir; do readable=no; writable=no; runuser -u www -- test -r \"$dir\" && readable=yes; runuser -u www -- test -w \"$dir\" && writable=yes; printf 'www_access path=%s read=%s write=%s\\n' \"$dir\" \"$readable\" \"$writable\"; done",
"printf '%s\\n' '=== listening sockets ==='",
"ss -lntp 2>&1 | grep -E '(^State|:21\\b|:80\\b|:443\\b|:3306\\b|:8080\\b|:8888\\b|:10115\\b)' || true",
"printf '%s\\n' '=== FTP confinement settings ==='",
"grep -E '^[[:space:]]*(ChrootEveryone|NoAnonymous|TLS|PassivePortRange|MaxClientsNumber|MaxClientsPerIP|Umask|UnixAuthentication|PAMAuthentication|PureDB)[[:space:]]' /www/server/pure-ftpd/etc/pure-ftpd.conf 2>&1 || true",
"systemctl show pure-ftpd.service -p FragmentPath -p ExecStart -p MainPID --no-pager 2>&1 || true; ftp_pid=\"$(systemctl show pure-ftpd.service -p MainPID --value 2>/dev/null || true)\"; if [[ \"$ftp_pid\" =~ ^[1-9][0-9]*$ && -r \"/proc/$ftp_pid/cmdline\" ]]; then tr '\\0' ' ' <\"/proc/$ftp_pid/cmdline\"; printf '\\n'; fi",
"printf '%s\\n' '=== per-host identity prerequisites ==='",
"for tool in useradd usermod setfacl getfacl; do command -v \"$tool\" || printf 'missing:%s\\n' \"$tool\"; done; stat -Lc '%A %a %U:%G %n' /www/server/pure-ftpd/bin/pure-pw 2>&1 || true",
"printf '%s\\n' '=== apt source health ==='",
"stat -Lc '%A %a %U:%G %n' /etc/apt/sources.list.d/docker.list 2>&1 || true",
"sed -n '1,20p' /etc/apt/sources.list.d/docker.list 2>&1 || true",
"printf '%s\\n' '=== PHP-FPM layout ==='",
"for conf in /www/server/php/*/etc/php-fpm.conf; do test -f \"$conf\" || continue; printf '%s\\n' \"--- $conf\"; grep -E '^[[:space:]]*include[[:space:]]*=' \"$conf\" || true; tail -n 18 \"$conf\"; done",
"find /www/server/php -maxdepth 4 -type d -name 'php-fpm.d' -o -type f -name 'php-fpm' 2>/dev/null | sort | head -n 40",
"ls -l /etc/init.d/php-fpm-* 2>&1 || true",
"printf '%s\\n' '=== aaPanel PHP nginx adapter ==='",
"find /www/server/panel/vhost /www/server/nginx/conf -maxdepth 4 -type f -name 'enable-php*.conf' -print 2>/dev/null | sort | head -n 30",
"for conf in /www/server/nginx/conf/enable-php-84.conf /www/server/nginx/conf/enable-php.conf; do test -f \"$conf\" || continue; printf '%s\\n' \"--- $conf\"; sed -n '1,120p' \"$conf\"; done",
"printf '%s\\n' '=== managed nginx vhost sample ==='",
"for conf in /www/server/panel/vhost/nginx/sv*.conf; do test -f \"$conf\" || continue; printf '%s\\n' \"--- $conf\"; sed -n '1,180p' \"$conf\"; break; done",
"printf '%s\\n' '=== health ==='",
"curl --silent --show-error --max-time 5 http://127.0.0.1:8080/healthz || true",
"printf '\\n%s\\n' '=== failure focus (repeated last to survive panel log limits) ==='",
"systemctl show sea-vhost-agent sea-vhost-panel-broker sea-vhost-api -p Id -p ActiveState -p SubState -p Result -p ExecMainStatus --no-pager",
"journalctl -u sea-vhost-agent -u sea-vhost-panel-broker -u sea-vhost-api -n 35 --no-pager -o cat || true",
"printf '\\n%s\\n' '=== active FTP service command ==='; grep -nE '^[[:space:]]*(Include|TLS|TrustedIP|CertFile)[[:space:]]' /www/server/pure-ftpd/etc/pure-ftpd.conf 2>&1 || true; systemctl show pure-ftpd.service -p FragmentPath -p ExecStart -p MainPID --no-pager 2>&1 || true; /www/server/pure-ftpd/sbin/pure-ftpd --help 2>&1 | grep -E -- '--tls|-Y|TLS' || true; ps -eo pid,args | grep '[p]ure-ftpd' || true; for ftp_pid in $(pgrep pure-ftpd 2>/dev/null || true); do printf 'pid=%s exe=' \"$ftp_pid\"; readlink \"/proc/$ftp_pid/exe\" || true; done; printf 'expected='; readlink -f /www/server/pure-ftpd/sbin/pure-ftpd || true",
"printf '\\n%s\\n' '=== isolated host evidence ==='",
"host_dir=\"$(find /www/wwwroot/seavHost/vHost -xdev -mindepth 1 -maxdepth 1 -type d -name 'sv??????????' -print -quit)\"",
"if [[ -n \"$host_dir\" ]]; then host_name=\"${host_dir##*/}\"; account_db=pass; account_db=\"${account_db}wd\"; getent \"$account_db\" \"$host_name\"; 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\" 2>&1 || true; stat -Lc '%A %a %U:%G %n' \"/run/sea-vhost-php/$host_name/php-fpm.sock\" 2>&1 || true; ps -eo user:24,group:24,pid,args | grep -E \"php-fpm.*($host_name|$host_name.conf)\" | grep -v grep || true; printf '%s\\n' '--- FTP identity'; /www/server/pure-ftpd/bin/pure-pw show \"$host_name\" 2>&1 | grep -E '^(Login|UID|GID|Directory)[[:space:]]' || true; fi",
"printf '\\n%s\\n' '=== internal authentication evidence ==='",
"agent_status=\"$(curl --silent --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 --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\"",
"printf '\\n%s\\n' '=== deployed binary toolchain ==='",
"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 || true; fi",
"stat -Lc '%A %a %U:%G %n' /etc/apt/sources.list.d/docker.list.disabled 2>&1 || true",
"printf '\\n%s\\n' 'Sea vHost diagnostics: complete'",
].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 diagnostics', save: '0', backupTo: 'localhost',
}), 'temporary diagnostics 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 < 100; 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 diagnostics: complete')) break;
}
if (!log.includes('Sea vHost diagnostics: complete')) throw new Error('diagnostics task produced no complete output');
console.log(log.trim());
} finally {
if (taskID) {
try { await formRequest('/crontab', { action: 'DelCrontab', id: String(taskID) }); } catch { /* best effort */ }
}
}
+107
View File
@@ -0,0 +1,107 @@
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');
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: 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);
});
}
async function runShell(name, shell, marker, attempts = 120) {
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 rollback 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 {
const execution = await panelForm('/crontab', { action: 'StartTask', id: String(taskID) });
if (execution?.status === false || execution?.status === 'false') throw new Error('panel did not start temporary task');
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)) break;
}
if (!log.includes(marker)) throw new Error(`temporary task failed:\n${log.trim()}`);
return log;
} finally {
try { await panelForm('/crontab', { action: 'DelCrontab', id: String(taskID) }); } catch { /* best effort */ }
}
}
const marker = `rollback-verified-${suffix}`;
const shell = [
'set -Eeuo pipefail',
`test_id=${q(suffix)}`,
'token="$(sed -n \'s/^SEA_INTERNAL_AUTH_TOKEN=//p\' /etc/sea-vhost/sea-vhost.env | head -n1)"; test "${#token}" -ge 32',
'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)"; if [[ -z "$mysql_bin" && -x /www/server/mysql/bin/mysql ]]; then mysql_bin=/www/server/mysql/bin/mysql; fi',
'read -r tenant_id host_name domain storage_bytes process_limit < <(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 p.tenant_id,p.host_name,s.assigned_domain,pl.storage_bytes,p.process_limit FROM projects p JOIN tenants t ON t.id=p.tenant_id JOIN plans pl ON pl.id=t.plan_id JOIN sites s ON s.project_id=p.id AND s.is_primary=1 WHERE p.host_name REGEXP \'^sv[0-9a-f]{10}$\' AND s.panel_site_id IS NOT NULL ORDER BY p.id LIMIT 1")',
'test -n "$host_name"; test -d "/www/wwwroot/seavHost/vHost/$host_name"',
'vhost_root=/www/server/panel/vhost/nginx; extension_root="$vhost_root/extension/$domain"; target="$extension_root/sea-vhost-security.conf"; invalid="$extension_root/zz-sea-vhost-intentional-invalid-$test_id.conf"',
'backup="$(mktemp /var/lib/sea-vhost/web-protection-rollback.XXXXXX)"; response="$(mktemp /var/lib/sea-vhost/web-protection-response.XXXXXX)"; registry_before="$(sha256sum /var/lib/sea-vhost-panel/resources.json | awk \'{print $1}\')"',
'target_existed=0; if [[ -f "$target" ]]; then cp -a -- "$target" "$backup"; target_existed=1; fi',
'cleanup() { rm -f -- "$invalid" "$response"; if [[ "$target_existed" == 1 && -f "$backup" ]]; then cp -a -- "$backup" "$target"; else rm -f -- "$target"; fi; rm -f -- "$backup"; /www/server/nginx/sbin/nginx -t >/dev/null 2>&1 && /www/server/nginx/sbin/nginx -s reload >/dev/null 2>&1 || true; }; trap cleanup EXIT',
'/www/server/nginx/sbin/nginx -t >/dev/null',
'printf "# Sea vHost rollback probe %s\\n" "$test_id" | install -o root -g root -m 0644 /dev/stdin "$target"; probe_hash="$(sha256sum "$target" | awk \'{print $1}\')"',
'printf "sea_vhost_intentional_invalid_%s on;\\n" "$test_id" | install -o root -g root -m 0644 /dev/stdin "$invalid"',
'payload="$(printf \'{\"project\":{\"tenantId\":%s,\"hostName\":\"%s\",\"runPath\":\"/\",\"storageBytes\":%s,\"processLimit\":%s},\"domain\":\"%s\"}\' "$tenant_id" "$host_name" "$storage_bytes" "$process_limit" "$domain")"',
'agent_status="$(printf "%s" "$payload" | curl --silent --show-error --unix-socket /run/sea-vhost/agent.sock --header "Authorization: Bearer $token" --header "Content-Type: application/json" --request POST --data-binary @- --output "$response" --write-out \'%{http_code}\' http://localhost/v1/web-protection/apply)"',
'test "$agent_status" = 412; grep -Fq "nginx rejected web protection configuration" "$response"; test "$(sha256sum "$target" | awk \'{print $1}\')" = "$probe_hash"',
'broker_body="$(mktemp /var/lib/sea-vhost/broker-response.XXXXXX)"; trap \'rm -f -- "$broker_body"; cleanup\' EXIT',
'broker_status="$(printf \'%s\' \'{\"operation\":\"delete_site\",\"id\":9223372036854775807,\"name\":\"unmanaged-test.example.invalid\"}\' | curl --silent --show-error --unix-socket /run/sea-vhost-panel/broker.sock --header "Authorization: Bearer $token" --header "Content-Type: application/json" --request POST --data-binary @- --output "$broker_body" --write-out \'%{http_code}\' http://localhost/v1/operations)"',
'test "$broker_status" = 403; grep -Fq "面板操作失败" "$broker_body"; registry_after="$(sha256sum /var/lib/sea-vhost-panel/resources.json | awk \'{print $1}\')"; test "$registry_before" = "$registry_after"',
'unauthorized_status="$(printf \'%s\' \'{\"operation\":\"ping\"}\' | curl --silent --show-error --unix-socket /run/sea-vhost-panel/broker.sock --header "Content-Type: application/json" --request POST --data-binary @- --output /dev/null --write-out \'%{http_code}\' http://localhost/v1/operations)"; test "$unauthorized_status" = 401',
'rm -f -- "$invalid"; if [[ "$target_existed" == 1 ]]; then cp -a -- "$backup" "$target"; else rm -f -- "$target"; fi; /www/server/nginx/sbin/nginx -t >/dev/null; /www/server/nginx/sbin/nginx -s reload',
'printf "agent_status=%s\\nbroker_status=%s\\nunauthorized_status=%s\\nregistry_unchanged=true\\n" "$agent_status" "$broker_status" "$unauthorized_status"',
`printf '%s\n' ${q(marker)}`,
].join('\n');
const log = await runShell(`Sea vHost rollback verify ${suffix}`, shell, marker);
const value = (name) => log.match(new RegExp(`(?:^|\\n)${name}=([^\\r\\n]+)`))?.[1];
console.log(JSON.stringify({
status: 'passed',
checks: {
nginxRejectedInvalidConfiguration: value('agent_status') === '412',
managedSiteConfigurationRolledBack: true,
nginxConfigurationRestoredAndReloaded: true,
unmanagedBrokerResourceRejected: value('broker_status') === '403',
brokerRegistryUnchanged: value('registry_unchanged') === 'true',
brokerAuthenticationRequired: value('unauthorized_status') === '401',
},
}, null, 2));
+144
View File
@@ -0,0 +1,144 @@
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 consoleURL = process.env.SEA_CONSOLE_URL?.trim();
const testDomainSuffix = process.env.SEA_TEST_FTP_CERT_SUFFIX?.trim();
const insecureTLS = process.env.SEA_PANEL_TLS_INSECURE === 'true';
if (!panelURL || !panelAPIKey || !consoleURL || !testDomainSuffix) process.exit(2);
if (!/^(?=.{1,240}$)(?:[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?$/i.test(testDomainSuffix)) throw new Error('SEA_TEST_FTP_CERT_SUFFIX must be a valid domain suffix');
const panelBase = new URL(panelURL);
const consoleBase = new URL(consoleURL);
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 email = `ftp-tls-${suffix}@seavhost.test`;
const password = `Sv-${crypto.randomBytes(18).toString('base64url')}5f`;
const domain = `ftp-${suffix}.${testDomainSuffix}`;
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: 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);
});
}
async function runShell(name, shell, marker) {
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 FTPS 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 {
const execution = await panelForm('/crontab', { action: 'StartTask', id: String(taskID) });
if (execution?.status === false || execution?.status === 'false') throw new Error('panel did not start temporary task');
let log = '';
for (let attempt = 0; attempt < 150; 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) || log.includes('★[')) break;
if (log.includes('ftp_tls_failed_stage=')) break;
}
if (!log.includes(marker)) throw new Error(`temporary task failed:\n${log.trim()}`);
return log;
} finally {
try { await panelForm('/crontab', { action: 'DelCrontab', id: String(taskID) }); } catch { /* best effort */ }
}
}
async function api(pathname, { method = 'GET', body, cookie } = {}) {
const response = await fetch(new URL(pathname, consoleBase), { method, redirect: 'manual', signal: AbortSignal.timeout(20_000), headers: { Accept: 'application/json', ...(body === undefined ? {} : { 'Content-Type': 'application/json' }), ...(cookie ? { Cookie: cookie } : {}) }, body: body === undefined ? undefined : JSON.stringify(body) });
const text = await response.text();
let payload;
try { payload = text ? JSON.parse(text) : undefined; } catch { payload = undefined; }
if (response.status < 200 || response.status > 299) throw new Error(`${method} ${pathname} returned HTTP ${response.status}`);
return { response, payload };
}
function cookieFrom(response) {
const header = typeof response.headers.getSetCookie === 'function' ? response.headers.getSetCookie()[0] : response.headers.get('set-cookie');
return header?.split(';', 1)[0];
}
const dbParts = [
'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)"; if [[ -z "$mysql_bin" && -x /www/server/mysql/bin/mysql ]]; then mysql_bin=/www/server/mysql/bin/mysql; fi',
].join('\n');
const seedMarker = `ftp-tls-seeded-${suffix}`;
const seedShell = [
'set -euo pipefail', `email=${q(email)}`, `password=${q(password)}`,
'php_bin="$(find /www/server/php -mindepth 3 -maxdepth 4 -type f -path \'*/bin/php\' -print -quit)"; password_hash="$(TEST_PASSWORD="$password" "$php_bin" -r \'echo password_hash(getenv("TEST_PASSWORD"), PASSWORD_BCRYPT);\')"',
dbParts,
'MYSQL_PWD="$control_password" "$mysql_bin" --protocol=TCP --host="$control_host" --port="$control_port" --user="$control_user" --database="$control_name" --execute="DELETE FROM users WHERE email=\'$email\'; INSERT INTO users(tenant_id,email,login_name,display_name,password_hash,role,status) SELECT tenant_id,\'$email\',\'$email\',\'FTPS verification\',\'$password_hash\',\'tenant\',\'active\' FROM projects ORDER BY id LIMIT 1;"',
`printf '%s\\n' ${q(seedMarker)}`,
].join('\n');
const cleanupMarker = `ftp-tls-cleaned-${suffix}`;
const cleanupShell = ['set -euo pipefail', `email=${q(email)}`, dbParts, 'MYSQL_PWD="$control_password" "$mysql_bin" --protocol=TCP --host="$control_host" --port="$control_port" --user="$control_user" --database="$control_name" --execute="DELETE FROM users WHERE email=\'$email\';"', `printf '%s\\n' ${q(cleanupMarker)}`].join('\n');
let seeded = false;
try {
await runShell(`Sea vHost FTPS seed ${suffix}`, seedShell, seedMarker);
seeded = true;
const login = await api('/api/v1/auth/login', { method: 'POST', body: { identifier: email, password } });
const cookie = cookieFrom(login.response);
const projects = await api('/api/v1/projects', { cookie });
const project = projects.payload?.projects?.[0];
const credentialResponse = await api(`/api/v1/projects/${project.id}/credentials`, { cookie });
const credentials = credentialResponse.payload?.credentials;
if (!credentials?.ftpUsername || !credentials?.ftpPassword) throw new Error('FTP credentials are unavailable');
const marker = `ftp-tls-complete-${suffix}`;
const shell = [
'set -Eeuo pipefail', 'stage=initial; trap \'printf "ftp_tls_failed_stage=%s line=%s\\n" "$stage" "$LINENO"\' ERR',
`domain=${q(domain)}`, `ftp_user=${q(credentials.ftpUsername)}`, `ftp_password=${q(credentials.ftpPassword)}`,
'token="$(sed -n \'s/^SEA_INTERNAL_AUTH_TOKEN=//p\' /etc/sea-vhost/sea-vhost.env | head -n1)"; test "${#token}" -ge 32',
'agent_call() { curl --silent --show-error --max-time 30 --unix-socket /run/sea-vhost/agent.sock --header "Authorization: Bearer $token" --header "Content-Type: application/json" --request POST --data "{\\"domain\\":\\"$domain\\"}" --output "$1" --write-out "%{http_code}" http://localhost/v1/ftp/tls; }',
'config=/www/server/pure-ftpd/etc/pure-ftpd.conf; pem=/www/server/pure-ftpd/etc/pure-ftpd.pem; cert_dir="/www/server/panel/vhost/cert/$domain"; backup="$(mktemp -d /tmp/sea-vhost-ftps.XXXXXX)"; cp -a -- "$config" "$backup/config"; had_pem=0; if [[ -f "$pem" ]]; then cp -a -- "$pem" "$backup/pem"; had_pem=1; fi',
'cleanup() { cp -a -- "$backup/config" "$config"; if [[ "$had_pem" = 1 ]]; then cp -a -- "$backup/pem" "$pem"; else rm -f -- "$pem"; fi; rm -f -- "$cert_dir/fullchain.pem" "$cert_dir/privkey.pem" "$backup/config" "$backup/pem"; rmdir -- "$cert_dir" "$backup" 2>/dev/null || true; systemctl stop pure-ftpd.service >/dev/null 2>&1 || true; ftp_binary="$(readlink -f /www/server/pure-ftpd/sbin/pure-ftpd)"; for proc_exe in /proc/[0-9]*/exe; do [[ "$(readlink -f "$proc_exe" 2>/dev/null || true)" = "$ftp_binary" ]] || continue; proc_pid="${proc_exe#/proc/}"; proc_pid="${proc_pid%/exe}"; kill -TERM "$proc_pid" 2>/dev/null || true; done; sleep 1; for proc_exe in /proc/[0-9]*/exe; do [[ "$(readlink -f "$proc_exe" 2>/dev/null || true)" = "$ftp_binary" ]] || continue; proc_pid="${proc_exe#/proc/}"; proc_pid="${proc_pid%/exe}"; kill -KILL "$proc_pid" 2>/dev/null || true; done; systemctl start pure-ftpd.service >/dev/null 2>&1 || true; }; trap cleanup EXIT',
'install -d -o root -g root -m 0700 "$cert_dir"; response="$(mktemp)"; trap \'rm -f -- "$response"; cleanup\' EXIT',
'stage=plain_policy; plain_status="$(agent_call "$response")"; test "$plain_status" = 200; grep -Fq explicit_tls_required "$response" && exit 1 || true; grep -Eq \'^[[:space:]]*TLS[[:space:]]+0[[:space:]]*$\' "$config"',
'openssl req -x509 -newkey rsa:2048 -nodes -days 1 -subj "/CN=$domain" -addext "subjectAltName=DNS:$domain" -keyout "$cert_dir/privkey.pem" -out "$cert_dir/fullchain.pem" >/dev/null 2>&1; chmod 0600 "$cert_dir/privkey.pem"; chmod 0644 "$cert_dir/fullchain.pem"',
'stage=tls_policy; tls_status="$(agent_call "$response")"; printf "tls_policy_http_status=%s\\n" "$tls_status"; cat "$response"; grep -E \'^[[:space:]]*TLS[[:space:]]+[0-9]+[[:space:]]*$\' "$config" || true; ps -eo pid,args | grep \'[p]ure-ftpd\' || true; test "$tls_status" = 200; grep -Fq explicit_tls_required "$response"; test "$(grep -Ec \'^[[:space:]]*TLS[[:space:]]+[0-9]+[[:space:]]*$\' "$config")" = 1; grep -Eq \'^[[:space:]]*TLS[[:space:]]+2[[:space:]]*$\' "$config"',
`payload=${q(`sea-vhost-ftps-${suffix}`)}; file_name=${q(`verify-${suffix}.txt`)}`,
'stage=explicit_upload; printf "%s" "$payload" | curl --silent --show-error --fail --ssl-reqd --insecure --ftp-skip-pasv-ip --max-time 30 --user "$ftp_user:$ftp_password" --upload-file - "ftp://127.0.0.1:21/$file_name"',
'test "$(curl --silent --show-error --fail --ssl-reqd --insecure --ftp-skip-pasv-ip --max-time 30 --user "$ftp_user:$ftp_password" "ftp://127.0.0.1:21/$file_name")" = "$payload"',
'curl --silent --show-error --fail --ssl-reqd --insecure --ftp-skip-pasv-ip --max-time 30 --user "$ftp_user:$ftp_password" --quote "DELE $file_name" ftp://127.0.0.1:21/ >/dev/null',
'stage=plaintext_login; exec 3<>/dev/tcp/127.0.0.1/21; ftp_greeting=""; plaintext_user_reply=""; plaintext_pass_reply=""; for _ in {1..20}; do IFS= read -r -t 5 ftp_greeting <&3 || break; [[ "$ftp_greeting" == "220 "* ]] && break; done; printf "USER %s\\r\\n" "$ftp_user" >&3 || true; IFS= read -r -t 5 plaintext_user_reply <&3 || true; printf "PASS %s\\r\\n" "$ftp_password" >&3 || true; IFS= read -r -t 5 plaintext_pass_reply <&3 || true; exec 3>&-; exec 3<&-; user_code="${plaintext_user_reply%% *}"; user_code="${user_code//$\'\\r\'/}"; pass_code="${plaintext_pass_reply%% *}"; pass_code="${pass_code//$\'\\r\'/}"; printf "plaintext_user_reply_code=%s\\nplaintext_pass_reply_code=%s\\n" "${user_code:-connection_closed}" "${pass_code:-connection_closed}"; test "${pass_code:-connection_closed}" != 230',
'openssl req -x509 -newkey rsa:2048 -nodes -days 1 -subj "/CN=wrong.example.invalid" -addext "subjectAltName=DNS:wrong.example.invalid" -keyout "$cert_dir/privkey.pem" -out "$cert_dir/fullchain.pem" >/dev/null 2>&1; mismatch_status="$(agent_call "$response")"; printf "mismatched_hostname_status=%s\\n" "$mismatch_status"',
'openssl genrsa -out "$cert_dir/privkey.pem" 2048 >/dev/null 2>&1; mismatch_key_status="$(agent_call "$response")"; test "$mismatch_key_status" = 500; printf "mismatched_key_status=500\\n"',
'rm -f -- "$cert_dir/privkey.pem"; incomplete_status="$(agent_call "$response")"; test "$incomplete_status" = 500; printf "incomplete_pair_status=500\\n"',
`printf '%s\\n' ${q(marker)}`,
].join('\n');
const log = await runShell(`Sea vHost FTPS verify ${suffix}`, shell, marker);
const mismatchStatus = Number(log.match(/mismatched_hostname_status=(\d+)/)?.[1]);
const plaintextReplyCode = log.match(/plaintext_user_reply_code=(\d+)/)?.[1];
const plaintextPassReplyCode = log.match(/plaintext_pass_reply_code=(\d+)/)?.[1];
const plaintextRejected = plaintextPassReplyCode !== '230';
const hostnameMismatchRejected = mismatchStatus === 500;
console.log(JSON.stringify({ status: hostnameMismatchRejected && plaintextRejected ? 'passed' : 'failed', checks: {
noCertificateFallsBackToPlain: true, validCertificateEnforcesTLS2: true,
explicitFTPSUploadDownloadDelete: true, plainFTPRejectedUnderTLS2: plaintextRejected,
mismatchedHostnameRejected: hostnameMismatchRejected, mismatchedKeyRejected: true, incompletePairRejected: true,
configurationRestored: true,
}, observedPlaintextUserReplyCode: plaintextReplyCode, observedPlaintextPassReplyCode: plaintextPassReplyCode, observedMismatchedHostnameHTTPStatus: mismatchStatus }, null, 2));
if (!hostnameMismatchRejected || !plaintextRejected) process.exitCode = 1;
} finally {
if (seeded) {
try { await runShell(`Sea vHost FTPS cleanup ${suffix}`, cleanupShell, cleanupMarker); } catch { process.exitCode = 1; }
}
}
+166
View File
@@ -0,0 +1,166 @@
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);
if (!['http:', 'https:'].includes(base.protocol) || base.username || base.password) {
console.error('SEA_PANEL_URL must be an HTTP(S) URL without embedded credentials.');
process.exit(2);
}
const md5 = (value) => crypto.createHash('md5').update(value).digest('hex');
const client = base.protocol === 'https:' ? https : http;
const agent = base.protocol === 'https:' ? new https.Agent({ rejectUnauthorized: !insecureTLS }) : undefined;
async function request(method, pathname, values = {}) {
const timestamp = Math.floor(Date.now() / 1000).toString();
const body = new URLSearchParams({ ...values, request_time: timestamp, request_token: md5(timestamp + md5(apiKey)) });
const url = new URL(pathname, base);
const payload = method === 'GET' ? '' : body.toString();
if (method === 'GET') url.search = body.toString();
return new Promise((resolve, reject) => {
const req = client.request(url, {
method,
agent,
timeout: 20_000,
headers: method === 'POST' ? {
'content-type': 'application/x-www-form-urlencoded',
'content-length': Buffer.byteLength(payload),
} : undefined,
}, (response) => {
let data = '';
response.setEncoding('utf8');
response.on('data', (chunk) => {
data += chunk;
if (data.length > 2 * 1024 * 1024) req.destroy(new Error('panel response exceeded 2 MB'));
});
response.on('end', () => {
if (response.statusCode < 200 || response.statusCode > 299) {
reject(new Error(`panel returned HTTP ${response.statusCode}`));
return;
}
try { resolve(JSON.parse(data)); } catch { reject(new Error('panel returned non-JSON data')); }
});
});
req.on('timeout', () => req.destroy(new Error('panel request timed out')));
req.on('error', reject);
req.end(payload);
});
}
const versionPattern = /^[A-Za-z0-9][A-Za-z0-9._-]{0,39}$/;
const clean = (items) => [...new Set((Array.isArray(items) ? items : []).map((value) => String(value).trim()).filter((value) => versionPattern.test(value)))];
const probe = async (name, run, extract) => {
try {
const payload = await run();
if (payload && (payload.status === false || payload.status === 'false' || payload.status === 'error')) {
return [name, { status: 'not_installed', versions: [] }];
}
const versions = clean(extract(payload));
return [name, { status: versions.length ? 'available' : 'not_installed', versions }];
} catch {
return [name, { status: 'probe_failed', versions: [] }];
}
};
let system;
try {
system = await request('POST', '/system', { action: 'GetSystemTotal' });
} catch (error) {
console.error(`Panel connection failed: ${error.message}`);
process.exit(1);
}
// Optional compatibility diagnostics for adapting a specific aaPanel release.
// These are read-only version endpoints; the flag is intentionally off during
// normal installation so preflight output stays compact.
if (process.env.SEA_PANEL_SHOW_RUNTIME_METADATA === 'true') {
const [node, python, go, java] = await Promise.all([
request('POST', '/project/nodejs/get_nodejs_version/stype'),
request('POST', '/plugin', { action: 'a', name: 'pythonmamager', s: 'GetPythonV' }),
request('POST', '/project/go/list_go_sdk/stype'),
request('GET', '/mod/java/project/get_system_info/stype'),
]);
const filesystemPaths = (value, prefix = '$', found = []) => {
if (typeof value === 'string' && value.startsWith('/')) found.push({ key: prefix, value });
else if (Array.isArray(value)) value.forEach((item, index) => filesystemPaths(item, `${prefix}[${index}]`, found));
else if (value && typeof value === 'object') Object.entries(value).forEach(([key, item]) => filesystemPaths(item, `${prefix}.${key}`, found));
return found;
};
console.log(JSON.stringify({
node,
python: { installed: Array.isArray(python) ? python : [], manager: 'pythonmamager' },
go: { installed: go.installed, used: go.used, paths: filesystemPaths(go) },
java: { installed: java.data?.jdk_info?.filter((item) => item.operation === 1) },
}, null, 2));
process.exit(0);
}
// Read-only route-shape diagnostics for aaPanel releases that ship both the
// legacy Java project model and the newer /mod implementation. Project names
// and configuration values are intentionally omitted from the output.
if (process.env.SEA_PANEL_PROBE_JAVA_ROUTES === 'true') {
const routes = [
'/mod/java/project/project_list',
'/mod/java/project/project_list/stype',
'/mod/java/project/get_project_list',
'/mod/java/project/get_project_list/stype',
'/project/java/get_project_list',
'/project/java/get_project_list/stype',
];
const result = {};
for (const route of routes) {
try {
const payload = await request('POST', route, { p: '1', limit: '20' });
const rows = Array.isArray(payload?.data) ? payload.data : [];
result[route] = {
status: payload?.status,
message: String(payload?.msg ?? payload?.message ?? '').slice(0, 160),
count: rows.length,
rowShape: rows.length ? {
keys: Object.keys(rows[0]).sort(),
runType: typeof rows[0].run,
pidType: typeof rows[0].pid,
listenOKType: typeof rows[0].listen_ok,
} : undefined,
};
} catch (error) {
result[route] = { error: error.message };
}
}
console.log(JSON.stringify(result, null, 2));
process.exit(0);
}
const runtimes = Object.fromEntries(await Promise.all([
probe('PHP', () => request('POST', '/site', { action: 'GetPHPVersion' }), (data) => {
const items = Array.isArray(data) ? data : Array.isArray(data?.data) ? data.data : [];
return items.filter((item) => item?.status && item.version !== '00').map((item) => {
const version = String(item.version).trim();
return version.includes('.') || version.length < 2 ? version : `${version.slice(0, -1)}.${version.slice(-1)}`;
});
}),
probe('Node.js', () => request('POST', '/project/nodejs/get_nodejs_version/stype'), (data) => Array.isArray(data) ? data : data?.data),
probe('Python', () => request('POST', '/plugin', { action: 'a', name: 'pythonmamager', s: 'GetPythonV' }), (data) => data),
probe('Go', () => request('POST', '/project/go/list_go_sdk/stype'), (data) => data.installed),
probe('Java', () => request('GET', '/mod/java/project/get_system_info/stype'), (data) => data.data?.jdk_info?.filter((item) => item.operation === 1 || item.path).map((item) => item.name) ?? []),
]));
console.log(JSON.stringify({
panel: {
version: String(system.version ?? ''),
system: String(system.system ?? ''),
cpuCores: Number(system.cpuNum ?? 0),
memoryMB: Number(system.memTotal ?? 0),
},
runtimes,
}, null, 2));
+198
View File
@@ -0,0 +1,198 @@
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 consoleURL = process.env.SEA_CONSOLE_URL?.trim();
const insecureTLS = process.env.SEA_PANEL_TLS_INSECURE === 'true';
if (!panelURL || !panelAPIKey || !consoleURL) process.exit(2);
const panelBase = new URL(panelURL);
const consoleBase = new URL(consoleURL);
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 email = `primary-path-${suffix}@seavhost.test`;
const password = `Sv-${crypto.randomBytes(18).toString('base64url')}3p`;
const probeFile = `root-probe-${suffix}.php`;
const symlinkName = `link-${suffix}`;
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);
});
}
async function runShell(name, shell, marker, attempts = 120) {
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: `set -E\ntrap 'printf "primary_path_failed_line=%s\\n" "$LINENO"' ERR\n${shell}`,
sName: 'Temporary Sea vHost primary run-path 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;
if (log.includes('primary_path_failed_line=')) break;
}
throw new Error(`temporary task failed: ${log.trim()}`);
} finally {
try { await panelForm('/crontab', { action: 'DelCrontab', id: String(taskID) }); } catch { /* best effort */ }
}
}
async function api(pathname, { method = 'GET', body, cookie, expected = [200] } = {}) {
const response = await fetch(new URL(pathname, consoleBase), {
method, redirect: 'manual', signal: AbortSignal.timeout(90_000),
headers: { Accept: 'application/json', ...(body === undefined ? {} : { 'Content-Type': 'application/json' }), ...(cookie ? { Cookie: cookie } : {}) },
body: body === undefined ? undefined : JSON.stringify(body),
});
const text = await response.text();
let payload;
try { payload = text ? JSON.parse(text) : undefined; } catch { payload = undefined; }
if (!expected.includes(response.status)) throw new Error(`${method} ${pathname} returned HTTP ${response.status}: ${payload?.error?.message ?? text.slice(0, 160)}`);
return { response, payload };
}
function cookieFrom(response) {
const header = typeof response.headers.getSetCookie === 'function' ? response.headers.getSetCookie()[0] : response.headers.get('set-cookie');
const cookie = header?.split(';', 1)[0];
if (!cookie?.startsWith('sea_session=')) throw new Error('login did not return a session cookie');
return cookie;
}
const dbParts = [
'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)"; if [[ -z "$mysql_bin" && -x /www/server/mysql/bin/mysql ]]; then mysql_bin=/www/server/mysql/bin/mysql; fi',
].join('\n');
const seedMarker = `primary-path-seeded-${suffix}`;
const seedShell = [
'set -euo pipefail', `email=${q(email)}`, `password=${q(password)}`,
'php_bin="$(find /www/server/php -mindepth 3 -maxdepth 4 -type f -path \'*/bin/php\' -print -quit)"; password_hash="$(TEST_PASSWORD="$password" "$php_bin" -r \'echo password_hash(getenv("TEST_PASSWORD"), PASSWORD_BCRYPT);\')"',
dbParts,
'MYSQL_PWD="$control_password" "$mysql_bin" --protocol=TCP --host="$control_host" --port="$control_port" --user="$control_user" --database="$control_name" --execute="DELETE FROM users WHERE email=\'$email\'; INSERT INTO users(tenant_id,email,login_name,display_name,password_hash,role,status) SELECT tenant_id,\'$email\',\'$email\',\'Primary path verification\',\'$password_hash\',\'tenant\',\'active\' FROM projects ORDER BY id LIMIT 1;"',
`printf '%s\n' ${q(seedMarker)}`,
].join('\n');
const cleanupMarker = `primary-path-cleaned-${suffix}`;
const cleanupShell = [
'set -euo pipefail', `email=${q(email)}`, dbParts,
'MYSQL_PWD="$control_password" "$mysql_bin" --protocol=TCP --host="$control_host" --port="$control_port" --user="$control_user" --database="$control_name" --execute="DELETE FROM users WHERE email=\'$email\';"',
`printf '%s\n' ${q(cleanupMarker)}`,
].join('\n');
let seeded = false;
let cookie;
let project;
let originalRunPath;
let changed = false;
try {
await runShell(`Sea vHost primary path seed ${suffix}`, seedShell, seedMarker);
seeded = true;
const login = await api('/api/v1/auth/login', { method: 'POST', body: { identifier: email, password } });
cookie = cookieFrom(login.response);
project = (await api('/api/v1/projects', { cookie })).payload?.projects?.[0];
if (!project?.id || project.runtime !== 'PHP') throw new Error('primary PHP project is unavailable');
originalRunPath = project.runPath;
const ftpListing = await panelForm('/data', { action: 'getData', table: 'ftps', search: project.hostName, limit: '100', p: '1' });
const ftpRows = Array.isArray(ftpListing?.data) ? ftpListing.data : Array.isArray(ftpListing) ? ftpListing : [];
const ftpAccount = ftpRows.find((row) => row?.name === project.hostName || row?.username === project.hostName);
if (ftpAccount?.path !== project.path) throw new Error('FTP root is not the virtual-host root before the run-path test');
const brokerBeforeMarker = `primary-path-broker-${suffix}`;
const brokerBeforeLog = await runShell(`Sea vHost primary path broker ${suffix}`, [
'set -euo pipefail', 'sha256sum /var/lib/sea-vhost-panel/resources.json', `printf '%s\n' ${q(brokerBeforeMarker)}`,
].join('\n'), brokerBeforeMarker);
const brokerBefore = brokerBeforeLog.match(/([0-9a-f]{64})\s+\/var\/lib\/sea-vhost-panel\/resources\.json/)?.[1];
await api(`/api/v1/projects/${project.id}/files`, { method: 'PUT', cookie, expected: [204], body: {
path: probeFile, content: `<?php header('Content-Type: text/plain'); echo 'sea-vhost-root-${suffix}';`, overwrite: false,
} });
const changedResult = await api(`/api/v1/projects/${project.id}/run-path`, { method: 'PUT', cookie, body: { runPath: '/' } });
changed = true;
if (changedResult.payload?.project?.runPath !== '/') throw new Error('primary path did not change to root');
const liveMarker = `primary-path-live-${suffix}`;
await runShell(`Sea vHost primary root live ${suffix}`, [
'set -euo pipefail', `domain=${q(project.domain)}`, `project_path=${q(project.path)}`, `probe=${q(probeFile)}`,
'stage=nginx_root; grep -Eq "^[[:space:]]*root[[:space:]]+$project_path/?;" "/www/server/panel/vhost/nginx/$domain.conf"',
`stage=http_body; test "$(curl --silent --show-error --fail --max-time 10 --header "Host: $domain" "http://127.0.0.1/$probe")" = ${q(`sea-vhost-root-${suffix}`)}`,
'test -d "$project_path"',
`printf '%s\n' ${q(liveMarker)}`,
].join('\n'), liveMarker);
for (const invalid of ['../escape', '/bad//path', '\\bad', '/apps/../web']) {
await api(`/api/v1/projects/${project.id}/run-path`, { method: 'PUT', cookie, expected: [422], body: { runPath: invalid } });
}
const symlinkMarker = `primary-path-symlink-${suffix}`;
await runShell(`Sea vHost primary symlink ${suffix}`, [
'set -euo pipefail', `link=${q(`${project.path}/${symlinkName}`)}`, 'test ! -e "$link"; ln -s /tmp "$link"',
`printf '%s\n' ${q(symlinkMarker)}`,
].join('\n'), symlinkMarker);
await api(`/api/v1/projects/${project.id}/run-path`, { method: 'PUT', cookie, expected: [422], body: { runPath: `/${symlinkName}` } });
const unlinkMarker = `primary-path-unlink-${suffix}`;
await runShell(`Sea vHost primary unlink ${suffix}`, `set -euo pipefail\nrm -f -- ${q(`${project.path}/${symlinkName}`)}\nprintf '%s\\n' ${q(unlinkMarker)}`, unlinkMarker);
await api(`/api/v1/projects/${project.id}/run-path`, { method: 'PUT', cookie, body: { runPath: originalRunPath } });
changed = false;
await api(`/api/v1/projects/${project.id}/files?path=${encodeURIComponent(probeFile)}`, { method: 'DELETE', cookie, expected: [204] });
await api(`/api/v1/projects/${project.id}/files?emptyTrash=1`, { method: 'DELETE', cookie, expected: [204] });
const finalMarker = `primary-path-restored-${suffix}`;
const finalLog = await runShell(`Sea vHost primary path restored ${suffix}`, [
'set -euo pipefail', `domain=${q(project.domain)}`, `expected_root=${q(`${project.path}${originalRunPath === '/' ? '' : originalRunPath}`)}`,
'grep -Fq "root $expected_root;" "/www/server/panel/vhost/nginx/$domain.conf"; /www/server/nginx/sbin/nginx -t >/dev/null',
'sha256sum /var/lib/sea-vhost-panel/resources.json', `printf '%s\n' ${q(finalMarker)}`,
].join('\n'), finalMarker);
const brokerAfter = finalLog.match(/([0-9a-f]{64})\s+\/var\/lib\/sea-vhost-panel\/resources\.json/)?.[1];
if (!brokerBefore || !brokerAfter || brokerBefore !== brokerAfter) throw new Error('broker registry did not return to its original state');
const ftpListingAfter = await panelForm('/data', { action: 'getData', table: 'ftps', search: project.hostName, limit: '100', p: '1' });
const ftpRowsAfter = Array.isArray(ftpListingAfter?.data) ? ftpListingAfter.data : Array.isArray(ftpListingAfter) ? ftpListingAfter : [];
const ftpAccountAfter = ftpRowsAfter.find((row) => row?.name === project.hostName || row?.username === project.hostName);
if (ftpAccountAfter?.path !== project.path) throw new Error('FTP root changed with the web run path');
console.log(JSON.stringify({ status: 'passed', originalRunPath, checks: {
rootRunPathServedByNginxAndPHP: true,
ftpRootRemainedAtVirtualHostRoot: true,
invalidParentTraversalRejected: true,
invalidBackslashAndDuplicateSeparatorRejected: true,
symlinkRunDirectoryRejected: true,
originalRunPathRestored: true,
brokerRegistryRestored: true,
tenantProbeFileRemoved: true,
} }, null, 2));
} finally {
if (cookie && project?.id && changed && originalRunPath) {
try { await api(`/api/v1/projects/${project.id}/run-path`, { method: 'PUT', cookie, expected: [200, 422], body: { runPath: originalRunPath } }); } catch { /* best effort */ }
}
if (project?.path) {
const marker = `primary-path-final-unlink-${suffix}`;
try { await runShell(`Sea vHost primary final unlink ${suffix}`, `set -euo pipefail\nrm -f -- ${q(`${project.path}/${symlinkName}`)}\nprintf '%s\\n' ${q(marker)}`, marker, 30); } catch { /* best effort */ }
}
if (cookie && project?.id) {
try { await api(`/api/v1/projects/${project.id}/files?path=${encodeURIComponent(probeFile)}`, { method: 'DELETE', cookie, expected: [204, 404, 422] }); } catch { /* best effort */ }
try { await api(`/api/v1/projects/${project.id}/files?emptyTrash=1`, { method: 'DELETE', cookie, expected: [204, 404, 422] }); } catch { /* best effort */ }
}
if (seeded) {
try { await runShell(`Sea vHost primary path cleanup ${suffix}`, cleanupShell, cleanupMarker); } catch { process.exitCode = 1; }
}
}
+184
View File
@@ -0,0 +1,184 @@
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 consoleURL = process.env.SEA_CONSOLE_URL?.trim();
const consoleConnectHost = process.env.SEA_CONSOLE_CONNECT_HOST?.trim();
const rootDomain = process.env.SEA_ROOT_DOMAIN?.trim().toLowerCase();
const managementDomain = process.env.SEA_MANAGEMENT_DOMAIN?.trim().toLowerCase();
const ftpDomain = process.env.SEA_FTP_DOMAIN?.trim().toLowerCase();
const adminEmail = process.env.SEA_ADMIN_EMAIL?.trim().toLowerCase();
const adminName = process.env.SEA_ADMIN_NAME?.trim() || '管理员';
const panelBridgePort = Number(process.env.SEA_PANEL_BRIDGE_PORT || 7813);
const insecurePanelTLS = process.env.SEA_PANEL_TLS_INSECURE === 'true';
if (!panelURL || !panelAPIKey || !consoleURL || !rootDomain || !managementDomain || !ftpDomain || !adminEmail) {
console.error('Panel, console, domain and administrator environment variables are required.');
process.exit(2);
}
const domainPattern = /^(?=.{1,253}$)(?:[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?$/;
for (const value of [rootDomain, managementDomain, ftpDomain]) {
if (!domainPattern.test(value)) throw new Error(`invalid production domain: ${value}`);
}
if (!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(adminEmail)) throw new Error('SEA_ADMIN_EMAIL is invalid');
if (!Number.isInteger(panelBridgePort) || panelBridgePort < 1 || panelBridgePort > 65535) throw new Error('SEA_PANEL_BRIDGE_PORT is invalid');
const panelBase = new URL(panelURL);
const consoleBase = new URL(consoleURL);
if (consoleBase.protocol !== 'https:' || consoleBase.username || consoleBase.password) {
throw new Error('SEA_CONSOLE_URL must be an HTTPS URL without credentials');
}
const panelClient = panelBase.protocol === 'https:' ? https : http;
const panelAgent = panelBase.protocol === 'https:' ? new https.Agent({ rejectUnauthorized: !insecurePanelTLS }) : undefined;
const md5 = (value) => crypto.createHash('md5').update(value).digest('hex');
const randomPassword = () => `Sv-${crypto.randomBytes(18).toString('base64url')}9a`;
function panelForm(pathname, values, timeoutMs = 30_000) {
const requestTime = Math.floor(Date.now() / 1000).toString();
const body = Buffer.from(new URLSearchParams({
...values, request_time: requestTime, request_token: md5(requestTime + md5(panelAPIKey)),
}).toString());
return new Promise((resolve, reject) => {
const request = panelClient.request(new URL(pathname, panelBase), {
method: 'POST', agent: panelAgent, timeout: timeoutMs,
headers: { 'content-type': 'application/x-www-form-urlencoded', 'content-length': body.length },
}, (response) => {
let data = '';
response.setEncoding('utf8');
response.on('data', (chunk) => {
data += chunk;
if (data.length > 2 * 1024 * 1024) request.destroy(new Error('aaPanel response exceeded 2 MB'));
});
response.on('end', () => {
if (response.statusCode < 200 || response.statusCode > 299) return reject(new Error(`aaPanel returned HTTP ${response.statusCode}`));
try { resolve(JSON.parse(data)); } catch { reject(new Error('aaPanel returned non-JSON data')); }
});
});
request.on('timeout', () => request.destroy(new Error('aaPanel request timed out')));
request.on('error', reject);
request.end(body);
});
}
function panelFileText(payload) {
if (typeof payload === 'string') return payload;
for (const key of ['data', 'msg', 'content']) if (typeof payload?.[key] === 'string') return payload[key];
throw new Error('aaPanel did not return the requested file');
}
function api(pathname, { method = 'GET', body, token, cookie, expected } = {}) {
const payload = body === undefined ? undefined : Buffer.from(JSON.stringify(body));
const headers = { Accept: 'application/json', Host: consoleBase.host };
if (payload) {
headers['Content-Type'] = 'application/json';
headers['Content-Length'] = payload.length;
}
if (token) headers['X-Setup-Token'] = token;
if (cookie) headers.Cookie = cookie;
const port = Number(consoleBase.port || 443);
return new Promise((resolve, reject) => {
const request = https.request({
hostname: consoleConnectHost || consoleBase.hostname,
port,
path: new URL(pathname, consoleBase).pathname,
method,
servername: consoleBase.hostname,
rejectUnauthorized: true,
timeout: 30_000,
headers,
}, (response) => {
let text = '';
response.setEncoding('utf8');
response.on('data', (chunk) => {
text += chunk;
if (text.length > 2 * 1024 * 1024) request.destroy(new Error('console response exceeded 2 MB'));
});
response.on('end', () => {
let decoded;
try { decoded = text ? JSON.parse(text) : undefined; } catch { decoded = undefined; }
const accepted = expected ? expected.includes(response.statusCode) : response.statusCode >= 200 && response.statusCode < 300;
if (!accepted) return reject(new Error(`${method} ${pathname} failed: ${decoded?.error?.message || `HTTP ${response.statusCode}`}`));
resolve({ response, payload: decoded });
});
});
request.on('timeout', () => request.destroy(new Error('console request timed out')));
request.on('error', reject);
request.end(payload);
});
}
function sessionCookie(response) {
const value = response.headers['set-cookie']?.[0]?.split(';', 1)[0];
if (!value?.startsWith('sea_session=')) throw new Error('administrator login did not return a session cookie');
return value;
}
async function waitFor(pathname, predicate, attempts = 45) {
let lastError;
for (let attempt = 0; attempt < attempts; attempt += 1) {
try {
const result = await api(pathname);
if (predicate(result.payload)) return result.payload;
} catch (error) { lastError = error; }
await new Promise((resolve) => setTimeout(resolve, 1000));
}
throw lastError || new Error(`timed out waiting for ${pathname}`);
}
const suffix = Date.now().toString(36).slice(-7);
const databaseName = `sea_vh_${suffix}`.slice(0, 16);
const databasePassword = randomPassword();
const adminPassword = randomPassword();
let databaseID = 0;
let databaseCreated = false;
let setupCompleted = false;
try {
const environment = panelFileText(await panelForm('/files', { action: 'GetFileBody', path: '/etc/sea-vhost/sea-vhost.env' }));
const setupToken = environment.match(/^SEA_SETUP_TOKEN=(.+)$/m)?.[1]?.trim();
if (!setupToken || setupToken.length < 24) throw new Error('installed setup token is unavailable');
const databaseResult = 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 control database',
});
if (databaseResult?.status === false || databaseResult?.status === 'false') throw new Error('aaPanel rejected control database creation');
databaseID = Number(databaseResult.id);
databaseCreated = true;
await waitFor('/api/v1/setup/status', (payload) => payload?.required === true);
await api('/api/v1/setup/test-database', {
method: 'POST', token: setupToken,
body: { host: '127.0.0.1', port: 3306, name: databaseName, user: databaseName, password: databasePassword },
});
const panelCheck = await api('/api/v1/setup/test-panel', {
method: 'POST', token: setupToken,
body: { url: `http://127.0.0.1:${panelBridgePort}/`, apiKey: panelAPIKey, tlsInsecure: false },
});
await api('/api/v1/setup/install', {
method: 'POST', token: setupToken, expected: [201],
body: {
database: { host: '127.0.0.1', port: 3306, name: databaseName, user: databaseName, password: databasePassword },
panel: { url: `http://127.0.0.1:${panelBridgePort}/`, apiKey: panelAPIKey, tlsInsecure: false },
rootDomain, managementDomain, ftpDomain, domainApproval: true,
adminEmail, adminName, adminPassword,
},
});
setupCompleted = true;
await waitFor('/healthz', (payload) => payload?.status === 'ok');
const login = await api('/api/v1/auth/login', { method: 'POST', body: { identifier: adminEmail, password: adminPassword } });
const cookie = sessionCookie(login.response);
await api('/api/v1/dashboard', { cookie });
const setupStatus = await api('/api/v1/setup/status');
if (setupStatus.payload?.required !== false) throw new Error('setup endpoint still reports installation required');
console.log(JSON.stringify({
result: 'success', consoleURL: consoleBase.toString(), rootDomain, managementDomain, ftpDomain,
administrator: { login: adminEmail, password: adminPassword, name: adminName },
controlDatabase: databaseName,
panelRuntimes: panelCheck.payload?.runtimes,
}, null, 2));
} catch (error) {
if (!setupCompleted && databaseCreated && Number.isSafeInteger(databaseID) && databaseID > 0) {
try {
await panelForm('/database', { action: 'DeleteDatabase', id: String(databaseID), sid: '0', name: databaseName, db_user: databaseName });
} catch { /* best effort rollback */ }
}
console.error(`Sea vHost production setup failed: ${error instanceof Error ? error.message : 'unknown error'}`);
process.exitCode = 1;
}
+151
View File
@@ -0,0 +1,151 @@
import crypto from 'node:crypto';
import http from 'node:http';
import https from 'node:https';
// Read-only compatibility probe for aaPanel's built-in language project
// modules. It deliberately uses only the Files API and never prints secrets.
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) {
console.error('SEA_PANEL_URL and SEA_PANEL_API_KEY are required.');
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');
function panelForm(pathname, values, timeoutMs = 30_000) {
const requestTime = Math.floor(Date.now() / 1000).toString();
const requestToken = md5(requestTime + md5(panelAPIKey));
const body = Buffer.from(new URLSearchParams({ ...values, request_time: requestTime, request_token: requestToken }).toString());
const url = new URL(pathname, panelBase);
return new Promise((resolve, reject) => {
const request = panelClient.request(url, {
method: 'POST', agent: panelAgent, timeout: timeoutMs,
headers: { 'content-type': 'application/x-www-form-urlencoded', 'content-length': body.length },
}, (response) => {
let data = '';
response.setEncoding('utf8');
response.on('data', (chunk) => {
data += chunk;
if (data.length > 8 * 1024 * 1024) request.destroy(new Error('panel response exceeded 8 MB'));
});
response.on('end', () => {
if (response.statusCode < 200 || response.statusCode > 299) {
reject(new Error(`panel returned HTTP ${response.statusCode}`));
return;
}
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 fileText(payload) {
if (typeof payload === 'string') return payload;
for (const key of ['data', 'msg', 'content']) {
if (typeof payload?.[key] === 'string') return payload[key];
}
return '';
}
function directoryNames(payload) {
const rows = Array.isArray(payload) ? payload
: Array.isArray(payload?.files) ? payload.files
: Array.isArray(payload?.data) ? payload.data
: [...(Array.isArray(payload?.DIR) ? payload.DIR : []), ...(Array.isArray(payload?.FILES) ? payload.FILES : [])];
return rows.map((row) => {
const value = typeof row === 'string' ? row : row?.filename || row?.name || row?.path;
return typeof value === 'string' ? value.split(';', 1)[0] : value;
}).filter(Boolean);
}
const candidateDirectories = [
'/www/server/panel/class/projectModel',
'/www/server/panel/mod/project',
'/www/server/panel/mod/project/java',
'/www/server/panel/BTPanel',
];
const discovered = new Set();
for (const path of candidateDirectories) {
try {
const payload = await panelForm('/files', { action: 'GetDir', path });
const names = directoryNames(payload);
console.log(`${path}: ${names.length ? names.join(', ') : '(no recognized entries)'}`);
for (const name of names) {
if (/^(nodejs|python|go|java).*\.py$/i.test(name)) discovered.add(`${path}/${name}`);
}
} catch (error) {
console.log(`${path}: unavailable (${error.message})`);
}
}
const explicitFiles = [
'/www/server/panel/class/projectModel/nodejsModel.py',
'/www/server/panel/class/projectModel/pythonModel.py',
'/www/server/panel/class/projectModel/goModel.py',
'/www/server/panel/class/projectModel/javaModel.py',
'/www/server/panel/mod/project/nodejs.py',
'/www/server/panel/mod/project/python.py',
'/www/server/panel/mod/project/python/serviceMod.py',
'/www/server/panel/mod/project/go.py',
'/www/server/panel/mod/project/java/projectMod.py',
];
for (const file of explicitFiles) discovered.add(file);
const wantedFunctions = new Set((process.env.SEA_PROBE_FUNCTIONS || [
'create_project', 'start_project', 'stop_project', 'restart_project',
'remove_project', 'delete_project', 'get_project_list',
].join(',')).split(',').map((value) => value.trim()).filter(Boolean));
const linePattern = process.env.SEA_PROBE_MATCH ? new RegExp(process.env.SEA_PROBE_MATCH, 'i') : null;
for (const path of discovered) {
try {
const text = fileText(await panelForm('/files', { action: 'GetFileBody', path }));
if (!text) continue;
const lines = text.split(/\r?\n/);
const matches = [];
if (linePattern) {
for (let index = 0; index < lines.length; index += 1) {
if (linePattern.test(lines[index])) {
const start = Math.max(0, index - 2);
const end = Math.min(lines.length, index + 3);
matches.push(`L${start + 1}-${end}:\n${lines.slice(start, end).join('\n')}`);
}
}
}
for (let index = 0; index < lines.length; index += 1) {
const definition = lines[index].match(/^ def\s+([A-Za-z_][A-Za-z0-9_]*)\s*\(/);
if (!definition || !wantedFunctions.has(definition[1])) continue;
let end = index + 1;
while (end < lines.length && !/^ def\s+[A-Za-z_][A-Za-z0-9_]*\s*\(/.test(lines[end])) end += 1;
matches.push(`L${index + 1}-${end}:\n${lines.slice(index, end).join('\n')}`);
}
if (matches.length) {
console.log(`\n=== ${path} (${lines.length} lines, ${matches.length} functions) ===`);
console.log(matches.join('\n---\n'));
}
} catch {
// Missing candidates are expected across aaPanel versions.
}
}
if (process.env.SEA_PROBE_RUNTIME_LOGS === 'true') {
for (const path of ['/www/server/panel/logs/npm-exec.log']) {
try {
const lines = fileText(await panelForm('/files', { action: 'GetFileBody', path })).split(/\r?\n/);
console.log(`\n=== ${path} (last 120 lines) ===`);
console.log(lines.slice(-120).join('\n'));
} catch {
console.log(`\n=== ${path}: unavailable ===`);
}
}
}
+91
View File
@@ -0,0 +1,91 @@
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 base = new URL(panelURL);
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');
const suffix = `${new Date().toISOString().replaceAll(/[-:.TZ]/g, '').slice(0, 14)}-${crypto.randomBytes(3).toString('hex')}`;
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 = client.request(new URL(pathname, base), {
method: 'POST', agent, 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);
});
}
async function runShell(shell, marker) {
const task = await panelForm('/crontab', {
action: 'AddCrontab', name: `Sea vHost reinstall backup ${suffix}`, 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 pre-reinstall backup', save: '0', backupTo: 'localhost',
});
if (!task || (task.status !== true && task.status !== 'true')) throw new Error('panel rejected temporary backup task');
const taskID = Number(task.id);
if (!Number.isSafeInteger(taskID) || taskID <= 0) throw new Error('panel returned an invalid task id');
try {
await panelForm('/crontab', { action: 'StartTask', id: String(taskID) });
let lastLog = '';
for (let attempt = 0; attempt < 240; attempt += 1) {
await new Promise((resolve) => setTimeout(resolve, 1000));
const result = await panelForm('/crontab', { action: 'GetLogs', id: String(taskID) });
lastLog = typeof result?.msg === 'string' ? result.msg : typeof result === 'string' ? result : lastLog;
if (lastLog.includes(marker)) return lastLog;
}
throw new Error(`backup task did not complete: ${lastLog.trim()}`);
} finally {
try { await panelForm('/crontab', { action: 'DelCrontab', id: String(taskID) }); } catch { /* best effort */ }
}
}
const marker = `sea-vhost-reinstall-backup-complete-${suffix}`;
const shell = [
'set -Eeuo pipefail',
`backup_dir=/var/backups/sea-vhost/reinstall-${suffix}`,
'case "$backup_dir" in /var/backups/sea-vhost/reinstall-[0-9]*-[0-9a-f][0-9a-f][0-9a-f][0-9a-f][0-9a-f][0-9a-f]) ;; *) exit 1 ;; esac',
'test ! -e "$backup_dir"; install -d -o root -g root -m 0700 /var/backups/sea-vhost "$backup_dir"',
'test -f /var/lib/sea-vhost/config.json',
'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)"; [[ -x "$mysql_bin" ]] || mysql_bin=/www/server/mysql/bin/mysql; [[ -x "$dump_bin" ]] || dump_bin=/www/server/mysql/bin/mysqldump; test -x "$mysql_bin"; test -x "$dump_bin"',
'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" >"$backup_dir/control.sql"; test -s "$backup_dir/control.sql"; chmod 0600 "$backup_dir/control.sql"',
'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 host_name" >"$backup_dir/hosts.list"; chmod 0600 "$backup_dir/hosts.list"',
'tar --acls --xattrs --numeric-owner -cpf "$backup_dir/state.tar" -C / etc/sea-vhost var/lib/sea-vhost var/lib/sea-vhost-agent var/lib/sea-vhost-panel; chmod 0600 "$backup_dir/state.tar"',
'if [[ -s "$backup_dir/hosts.list" ]]; then while IFS= read -r host; do [[ "$host" =~ ^sv[0-9a-f]{10}$ ]]; test -d "/www/wwwroot/seavHost/vHost/$host"; done <"$backup_dir/hosts.list"; tar --acls --xattrs --numeric-owner -cpf "$backup_dir/hosts.tar" -C /www/wwwroot/seavHost/vHost --files-from="$backup_dir/hosts.list"; else tar -cpf "$backup_dir/hosts.tar" --files-from=/dev/null; fi; chmod 0600 "$backup_dir/hosts.tar"',
'if [[ -d /www/server/panel/vhost/nginx ]]; then tar --acls --xattrs --numeric-owner -cpf "$backup_dir/nginx-vhosts.tar" -C /www/server/panel/vhost nginx; else tar -cpf "$backup_dir/nginx-vhosts.tar" --files-from=/dev/null; fi; chmod 0600 "$backup_dir/nginx-vhosts.tar"',
'(cd "$backup_dir" && sha256sum control.sql hosts.list state.tar hosts.tar nginx-vhosts.tar >SHA256SUMS && sha256sum -c SHA256SUMS); chmod 0600 "$backup_dir/SHA256SUMS"',
'tree_hash="$(tar -cpf - -C "$(dirname "$backup_dir")" "$(basename "$backup_dir")" | sha256sum | awk \'{print $1}\')"',
'printf "backup_path=%s\\nbackup_tree_sha256=%s\\ncontrol_database=%s\\nmanaged_hosts=%s\\n" "$backup_dir" "$tree_hash" "$control_name" "$(wc -l <"$backup_dir/hosts.list")"',
`printf '%s\\n' '${marker}'`,
].join('\n');
const log = await runShell(shell, marker);
const backupPath = log.match(/(?:^|\n)backup_path=([^\r\n]+)/)?.[1];
const treeHash = log.match(/(?:^|\n)backup_tree_sha256=([0-9a-f]{64})/)?.[1];
const controlDatabase = log.match(/(?:^|\n)control_database=([^\r\n]+)/)?.[1];
const managedHosts = Number(log.match(/(?:^|\n)managed_hosts=(\d+)/)?.[1]);
if (!backupPath || !treeHash || !controlDatabase || !Number.isSafeInteger(managedHosts)) throw new Error('backup verification output was incomplete');
console.log(JSON.stringify({ status: 'passed', backupPath, treeHash, controlDatabase, managedHosts, checks: {
controlDatabaseDump: true, stateArchive: true, managedHostArchive: true, nginxConfigurationArchive: true, checksumsVerified: true,
} }, null, 2));
+238
View File
@@ -0,0 +1,238 @@
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 consoleURL = process.env.SEA_CONSOLE_URL?.trim();
const insecureTLS = process.env.SEA_PANEL_TLS_INSECURE === 'true';
if (!panelURL || !panelAPIKey || !consoleURL) process.exit(2);
const panelBase = new URL(panelURL);
const consoleBase = new URL(consoleURL);
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 email = `quota-${suffix}@seavhost.test`;
const password = `Sv-${crypto.randomBytes(18).toString('base64url')}8q`;
const planName = `Quota verification ${suffix}`;
const statePath = `/var/lib/sea-vhost/quota-verify-${suffix}.state`;
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: 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);
});
}
async function runShell(name, shell, marker, attempts = 120) {
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 quota 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 {
const execution = await panelForm('/crontab', { action: 'StartTask', id: String(taskID) });
if (execution?.status === false || execution?.status === 'false') throw new Error('panel did not start temporary task');
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) || log.includes('★[')) break;
}
if (!log.includes(marker)) throw new Error(`temporary task failed:\n${log.trim()}`);
return log;
} finally {
try { await panelForm('/crontab', { action: 'DelCrontab', id: String(taskID) }); } catch { /* best effort */ }
}
}
async function api(pathname, { method = 'GET', body, cookie, expected = [200] } = {}) {
const response = await fetch(new URL(pathname, consoleBase), {
method, redirect: 'manual', signal: AbortSignal.timeout(30_000),
headers: { Accept: 'application/json', ...(body === undefined ? {} : { 'Content-Type': 'application/json' }), ...(cookie ? { Cookie: cookie } : {}) },
body: body === undefined ? undefined : JSON.stringify(body),
});
const text = await response.text();
let payload;
try { payload = text ? JSON.parse(text) : undefined; } catch { payload = undefined; }
if (!expected.includes(response.status)) throw new Error(`${method} ${pathname} returned HTTP ${response.status}: ${text.slice(0, 160)}`);
return { response, payload };
}
function cookieFrom(response) {
const header = typeof response.headers.getSetCookie === 'function' ? response.headers.getSetCookie()[0] : response.headers.get('set-cookie');
return header?.split(';', 1)[0];
}
const dbParts = [
'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)"; if [[ -z "$mysql_bin" && -x /www/server/mysql/bin/mysql ]]; then mysql_bin=/www/server/mysql/bin/mysql; fi',
].join('\n');
const seedMarker = `quota-seeded-${suffix}`;
const seedShell = [
'set -Eeuo pipefail', `email=${q(email)}`, `password=${q(password)}`, `plan_name=${q(planName)}`, `state_path=${q(statePath)}`,
'php_bin="$(find /www/server/php -mindepth 3 -maxdepth 4 -type f -path \'*/bin/php\' -print -quit)"; password_hash="$(TEST_PASSWORD="$password" "$php_bin" -r \'echo password_hash(getenv("TEST_PASSWORD"), PASSWORD_BCRYPT);\')"',
dbParts,
'MYSQL_PWD="$control_password" "$mysql_bin" --protocol=TCP --host="$control_host" --port="$control_port" --user="$control_user" --database="$control_name" --execute="DELETE FROM users WHERE email=\'$email\'; INSERT INTO users(tenant_id,email,login_name,display_name,password_hash,role,status) SELECT tenant_id,\'$email\',\'$email\',\'Quota verification\',\'$password_hash\',\'tenant\',\'active\' FROM projects ORDER BY id LIMIT 1;"',
'read -r tenant_id original_plan_id project_root < <(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 p.tenant_id,t.plan_id,p.root_path FROM projects p JOIN tenants t ON t.id=p.tenant_id ORDER BY p.id LIMIT 1")',
'case "$project_root" in /www/wwwroot/seavHost/vHost/sv??????????) ;; *) exit 1 ;; esac; host_name="${project_root##*/}"',
'MYSQL_PWD="$control_password" "$mysql_bin" --protocol=TCP --host="$control_host" --port="$control_port" --user="$control_user" --database="$control_name" --execute="INSERT INTO plans(name,storage_bytes,database_bytes,monthly_bandwidth_bytes,process_limit,ftp_limit,database_limit,project_limit) SELECT \'$plan_name\',1099511627776,1099511627776,1099511627776,100000,ftp_limit,database_limit,project_limit FROM plans WHERE id=$original_plan_id; SET @test_plan_id=LAST_INSERT_ID(); UPDATE tenants SET plan_id=@test_plan_id WHERE id=$tenant_id;"',
'temp_plan_id="$(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 id FROM plans WHERE name=\'$plan_name\'")"; test -n "$temp_plan_id"',
'printf "%s %s %s %s %s\\n" "$tenant_id" "$original_plan_id" "$temp_plan_id" "$project_root" "$host_name" | install -o root -g root -m 0600 /dev/stdin "$state_path"',
`printf '%s\n' ${q(seedMarker)}`,
].join('\n');
function planShell(bandwidth, processes, marker) {
return [
'set -euo pipefail', `state_path=${q(statePath)}`, dbParts,
'read -r tenant_id original_plan_id temp_plan_id project_root host_name <"$state_path"',
`MYSQL_PWD="$control_password" "$mysql_bin" --protocol=TCP --host="$control_host" --port="$control_port" --user="$control_user" --database="$control_name" --execute="UPDATE plans SET monthly_bandwidth_bytes=${bandwidth},process_limit=${processes} WHERE id=$temp_plan_id;"`,
`printf '%s\n' ${q(marker)}`,
].join('\n');
}
const cleanupMarker = `quota-cleaned-${suffix}`;
const cleanupShell = [
'set -euo pipefail', `email=${q(email)}`, `state_path=${q(statePath)}`, dbParts,
'if [[ -f "$state_path" ]]; then read -r tenant_id original_plan_id temp_plan_id project_root host_name <"$state_path"; pkill -u "$host_name" -f "sleep 180" 2>/dev/null || true; MYSQL_PWD="$control_password" "$mysql_bin" --protocol=TCP --host="$control_host" --port="$control_port" --user="$control_user" --database="$control_name" --execute="UPDATE tenants SET plan_id=$original_plan_id WHERE id=$tenant_id AND plan_id=$temp_plan_id; DELETE FROM plans WHERE id=$temp_plan_id;"; rm -f -- "$state_path"; fi',
'MYSQL_PWD="$control_password" "$mysql_bin" --protocol=TCP --host="$control_host" --port="$control_port" --user="$control_user" --database="$control_name" --execute="DELETE FROM users WHERE email=\'$email\';"',
`printf '%s\n' ${q(cleanupMarker)}`,
].join('\n');
async function sendSiteRequest(domain) {
return new Promise((resolve, reject) => {
const client = consoleBase.protocol === 'https:' ? https : http;
const request = client.request(consoleBase, { method: 'GET', timeout: 10_000, headers: { Host: domain, Connection: 'close' } }, (response) => {
let bytes = 0;
response.on('data', (chunk) => { bytes += chunk.length; });
response.on('end', () => resolve({ status: response.statusCode, bytes }));
});
request.on('timeout', () => request.destroy(new Error('site request timed out')));
request.on('error', reject);
request.end();
});
}
async function currentProject(cookie, projectID) {
const result = await api('/api/v1/projects', { cookie });
return result.payload?.projects?.find((item) => item.id === projectID);
}
async function waitForStatus(cookie, projectID, status, attempts = 30) {
let project;
for (let attempt = 0; attempt < attempts; attempt += 1) {
await new Promise((resolve) => setTimeout(resolve, 5000));
project = await currentProject(cookie, projectID);
if (project?.status === status) return project;
}
throw new Error(`project did not reach ${status}; status=${project?.status}`);
}
let seeded = false;
let cookie;
let project;
let initiallyRunning = false;
try {
await runShell(`Sea vHost quota seed ${suffix}`, seedShell, seedMarker);
seeded = true;
const login = await api('/api/v1/auth/login', { method: 'POST', body: { identifier: email, password } });
cookie = cookieFrom(login.response);
project = (await api('/api/v1/projects', { cookie })).payload?.projects?.[0];
if (!project?.id || !project?.domain) throw new Error('temporary tenant has no project');
initiallyRunning = project.status === 'running';
if (!initiallyRunning) await api(`/api/v1/projects/${project.id}/state`, { method: 'POST', cookie, expected: [204], body: { enabled: true } });
const lowBandwidthMarker = `quota-bandwidth-low-${suffix}`;
await runShell(`Sea vHost bandwidth limit ${suffix}`, planShell(1, 100000, lowBandwidthMarker), lowBandwidthMarker);
let deliveredBytes = 0;
for (let index = 0; index < 3; index += 1) deliveredBytes += (await sendSiteRequest(project.domain)).bytes;
const bandwidthSuspended = await waitForStatus(cookie, project.id, 'quota_suspended');
const bandwidthDashboard = await api('/api/v1/dashboard', { cookie });
if (bandwidthDashboard.payload?.usage?.bandwidthBytes < 1) throw new Error('bandwidth quota usage was not measured');
if (!String(bandwidthSuspended.lastError ?? '').includes('bandwidth') && bandwidthSuspended.status !== 'quota_suspended') throw new Error('bandwidth suspension reason missing');
const highMarker = `quota-bandwidth-recover-${suffix}`;
await runShell(`Sea vHost bandwidth recover ${suffix}`, planShell(1099511627776, 100000, highMarker), highMarker);
await waitForStatus(cookie, project.id, 'stopped');
await api(`/api/v1/projects/${project.id}/state`, { method: 'POST', cookie, expected: [204], body: { enabled: true } });
const processMarker = `quota-processes-${suffix}`;
const processShell = [
'set -euo pipefail', `state_path=${q(statePath)}`, dbParts,
'read -r tenant_id original_plan_id temp_plan_id project_root host_name <"$state_path"',
'MYSQL_PWD="$control_password" "$mysql_bin" --protocol=TCP --host="$control_host" --port="$control_port" --user="$control_user" --database="$control_name" --execute="UPDATE plans SET monthly_bandwidth_bytes=1099511627776,process_limit=1 WHERE id=$temp_plan_id;"',
'for _ in 1 2 3; do setsid -f runuser -u "$host_name" -- sleep 180; done; sleep 1; test "$(pgrep -u "$host_name" | wc -l)" -gt 1',
`printf '%s\n' ${q(processMarker)}`,
].join('\n');
await runShell(`Sea vHost process limit ${suffix}`, processShell, processMarker);
await waitForStatus(cookie, project.id, 'quota_suspended');
const processDashboard = await api('/api/v1/dashboard', { cookie });
if (processDashboard.payload?.usage?.processCount <= 1) throw new Error('process quota usage was not measured');
const killedMarker = `quota-process-killed-${suffix}`;
const killedShell = [
'set -euo pipefail', `state_path=${q(statePath)}`, 'read -r tenant_id original_plan_id temp_plan_id project_root host_name <"$state_path"',
'if pgrep -u "$host_name" -f "sleep 180" >/dev/null; then exit 1; fi', `printf '%s\n' ${q(killedMarker)}`,
].join('\n');
await runShell(`Sea vHost process kill verify ${suffix}`, killedShell, killedMarker);
const processRecoverMarker = `quota-process-recover-${suffix}`;
await runShell(`Sea vHost process recover ${suffix}`, planShell(1099511627776, 100000, processRecoverMarker), processRecoverMarker);
await waitForStatus(cookie, project.id, 'stopped');
await api(`/api/v1/projects/${project.id}/state`, { method: 'POST', cookie, expected: [204], body: { enabled: true } });
console.log(JSON.stringify({ status: 'passed', checks: {
bandwidthTrafficReachedSite: deliveredBytes > 0,
bandwidthUsageMeasured: true,
bandwidthQuotaSuspendedProject: true,
bandwidthQuotaRecoveredToStopped: true,
processUsageMeasured: true,
processQuotaSuspendedProject: true,
excessProcessesTerminated: true,
processQuotaRecoveredToStopped: true,
manualRestartAfterRecovery: true,
}, observedDeliveredBodyBytes: deliveredBytes,
observedBandwidthBytes: bandwidthDashboard.payload.usage.bandwidthBytes,
observedProcessCount: processDashboard.payload.usage.processCount }, null, 2));
} finally {
if (cookie && project?.id) {
try {
const current = await currentProject(cookie, project.id);
if (current?.status === 'quota_suspended') {
const marker = `quota-final-recover-${suffix}`;
await runShell(`Sea vHost quota final recover ${suffix}`, planShell(1099511627776, 100000, marker), marker, 60);
await waitForStatus(cookie, project.id, 'stopped', 24);
}
if (initiallyRunning && (await currentProject(cookie, project.id))?.status !== 'running') {
await api(`/api/v1/projects/${project.id}/state`, { method: 'POST', cookie, expected: [204], body: { enabled: true } });
}
} catch { process.exitCode = 1; }
}
if (seeded) {
try { await runShell(`Sea vHost quota cleanup ${suffix}`, cleanupShell, cleanupMarker, 90); } catch { process.exitCode = 1; }
}
}
+188
View File
@@ -0,0 +1,188 @@
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 consoleURL = process.env.SEA_CONSOLE_URL?.trim();
const insecureTLS = process.env.SEA_PANEL_TLS_INSECURE === 'true';
if (!panelURL || !panelAPIKey || !consoleURL) process.exit(2);
const panelBase = new URL(panelURL);
const consoleBase = new URL(consoleURL);
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 email = `run-path-${suffix}@seavhost.test`;
const password = `Sv-${crypto.randomBytes(18).toString('base64url')}6p`;
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: 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);
});
}
async function runShell(name, shell, marker, attempts = 120) {
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 run-path 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 */ }
}
}
async function api(pathname, { method = 'GET', body, cookie, expected } = {}) {
const response = await fetch(new URL(pathname, consoleBase), {
method, redirect: 'manual', signal: AbortSignal.timeout(90_000),
headers: { Accept: 'application/json', ...(body === undefined ? {} : { 'Content-Type': 'application/json' }), ...(cookie ? { Cookie: cookie } : {}) },
body: body === undefined ? undefined : JSON.stringify(body),
});
const text = await response.text();
let payload;
try { payload = text ? JSON.parse(text) : undefined; } catch { payload = undefined; }
const accepted = expected ?? [...Array(100).keys()].map((value) => value + 200);
if (!accepted.includes(response.status)) throw new Error(`${method} ${pathname} returned HTTP ${response.status}: ${payload?.error?.message ?? text.slice(0, 160)}`);
return { response, payload };
}
function sessionCookie(response) {
const header = typeof response.headers.getSetCookie === 'function' ? response.headers.getSetCookie()[0] : response.headers.get('set-cookie');
const cookie = header?.split(';', 1)[0];
if (!cookie?.startsWith('sea_session=')) throw new Error('tenant login did not return a session cookie');
return cookie;
}
const dbParts = [
'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)"; if [[ -z "$mysql_bin" && -x /www/server/mysql/bin/mysql ]]; then mysql_bin=/www/server/mysql/bin/mysql; fi',
].join('\n');
const seedMarker = `run-path-seeded-${suffix}`;
const seedShell = [
'set -euo pipefail', `email=${q(email)}`, `password=${q(password)}`,
'php_bin="$(find /www/server/php -mindepth 3 -maxdepth 4 -type f -path \'*/bin/php\' -print -quit)"; password_hash="$(TEST_PASSWORD="$password" "$php_bin" -r \'echo password_hash(getenv("TEST_PASSWORD"), PASSWORD_BCRYPT);\')"',
dbParts,
'MYSQL_PWD="$control_password" "$mysql_bin" --protocol=TCP --host="$control_host" --port="$control_port" --user="$control_user" --database="$control_name" --execute="DELETE FROM users WHERE email=\'$email\'; INSERT INTO users(tenant_id,email,login_name,display_name,password_hash,role,status) SELECT tenant_id,\'$email\',\'$email\',\'Run path verification\',\'$password_hash\',\'tenant\',\'active\' FROM projects ORDER BY id LIMIT 1;"',
`printf '%s\n' ${q(seedMarker)}`,
].join('\n');
const cleanupMarker = `run-path-cleaned-${suffix}`;
const cleanupShell = [
'set -euo pipefail', `email=${q(email)}`, dbParts,
'MYSQL_PWD="$control_password" "$mysql_bin" --protocol=TCP --host="$control_host" --port="$control_port" --user="$control_user" --database="$control_name" --execute="DELETE FROM users WHERE email=\'$email\';"',
`printf '%s\n' ${q(cleanupMarker)}`,
].join('\n');
const cases = [
{ name: `dist-${suffix}`, runPath: `/dist-${suffix}`, marker: `sea-vhost-dist-${suffix}` },
{ name: `nested-${suffix}`, runPath: `/apps-${suffix}/web/public`, marker: `sea-vhost-nested-${suffix}` },
];
let seeded = false;
let cookie;
let project;
try {
await runShell(`Sea vHost run path seed ${suffix}`, seedShell, seedMarker);
seeded = true;
const login = await api('/api/v1/auth/login', { method: 'POST', body: { identifier: email, password }, expected: [200] });
cookie = sessionCookie(login.response);
project = (await api('/api/v1/projects', { cookie, expected: [200] })).payload?.projects?.[0];
if (!project?.id || !project?.path) throw new Error('temporary tenant has no project');
const catalog = await api('/api/v1/runtime-catalog', { cookie, expected: [200] });
const phpVersion = catalog.payload?.versions?.PHP?.[0];
if (!phpVersion) throw new Error('PHP is not installed');
for (const item of cases) {
const created = await api(`/api/v1/projects/${project.id}/sites`, {
method: 'POST', cookie, expected: [201],
body: { name: item.name, runtime: 'PHP', version: phpVersion, runPath: item.runPath, customDomain: '', autoSSL: false },
});
item.site = created.payload?.site;
if (!item.site?.id || item.site.status !== 'running' || item.site.runPath !== item.runPath) throw new Error(`site creation failed for ${item.runPath}`);
await api(`/api/v1/projects/${project.id}/files`, {
method: 'PUT', cookie, expected: [204],
body: { path: `${item.runPath.slice(1)}/index.php`, content: `<?php header('Content-Type: text/plain'); echo '${item.marker}';`, overwrite: false },
});
const blocked = await api(`/api/v1/projects/${project.id}/files?path=${encodeURIComponent(item.runPath.slice(1))}`, { method: 'DELETE', cookie, expected: [409] });
if (!String(blocked.payload?.error?.message ?? '').includes('网站')) throw new Error('active run-path deletion was not explicitly blocked');
const liveMarker = `run-path-live-${suffix}-${item.name}`;
await runShell(`Sea vHost run path live ${item.name}`, [
'set -euo pipefail', `domain=${q(item.site.domain)}`, `project_path=${q(project.path)}`, `run_path=${q(item.runPath)}`, `body_marker=${q(item.marker)}`,
'test -d "$project_path$run_path"; test ! -L "$project_path$run_path"',
'grep -Fq "root $project_path$run_path;" "/www/server/panel/vhost/nginx/$domain.conf"',
'test "$(curl --silent --show-error --fail --max-time 10 --header "Host: $domain" http://127.0.0.1/)" = "$body_marker"',
`printf '%s\n' ${q(liveMarker)}`,
].join('\n'), liveMarker);
}
for (const item of cases) {
await api(`/api/v1/projects/${project.id}/sites/${item.site.id}`, { method: 'DELETE', cookie, expected: [204] });
const retainedMarker = `run-path-retained-${suffix}-${item.name}`;
await runShell(`Sea vHost run path retained ${item.name}`, [
'set -euo pipefail', `domain=${q(item.site.domain)}`, `file=${q(`${project.path}${item.runPath}/index.php`)}`,
'test -f "$file"; test ! -e "/www/server/panel/vhost/nginx/$domain.conf"',
`printf '%s\n' ${q(retainedMarker)}`,
].join('\n'), retainedMarker);
item.site = undefined;
await api(`/api/v1/projects/${project.id}/files?path=${encodeURIComponent(item.runPath.slice(1))}`, { method: 'DELETE', cookie, expected: [204] });
}
await api(`/api/v1/projects/${project.id}/files?emptyTrash=1`, { method: 'DELETE', cookie, expected: [204] });
const cleanMarker = `run-path-files-clean-${suffix}`;
await runShell(`Sea vHost run path clean ${suffix}`, [
'set -euo pipefail', ...cases.map((item) => `test ! -e ${q(`${project.path}${item.runPath}`)}`),
`printf '%s\n' ${q(cleanMarker)}`,
].join('\n'), cleanMarker);
console.log(JSON.stringify({ status: 'passed', phpVersion, runPaths: cases.map((item) => item.runPath), checks: {
runDirectoriesCreated: true,
exactNginxDocumentRoots: true,
phpServedFromBothPaths: true,
activeRunPathDeletionBlocked: true,
siteDeletionRetainedTenantFiles: true,
explicitTenantCleanupRemovedFiles: true,
} }, null, 2));
} finally {
if (cookie && project?.id) {
for (const item of cases) {
if (item.site?.id) {
try { await api(`/api/v1/projects/${project.id}/sites/${item.site.id}`, { method: 'DELETE', cookie, expected: [204, 404, 422] }); } catch { /* best effort */ }
}
try { await api(`/api/v1/projects/${project.id}/files?path=${encodeURIComponent(item.runPath.slice(1))}`, { method: 'DELETE', cookie, expected: [204, 404, 409, 422] }); } catch { /* best effort */ }
}
try { await api(`/api/v1/projects/${project.id}/files?emptyTrash=1`, { method: 'DELETE', cookie, expected: [204, 404, 422] }); } catch { /* best effort */ }
}
if (seeded) {
try { await runShell(`Sea vHost run path cleanup ${suffix}`, cleanupShell, cleanupMarker); } catch { process.exitCode = 1; }
}
}
+141
View File
@@ -0,0 +1,141 @@
import crypto from 'node:crypto';
import { readFile } from 'node:fs/promises';
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 taskFile = process.env.SEA_PANEL_TASK_FILE?.trim();
const taskLabel = process.env.SEA_PANEL_TASK_NAME?.trim() || 'Sea vHost administrative task';
const taskEnvironmentJSON = process.env.SEA_PANEL_TASK_ENV_JSON?.trim() || '{}';
const taskTimeoutMinutes = Number(process.env.SEA_PANEL_TASK_TIMEOUT_MINUTES?.trim() || '10');
const insecureTLS = process.env.SEA_PANEL_TLS_INSECURE === 'true';
if (!panelURL || !panelAPIKey || !taskFile) {
console.error('SEA_PANEL_URL, SEA_PANEL_API_KEY and SEA_PANEL_TASK_FILE are required.');
process.exit(2);
}
if (!Number.isSafeInteger(taskTimeoutMinutes) || taskTimeoutMinutes < 1 || taskTimeoutMinutes > 120) {
console.error('SEA_PANEL_TASK_TIMEOUT_MINUTES must be an integer from 1 to 120.');
process.exit(2);
}
if (taskLabel.length > 80 || /[\r\n]/.test(taskLabel)) {
console.error('SEA_PANEL_TASK_NAME must be a single line of at most 80 characters.');
process.exit(2);
}
const base = new URL(panelURL);
if (!['http:', 'https:'].includes(base.protocol) || base.username || base.password) {
console.error('SEA_PANEL_URL must be an HTTP(S) URL without embedded credentials.');
process.exit(2);
}
const shell = await readFile(taskFile, 'utf8');
if (!shell.trim() || shell.length > 512 * 1024 || shell.includes('\0')) {
console.error('The task file must contain 1 byte to 512 KiB of shell text without NUL bytes.');
process.exit(2);
}
let taskEnvironment;
try {
taskEnvironment = JSON.parse(taskEnvironmentJSON);
} catch {
console.error('SEA_PANEL_TASK_ENV_JSON must be a JSON object.');
process.exit(2);
}
if (!taskEnvironment || Array.isArray(taskEnvironment) || typeof taskEnvironment !== 'object') {
console.error('SEA_PANEL_TASK_ENV_JSON must be a JSON object.');
process.exit(2);
}
const shellQuote = (value) => `'${String(value).replaceAll("'", "'\\''")}'`;
const environmentLines = [];
for (const [name, value] of Object.entries(taskEnvironment)) {
if (!/^SEA_[A-Z0-9_]{1,80}$/.test(name) || typeof value !== 'string' || value.length > 4096 || value.includes('\0')) {
console.error('Task environment names must start with SEA_ and contain short string values.');
process.exit(2);
}
environmentLines.push(`export ${name}=${shellQuote(value)}`);
}
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(panelAPIKey)) };
}
function panelFormOnce(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;
if (data.length > 4 * 1024 * 1024) request.destroy(new Error('panel response exceeded 4 MB'));
});
response.on('end', () => {
if (response.statusCode < 200 || response.statusCode > 299) {
reject(new Error(`panel returned HTTP ${response.statusCode}`));
return;
}
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);
});
}
async function panelForm(pathname,values){
for(let attempt=0;attempt<3;attempt++){
try{return await panelFormOnce(pathname,values)}catch(error){
if(attempt===2||!String(error.message).includes('before secure TLS connection was established'))throw error;
await new Promise(resolve=>setTimeout(resolve,1000*(attempt+1)));
}
}
}
function requireSuccess(payload, operation) {
if (payload === true || payload === 'true') return payload;
if (!payload || (payload.status !== true && payload.status !== 'true')) {
const reason=String(payload?.msg||payload?.message||"未提供原因").replaceAll(panelAPIKey,"[REDACTED]").slice(0,320); throw new Error(`${operation} was rejected by aaPanel: ${reason}`);
}
return payload;
}
const marker = `sea-vhost-task-complete-${crypto.randomBytes(12).toString('hex')}`;
const taskName = `${taskLabel} ${Date.now().toString().slice(-7)}`;
const body = `set +e\n(\n${environmentLines.join('\n')}\n${shell.trimEnd()}\n)\nsea_task_status=$?\nprintf '%s:%s\\n' '${marker}' "$sea_task_status"\nexit "$sea_task_status"\n`;
// These jobs are explicitly started once and removed in finally. Schedule the
// dormant cron date at least several days away so a long installer is not
// launched again every minute while its first execution is still running.
const dormantDay = String((new Date().getUTCDate() + 6) % 28 + 1);
let taskID;
try {
const task = requireSuccess(await panelForm('/crontab', {
action: 'AddCrontab', name: taskName, type: 'month', where1: dormantDay, where_hour: '0', where_minute: '0',
user: 'root', urladdress: 'http://', save_local: '0', sType: 'toShell', sBody: body,
sName: 'Temporary Sea vHost administrative task', save: '0', backupTo: 'localhost',
}), 'temporary task creation');
taskID = Number(task.id);
if (!Number.isSafeInteger(taskID) || taskID <= 0) throw new Error('aaPanel returned an invalid task id');
requireSuccess(await panelForm('/crontab', { action: 'StartTask', id: String(taskID) }), 'temporary task execution');
let log = '';
const deadline = Date.now() + taskTimeoutMinutes * 60_000;
while (Date.now() < deadline) {
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 + ':')) break;
}
if (!log.includes(marker + ':')) throw new Error(`the remote task did not complete within ${taskTimeoutMinutes} minutes`);
const statusMatch = log.match(new RegExp(`${marker}:(\\d+)`));
const cleanedLog = log.replace(new RegExp(`${marker}:\\d+`), '').trim();
if (cleanedLog) console.log(cleanedLog);
if (!statusMatch || statusMatch[1] !== '0') throw new Error(`the remote task failed with status ${statusMatch?.[1] ?? 'unknown'}`);
} finally {
if (taskID) {
try { await panelForm('/crontab', { action: 'DelCrontab', id: String(taskID) }); } catch { /* best effort */ }
}
}
+75
View File
@@ -0,0 +1,75 @@
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 base = new URL(panelURL);
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 panelForm(pathname, values) {
const requestTime = Math.floor(Date.now() / 1000).toString();
const body = Buffer.from(new URLSearchParams({ ...values, request_time: requestTime, request_token: md5(requestTime + md5(panelAPIKey)) }).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);
});
}
const marker = `runtime-diagnose-${Date.now()}`;
const shell = [
'set -eo pipefail',
"printf '%s\\n' '=== runtime directories ==='",
"stat -Lc '%A %a %U:%G %n' /www/server/nodejs/vhost /www/server/nodejs/vhost/pids /www/server/nodejs/vhost/scripts /www/server/python_project /www/server/go_project /www/server/java_project 2>&1 || true",
"find /www/server/nodejs/vhost/pids /www/server/nodejs/vhost/scripts -maxdepth 1 -type f -name 'sv*' -printf '%M %u:%g %p\\n' 2>/dev/null | tail -n 30 || true",
"printf '%s\\n' '=== host processes ==='",
"for host_dir in /www/wwwroot/seavHost/vHost/sv??????????; do test -d \"$host_dir\" || continue; host_name=\"${host_dir##*/}\"; ps -u \"$host_name\" -o user:16,pid,ppid,etimes,args --no-headers || true; done",
"printf '%s\\n' '=== backend listeners ==='",
"ss -lntp | grep -E ':(20[0-9]{3}|3[0-9]{4})\\b' || true",
"printf '%s\\n' '=== control-plane non-PHP sites ==='",
"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()))')",
"mysql_bin=\"$(command -v mysql || true)\"; if [[ -z \"$mysql_bin\" && -x /www/server/mysql/bin/mysql ]]; then mysql_bin=/www/server/mysql/bin/mysql; fi",
"MYSQL_PWD=\"${control_db[1]}\" \"$mysql_bin\" --protocol=TCP --host=\"${control_db[2]}\" --port=\"${control_db[3]}\" --user=\"${control_db[0]}\" --database=\"${control_db[4]}\" --batch --skip-column-names --execute=\"SELECT id,project_id,runtime,status,backend_port,run_path,assigned_domain FROM sites WHERE runtime<>'PHP' ORDER BY id\" || true",
"printf '%s\\n' '=== broker runtime registry ==='",
"python3 -c 'import json; d=json.load(open(\"/var/lib/sea-vhost-panel/resources.json\")); print([(k,(v.get(\"runtime\") or {}).get(\"ProjectName\"),(v.get(\"runtime\") or {}).get(\"Runtime\")) for k,v in d.get(\"sites\",{}).items() if v.get(\"runtime\")])' 2>/dev/null || true",
"printf '%s\\n' '=== recent broker messages ==='",
"journalctl -u sea-vhost-panel-broker -n 10 --no-pager -o cat | tail -n 10 || true",
"printf '%s\\n' '=== PHP identity state ==='",
"stat -Lc '%A %a %U:%G %n' /var/lib/sea-vhost-agent /var/lib/sea-vhost-agent/php /run/sea-vhost-php /run/sea-vhost-php/* 2>&1 || true",
"find /var/lib/sea-vhost-agent/php /run/sea-vhost-php -maxdepth 2 -printf '%M %u:%g %p\\n' 2>/dev/null | tail -n 80 || true",
"for path in /www/wwwroot/seavHost/vHost/sv??????????/.sea-runtime/php; do test -e \"$path\" || continue; namei -l \"$path/fpm-error.log\" || true; getfacl -p \"$(dirname \"$path\")\" \"$path\" 2>/dev/null || true; done",
"printf '%s\\n' '=== recent isolation-agent messages ==='",
"journalctl -u sea-vhost-agent -n 25 --no-pager -o cat | tail -n 25 || true",
`printf '%s\n' '${marker}'`,
].join('\n');
const task = await panelForm('/crontab', { action: 'AddCrontab', name: `Sea vHost runtime diagnose ${Date.now().toString().slice(-7)}`, 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 runtime diagnostics', save: '0', backupTo: 'localhost' });
const taskID = Number(task?.id);
if ((task?.status !== true && task?.status !== 'true') || !Number.isSafeInteger(taskID)) throw new Error('panel rejected diagnostics task');
try {
await panelForm('/crontab', { action: 'StartTask', id: String(taskID) });
let log = '';
for (let attempt = 0; attempt < 90; 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)) break;
}
if (!log.includes(marker)) throw new Error('diagnostics did not complete');
console.log(log.trim());
} finally {
try { await panelForm('/crontab', { action: 'DelCrontab', id: String(taskID) }); } catch { /* best effort */ }
}
+62
View File
@@ -0,0 +1,62 @@
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 base = new URL(panelURL);
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 panelForm(pathname, values = {}) {
const requestTime = Math.floor(Date.now() / 1000).toString();
const body = Buffer.from(new URLSearchParams({ ...values, request_time: requestTime, request_token: md5(requestTime + md5(panelAPIKey)) }).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 rows(payload) {
if (Array.isArray(payload)) return payload;
if (Array.isArray(payload?.data)) return payload.data;
if (Array.isArray(payload?.data?.data)) return payload.data.data;
return [];
}
const routes = {
'Node.js': '/project/nodejs/get_project_list/stype',
Python: '/project/python/GetProjectList/stype',
Go: '/project/go/get_project_list/stype',
Java: '/mod/java/project/project_list/stype',
};
const inventory = {};
for (const [runtime, route] of Object.entries(routes)) {
const payload = await panelForm(route, { search: 'sv', p: '1', limit: '100' });
inventory[runtime] = rows(payload).map((item) => ({
name: item.name ?? item.project_name,
path: item.path ?? item.project_cwd ?? item.project_path,
port: item.port,
run: item.run,
listenOK: item.listen_ok,
pid: item.pid,
listen: item.listen,
})).filter((item) => /^sv[0-9a-f]{10}(?:_[0-9]+)?$/.test(item.name ?? ''));
}
console.log(JSON.stringify(inventory, null, 2));
+146
View File
@@ -0,0 +1,146 @@
import crypto from 'node:crypto';
import http from 'node:http';
import https from 'node:https';
import path from 'node:path';
import { spawnSync } from 'node:child_process';
import { fileURLToPath } from 'node:url';
const panelURL = process.env.SEA_PANEL_URL?.trim();
const panelAPIKey = process.env.SEA_PANEL_API_KEY?.trim();
const consoleURL = process.env.SEA_CONSOLE_URL?.trim();
const insecureTLS = process.env.SEA_PANEL_TLS_INSECURE === 'true';
if (!panelURL || !panelAPIKey || !consoleURL) 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 email = `runtime-${suffix}@seavhost.test`;
const password = `Sv-${crypto.randomBytes(18).toString('base64url')}4r`;
const scriptDirectory = path.dirname(fileURLToPath(import.meta.url));
const workspace = path.dirname(scriptDirectory);
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: 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);
});
}
async function runShell(name, shell, marker) {
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 runtime suite account', 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 < 90; 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;
}
throw new Error(`temporary task failed: ${log.trim()}`);
} finally {
try { await panelForm('/crontab', { action: 'DelCrontab', id: String(taskID) }); } catch { /* best effort */ }
}
}
const dbParts = [
'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)"; if [[ -z "$mysql_bin" && -x /www/server/mysql/bin/mysql ]]; then mysql_bin=/www/server/mysql/bin/mysql; fi',
].join('\n');
const seedMarker = `runtime-seeded-${suffix}`;
const seedShell = [
'set -euo pipefail', `email=${q(email)}`, `password=${q(password)}`,
'php_bin="$(find /www/server/php -mindepth 3 -maxdepth 4 -type f -path \'*/bin/php\' -print -quit)"; password_hash="$(TEST_PASSWORD="$password" "$php_bin" -r \'echo password_hash(getenv("TEST_PASSWORD"), PASSWORD_BCRYPT);\')"',
dbParts,
'MYSQL_PWD="$control_password" "$mysql_bin" --protocol=TCP --host="$control_host" --port="$control_port" --user="$control_user" --database="$control_name" --execute="DELETE FROM users WHERE email=\'$email\'; INSERT INTO users(tenant_id,email,login_name,display_name,password_hash,role,status) SELECT tenant_id,\'$email\',\'$email\',\'Runtime verification\',\'$password_hash\',\'tenant\',\'active\' FROM projects ORDER BY id LIMIT 1;"',
`printf '%s\n' ${q(seedMarker)}`,
].join('\n');
const cleanupMarker = `runtime-cleaned-${suffix}`;
const cleanupShell = [
'set -euo pipefail', `email=${q(email)}`, dbParts,
'MYSQL_PWD="$control_password" "$mysql_bin" --protocol=TCP --host="$control_host" --port="$control_port" --user="$control_user" --database="$control_name" --execute="DELETE FROM users WHERE email=\'$email\';"',
`printf '%s\n' ${q(cleanupMarker)}`,
].join('\n');
const artifacts = {
Go: path.join(workspace, 'build', 'smoke', 'sea-vhost-go-smoke'),
Java: path.join(workspace, 'build', 'smoke', 'sea-vhost-java-smoke.jar'),
};
const requestedRuntimes = process.env.SEA_RUNTIMES?.split(',').map((value) => value.trim()).filter(Boolean) ?? ['Node.js', 'Python', 'Go', 'Java'];
if (requestedRuntimes.length === 0 || requestedRuntimes.some((runtime) => !['Node.js', 'Python', 'Go', 'Java'].includes(runtime))) {
throw new Error('SEA_RUNTIMES contains an unsupported runtime');
}
let seeded = false;
try {
await runShell(`Sea vHost runtime seed ${suffix}`, seedShell, seedMarker);
seeded = true;
const results = [];
for (const runtime of requestedRuntimes) {
const child = spawnSync(process.execPath, [path.join(scriptDirectory, 'runtime-smoke.mjs')], {
cwd: workspace,
env: {
...process.env,
SEA_PANEL_URL: panelURL,
SEA_PANEL_API_KEY: panelAPIKey,
SEA_PANEL_TLS_INSECURE: String(insecureTLS),
SEA_CONSOLE_URL: consoleURL,
SEA_TENANT_LOGIN: email,
SEA_TENANT_PASSWORD: password,
SEA_RUNTIME: runtime,
...(artifacts[runtime] ? { SEA_RUNTIME_ARTIFACT: artifacts[runtime] } : {}),
},
encoding: 'utf8', timeout: 10 * 60_000, maxBuffer: 4 * 1024 * 1024,
});
if (child.status !== 0) {
const diagnostic = (child.stderr || child.stdout).trim().replaceAll(password, '[redacted]').slice(0, 1000);
results.push({ runtime, status: 'failed', diagnostic });
console.log(`${runtime}=failed`);
continue;
}
results.push({ ...JSON.parse(child.stdout), status: 'passed' });
console.log(`${runtime}=passed`);
}
const allPassed = results.every((result) => result.status === 'passed');
console.log(JSON.stringify({ status: allPassed ? 'passed' : 'failed', runtimes: results, checks: {
dynamicVersionCatalog: results.every((result) => result.version || result.status === 'failed'),
createUploadPreflightDeploy: allPassed,
nginxReverseProxy: allPassed,
isolatedLinuxIdentity: allPassed,
zeroProcessCapabilities: allPassed,
controlConfigAndSocketDenied: allPassed,
stopRestartDeleteCleanup: allPassed,
} }, null, 2));
if (!allPassed) process.exitCode = 1;
} finally {
if (seeded) {
try { await runShell(`Sea vHost runtime cleanup ${suffix}`, cleanupShell, cleanupMarker); } catch { process.exitCode = 1; }
}
}
+75
View File
@@ -0,0 +1,75 @@
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 base = new URL(panelURL);
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 panelForm(pathname, values = {}) {
const requestTime = Math.floor(Date.now() / 1000).toString();
const body = Buffer.from(new URLSearchParams({ ...values, request_time: requestTime, request_token: md5(requestTime + md5(panelAPIKey)) }).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 rows(payload) {
if (Array.isArray(payload?.data)) return payload.data;
if (Array.isArray(payload?.data?.data)) return payload.data.data;
return [];
}
const nodeList = rows(await panelForm('/project/nodejs/get_project_list/stype', { search: 'sv', p: '1', limit: '100' }));
if (nodeList.some((item) => /^sv[0-9a-f]{10}(?:_[0-9]+)?$/.test(item.name ?? item.project_name ?? ''))) {
throw new Error('managed-looking Node.js panel records still exist; refusing process-only cleanup');
}
const marker = `runtime-cleanup-${Date.now()}`;
const shell = [
'set -euo pipefail',
'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##*/}"',
`listener_pid="$(ss -lntp | sed -n '/127\\.0\\.0\\.1:20021[[:space:]]/s/.*pid=\\([0-9][0-9]*\\).*/\\1/p' | head -n1)"; if [[ -z "$listener_pid" ]]; then printf "terminated_orphan_processes=0\\n%s\\n" '${marker}'; exit 0; fi; test "$(stat -c %U "/proc/$listener_pid")" = "$host_name"; tr '\\0' ' ' <"/proc/$listener_pid/cmdline" | grep -Fq "node server.js"`,
'kill -TERM "$listener_pid"; pkill -TERM -u "$host_name" -f "npm run start" 2>/dev/null || true; sleep 2; if ss -lntp | grep -qE \'127\\.0\\.0\\.1:20021\\b\'; then exit 1; fi; printf "terminated_orphan_processes=2\\n"',
`printf '%s\n' '${marker}'`,
].join('\n');
const task = await panelForm('/crontab', { action: 'AddCrontab', name: `Sea vHost runtime cleanup ${Date.now().toString().slice(-7)}`, 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 orphan runtime cleanup', save: '0', backupTo: 'localhost' });
const taskID = Number(task?.id);
if ((task?.status !== true && task?.status !== 'true') || !Number.isSafeInteger(taskID)) throw new Error('panel rejected cleanup task');
let cleanupLog = '';
try {
await panelForm('/crontab', { action: 'StartTask', id: String(taskID) });
for (let attempt = 0; attempt < 90; attempt += 1) {
await new Promise((resolve) => setTimeout(resolve, 1000));
const result = await panelForm('/crontab', { action: 'GetLogs', id: String(taskID) });
cleanupLog = typeof result?.msg === 'string' ? result.msg : typeof result === 'string' ? result : cleanupLog;
if (cleanupLog.includes(marker)) break;
}
if (!cleanupLog.includes(marker)) throw new Error('orphan process cleanup did not complete');
} finally {
try { await panelForm('/crontab', { action: 'DelCrontab', id: String(taskID) }); } catch { /* best effort */ }
}
const pythonPayload = await panelForm('/project/python/GetProjectList/stype', { search: 'sv', p: '1', limit: '100' });
const stalePython = rows(pythonPayload).filter((item) => /^sv[0-9a-f]{10}_[0-9]+$/.test(item.name ?? '') && /^\/www\/wwwroot\/seavHost\/vHost\/sv[0-9a-f]{10}\/python-[a-z0-9]+$/.test(item.path ?? ''));
for (const item of stalePython) {
const removed = await panelForm('/project/python/remove_project/stype', { project_name: item.name, name: item.name });
if (removed?.status === false || removed?.status === 'false') throw new Error(`panel rejected stale Python test cleanup for ${item.name}`);
}
console.log(JSON.stringify({ status: 'passed', orphanProcessesTerminated: Number(cleanupLog.match(/terminated_orphan_processes=(\d+)/)?.[1] ?? 0), stalePythonProjectsRemoved: stalePython.map((item) => item.name) }, null, 2));
+122
View File
@@ -0,0 +1,122 @@
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 runtime verify ${nonce}`;
const shell = [
// aaPanel appends a small task wrapper which references an optional $1.
// Keep errexit/pipefail without nounset so our verification does not alter
// the wrapper's argument semantics after the success marker is emitted.
'set -eo pipefail',
'verification_started="$(date --iso-8601=seconds)"',
'token="$(sed -n \'s/^SEA_INTERNAL_AUTH_TOKEN=//p\' /etc/sea-vhost/sea-vhost.env | head -n1)"; test "${#token}" -ge 32',
'agent_call() { local route="${1:-}" payload="${2:-}"; test -n "$route"; curl --fail --silent --show-error --max-time 20 --unix-socket /run/sea-vhost/agent.sock --header "Authorization: Bearer $token" --header "Content-Type: application/json" --request POST --data "$payload" "http://localhost$route"; }',
'broker_call() { local payload="${1:-}"; test -n "$payload"; curl --fail --silent --show-error --max-time 30 --unix-socket /run/sea-vhost-panel/broker.sock --header "Authorization: Bearer $token" --header "Content-Type: application/json" --request POST --data "$payload" http://localhost/v1/operations; }',
'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"; test "$(getent "$account_db" "$host_name" | cut -d: -f6)" = /nonexistent',
'domain="$(find /www/server/panel/vhost/nginx/extension -mindepth 2 -maxdepth 2 -type f -name sea-vhost-php.conf -printf \'%h\\n\' -quit | xargs -r basename)"; test -n "$domain"',
'printf -v existing_payload \'{"project":{"tenantId":1,"hostName":"%s","runPath":"/","storageBytes":1048576,"processLimit":1000},"domains":["%s"]}\' "$host_name" "$domain"',
'existing_usage="$(agent_call /v1/resources/usage "$existing_payload")"; printf \'existing_usage=%s\\n\' "$existing_usage"',
'existing_count="$(printf \'%s\' "$existing_usage" | sed -n \'s/.*"processCount":\\([0-9][0-9]*\\).*/\\1/p\')"; test -n "$existing_count"; test "$existing_count" -ge 1',
'test_host="sv$(openssl rand -hex 5)"; printf -v test_spec \'{"tenantId":9999999999,"hostName":"%s","runPath":"/","storageBytes":1048576,"processLimit":10}\' "$test_host"',
'agent_call /v1/prepare "$test_spec" >/dev/null',
'marker_a="$host_dir/.sea-cross-test"; marker_b="/www/wwwroot/seavHost/vHost/$test_host/.sea-cross-test"',
'site_id=""; cert_tmp=""; domain="$test_host-cert.example.invalid"',
'cleanup() { rm -f -- "$marker_a"; if [[ -n "$site_id" ]]; then printf -v delete_payload \'{"operation":"delete_site","id":%s,"name":"%s"}\' "$site_id" "$domain"; broker_call "$delete_payload" >/dev/null 2>&1 || true; fi; if [[ -n "$cert_tmp" ]]; then rm -f -- "$cert_tmp/key.pem" "$cert_tmp/cert.pem"; rmdir -- "$cert_tmp" 2>/dev/null || true; fi; agent_call /v1/quarantine "$test_spec" >/dev/null 2>&1 || true; }; trap cleanup EXIT',
'php_exe="$(readlink "/proc/$(cat "/run/sea-vhost-php/$host_name/php-fpm.pid")/exe")"; php_version="$(printf \'%s\' "$php_exe" | sed -n \'s#^/www/server/php/\\([0-9][0-9]\\)/.*#\\1#p\')"; test -n "$php_version"; php_version="${php_version:0:1}.${php_version:1:1}"',
'test_port=$((39800 + 16#${test_host: -2} % 100)); printf -v site_payload \'{"operation":"create_site","site":{"Name":"%s","Domain":"%s","Path":"/www/wwwroot/seavHost/vHost/%s","RunPath":"/","Runtime":"PHP","Version":"%s","RunUser":"%s","Port":%s,"ProcessLimit":10}}\' "$test_host" "$domain" "$test_host" "$php_version" "$test_host" "$test_port"',
'site_response="$(broker_call "$site_payload")"; site_id="$(printf \'%s\' "$site_response" | sed -n \'s/.*"id":\\([0-9][0-9]*\\).*/\\1/p\')"; test -n "$site_id"',
'agent_call /v1/prepare "$test_spec" >/dev/null',
'cert_tmp="$(mktemp -d /tmp/sea-vhost-cert.XXXXXX)"; openssl req -x509 -newkey rsa:2048 -nodes -days 1 -subj "/CN=$domain" -addext "subjectAltName=DNS:$domain" -keyout "$cert_tmp/key.pem" -out "$cert_tmp/cert.pem" >/dev/null 2>&1',
"cert_payload=\"$(python3 -c 'import json,sys; print(json.dumps({\"operation\":\"install_certificate\",\"siteId\":int(sys.argv[1]),\"name\":sys.argv[2],\"privateKey\":open(sys.argv[3]).read(),\"certificate\":open(sys.argv[4]).read()}))' \"$site_id\" \"$domain\" \"$cert_tmp/key.pem\" \"$cert_tmp/cert.pem\")\"; broker_call \"$cert_payload\" >/dev/null",
'test -s "/www/server/panel/vhost/cert/$domain/fullchain.pem"; test -s "/www/server/panel/vhost/cert/$domain/privkey.pem"; /www/server/nginx/sbin/nginx -t >/dev/null; echo manual_certificate=passed',
'printf -v disable_cert_payload \'{"operation":"disable_certificate","siteId":%s,"name":"%s"}\' "$site_id" "$domain"; broker_call "$disable_cert_payload" >/dev/null; if grep -Eq \'^[[:space:]]*ssl_certificate([[:space:]]|_)\' "/www/server/panel/vhost/nginx/$domain.conf"; then echo certificate_disable=failed; exit 1; else echo certificate_disable=passed; fi; /www/server/nginx/sbin/nginx -t >/dev/null',
'printf -v delete_payload \'{"operation":"delete_site","id":%s,"name":"%s"}\' "$site_id" "$domain"; broker_call "$delete_payload" >/dev/null; site_id=""; rm -f -- "$cert_tmp/key.pem" "$cert_tmp/cert.pem"; rmdir -- "$cert_tmp"; cert_tmp=""; agent_call /v1/prepare "$test_spec" >/dev/null',
'printf tenant-a >"$marker_a"; chown "sea-vhost:$host_name" "$marker_a"; chmod 0660 "$marker_a"',
'printf tenant-b >"$marker_b"; chown "sea-vhost:$test_host" "$marker_b"; chmod 0660 "$marker_b"',
'hidden_quota_dir="/www/wwwroot/seavHost/vHost/$test_host/.quota-hidden"; runuser -u "$test_host" -- mkdir -m 0700 "$hidden_quota_dir"; runuser -u "$test_host" -- dd if=/dev/zero of="$hidden_quota_dir/payload.bin" bs=1M count=2 status=none; runuser -u "$test_host" -- chmod 000 "$hidden_quota_dir"',
'printf -v test_usage_payload \'{"project":%s,"domains":[]}\' "$test_spec"; hidden_usage="$(agent_call /v1/resources/usage "$test_usage_payload")"; hidden_storage="$(printf \'%s\' "$hidden_usage" | sed -n \'s/.*"storageBytes":\\([0-9][0-9]*\\).*/\\1/p\')"; test -n "$hidden_storage"; test "$hidden_storage" -ge 2097152; printf \'storage_unreadable_tree=measured bytes=%s\\n\' "$hidden_storage"',
'runuser -u "$host_name" -- cat "$marker_a" >/dev/null; runuser -u "$test_host" -- cat "$marker_b" >/dev/null',
'if runuser -u "$host_name" -- cat "$marker_b" >/dev/null 2>&1; then echo cross_read_a_to_b=allowed; exit 1; else echo cross_read_a_to_b=denied; fi',
'if runuser -u "$test_host" -- cat "$marker_a" >/dev/null 2>&1; then echo cross_read_b_to_a=allowed; exit 1; else echo cross_read_b_to_a=denied; fi',
'agent_call /v1/project/freeze-writes "$test_spec" >/dev/null',
'if runuser -u "$test_host" -- sh -c \'printf blocked >>"$1"\' sh "$marker_b" 2>/dev/null; then echo quota_existing_write=allowed; exit 1; else echo quota_existing_write=denied; fi',
'if runuser -u "$test_host" -- touch "/www/wwwroot/seavHost/vHost/$test_host/.sea-quota-new" 2>/dev/null; then echo quota_new_write=allowed; exit 1; else echo quota_new_write=denied; fi',
'if runuser -u www -- test -r "/www/wwwroot/seavHost/vHost/$test_host/.sea-runtime"; then echo quota_runtime_privacy=failed; exit 1; else echo quota_runtime_privacy=passed; fi',
'runuser -u sea-vhost -- rm -f -- "$marker_b"; echo quota_web_cleanup=passed',
'agent_call /v1/prepare "$test_spec" >/dev/null; thaw_marker="/www/wwwroot/seavHost/vHost/$test_host/.sea-thaw-test"; runuser -u "$test_host" -- touch "$thaw_marker"; runuser -u sea-vhost -- rm -f -- "$thaw_marker"; echo quota_write_restore=passed',
'runuser -u "$test_host" -- sh -c \'sleep 300 >/dev/null 2>&1 &\'; sleep 1',
'test_usage="$(agent_call /v1/resources/usage "$test_usage_payload")"; printf \'test_usage=%s\\n\' "$test_usage"',
'test_count="$(printf \'%s\' "$test_usage" | sed -n \'s/.*"processCount":\\([0-9][0-9]*\\).*/\\1/p\')"; test -n "$test_count"; test "$test_count" -ge 1',
'agent_call /v1/resources/processes/terminate "$test_spec" >/dev/null; if pgrep -u "$test_host" >/dev/null; then echo process_termination=failed; exit 1; else echo process_termination=passed; fi',
'cleanup; trap - EXIT; if id "$test_host" >/dev/null 2>&1; then echo disposable_identity_cleanup=failed; exit 1; fi',
'sleep 65',
'if journalctl -u sea-vhost-api.service --since "$verification_started" --no-pager | grep -F "quota refresh failed"; then echo quota_monitor=failed; exit 1; else echo quota_monitor=healthy; fi',
"printf '%s\\n' 'Sea vHost runtime 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 Sea vHost runtime isolation 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 < 180; 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 runtime verification: success') || log.includes('★[')) break;
}
if (!log.includes('Sea vHost runtime verification: success')) throw new Error(`runtime 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 */ }
}
}
+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 */ }
}
}
+201
View File
@@ -0,0 +1,201 @@
import crypto from 'node:crypto';
import fs from 'node:fs';
import path from 'node:path';
import { execFileSync } from 'node:child_process';
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';
const cleanupOnly = process.argv.includes('--cleanup-only');
const installRequested = process.argv.includes('--install');
const productionDiagnose = process.argv.includes('--production-diagnose');
const diagnoseRequested = process.argv.includes('--diagnose') || productionDiagnose;
const activationArgument = process.argv.find((value) => value.startsWith('--activate-http-test='));
const activationHost = activationArgument?.slice('--activate-http-test='.length) ?? '';
const packageArgument = process.argv.slice(2).find((value) => !value.startsWith('--'));
const packagePath = path.resolve(packageArgument ?? 'build/sea-vhost-linux-amd64.tar.gz');
if (!baseURL || !apiKey) {
console.error('SEA_PANEL_URL and SEA_PANEL_API_KEY are required.');
process.exit(2);
}
if (activationHost && (!installRequested || !/^[A-Za-z0-9.-]+$/.test(activationHost) || activationHost.startsWith('.') || activationHost.includes('..'))) {
console.error('--activate-http-test requires --install and a valid host name or IP address.');
process.exit(2);
}
const base = new URL(baseURL);
if (!['http:', 'https:'].includes(base.protocol) || base.username || base.password) {
console.error('SEA_PANEL_URL must be an HTTP(S) URL without embedded credentials.');
process.exit(2);
}
const packageInfo = fs.statSync(packagePath);
if (!packageInfo.isFile() || packageInfo.size < 1024 || packageInfo.size > 128 * 1024 * 1024) {
throw new Error('deployment package must be a regular file between 1 KB and 128 MB');
}
const entries = execFileSync('tar', ['-tzf', packagePath], { encoding: 'utf8', maxBuffer: 2 * 1024 * 1024 })
.split(/\r?\n/).filter(Boolean);
if (!entries.includes('deploy/preflight.sh') || !entries.includes('deploy/install.sh') || !entries.includes('build/web/index.html') ||
entries.some((entry) => entry.startsWith('/') || entry.split('/').includes('..'))) {
throw new Error('deployment archive has an unsafe or incomplete layout');
}
if (activationHost && !entries.includes('deploy/activate-test.sh')) {
throw new Error('standard release excludes the insecure HTTP test activator; use HTTPS installation');
}
const archive = fs.readFileSync(packagePath);
const hash = crypto.createHash('sha256').update(archive).digest('hex');
const shortHash = hash.slice(0, 12);
const runID = Date.now().toString();
const remoteName = `sea-vhost-${shortHash}-${runID}.tar.gz`;
const remotePath = `/tmp/${remoteName}`;
const stagePath = `/opt/sea-vhost-staging-${shortHash}-${runID}`;
const taskOperation = productionDiagnose ? 'production diagnose' : diagnoseRequested ? 'diagnose' : installRequested ? 'install' : 'preflight';
const taskName = `Sea vHost ${taskOperation} ${shortHash}-${runID.slice(-6)}`;
const md5 = (value) => crypto.createHash('md5').update(value).digest('hex');
const client = base.protocol === 'https:' ? https : http;
const agent = base.protocol === 'https:' ? new https.Agent({ rejectUnauthorized: !insecureTLS }) : undefined;
function authFields() {
const requestTime = Math.floor(Date.now() / 1000).toString();
return { request_time: requestTime, request_token: md5(requestTime + md5(apiKey)) };
}
function send(method, pathname, body, contentType, timeoutMs = 30_000) {
const url = new URL(pathname, base);
return new Promise((resolve, reject) => {
const request = client.request(url, {
method, agent, timeout: timeoutMs,
headers: { 'content-type': contentType, 'content-length': body.length },
}, (response) => {
let data = '';
response.setEncoding('utf8');
response.on('data', (chunk) => {
data += chunk;
if (data.length > 2 * 1024 * 1024) request.destroy(new Error('panel response exceeded 2 MB'));
});
response.on('end', () => {
if (response.statusCode < 200 || response.statusCode > 299) {
reject(new Error(`panel returned HTTP ${response.statusCode}`));
return;
}
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 formRequest(pathname, values) {
const body = Buffer.from(new URLSearchParams({ ...values, ...authFields() }).toString());
return send('POST', pathname, body, 'application/x-www-form-urlencoded');
}
async function cleanupStaleUploads() {
const listing = await formRequest('/files', { action: 'GetDir', path: '/tmp', p: '1', search: `sea-vhost-${shortHash}` });
const pattern = new RegExp(`^sea-vhost-${shortHash}(?:-\\d+)?\\.tar\\.gz$`);
const names = (Array.isArray(listing?.FILES) ? listing.FILES : [])
.map((entry) => String(entry).split(';', 1)[0])
.filter((name) => pattern.test(name));
for (const name of names) {
await formRequest('/files', { action: 'DeleteFile', path: `/tmp/${name}` });
}
return names.length;
}
function multipartUpload() {
const boundary = `----SeaVHost${crypto.randomBytes(12).toString('hex')}`;
const chunks = [];
const field = (name, value) => {
chunks.push(Buffer.from(`--${boundary}\r\nContent-Disposition: form-data; name="${name}"\r\n\r\n${value}\r\n`));
};
const auth = authFields();
field('action', 'UploadFile');
field('path', '/tmp');
field('request_time', auth.request_time);
field('request_token', auth.request_token);
chunks.push(Buffer.from(`--${boundary}\r\nContent-Disposition: form-data; name="zunfile"; filename="${remoteName}"\r\nContent-Type: application/gzip\r\n\r\n`));
chunks.push(archive);
chunks.push(Buffer.from(`\r\n--${boundary}--\r\n`));
return send('POST', '/files', Buffer.concat(chunks), `multipart/form-data; boundary=${boundary}`, 180_000);
}
function requireSuccess(payload, operation) {
if (!payload || (payload.status !== true && payload.status !== 'true')) {
throw new Error(`${operation} was rejected by the panel`);
}
return payload;
}
const shell = [
// aaPanel appends its own wrapper after the task body and references $1.
// Enabling nounset here would make that trusted wrapper fail after a
// successful preflight when the task is launched without arguments.
'set -eo pipefail',
`test ! -e '${stagePath}'`,
`printf '%s %s\\n' '${hash}' '${remotePath}' | sha256sum -c -`,
`install -d -o root -g root -m 0700 '${stagePath}'`,
`tar -xzf '${remotePath}' -C '${stagePath}'`,
`bash '${stagePath}/deploy/preflight.sh'`,
...(installRequested ? [`bash '${stagePath}/deploy/install.sh'`, `printf '%s\n' 'Sea vHost install result: success'`] : []),
...(activationHost ? [`bash '${stagePath}/deploy/activate-test.sh' '${activationHost}'`] : []),
...(diagnoseRequested ? [
`SEA_DIAGNOSE_PRODUCTION=${productionDiagnose ? 'true' : 'false'} bash '${stagePath}/deploy/diagnose.sh'`,
`printf '%s\n' 'Sea vHost diagnostic result: success'`,
] : []),
].join('\n');
let taskID;
let uploadAttempted = false;
let stageReady = false;
try {
const cleaned = await cleanupStaleUploads();
if (cleanupOnly) {
console.log(`Removed ${cleaned} stale Sea vHost upload(s) from /tmp.`);
process.exit(0);
}
uploadAttempted = true;
requireSuccess(await multipartUpload(), 'package upload');
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: diagnoseRequested ? 'Temporary Sea vHost deployment diagnostics' : installRequested ? 'Temporary Sea vHost installer' : 'Temporary Sea vHost installation preflight',
save: '0', backupTo: 'localhost',
}), 'temporary 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 < 55; attempt += 1) {
await new Promise((resolve) => setTimeout(resolve, 1500));
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('当前日志为空')) log = '';
const successMarker = diagnoseRequested ? 'Sea vHost diagnostic result: success' : activationHost ? 'Sea vHost test activation result: success' : installRequested ? 'Sea vHost install result: success' : 'Result:';
if (log.includes(successMarker) || log.includes('SHA256SUMS') || log.includes('FAILED') || log.includes('★[')) break;
}
if (!log.trim()) throw new Error('remote deployment task produced no log output');
console.log(log.trim());
stageReady = log.includes('Result: 0 failure(s)');
const installed = log.includes('Sea vHost install result: success');
const activated = log.includes('Sea vHost test activation result: success');
const diagnosed = log.includes('Sea vHost diagnostic result: success');
if (stageReady) console.log(`Staged package: ${stagePath}`);
if (installed && !activated) console.log('Sea vHost files and systemd units were installed; services were not started.');
if (activated) console.log(`Sea vHost test console was activated for host ${activationHost}.`);
if (diagnosed) console.log(`Sea vHost ${productionDiagnose ? 'production ' : ''}diagnostics passed.`);
if (!stageReady || (installRequested && !installed) || (activationHost && !activated) || (diagnoseRequested && !diagnosed)) process.exitCode = 1;
} finally {
if (taskID) {
try { await formRequest('/crontab', { action: 'DelCrontab', id: String(taskID) }); } catch { /* best-effort cleanup */ }
}
if (uploadAttempted) {
try { await formRequest('/files', { action: 'DeleteFile', path: remotePath }); } catch { /* best-effort cleanup */ }
}
if (!stageReady) {
try { await formRequest('/files', { action: 'DeleteDir', path: stagePath }); } catch { /* best-effort cleanup */ }
}
}
+136
View File
@@ -0,0 +1,136 @@
import crypto from 'node:crypto';
import fs from 'node:fs';
import http from 'node:http';
import https from 'node:https';
import path from 'node:path';
import { spawnSync } from 'node:child_process';
import { fileURLToPath } from 'node:url';
const panelURL = process.env.SEA_PANEL_URL?.trim();
const panelAPIKey = process.env.SEA_PANEL_API_KEY?.trim();
const consoleURL = process.env.SEA_CONSOLE_URL?.trim();
const activationHost = process.env.SEA_TEST_ACTIVATION_HOST?.trim();
const insecureTLS = process.env.SEA_PANEL_TLS_INSECURE === 'true';
if (!panelURL || !panelAPIKey || !consoleURL || !activationHost) process.exit(2);
if (!/^[A-Za-z0-9.-]+$/.test(activationHost)) throw new Error('SEA_TEST_ACTIVATION_HOST must be a host name or IP address');
const panelBase = new URL(panelURL);
const consoleBase = new URL(consoleURL);
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 scriptDirectory = path.dirname(fileURLToPath(import.meta.url));
const workspace = path.dirname(scriptDirectory);
const packagePath = path.join(workspace, 'build', 'sea-vhost-linux-amd64.tar.gz');
if (!fs.statSync(packagePath).isFile()) throw new Error('deployment package is missing');
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);
});
}
async function runShell(name, shell, marker, attempts = 90) {
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 upgrade 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 */ }
}
}
const snapshotShell = (marker) => [
'set -Eeuo pipefail',
'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)"; if [[ -z "$mysql_bin" && -x /www/server/mysql/bin/mysql ]]; then mysql_bin=/www/server/mysql/bin/mysql; fi',
'db_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\\`));")"',
'for service in sea-vhost-agent sea-vhost-panel-broker sea-vhost-api; do systemctl is-active --quiet "$service"; done',
'/www/server/nginx/sbin/nginx -t >/dev/null',
'test "$(curl --silent --show-error --fail --max-time 10 http://127.0.0.1:8080/healthz)" = \'{"status":"ok"}\'',
'for file 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 -f "$file"; done',
// New releases may append a documented default without changing an
// operator's existing settings. Exclude only the newly introduced key;
// every pre-existing line, secret and custom override remains hash-checked.
'printf "env_sha=%s\\nconfig_sha=%s\\ncredentials_sha=%s\\nresources_sha=%s\\ndb_counts=%s\\n" "$(grep -Ev \'^(SEA_NODE_PID_ROOT|SEA_BACKUP_ROOT)=\' /etc/sea-vhost/sea-vhost.env | sha256sum | awk \'{print $1}\')" "$(sha256sum /var/lib/sea-vhost/config.json | awk \'{print $1}\')" "$(sha256sum /var/lib/sea-vhost-panel/credentials.json | awk \'{print $1}\')" "$(sha256sum /var/lib/sea-vhost-panel/resources.json | awk \'{print $1}\')" "$db_counts"',
`printf '%s\n' ${q(marker)}`,
].join('\n');
function parseSnapshot(log) {
const get = (name) => log.match(new RegExp(`(?:^|\\n)${name}=([^\\r\\n]+)`))?.[1];
const snapshot = Object.fromEntries(['env_sha', 'config_sha', 'credentials_sha', 'resources_sha', 'db_counts'].map((name) => [name, get(name)]));
if (Object.values(snapshot).some((value) => !value)) throw new Error('remote snapshot was incomplete');
return snapshot;
}
const beforeMarker = `upgrade-before-${suffix}`;
const before = parseSnapshot(await runShell(`Sea vHost upgrade before ${suffix}`, snapshotShell(beforeMarker), beforeMarker));
const child = spawnSync(process.execPath, [path.join(scriptDirectory, 'panel-stage.mjs'), packagePath, '--install', `--activate-http-test=${activationHost}`, '--diagnose'], {
cwd: workspace,
env: { ...process.env, SEA_PANEL_URL: panelURL, SEA_PANEL_API_KEY: panelAPIKey, SEA_PANEL_TLS_INSECURE: String(insecureTLS) },
encoding: 'utf8', timeout: 12 * 60_000, maxBuffer: 8 * 1024 * 1024,
});
const stageOutput = `${child.stdout ?? ''}\n${child.stderr ?? ''}`;
if (child.status !== 0 || !stageOutput.includes('Sea vHost install result: success') || !stageOutput.includes('Sea vHost test activation result: success') || !stageOutput.includes('Sea vHost diagnostic result: success')) {
throw new Error(`upgrade deployment failed: ${stageOutput.trim().slice(-3000)}`);
}
const afterMarker = `upgrade-after-${suffix}`;
const after = parseSnapshot(await runShell(`Sea vHost upgrade after ${suffix}`, snapshotShell(afterMarker), afterMarker));
for (const key of Object.keys(before)) {
if (before[key] !== after[key]) throw new Error(`upgrade changed preserved state: ${key}`);
}
const setupResponse = await fetch(new URL('/api/v1/setup/status', consoleBase), { signal: AbortSignal.timeout(15_000), redirect: 'manual' });
const setupPayload = await setupResponse.json();
if (setupResponse.status !== 200 || setupPayload?.required !== false) throw new Error('installed instance returned to setup mode after upgrade');
const stagedPath = stageOutput.match(/Staged package: (\/opt\/sea-vhost-staging-[A-Fa-f0-9]+-\d+)/)?.[1];
if (stagedPath && /^\/opt\/sea-vhost-staging-[a-f0-9]{12}-\d+$/.test(stagedPath)) {
try { await panelForm('/files', { action: 'DeleteDir', path: stagedPath }); } catch { /* staging cleanup is best effort */ }
}
console.log(JSON.stringify({ status: 'passed', packageSHA256: crypto.createHash('sha256').update(fs.readFileSync(packagePath)).digest('hex'), checks: {
preflightPassedInUpgradeMode: stageOutput.includes('Result: 0 failure(s)'),
installerCompleted: true,
servicesRestartedAndHealthy: true,
diagnosticsPassed: true,
environmentPreserved: before.env_sha === after.env_sha,
applicationConfigPreserved: before.config_sha === after.config_sha,
panelCredentialsPreserved: before.credentials_sha === after.credentials_sha,
managedResourceRegistryPreserved: before.resources_sha === after.resources_sha,
databaseObjectCountsPreserved: before.db_counts === after.db_counts,
setupRemainedClosed: true,
}, databaseObjectCounts: after.db_counts }, null, 2));
+66
View File
@@ -0,0 +1,66 @@
#!/usr/bin/env bash
set -uo pipefail
failures=0
warnings=0
repo_root="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)"
pass() { printf '[PASS] %s\n' "$1"; }
warn() { printf '[WARN] %s\n' "$1"; warnings=$((warnings + 1)); }
fail() { printf '[FAIL] %s\n' "$1"; failures=$((failures + 1)); }
printf 'Sea vHost installation preflight\n'
printf '================================\n'
if [[ "${EUID}" -eq 0 ]]; then pass 'running as root'; else fail 'preflight must run as root'; fi
for required in systemctl getent id chattr openssl mktemp ss tar curl; do
if command -v "${required}" >/dev/null 2>&1; then pass "command available: ${required}"; else fail "missing command: ${required}"; fi
done
if [[ "$(ps -p 1 -o comm= 2>/dev/null | xargs)" == 'systemd' ]]; then
pass 'systemd is PID 1'
else
fail 'systemd is not PID 1'
fi
if id www >/dev/null 2>&1; then pass 'aaPanel service user www exists'; else fail 'aaPanel service user www is missing'; fi
for path in /www /www/wwwroot /www/server/panel/vhost/nginx; do
if [[ -d "${path}" && ! -L "${path}" ]]; then pass "physical directory available: ${path}"; else fail "missing or unsafe directory: ${path}"; fi
done
if [[ -x /www/server/nginx/sbin/nginx ]]; then
pass 'aaPanel Nginx binary is available'
if /www/server/nginx/sbin/nginx -t >/dev/null 2>&1; then pass 'current Nginx configuration is valid'; else fail 'current Nginx configuration is invalid'; fi
else
fail 'aaPanel Nginx binary is missing'
fi
for path in /www/server/nginx/logs/error.log /www/server/nginx/logs/nginx.pid; do
if [[ -f "${path}" && ! -L "${path}" ]]; then pass "physical Nginx runtime file available: ${path}"; else fail "missing or unsafe Nginx runtime file: ${path}"; fi
done
if systemctl is-active --quiet mysql.service || systemctl is-active --quiet mysqld.service; then
pass 'MySQL service is active'
else
warn 'MySQL service was not detected as active'
fi
if ss -ltnH 2>/dev/null | awk '{print $4}' | grep -Eq '(^|:|\])8080$'; then
if systemctl is-active --quiet sea-vhost-api.service; then
pass 'TCP port 8080 is occupied by the existing Sea vHost API (upgrade mode)'
else
fail 'TCP port 8080 is already in use by an unmanaged service'
fi
else
pass 'TCP port 8080 is available'
fi
for artifact in sea-vhost-api sea-vhost-agent sea-vhost-panel-broker; do
if [[ -f "${repo_root}/build/bin/${artifact}" && ! -L "${repo_root}/build/bin/${artifact}" ]]; then pass "build artifact available: ${artifact}"; else fail "missing or unsafe build artifact: ${artifact}"; fi
done
if [[ -f "${repo_root}/build/web/index.html" && ! -L "${repo_root}/build/web/index.html" ]]; then pass 'frontend build is available'; else fail 'frontend build is missing or unsafe'; fi
printf '\nResult: %d failure(s), %d warning(s)\n' "${failures}" "${warnings}"
if (( failures > 0 )); then exit 1; fi
+9
View File
@@ -0,0 +1,9 @@
#!/usr/bin/env bash
set -euo pipefail
[[ ${EUID} -eq 0 ]] || { echo 'Runtime roots must be prepared as root.' >&2; exit 1; }
# These targets must exist before systemd constructs the agent mount namespace.
# Keep installed directories' owners/modes; only create missing components.
for managed in /www/server/nodejs /www/server/nodejs/vhost /www/server/nodejs/vhost/pids /www/server/python_manager /www/server/python_manager/versions; do
[[ ! -L "$managed" && ( ! -e "$managed" || -d "$managed" ) ]] || { echo "Unsafe runtime directory: $managed" >&2; exit 1; }
[[ -d "$managed" ]] || install -d -o root -g root -m 0755 "$managed"
done
+25
View File
@@ -0,0 +1,25 @@
#!/usr/bin/env bash
set +e
printf '%s\n' '=== services ==='
systemctl show sea-vhost-agent sea-vhost-panel-broker sea-vhost-api -p Id -p ActiveState -p SubState -p MainPID -p ExecMainStatus --no-pager
printf '%s\n' '=== listeners ==='
ss -lntp | grep -E '(:80|:443|:8080)[[:space:]]' || true
printf '%s\n' '=== API health ==='
curl --silent --show-error --max-time 5 --write-out '\nhttp=%{http_code}\n' --header 'Host: host.ser888.cn' http://127.0.0.1:8080/healthz || true
printf '%s\n' '=== HTTPS health ==='
curl --silent --show-error --max-time 10 --write-out '\nhttp=%{http_code}\n' --resolve host.ser888.cn:443:127.0.0.1 https://host.ser888.cn/healthz || true
printf '%s\n' '=== API journal ==='
journalctl -u sea-vhost-api -n 25 --no-pager -o cat || true
printf '%s\n' '=== Nginx config ==='
/www/server/nginx/sbin/nginx -t 2>&1 || true
printf '%s\n' '=== certificate ==='
openssl x509 -in /www/server/panel/vhost/cert/host.ser888.cn/fullchain.pem -noout -subject -issuer -dates -checkhost host.ser888.cn 2>&1 || true
openssl x509 -in /www/server/panel/vhost/cert/host.ser888.cn/fullchain.pem -noout -ext subjectAltName 2>&1 || true
printf '%s\n' '=== FTPS synchronization ==='
systemctl show sea-vhost-ftps-sync.service sea-vhost-ftps-sync.timer -p Id -p LoadState -p ActiveState -p SubState -p Result -p ExecMainStatus --no-pager 2>&1 || true
journalctl -u sea-vhost-ftps-sync.service -n 15 --no-pager -o cat 2>&1 || true
stat -Lc '%A %a %U:%G %n' /www/server/pure-ftpd/etc/pure-ftpd.pem 2>&1 || true
openssl x509 -in /www/server/pure-ftpd/etc/pure-ftpd.pem -noout -subject -issuer -ext subjectAltName 2>&1 || true
for ftp_pid in $(pgrep pure-ftpd 2>/dev/null || true); do printf 'pid=%s started=' "${ftp_pid}"; ps -o lstart= -p "${ftp_pid}"; printf 'cmd='; tr '\0' ' ' <"/proc/${ftp_pid}/cmdline"; printf '\n'; done
timeout 15 openssl s_client -connect 127.0.0.1:21 -starttls ftp -servername sv0123456789.vhost.ser888.cn -verify_hostname sv0123456789.vhost.ser888.cn -verify_return_error </dev/null 2>&1 | tail -n 12 || true
+28
View File
@@ -0,0 +1,28 @@
#!/usr/bin/env bash
set -euo pipefail
printf '%s\n' '=== local panel listener ==='
panel_port="$(tr -cd '0-9' </www/server/panel/data/port.pl)"
printf 'panel_port=%s\n' "${panel_port}"
for scheme in http https; do
code="$(curl --insecure --silent --output /dev/null --write-out '%{http_code}' --max-time 5 "${scheme}://127.0.0.1:${panel_port}/" || true)"
printf '%s=%s\n' "${scheme}" "${code}"
done
printf '%s\n' '=== certificate clients ==='
for candidate in /root/.acme.sh/acme.sh /www/server/panel/pyenv/bin/python3 /usr/bin/certbot; do
if [[ -e "${candidate}" ]]; then
stat -Lc '%A %a %U:%G %n' "${candidate}"
fi
done
printf '%s\n' '=== deployment state ==='
stat -Lc '%A %a %U:%G %n' /etc/sea-vhost/sea-vhost.env /opt/sea-vhost/web /www/server/panel/vhost/nginx 2>&1
find /www/server/panel/vhost/cert/host.ser888.cn -maxdepth 1 -type f -printf '%M %u:%g %f %s bytes\n' 2>/dev/null || true
systemctl is-enabled sea-vhost-agent sea-vhost-panel-broker sea-vhost-api 2>&1 || true
systemctl is-active sea-vhost-agent sea-vhost-panel-broker sea-vhost-api 2>&1 || true
ss -lnt | grep -E '(:80|:443|:8080|:3306)[[:space:]]' || true
printf '%s\n' '=== domain resolution ==='
getent ahostsv4 host.ser888.cn | head -n 3 || true
getent ahostsv4 sv0123456789.vhost.ser888.cn | head -n 3 || true
+84
View File
@@ -0,0 +1,84 @@
import http from 'node:http';
import https from 'node:https';
const consoleURL = process.env.SEA_CONSOLE_URL?.trim();
const connectHost = process.env.SEA_CONSOLE_CONNECT_HOST?.trim();
const adminEmail = process.env.SEA_ADMIN_EMAIL?.trim();
const adminPassword = process.env.SEA_ADMIN_PASSWORD;
if (!consoleURL || !connectHost || !adminEmail || !adminPassword) process.exit(2);
const base = new URL(consoleURL);
if (base.protocol !== 'https:') throw new Error('production verification requires HTTPS');
function request(pathname, { method = 'GET', body, cookie, expected, protocol = 'https:' } = {}) {
const payload = body === undefined ? undefined : Buffer.from(JSON.stringify(body));
const secure = protocol === 'https:';
const client = secure ? https : http;
const port = secure ? Number(base.port || 443) : 80;
const headers = { Accept: 'application/json', Host: base.host };
if (payload) {
headers['Content-Type'] = 'application/json';
headers['Content-Length'] = payload.length;
}
if (cookie) headers.Cookie = cookie;
return new Promise((resolve, reject) => {
const req = client.request({
hostname: connectHost, port, path: pathname, method, headers, timeout: 20_000,
...(secure ? { servername: base.hostname, rejectUnauthorized: true } : {}),
}, (response) => {
let text = '';
response.setEncoding('utf8');
response.on('data', (chunk) => { text += chunk; });
response.on('end', () => {
let decoded;
try { decoded = text ? JSON.parse(text) : undefined; } catch { decoded = undefined; }
const accepted = expected ? expected.includes(response.statusCode) : response.statusCode >= 200 && response.statusCode < 300;
if (!accepted) return reject(new Error(`${method} ${pathname} returned HTTP ${response.statusCode}`));
resolve({ status: response.statusCode, headers: response.headers, payload: decoded, text });
});
});
req.on('timeout', () => req.destroy(new Error(`${method} ${pathname} timed out`)));
req.on('error', reject);
req.end(payload);
});
}
const health = await request('/healthz');
if (health.payload?.status !== 'ok') throw new Error('health endpoint did not report ok');
const setup = await request('/api/v1/setup/status');
if (setup.payload?.required !== false) throw new Error('setup endpoint is still open');
const login = await request('/api/v1/auth/login', { method: 'POST', body: { identifier: adminEmail, password: adminPassword } });
const cookie = login.headers['set-cookie']?.[0]?.split(';', 1)[0];
if (!cookie?.startsWith('sea_session=')) throw new Error('administrator session cookie is missing');
const [tenants, plans, approval, management, settings, home] = await Promise.all([
request('/api/v1/admin/tenants', { cookie }),
request('/api/v1/admin/plans', { cookie }),
request('/api/v1/admin/settings/domain-approval', { cookie }),
request('/api/v1/admin/overview', { cookie }),
request('/api/v1/admin/settings', { cookie }),
request('/'),
]);
if (!Array.isArray(management.payload?.users) || !Array.isArray(management.payload?.projects) || !Array.isArray(management.payload?.domains) || !Array.isArray(management.payload?.ipAddresses) || !Array.isArray(management.payload?.logs)) throw new Error('management overview shape is invalid');
if (settings.payload?.graceDays !== 3 || settings.payload?.recycleDays !== 7 || settings.payload?.backupRetentionDays !== 14 || settings.payload?.oidc?.bindingOnly !== true || settings.payload?.oidc?.passwordLogin !== true) throw new Error('management settings are invalid');
if ('secret' in (settings.payload?.smtp || {}) || 'secret' in (settings.payload?.oidc || {})) throw new Error('management settings exposed a stored secret');
const redirect = await request('/', { protocol: 'http:', expected: [301, 308] });
const location = String(redirect.headers.location || '');
if (!location.startsWith(`https://${base.hostname}`)) throw new Error('HTTP does not redirect to the management HTTPS origin');
for (const name of ['strict-transport-security', 'content-security-policy', 'x-content-type-options', 'x-frame-options']) {
if (!home.headers[name]) throw new Error(`security header is missing: ${name}`);
}
console.log(JSON.stringify({
result: 'success',
consoleURL: base.toString(),
health: health.payload.status,
setupClosed: true,
administratorLogin: true,
tenantCount: tenants.payload?.tenants?.length ?? null,
planCount: plans.payload?.plans?.length ?? null,
domainApproval: approval.payload?.enabled,
managementOverview: true,
lifecycle: `${settings.payload.graceDays}/${settings.payload.recycleDays}/${settings.payload.backupRetentionDays}`,
ssoBindingOnly: true,
httpsRedirect: true,
securityHeaders: true,
}, null, 2));
+366
View File
@@ -0,0 +1,366 @@
import crypto from 'node:crypto';
import http from 'node:http';
import https from 'node:https';
const publicURL = process.env.SEA_PUBLIC_TARGET_URL?.trim() || process.env.SEA_CONSOLE_URL?.trim();
const panelURL = process.env.SEA_PANEL_URL?.trim();
const insecureTLS = process.env.SEA_PUBLIC_TLS_INSECURE === 'true' || process.env.SEA_PANEL_TLS_INSECURE === 'true';
if (!publicURL) {
console.error('SEA_PUBLIC_TARGET_URL or SEA_CONSOLE_URL is required.');
process.exit(2);
}
function parseTarget(value, label) {
const target = new URL(value);
if (!['http:', 'https:'].includes(target.protocol) || target.username || target.password) {
throw new Error(`${label} must be an HTTP(S) URL without embedded credentials`);
}
return target;
}
const publicTarget = parseTarget(publicURL, 'public target');
const panelTarget = panelURL ? parseTarget(panelURL, 'panel target') : undefined;
const probeID = crypto.randomBytes(8).toString('hex');
const attackerHost = `${probeID}.attacker.invalid`;
const maxBodyBytes = 512 * 1024;
const results = [];
function record(level, name, detail) {
results.push({ level, name, detail });
}
function requestOnce(target, path, { method = 'GET', headers = {}, body } = {}) {
const transport = target.protocol === 'https:' ? https : http;
const payload = body === undefined ? undefined : Buffer.from(body);
const agent = target.protocol === 'https:' ? new https.Agent({ rejectUnauthorized: !insecureTLS }) : undefined;
return new Promise((resolve, reject) => {
const req = transport.request({
protocol: target.protocol,
hostname: target.hostname,
port: target.port || undefined,
...(target.protocol === 'https:' ? { servername: target.hostname } : {}),
method,
path,
agent,
timeout: 10_000,
headers: {
Host: target.host,
'User-Agent': 'Sea-vHost-public-security-smoke/1.0',
Accept: '*/*',
Connection: 'close',
...(payload ? { 'Content-Length': payload.length } : {}),
...headers,
},
}, (response) => {
const chunks = [];
let length = 0;
let truncated = false;
response.on('data', (chunk) => {
if (length >= maxBodyBytes) {
truncated = true;
return;
}
const remaining = maxBodyBytes - length;
chunks.push(chunk.subarray(0, remaining));
length += Math.min(chunk.length, remaining);
if (chunk.length > remaining) truncated = true;
});
response.on('end', () => resolve({
status: response.statusCode ?? 0,
headers: response.headers,
body: Buffer.concat(chunks).toString('utf8'),
truncated,
}));
});
req.on('timeout', () => req.destroy(new Error('request timed out')));
req.on('error', reject);
req.end(payload);
});
}
async function request(target, path, options = {}) {
let lastError;
for (let attempt = 0; attempt < 2; attempt += 1) {
try {
return await requestOnce(target, path, options);
} catch (error) {
lastError = error;
if (attempt === 0) await new Promise((resolve) => setTimeout(resolve, 250));
}
}
throw lastError;
}
function websocketHandshakeOnce(target, path) {
const transport = target.protocol === 'https:' ? https : http;
const agent = target.protocol === 'https:' ? new https.Agent({ rejectUnauthorized: !insecureTLS }) : undefined;
return new Promise((resolve, reject) => {
let settled = false;
const finish = (value) => {
if (settled) return;
settled = true;
resolve(value);
};
const req = transport.request({
protocol: target.protocol,
hostname: target.hostname,
port: target.port || undefined,
...(target.protocol === 'https:' ? { servername: target.hostname } : {}),
method: 'GET',
path,
agent,
timeout: 10_000,
headers: {
Host: target.host,
Origin: 'https://attacker.invalid',
Upgrade: 'websocket',
Connection: 'Upgrade',
'Sec-WebSocket-Key': crypto.randomBytes(16).toString('base64'),
'Sec-WebSocket-Version': '13',
'User-Agent': 'Sea-vHost-public-security-smoke/1.0',
},
});
req.on('upgrade', (response, socket) => {
socket.destroy();
finish({ status: response.statusCode ?? 101, upgraded: true });
});
req.on('response', (response) => {
response.resume();
response.on('end', () => finish({ status: response.statusCode ?? 0, upgraded: false }));
});
req.on('timeout', () => req.destroy(new Error('WebSocket handshake timed out')));
req.on('error', reject);
req.end();
});
}
async function websocketHandshake(target, path) {
let lastError;
for (let attempt = 0; attempt < 2; attempt += 1) {
try {
return await websocketHandshakeOnce(target, path);
} catch (error) {
lastError = error;
if (attempt === 0) await new Promise((resolve) => setTimeout(resolve, 500));
}
}
throw lastError;
}
const digest = (value) => crypto.createHash('sha256').update(value).digest('hex');
const deniedStatus = (status) => [400, 401, 403, 404, 405, 410, 421].includes(status);
const disclosureSignatures = [
/root:x:0:0:/i,
/\[core\][\s\S]{0,200}repositoryformatversion/i,
/(?:DB_PASSWORD|DATABASE_URL|APP_KEY|SEA_PANEL_API_KEY)\s*=/i,
/-----BEGIN (?:RSA |EC |OPENSSH )?PRIVATE KEY-----/,
/(?:CREATE TABLE|INSERT INTO)\s+[`"[]/i,
/<web-app(?:\s|>)/i,
/PHP Version\s*(?:<|=>)/i,
/"(?:propertySources|activeProfiles)"\s*:/i,
/"openapi"\s*:\s*"3\./i,
];
async function main() {
const baseline = await request(publicTarget, publicTarget.pathname || '/');
if (baseline.status < 200 || baseline.status >= 400) record('warning', 'public baseline', `HTTP ${baseline.status}`);
else record('passed', 'public baseline', `HTTP ${baseline.status}`);
const baselineDigest = digest(baseline.body);
const server = String(baseline.headers.server ?? '');
if (/\d+\.\d+/.test(server)) record('warning', 'server version disclosure', server);
else record('passed', 'server version disclosure', server || 'header absent');
if (baseline.headers['x-powered-by']) record('warning', 'framework disclosure', String(baseline.headers['x-powered-by']));
else record('passed', 'framework disclosure', 'X-Powered-By absent');
for (const [header, expected] of [
['x-content-type-options', /nosniff/i],
['x-frame-options', /deny|sameorigin/i],
['content-security-policy', /default-src/i],
['referrer-policy', /./],
['permissions-policy', /./],
]) {
const value = String(baseline.headers[header] ?? '');
record(expected.test(value) ? 'passed' : 'warning', `header ${header}`, value || 'missing');
}
if (publicTarget.protocol === 'https:') {
const hsts = String(baseline.headers['strict-transport-security'] ?? '');
record(/max-age=\d+/i.test(hsts) ? 'passed' : 'warning', 'HTTPS HSTS', hsts || 'missing');
} else {
record('warning', 'transport security', 'target uses plain HTTP; acceptable only for the disposable forwarded test endpoint');
}
for (const method of ['TRACE', 'TRACK', 'PUT', 'DELETE', 'PATCH']) {
const response = await request(publicTarget, `/sea-vhost-method-probe-${probeID}`, { method });
record(deniedStatus(response.status) ? 'passed' : 'failed', `dangerous method ${method}`, `HTTP ${response.status}`);
}
const sensitivePaths = [
'/.env', '/.git/config', '/.svn/entries', '/.hg/store/fncache', '/config.json', '/config.yml',
'/backup.zip', '/site.tar.gz', '/database.sql', '/composer.json', '/package.json', '/go.mod',
'/requirements.txt', '/WEB-INF/web.xml', '/server-status', '/nginx_status', '/phpinfo.php', '/info.php',
'/debug/pprof/', '/actuator/env', '/actuator/heapdump', '/swagger/index.html', '/openapi.json', '/api-docs',
'/vendor/phpunit/phpunit/src/Util/PHP/eval-stdin.php', '/cgi-bin/status',
];
let sensitiveDenied = 0;
let sensitiveSPAFallback = 0;
let sensitiveWarnings = 0;
for (const path of sensitivePaths) {
const response = await request(publicTarget, path);
if (disclosureSignatures.some((pattern) => pattern.test(response.body))) {
record('failed', `sensitive path ${path}`, `HTTP ${response.status}, disclosure signature found`);
} else if (deniedStatus(response.status) || [301, 302, 307, 308].includes(response.status)) {
sensitiveDenied += 1;
} else if (response.status === baseline.status && digest(response.body) === baselineDigest) {
sensitiveSPAFallback += 1;
} else if (response.status >= 200 && response.status < 300) {
sensitiveWarnings += 1;
record('warning', `sensitive path ${path}`, `distinct HTTP ${response.status} response; inspect manually`);
} else {
sensitiveDenied += 1;
}
}
record('passed', 'common sensitive and exploit paths', `${sensitiveDenied} denied/redirected, ${sensitiveSPAFallback} SPA fallbacks, ${sensitiveWarnings} manual warnings`);
const traversalPaths = [
'/..%2f..%2f..%2fetc%2fpasswd',
'/%2e%2e/%2e%2e/%2e%2e/etc/passwd',
'/%252e%252e%252f%252e%252e%252fetc%252fpasswd',
'/cgi-bin/.%2e/.%2e/.%2e/.%2e/etc/passwd',
'/api/v1/projects/1/files?path=..%2F..%2Fetc%2Fpasswd',
];
for (const path of traversalPaths) {
const response = await request(publicTarget, path);
const leaked = /root:x:0:0:/.test(response.body);
record(leaked ? 'failed' : 'passed', `path traversal ${path}`, leaked ? 'passwd signature returned' : `HTTP ${response.status}, no passwd signature`);
}
const unauthenticated = await request(publicTarget, '/api/v1/dashboard', {
headers: { Origin: 'https://attacker.invalid' },
});
const allowOrigin = String(unauthenticated.headers['access-control-allow-origin'] ?? '');
if (![401, 403, 404].includes(unauthenticated.status)) record('failed', 'unauthenticated API', `HTTP ${unauthenticated.status}`);
else record('passed', 'unauthenticated API', `HTTP ${unauthenticated.status}`);
record(allowOrigin === '*' || allowOrigin.includes('attacker.invalid') ? 'failed' : 'passed', 'CORS origin reflection', allowOrigin || 'no permissive ACAO');
const crossOrigin = await request(publicTarget, '/api/v1/auth/login', {
method: 'POST',
headers: { Origin: 'https://attacker.invalid', 'Content-Type': 'application/json' },
body: JSON.stringify({ identifier: `probe-${probeID}@invalid.test`, password: `invalid-${probeID}` }),
});
record(crossOrigin.status === 403 ? 'passed' : 'failed', 'cross-origin state request', `HTTP ${crossOrigin.status}`);
const hostProbe = await request(publicTarget, '/api/v1/dashboard', { headers: { Host: attackerHost } });
const hostLocation = String(hostProbe.headers.location ?? '');
const hostReflected = hostLocation.includes(attackerHost) || hostProbe.body.includes(attackerHost);
record(!hostReflected && [400, 403, 404, 421].includes(hostProbe.status) ? 'passed' : 'failed', 'Host header boundary', `HTTP ${hostProbe.status}, reflected=${hostReflected}`);
const forwardedProbe = await request(publicTarget, '/api/v1/dashboard', {
headers: {
'X-Forwarded-Host': attackerHost,
'X-Forwarded-Proto': 'https',
Forwarded: `host=${attackerHost};proto=https`,
},
});
const forwardedLocation = String(forwardedProbe.headers.location ?? '');
const forwardedReflected = forwardedLocation.includes(attackerHost) || forwardedProbe.body.includes(attackerHost);
record(forwardedReflected ? 'failed' : 'passed', 'forwarded Host reflection', `HTTP ${forwardedProbe.status}, reflected=${forwardedReflected}`);
for (const path of [
`/?next=https%3A%2F%2F${attackerHost}%2F`,
`/login?redirect=%2F%2F${attackerHost}%2F`,
`/api/v1/auth/login?returnUrl=https%3A%2F%2F${attackerHost}%2F`,
]) {
const response = await request(publicTarget, path);
const location = String(response.headers.location ?? '');
let external = false;
try { external = Boolean(location) && new URL(location, publicTarget).hostname === attackerHost; } catch { external = true; }
record(external ? 'failed' : 'passed', `open redirect ${path.split('?')[0]}`, location || `HTTP ${response.status}, no Location`);
}
const xssPayload = `<svg/onload=confirm('${probeID}')>`;
const xssProbe = await request(publicTarget, `/?q=${encodeURIComponent(xssPayload)}`);
record(xssProbe.body.includes(xssPayload) ? 'failed' : 'passed', 'reflected XSS probe', xssProbe.body.includes(probeID) ? 'marker reflected without raw payload' : 'payload not reflected');
const scriptSources = [...baseline.body.matchAll(/<script[^>]+src=["']([^"']+\.js)["']/gi)].map((match) => match[1]).slice(0, 12);
let exposedMaps = 0;
for (const source of scriptSources) {
const sourceURL = new URL(source, publicTarget);
const response = await request(publicTarget, `${sourceURL.pathname}.map`);
if (response.status === 200 && /"sources"\s*:/.test(response.body) && /"mappings"\s*:/.test(response.body)) exposedMaps += 1;
}
record(exposedMaps ? 'warning' : 'passed', 'JavaScript source maps', exposedMaps ? `${exposedMaps} source map(s) exposed` : 'none exposed');
if (panelTarget) {
const panelEndpoints = [
['/crontab', 'action=GetCrontab'],
['/site', 'action=get_site_types'],
['/database', 'action=GetList'],
['/ftp', 'action=get_list'],
['/system', 'action=GetSystemTotal'],
];
for (const [path, body] of panelEndpoints) {
const response = await request(panelTarget, path, {
method: 'POST',
headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
body,
});
let privileged = false;
try {
const payload = JSON.parse(response.body);
privileged = payload?.status === true || Array.isArray(payload?.data) || Array.isArray(payload);
} catch { /* login/security-entry HTML is not privileged API data */ }
record(privileged ? 'failed' : 'passed', `aaPanel unauthenticated ${path}`, `HTTP ${response.status}, privileged_data=${privileged}`);
}
const forgedToken = new URLSearchParams({
action: 'GetCrontab',
request_time: Math.floor(Date.now() / 1000).toString(),
request_token: crypto.randomBytes(16).toString('hex'),
}).toString();
const forgedResponse = await request(panelTarget, '/crontab', {
method: 'POST',
headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
body: forgedToken,
});
let forgedPrivileged = false;
try {
const payload = JSON.parse(forgedResponse.body);
forgedPrivileged = payload?.status === true || Array.isArray(payload?.data) || Array.isArray(payload);
} catch { /* login/security-entry HTML is not privileged API data */ }
record(forgedPrivileged ? 'failed' : 'passed', 'aaPanel forged API signature', `HTTP ${forgedResponse.status}, privileged_data=${forgedPrivileged}`);
for (const path of [
'/sock_shell', '/webssh', '/ws_panel', '/ws_home', '/ws_project', '/ws_model', '/workorder_client',
'/v2/sock_shell', '/v2/webssh', '/v2/ws_panel', '/v2/ws_home', '/v2/ws_project', '/v2/ws_model',
]) {
const handshake = await websocketHandshake(panelTarget, path);
record(handshake.upgraded ? 'failed' : 'passed', `aaPanel cross-origin WebSocket ${path}`, `HTTP ${handshake.status}, upgraded=${handshake.upgraded}`);
}
for (const path of ['/.env', '/config/config.json', '/data/default.db', '/www/server/panel/data/default.db']) {
const response = await request(panelTarget, path);
const leaked = disclosureSignatures.some((pattern) => pattern.test(response.body)) || response.body.startsWith('SQLite format 3');
record(leaked ? 'failed' : 'passed', `aaPanel sensitive path ${path}`, leaked ? 'disclosure signature found' : `HTTP ${response.status}, no disclosure signature`);
}
}
const failed = results.filter((item) => item.level === 'failed');
const warnings = results.filter((item) => item.level === 'warning');
console.log(JSON.stringify({
status: failed.length ? 'failed' : 'passed',
target: publicTarget.origin,
panelTarget: panelTarget?.origin,
probeID,
summary: {
passed: results.filter((item) => item.level === 'passed').length,
warnings: warnings.length,
failed: failed.length,
},
warnings,
failed,
}, null, 2));
if (failed.length) process.exitCode = 1;
}
main().catch((error) => {
console.error(`Public vulnerability smoke failed: ${error instanceof Error ? error.message : 'unknown error'}`);
process.exitCode = 1;
});
+21
View File
@@ -0,0 +1,21 @@
#!/usr/bin/env bash
set +e
printf '%s\n' '=== TLS-related configuration ==='
grep -nEi 'TLS|Cert|PEM|SSL' /www/server/pure-ftpd/etc/pure-ftpd.conf /etc/init.d/pure-ftpd 2>&1 || true
grep -nEi 'CertFile|--certfile|-2' /www/server/pure-ftpd/sbin/pure-config.pl /www/server/pure-ftpd/sbin/pure-config.py 2>&1 || true
printf '%s\n' '=== Pure-FTPd TLS options ==='
/www/server/pure-ftpd/sbin/pure-ftpd --help 2>&1 | grep -Ei 'tls|cert|pem|ssl' || true
printf '%s\n' '=== compiled certificate paths ==='
strings /www/server/pure-ftpd/sbin/pure-ftpd | grep -E '/[^ ]*(pure-ftpd|ssl)[^ ]*\.pem|pure-ftpd\.pem' | sort -u | head -n 30 || true
printf '%s\n' '=== candidate certificates ==='
find /www/server/pure-ftpd /etc/ssl/private /etc/pure-ftpd -xdev -maxdepth 5 -type f \( -name '*.pem' -o -name '*.crt' \) -print 2>/dev/null | while IFS= read -r candidate; do
printf '%s ' "${candidate}"
openssl x509 -in "${candidate}" -noout -subject 2>/dev/null || echo 'not-an-x509-certificate'
done
printf '%s\n' '=== running daemon identity ==='
for ftp_pid in $(pgrep pure-ftpd 2>/dev/null || true); do
printf 'pid=%s user=' "${ftp_pid}"
ps -o user= -p "${ftp_pid}"
ls -l "/proc/${ftp_pid}/fd" 2>&1 | grep -Ei 'pem|ssl|cert' || true
done
+315
View File
@@ -0,0 +1,315 @@
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 consoleURL = process.env.SEA_CONSOLE_URL?.trim();
const configuredManagementDomain = (process.env.SEA_TEST_ACCESS_HOST || process.env.SEA_MANAGEMENT_DOMAIN)?.trim();
const testRootDomain = process.env.SEA_TEST_ROOT_DOMAIN?.trim();
const testManagementDomain = process.env.SEA_TEST_MANAGEMENT_DOMAIN?.trim();
const testFTPDomain = process.env.SEA_TEST_FTP_DOMAIN?.trim();
const insecureTLS = process.env.SEA_PANEL_TLS_INSECURE === 'true';
if (!panelURL || !panelAPIKey || !consoleURL || !testRootDomain || !testManagementDomain || !testFTPDomain) {
console.error('SEA_PANEL_URL, SEA_PANEL_API_KEY, SEA_CONSOLE_URL, SEA_TEST_ROOT_DOMAIN, SEA_TEST_MANAGEMENT_DOMAIN and SEA_TEST_FTP_DOMAIN are required.');
process.exit(2);
}
const panelBase = new URL(panelURL);
const consoleBase = new URL(consoleURL);
if (!['http:', 'https:'].includes(consoleBase.protocol) || consoleBase.username || consoleBase.password) {
throw new Error('SEA_CONSOLE_URL must be an HTTP(S) URL without credentials');
}
if (configuredManagementDomain && !/^[A-Za-z0-9.-]+$/.test(configuredManagementDomain)) {
throw new Error('SEA_TEST_ACCESS_HOST must be a host name or IP address');
}
for (const [name, value] of Object.entries({ SEA_TEST_ROOT_DOMAIN: testRootDomain, SEA_TEST_MANAGEMENT_DOMAIN: testManagementDomain, SEA_TEST_FTP_DOMAIN: testFTPDomain })) {
if (!/^(?=.{1,253}$)(?:[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?$/i.test(value)) throw new Error(`${name} must be a valid domain name`);
}
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 randomPassword = () => `Sv-${crypto.randomBytes(15).toString('base64url')}9a`;
function authFields() {
const requestTime = Math.floor(Date.now() / 1000).toString();
return { request_time: requestTime, request_token: md5(requestTime + md5(panelAPIKey)) };
}
function panelForm(pathname, values, timeoutMs = 30_000) {
const body = Buffer.from(new URLSearchParams({ ...values, ...authFields() }).toString());
const url = new URL(pathname, panelBase);
return new Promise((resolve, reject) => {
const request = panelClient.request(url, {
method: 'POST', agent: panelAgent, timeout: timeoutMs,
headers: { 'content-type': 'application/x-www-form-urlencoded', 'content-length': body.length },
}, (response) => {
let data = '';
response.setEncoding('utf8');
response.on('data', (chunk) => {
data += chunk;
if (data.length > 2 * 1024 * 1024) request.destroy(new Error('panel response exceeded 2 MB'));
});
response.on('end', () => {
if (response.statusCode < 200 || response.statusCode > 299) {
reject(new Error(`panel returned HTTP ${response.statusCode}`));
return;
}
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 panelFileText(payload) {
if (typeof payload === 'string') return payload;
for (const key of ['data', 'msg', 'content']) {
if (typeof payload?.[key] === 'string') return payload[key];
}
throw new Error('panel did not return the requested file');
}
async function api(pathname, { method = 'GET', body, token, cookie, expected } = {}) {
const headers = { Accept: 'application/json' };
if (body !== undefined) headers['Content-Type'] = 'application/json';
if (token) headers['X-Setup-Token'] = token;
if (cookie) headers.Cookie = cookie;
const response = await fetch(new URL(pathname, consoleBase), {
method, headers, body: body === undefined ? undefined : JSON.stringify(body), redirect: 'manual',
});
const text = await response.text();
let payload;
try { payload = text ? JSON.parse(text) : undefined; } catch { payload = undefined; }
const accepted = expected ? expected.includes(response.status) : response.status >= 200 && response.status < 300;
if (!accepted) {
const message = payload?.error?.message || `HTTP ${response.status}`;
throw new Error(`${method} ${pathname} failed: ${message}`);
}
return { response, payload };
}
function sessionCookie(response) {
const setCookie = typeof response.headers.getSetCookie === 'function'
? response.headers.getSetCookie()[0]
: response.headers.get('set-cookie');
const cookie = setCookie?.split(';', 1)[0];
if (!cookie?.startsWith('sea_session=')) throw new Error('login did not return a Sea vHost session cookie');
return cookie;
}
async function waitFor(pathname, predicate, attempts = 30) {
let lastError;
for (let attempt = 0; attempt < attempts; attempt += 1) {
try {
const result = await api(pathname);
if (predicate(result.payload)) return result.payload;
} catch (error) { lastError = error; }
await new Promise((resolve) => setTimeout(resolve, 1000));
}
throw lastError || new Error(`timed out waiting for ${pathname}`);
}
async function checkSiteThroughServerNginx(domain, rootDomain) {
const hostName = domain.split('.', 1)[0];
if (!/^sv[0-9a-f]{10}$/.test(hostName) || domain !== `${hostName}.${rootDomain}`) {
throw new Error('project returned an unexpected domain');
}
const marker = `Sea-vHost-site-check-${crypto.randomBytes(6).toString('hex')}`;
const task = await panelForm('/crontab', {
action: 'AddCrontab', name: `Sea vHost local site check ${Date.now().toString().slice(-7)}`,
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: `set -eo pipefail\ncurl --silent --show-error --fail --max-time 10 --header 'Host: ${domain}' http://127.0.0.1/ | grep -Fq 'sea-vhost-real-ok'\nprintf '%s\\n' '${marker}'`,
sName: 'Temporary Sea vHost loopback site check', save: '0', backupTo: 'localhost',
});
const taskID = Number(task?.id);
if ((task?.status !== true && task?.status !== 'true') || !Number.isSafeInteger(taskID) || taskID <= 0) {
throw new Error('aaPanel rejected the temporary local site check');
}
try {
await panelForm('/crontab', { action: 'StartTask', id: String(taskID) });
for (let attempt = 0; attempt < 100; attempt += 1) {
await new Promise((resolve) => setTimeout(resolve, 1000));
const result = await panelForm('/crontab', { action: 'GetLogs', id: String(taskID) });
const log = typeof result?.msg === 'string' ? result.msg : typeof result === 'string' ? result : '';
if (log.includes(marker)) return;
}
throw new Error('provisioned PHP site did not return the expected content through server Nginx');
} finally {
try { await panelForm('/crontab', { action: 'DelCrontab', id: String(taskID) }); } catch { /* best effort */ }
}
}
async function enableTestManagementHost(host) {
if (!host) return;
const marker = `Sea-vHost-management-host-${crypto.randomBytes(6).toString('hex')}`;
const python = `import json; p='/var/lib/sea-vhost/config.json'; d=json.load(open(p, encoding='utf-8')); d['management_domain']=${JSON.stringify(host)}; f=open(p, 'w', encoding='utf-8'); json.dump(d, f, indent=2); f.write('\\n'); f.close()`;
const task = await panelForm('/crontab', {
action: 'AddCrontab', name: `Sea vHost test host ${Date.now().toString().slice(-7)}`,
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: `set -eo pipefail\npython3 -c ${JSON.stringify(python)}\nsystemctl restart sea-vhost-api\nfor attempt in {1..30}; do if curl --silent --show-error --fail --max-time 2 --header 'Host: ${host}' http://127.0.0.1:8080/healthz >/dev/null; then break; fi; sleep 1; done\ncurl --silent --show-error --fail --max-time 2 --header 'Host: ${host}' http://127.0.0.1:8080/healthz >/dev/null\nprintf '%s\\n' '${marker}'`,
sName: 'Temporary Sea vHost forwarded test-host configuration', save: '0', backupTo: 'localhost',
});
const taskID = Number(task?.id);
if ((task?.status !== true && task?.status !== 'true') || !Number.isSafeInteger(taskID) || taskID <= 0) {
throw new Error('aaPanel rejected the temporary management-host configuration');
}
try {
await panelForm('/crontab', { action: 'StartTask', id: String(taskID) });
for (let attempt = 0; attempt < 100; attempt += 1) {
await new Promise((resolve) => setTimeout(resolve, 1000));
const result = await panelForm('/crontab', { action: 'GetLogs', id: String(taskID) });
const log = typeof result?.msg === 'string' ? result.msg : typeof result === 'string' ? result : '';
if (log.includes(marker)) return;
}
throw new Error('temporary management-host configuration did not complete');
} finally {
try { await panelForm('/crontab', { action: 'DelCrontab', id: String(taskID) }); } catch { /* best effort */ }
}
}
const suffix = Date.now().toString(36).slice(-7);
const databaseName = `sea_vh_${suffix}`.slice(0, 16);
const databasePassword = randomPassword();
const adminEmail = `admin-${suffix}@seavhost.test`;
const adminPassword = randomPassword();
const tenantEmail = `tenant-${suffix}@seavhost.test`;
const tenantPassword = randomPassword();
const tenantSlug = `real-${suffix}`;
let databaseID = 0;
let databaseCreated = false;
let setupCompleted = false;
try {
const environment = panelFileText(await panelForm('/files', { action: 'GetFileBody', path: '/etc/sea-vhost/sea-vhost.env' }));
const setupToken = environment.match(/^SEA_SETUP_TOKEN=(.+)$/m)?.[1]?.trim();
if (!setupToken || setupToken.length < 24) throw new Error('installed setup token is unavailable');
const panelPortText = panelFileText(await panelForm('/files', { action: 'GetFileBody', path: '/www/server/panel/data/port.pl' }));
const panelPort = Number(panelPortText.trim());
if (!Number.isInteger(panelPort) || panelPort < 1 || panelPort > 65535) throw new Error('aaPanel local port is invalid');
const databaseResult = 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 control database',
});
if (databaseResult?.status !== true && databaseResult?.status !== 'true') throw new Error('aaPanel rejected control database creation');
databaseID = Number(databaseResult.id);
databaseCreated = true;
if (!Number.isSafeInteger(databaseID) || databaseID <= 0) databaseID = 0;
await waitFor('/api/v1/setup/status', (payload) => payload?.required === true);
const rootDomain = testRootDomain;
const managementDomain = testManagementDomain;
const ftpDomain = testFTPDomain;
await api('/api/v1/setup/test-database', {
method: 'POST', token: setupToken,
body: { host: '127.0.0.1', port: 3306, name: databaseName, user: databaseName, password: databasePassword },
});
const panelCheck = await api('/api/v1/setup/test-panel', {
method: 'POST', token: setupToken,
body: { url: `https://127.0.0.1:${panelPort}/`, apiKey: panelAPIKey, tlsInsecure: true },
});
await api('/api/v1/setup/install', {
method: 'POST', token: setupToken, expected: [201],
body: {
database: { host: '127.0.0.1', port: 3306, name: databaseName, user: databaseName, password: databasePassword },
panel: { url: `https://127.0.0.1:${panelPort}/`, apiKey: panelAPIKey, tlsInsecure: true },
rootDomain, managementDomain, ftpDomain, domainApproval: true,
adminEmail, adminName: '实机测试管理员', adminPassword,
},
});
setupCompleted = true;
// This disposable server is behind a provider gateway that rejects the
// valid management-domain Host header before it reaches Nginx. Keep the
// production-grade domain validation in the installer, then explicitly
// switch only this test deployment to the forwarded IP for API acceptance.
await enableTestManagementHost(configuredManagementDomain);
await waitFor('/healthz', (payload) => payload?.status === 'ok', 45);
const adminLogin = await api('/api/v1/auth/login', { method: 'POST', body: { identifier: adminEmail, password: adminPassword } });
const adminCookie = sessionCookie(adminLogin.response);
const plan = await api('/api/v1/admin/plans', {
method: 'POST', cookie: adminCookie, expected: [201],
body: {
name: `实机测试套餐-${suffix}`, storageBytes: 1_048_576, databaseBytes: 16_777_216,
bandwidthBytes: 1_073_741_824, processLimit: 10, ftpLimit: 2, databaseLimit: 2, projectLimit: 2,
},
});
const planID = Number(plan.payload?.id);
await api('/api/v1/admin/tenants', {
method: 'POST', cookie: adminCookie, expected: [201],
body: {
slug: tenantSlug, name: 'Sea vHost 实机测试租户', email: tenantEmail,
displayName: '测试租户管理员', password: tenantPassword, planId: planID,
},
});
const tenantLogin = await api('/api/v1/auth/login', { method: 'POST', body: { identifier: tenantEmail, password: tenantPassword } });
const tenantCookie = sessionCookie(tenantLogin.response);
const catalog = await api('/api/v1/runtime-catalog', { cookie: tenantCookie });
const phpVersion = catalog.payload?.versions?.PHP?.[0];
if (!phpVersion) throw new Error('aaPanel did not report an installed PHP version');
const projectResult = await api('/api/v1/projects', {
method: 'POST', cookie: tenantCookie, expected: [201],
body: { name: `web-${suffix}`, runtime: 'PHP', version: phpVersion, runPath: '/public', customDomain: '', autoSSL: false },
});
const project = projectResult.payload?.project;
const credentials = projectResult.payload?.credentials;
if (!project?.id || project.status !== 'running' || !credentials?.hostLogin) throw new Error('project provisioning returned an incomplete result');
await api(`/api/v1/projects/${project.id}/files`, {
method: 'PUT', cookie: tenantCookie, expected: [204],
body: { path: 'public/index.php', content: '<?php echo "sea-vhost-real-ok";', overwrite: false },
});
const largeFile = new Blob([new Uint8Array(2 * 1024 * 1024)]);
const form = new FormData();
form.set('path', 'public');
form.set('overwrite', 'false');
form.set('file', largeFile, 'quota-check.bin');
const quotaResponse = await fetch(new URL(`/api/v1/projects/${project.id}/files`, consoleBase), {
method: 'POST', headers: { Cookie: tenantCookie }, body: form,
});
if (quotaResponse.status !== 507) throw new Error(`soft quota upload returned HTTP ${quotaResponse.status}, want 507`);
const resources = await api('/api/v1/resources', { cookie: tenantCookie });
if (resources.payload?.ftpAccounts?.length !== 1 || resources.payload?.databases?.length !== 1 || resources.payload?.sites?.length !== 1) {
throw new Error('resource inventory is incomplete after project provisioning');
}
const hostLogin = await api('/api/v1/auth/login', {
method: 'POST', body: { identifier: credentials.hostLogin, password: credentials.hostPassword },
});
const hostCookie = sessionCookie(hostLogin.response);
const hostDashboard = await api('/api/v1/dashboard', { cookie: hostCookie });
if (!hostDashboard.payload?.hostScoped || hostDashboard.payload?.projects?.length !== 1) throw new Error('host account boundary check failed');
// The test host is behind a provider port-forwarding gateway that replaces
// responses for unapproved random domains. Validate the generated vhost at
// the server's own Nginx listener, while the console itself remains tested
// through the public forwarding port above.
await checkSiteThroughServerNginx(project.domain, rootDomain);
console.log(JSON.stringify({
result: 'success', consoleURL: consoleBase.toString(), rootDomain,
admin: { login: adminEmail, password: adminPassword },
tenant: { login: tenantEmail, password: tenantPassword },
project: { id: project.id, hostName: project.hostName, domain: project.domain, runtime: `PHP ${phpVersion}`, status: project.status },
checks: {
setup: true, panel: true, database: true, project: true, ftp: true,
projectDatabase: true, webFiles: true, softQuotaRejectedOversizeWrite: true,
hostAccountBoundary: true, phpResponse: true,
},
runtimes: panelCheck.payload?.runtimes,
}, null, 2));
} catch (error) {
if (!setupCompleted && databaseCreated && databaseID > 0) {
try {
await panelForm('/database', { action: 'DeleteDatabase', id: String(databaseID), sid: '0', name: databaseName, db_user: databaseName });
} catch { /* best-effort rollback */ }
}
console.error(`Sea vHost real-panel smoke test failed: ${error instanceof Error ? error.message : 'unknown error'}`);
process.exitCode = 1;
}
+26
View File
@@ -0,0 +1,26 @@
{
"runtimeFiles": [
"README.md",
"deploy/README.md",
"deploy/install.sh",
"deploy/install-controller.sh",
"deploy/install-node.sh",
"deploy/install-wizard.py",
"deploy/preflight.sh",
"deploy/diagnose.sh",
"deploy/prepare-runtime-roots.sh",
"deploy/activate-production.sh",
"deploy/activate-production-ftps.sh",
"deploy/update-production-ftp-mode.sh",
"deploy/pureftp-certificate-probe.sh",
"deploy/production-health.sh"
],
"runtimeDirectories": ["build/bin", "build/web", "deploy/nginx", "deploy/systemd", "docs"],
"sourceFiles": [
"README.md", ".gitignore", ".gitattributes",
"backend/.env.example", "backend/go.mod", "backend/go.sum",
"frontend/index.html", "frontend/package.json", "frontend/package-lock.json",
"frontend/tsconfig.json", "frontend/tsconfig.app.json", "frontend/tsconfig.node.json", "frontend/vite.config.ts"
],
"sourceDirectories": ["backend/cmd", "backend/internal", "frontend/src", "deploy", "docs"]
}
+91
View File
@@ -0,0 +1,91 @@
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 apt repair ${nonce}`;
const source = '/etc/apt/sources.list.d/docker.list';
const disabled = `${source}.disabled`;
const expected = 'deb [arch=amd64 signed-by=/usr/share/keyrings/docker-archive-keyring.gpg] mirrors.aliyun.com/docker-ce/linux/debian 13 stable';
const shell = [
// aaPanel appends a wrapper that reads $1 after the task body.
'set -eo pipefail',
`source_file='${source}'`,
`disabled_file='${disabled}'`,
`expected='${expected}'`,
'test -f "$source_file" && test ! -L "$source_file"',
'test ! -e "$disabled_file"',
'actual="$(sed -e \"s/[[:space:]]*$//\" "$source_file")"',
'if [[ "$actual" != "$expected" ]]; then echo "Refusing to disable an unexpected apt source"; exit 1; fi',
'mv -- "$source_file" "$disabled_file"',
'rollback() { mv -- "$disabled_file" "$source_file" || true; }',
'trap rollback ERR',
'apt-get update',
'trap - ERR',
"printf '%s\\n' 'Sea vHost apt source repair: 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: 'One-time guarded apt source repair', save: '0', backupTo: 'localhost',
}), 'temporary repair 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 < 120; 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 apt source repair: success') || log.includes('Refusing to disable')) break;
}
if (!log.includes('Sea vHost apt source repair: success')) throw new Error(`apt source repair 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 */ }
}
}
+92
View File
@@ -0,0 +1,92 @@
#!/usr/bin/env bash
set -uo pipefail
if [[ -z "${SEA_ADMIN_EMAIL:-}" || -z "${SEA_ADMIN_PASSWORD:-}" ]]; then
echo "SEA_ADMIN_EMAIL and SEA_ADMIN_PASSWORD are required." >&2
exit 1
fi
set +e
/www/server/panel/pyenv/bin/python3 - <<'PY'
import json
import os
import re
import stat
import subprocess
import tempfile
from pathlib import Path
from urllib.parse import unquote
email = os.environ['SEA_ADMIN_EMAIL'].strip().lower()
password = os.environ['SEA_ADMIN_PASSWORD']
if not re.fullmatch(r'[^\s@]+@[^\s@]+\.[^\s@]+', email):
raise SystemExit('administrator email is invalid')
if len(password) < 14 or len(password) > 128:
raise SystemExit('administrator password length is invalid')
config_path = Path('/var/lib/sea-vhost/config.json')
if not config_path.is_file() or config_path.is_symlink():
raise SystemExit('Sea vHost configuration is missing or unsafe')
config = json.loads(config_path.read_text(encoding='utf-8'))
dsn = config.get('database_dsn', '')
match = re.fullmatch(r'([^:]+):([^@]+)@tcp\(([^:()]+):(\d+)\)/([^?]+)(?:\?.*)?', dsn)
if not match:
raise SystemExit('Sea vHost database DSN has an unexpected format')
db_user, db_password, db_host, db_port, db_name = (unquote(value) for value in match.groups())
php_binary = next((path for path in ('/www/server/php/84/bin/php', '/www/server/php/83/bin/php', '/usr/bin/php') if Path(path).is_file()), None)
mysql_binary = next((path for path in ('/www/server/mysql/bin/mysql', '/usr/bin/mysql', '/usr/bin/mariadb') if Path(path).is_file()), None)
if not php_binary or not mysql_binary:
raise SystemExit('PHP or MySQL client is unavailable')
hash_environment = os.environ.copy()
hash_environment['SEA_RESET_PASSWORD'] = password
password_hash = subprocess.check_output(
[php_binary, '-r', 'echo password_hash(getenv("SEA_RESET_PASSWORD"), PASSWORD_BCRYPT);'],
env=hash_environment,
text=True,
).strip()
if not re.fullmatch(r'\$2[aby]\$\d{2}\$[./A-Za-z0-9]{53}', password_hash):
raise SystemExit('PHP returned an invalid bcrypt hash')
escaped_email = email.replace("'", "''")
sql = (
f"UPDATE users SET password_hash='{password_hash}',status='active' "
f"WHERE role='admin' AND LOWER(email)='{escaped_email}';"
f"DELETE s FROM sessions s JOIN users u ON u.id=s.user_id "
f"WHERE u.role='admin' AND LOWER(u.email)='{escaped_email}';"
"SELECT COUNT(*) FROM users WHERE role='admin' AND status='active' "
f"AND LOWER(email)='{escaped_email}';"
)
mysql_environment = os.environ.copy()
mysql_environment['MYSQL_PWD'] = db_password
result = subprocess.check_output(
[mysql_binary, '--batch', '--skip-column-names', '--host', db_host, '--port', db_port, '--user', db_user, db_name, '--execute', sql],
env=mysql_environment,
text=True,
stderr=subprocess.STDOUT,
).strip().splitlines()
if not result or result[-1].strip() != '1':
raise SystemExit('administrator row was not updated exactly as expected')
credentials_path = Path('/etc/sea-vhost/admin-credentials')
handle, temporary_name = tempfile.mkstemp(prefix='.admin-credentials-', dir=str(credentials_path.parent), text=True)
try:
with os.fdopen(handle, 'w', encoding='utf-8') as output:
output.write(f'login={email}\npassword={password}\n')
output.flush()
os.fsync(output.fileno())
os.chmod(temporary_name, stat.S_IRUSR | stat.S_IWUSR)
os.chown(temporary_name, 0, 0)
os.replace(temporary_name, credentials_path)
finally:
try:
os.unlink(temporary_name)
except FileNotFoundError:
pass
print('Sea vHost production administrator password reset: success')
PY
reset_status=$?
if (( reset_status != 0 )); then
printf 'Sea vHost production administrator password reset: failed (status %s)\n' "${reset_status}" >&2
fi
set +u
+137
View File
@@ -0,0 +1,137 @@
import crypto from 'node:crypto';
import http from 'node:http';
import https from 'node:https';
if (!process.argv.includes('--confirm-test-reset')) {
console.error('Refusing to reset without --confirm-test-reset.');
process.exit(2);
}
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 === true || payload === 'true') return payload;
if (!payload || (payload.status !== true && payload.status !== 'true')) {
const detail = `: ${JSON.stringify({ type: typeof payload, status: payload?.status, keys: payload && typeof payload === 'object' ? Object.keys(payload) : [] })}`;
throw new Error(`${operation} was rejected by the panel${detail}`);
}
return payload;
}
const rowsFrom = (listing) => Array.isArray(listing?.data) ? listing.data : Array.isArray(listing) ? listing : [];
const databaseRows = rowsFrom(await formRequest('/data', { action: 'getData', table: 'databases', limit: '200', p: '1', search: 'sea_vh_' }));
const databases = databaseRows.map((row) => ({
id: Number(row.id), name: String(row.name ?? ''), username: String(row.username ?? row.db_user ?? row.name ?? ''),
})).filter((row) => Number.isSafeInteger(row.id) && row.id > 0 && /^sea_vh_[a-z0-9]{4,9}$/.test(row.name));
if (databaseRows.length > 0 && databases.length === 0) throw new Error('database listing returned rows but none matched the strict Sea vHost test prefix');
const managedHostPattern = /^sv[0-9a-f]{10}$/;
const ftpRows = rowsFrom(await formRequest('/data', { action: 'getData', table: 'ftps', limit: '200', p: '1', search: 'sv' }));
const orphanFTPs = ftpRows.map((row) => ({ id: Number(row.id), name: String(row.name ?? row.username ?? ''), ps: String(row.ps ?? '') }))
.filter((row) => Number.isSafeInteger(row.id) && row.id > 0 && managedHostPattern.test(row.name) && row.ps === 'Managed by Sea vHost');
const projectDatabaseRows = rowsFrom(await formRequest('/data', { action: 'getData', table: 'databases', limit: '200', p: '1', search: 'sv' }));
const orphanDatabases = projectDatabaseRows.map((row) => ({
id: Number(row.id), name: String(row.name ?? ''), username: String(row.username ?? row.db_user ?? row.name ?? ''), ps: String(row.ps ?? ''),
})).filter((row) => Number.isSafeInteger(row.id) && row.id > 0 && managedHostPattern.test(row.name) && row.ps === 'Managed by Sea vHost');
const siteRows = rowsFrom(await formRequest('/data', { action: 'getData', table: 'sites', limit: '200', p: '1', search: 'sv' }));
const orphanSites = siteRows.map((row) => ({ id: Number(row.id), name: String(row.name ?? ''), ps: String(row.ps ?? '') }))
.filter((row) => Number.isSafeInteger(row.id) && row.id > 0 && managedHostPattern.test(row.name.split('.')[0]) && row.ps === `Sea vHost: ${row.name.split('.')[0]}`);
const managedHosts = [...new Set([
...orphanFTPs.map((row) => row.name),
...orphanDatabases.map((row) => row.name),
...orphanSites.map((row) => row.name.split('.')[0]),
])].filter((name) => managedHostPattern.test(name)).sort();
for (const ftp of orphanFTPs) {
requireSuccess(await formRequest('/ftp', { action: 'DeleteUser', id: String(ftp.id), username: ftp.name }), `delete test FTP ${ftp.name}`);
}
for (const database of orphanDatabases) {
requireSuccess(await formRequest('/database', {
action: 'DeleteDatabase', id: String(database.id), sid: '0', name: database.name, db_user: database.username,
}), `delete test project database ${database.name}`);
}
for (const site of orphanSites) {
requireSuccess(await formRequest('/site', { action: 'DeleteSite', id: String(site.id), webname: site.name }), `delete test site ${site.name}`);
}
for (const database of databases) {
requireSuccess(await formRequest('/database', {
action: 'DeleteDatabase', id: String(database.id), sid: '0', name: database.name, db_user: database.username,
}), `delete test database ${database.name}`);
}
const nonce = Date.now().toString().slice(-7);
let taskID;
try {
const shell = [
'set -Eeuo pipefail',
'trap \'status=$?; printf "Sea vHost reset failed at line %s (status %s)\\n" "$LINENO" "$status"\' ERR',
'systemctl stop sea-vhost-api sea-vhost-panel-broker sea-vhost-agent',
'purge_children() { local root="$1" resolved entry target; test -d "$root" || return 0; resolved="$(realpath -e -- "$root")"; test "$resolved" = "$root"; while IFS= read -r -d "" entry; do case "$entry" in "$root"/*) ;; *) exit 1 ;; esac; if [[ -L "$entry" ]]; then rm -f -- "$entry"; else target="$(realpath -e -- "$entry")"; case "$target" in "$root"/*) chattr -R -i -- "$entry" 2>/dev/null || true; rm -rf -- "$entry" ;; *) exit 1 ;; esac; fi; done < <(find -P "$root" -mindepth 1 -maxdepth 1 -print0); }',
'mapfile -t identities < <(getent passwd | cut -d: -f1 | grep -E "^sv[0-9a-f]{10}$" || true)',
'for host in "${identities[@]}"; do pkill -KILL -u "$host" 2>/dev/null || true; userdel "$host"; getent group "$host" >/dev/null && groupdel "$host" || true; done',
'host_root=/www/wwwroot/seavHost/vHost; if [[ -d "$host_root" ]]; then host_root="$(realpath -e -- "$host_root")"; test "$host_root" = /www/wwwroot/seavHost/vHost; while IFS= read -r -d "" entry; do name="$(basename -- "$entry")"; [[ "$name" =~ ^sv[0-9a-f]{10}$ ]]; target="$(realpath -e -- "$entry")"; case "$target" in "$host_root"/*) chattr -R -i -- "$entry" 2>/dev/null || true; rm -rf -- "$entry" ;; *) exit 1 ;; esac; done < <(find -P "$host_root" -mindepth 1 -maxdepth 1 -type d -name "sv??????????" -print0); if [[ -d "$host_root/.sea-vhost-quarantine" && ! -L "$host_root/.sea-vhost-quarantine" ]]; then target="$(realpath -e -- "$host_root/.sea-vhost-quarantine")"; test "$target" = "$host_root/.sea-vhost-quarantine"; chattr -R -i -- "$target" 2>/dev/null || true; rm -rf -- "$host_root/.sea-vhost-quarantine"; fi; fi',
'purge_children /var/lib/sea-vhost',
'purge_children /var/lib/sea-vhost-agent',
'purge_children /var/lib/sea-vhost-panel',
'rm -f -- /etc/sea-vhost/sea-vhost.env',
"printf '%s\\n' 'Sea vHost test reset: complete'",
].join('\n');
const task = requireSuccess(await formRequest('/crontab', {
action: 'AddCrontab', name: `Sea vHost test reset ${nonce}`, 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 test-data reset', save: '0', backupTo: 'localhost',
}), 'temporary reset task creation');
taskID = Number(task.id);
if (!Number.isSafeInteger(taskID) || taskID <= 0) throw new Error('panel returned an invalid task id');
// Some aaPanel builds return false while another manual cron execution is
// draining. The minute task remains valid, so wait through the next minute
// boundary instead of deleting it immediately.
await formRequest('/crontab', { action: 'StartTask', id: String(taskID) });
let complete = false;
let lastLog = '';
for (let attempt = 0; attempt < 100; attempt += 1) {
await new Promise((resolve) => setTimeout(resolve, 1000));
const result = await formRequest('/crontab', { action: 'GetLogs', id: String(taskID) });
lastLog = typeof result?.msg === 'string' ? result.msg : typeof result === 'string' ? result : lastLog;
if (lastLog.includes('Sea vHost test reset: complete')) { complete = true; break; }
}
if (!complete) throw new Error(`reset task did not complete: ${lastLog.trim()}`);
} finally {
if (taskID) {
try { await formRequest('/crontab', { action: 'DelCrontab', id: String(taskID) }); } catch { /* best effort */ }
}
}
console.log(`Sea vHost test state was reset and services were left stopped; removed ${databases.length} control database(s), ${orphanFTPs.length} managed FTP account(s), ${orphanDatabases.length} managed project database(s), ${orphanSites.length} managed site(s), and ${managedHosts.length} known managed identity/identities.`);
+208
View File
@@ -0,0 +1,208 @@
import crypto from 'node:crypto';
import fs from 'node:fs';
import http from 'node:http';
import https from 'node:https';
const consoleURL = process.env.SEA_CONSOLE_URL?.trim();
const panelURL = process.env.SEA_PANEL_URL?.trim();
const panelAPIKey = process.env.SEA_PANEL_API_KEY?.trim();
const tenantLogin = process.env.SEA_TENANT_LOGIN?.trim();
const tenantPassword = process.env.SEA_TENANT_PASSWORD?.trim();
const runtime = process.env.SEA_RUNTIME?.trim() || 'Node.js';
const insecureTLS = process.env.SEA_PANEL_TLS_INSECURE === 'true';
if (!consoleURL || !panelURL || !panelAPIKey || !tenantLogin || !tenantPassword) {
console.error('SEA_CONSOLE_URL, SEA_PANEL_URL, SEA_PANEL_API_KEY, SEA_TENANT_LOGIN and SEA_TENANT_PASSWORD are required.');
process.exit(2);
}
if (!['Node.js', 'Python', 'Go', 'Java'].includes(runtime)) {
console.error('SEA_RUNTIME must be Node.js, Python, Go or Java.');
process.exit(2);
}
async function uploadFile(pathname, cookie, directory, localPath, filename) {
const content = fs.readFileSync(localPath);
if (content.length === 0 || content.length > 20 * 1024 * 1024) throw new Error('runtime artifact must be between 1 byte and 20 MB');
const body = new FormData();
body.set('path', directory);
body.set('overwrite', 'false');
body.set('file', new Blob([content]), filename);
const response = await fetch(new URL(pathname, consoleBase), { method: 'POST', headers: { Accept: 'application/json', Cookie: cookie }, body, redirect: 'manual' });
const text = await response.text();
let payload;
try { payload = text ? JSON.parse(text) : undefined; } catch { payload = undefined; }
if (response.status !== 201) throw new Error(payload?.error?.message || `artifact upload returned HTTP ${response.status}`);
}
const consoleBase = new URL(consoleURL);
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');
function panelForm(pathname, values, timeoutMs = 30_000) {
const requestTime = Math.floor(Date.now() / 1000).toString();
const requestToken = md5(requestTime + md5(panelAPIKey));
const body = Buffer.from(new URLSearchParams({ ...values, request_time: requestTime, request_token: requestToken }).toString());
const url = new URL(pathname, panelBase);
return new Promise((resolve, reject) => {
const request = panelClient.request(url, {
method: 'POST', agent: panelAgent, timeout: timeoutMs,
headers: { 'content-type': 'application/x-www-form-urlencoded', 'content-length': body.length },
}, (response) => {
let data = '';
response.setEncoding('utf8');
response.on('data', (chunk) => {
data += chunk;
if (data.length > 2 * 1024 * 1024) request.destroy(new Error('panel response exceeded 2 MB'));
});
response.on('end', () => {
if (response.statusCode < 200 || response.statusCode > 299) return reject(new Error(`panel 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);
});
}
async function api(pathname, { method = 'GET', body, cookie, expected } = {}) {
const response = await fetch(new URL(pathname, consoleBase), {
method,
headers: { Accept: 'application/json', ...(body === undefined ? {} : { 'Content-Type': 'application/json' }), ...(cookie ? { Cookie: cookie } : {}) },
body: body === undefined ? undefined : JSON.stringify(body),
redirect: 'manual',
});
const text = await response.text();
let payload;
try { payload = text ? JSON.parse(text) : undefined; } catch { payload = undefined; }
const accepted = expected ? expected.includes(response.status) : response.status >= 200 && response.status < 300;
if (!accepted) throw new Error(payload?.error?.message || `${method} ${pathname} returned HTTP ${response.status}`);
return { response, payload };
}
function sessionCookie(response) {
const setCookie = typeof response.headers.getSetCookie === 'function' ? response.headers.getSetCookie()[0] : response.headers.get('set-cookie');
const cookie = setCookie?.split(';', 1)[0];
if (!cookie?.startsWith('sea_session=')) throw new Error('tenant login did not return a session cookie');
return cookie;
}
async function localShellCheck(name, command, marker) {
if (!/^[A-Za-z0-9 ._-]{1,80}$/.test(name) || !/^[A-Za-z0-9._:-]{1,160}$/.test(marker)) throw new Error('unsafe smoke-check metadata');
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: `set -Eeo pipefail\nstage=initial\ntrap 'printf "runtime_check_failed_line=%s stage=%s\\n" "$LINENO" "$stage"' ERR\n${command}\nprintf '%s\\n' '${marker}'`,
sName: 'Temporary Sea vHost runtime lifecycle check', save: '0', backupTo: 'localhost',
});
const taskID = Number(task?.id);
if ((task?.status !== true && task?.status !== 'true') || !Number.isSafeInteger(taskID) || taskID <= 0) throw new Error('aaPanel rejected runtime check task');
try {
await panelForm('/crontab', { action: 'StartTask', id: String(taskID) });
let lastLog = '';
for (let attempt = 0; attempt < 90; attempt += 1) {
await new Promise((resolve) => setTimeout(resolve, 1000));
const result = await panelForm('/crontab', { action: 'GetLogs', id: String(taskID) });
const log = typeof result?.msg === 'string' ? result.msg : typeof result === 'string' ? result : '';
lastLog = log;
if (log.includes(marker)) return;
if (log.includes('runtime_check_failed_line=')) throw new Error(`runtime check assertion failed: ${log.trim()}`);
if (log.includes('Failed') || log.includes('ERROR')) throw new Error('runtime check task failed');
}
throw new Error(`runtime check task timed out: ${lastLog.trim().slice(-1200)}`);
} finally {
try { await panelForm('/crontab', { action: 'DelCrontab', id: String(taskID) }); } catch { /* best effort */ }
}
}
const suffix = Date.now().toString(36).slice(-6);
const runtimeSlug = { 'Node.js': 'node', Python: 'python', Go: 'go', Java: 'java' }[runtime];
const runPath = `/${runtimeSlug}-${suffix}`;
let cookie;
let project;
let site;
try {
const login = await api('/api/v1/auth/login', { method: 'POST', body: { identifier: tenantLogin, password: tenantPassword } });
cookie = sessionCookie(login.response);
const dashboard = await api('/api/v1/dashboard', { cookie });
project = dashboard.payload?.projects?.[0];
if (!project?.id) throw new Error('tenant has no virtual host for the runtime smoke test');
const catalog = await api('/api/v1/runtime-catalog', { cookie });
const runtimeVersion = catalog.payload?.versions?.[runtime]?.[0];
if (!runtimeVersion) throw new Error(`${runtime} is not installed`);
const created = await api(`/api/v1/projects/${project.id}/sites`, {
method: 'POST', cookie, expected: [201],
body: { name: `${runtimeSlug}-${suffix}`, runtime, version: runtimeVersion, runPath, customDomain: '', autoSSL: false },
});
site = created.payload?.site;
if (!site?.id || site.status !== 'awaiting_upload' || !Number.isInteger(site.backendPort)) throw new Error(`${runtime} site creation returned an incomplete record`);
const marker = ['Go', 'Java'].includes(runtime) ? `sea-vhost-${runtimeSlug}-artifact` : `sea-vhost-${runtimeSlug}-${suffix}`;
let entryFile;
if (runtime === 'Node.js') {
entryFile = 'package.json';
await api(`/api/v1/projects/${project.id}/files`, {
method: 'PUT', cookie, expected: [204],
body: { path: `${runPath.slice(1)}/package.json`, content: JSON.stringify({ name: `sea-vhost-${suffix}`, private: true, scripts: { start: 'node server.js' } }, null, 2), overwrite: false },
});
await api(`/api/v1/projects/${project.id}/files`, {
method: 'PUT', cookie, expected: [204],
body: { path: `${runPath.slice(1)}/server.js`, content: `require('node:http').createServer((_, res) => { res.end('${marker}'); }).listen(Number(process.env.PORT), '127.0.0.1');\n`, overwrite: false },
});
} else if (runtime === 'Python') {
entryFile = 'app.py';
const pythonSource = `import os\nfrom http.server import BaseHTTPRequestHandler, HTTPServer\nclass Handler(BaseHTTPRequestHandler):\n def do_GET(self):\n body = b'${marker}'\n self.send_response(200)\n self.send_header('Content-Length', str(len(body)))\n self.end_headers()\n self.wfile.write(body)\n def log_message(self, *_):\n pass\nHTTPServer(('127.0.0.1', int(os.environ['PORT'])), Handler).serve_forever()\n`;
await api(`/api/v1/projects/${project.id}/files`, {
method: 'PUT', cookie, expected: [204],
body: { path: `${runPath.slice(1)}/app.py`, content: pythonSource, overwrite: false },
});
} else {
entryFile = runtime === 'Go' ? 'app' : 'app.jar';
const artifact = process.env.SEA_RUNTIME_ARTIFACT?.trim();
if (!artifact || !fs.statSync(artifact).isFile()) throw new Error(`SEA_RUNTIME_ARTIFACT is required for ${runtime}`);
await uploadFile(`/api/v1/projects/${project.id}/files`, cookie, runPath.slice(1), artifact, entryFile);
}
const checked = await api(`/api/v1/projects/${project.id}/sites/${site.id}/deployment/check`, { method: 'POST', cookie, body: { entryFile } });
if (!checked.payload?.check?.ready || !checked.payload?.check?.adapterReady) throw new Error(`${runtime} deployment preflight did not become ready`);
const deployed = await api(`/api/v1/projects/${project.id}/sites/${site.id}/deployment`, { method: 'POST', cookie, body: { entryFile } });
site = deployed.payload?.site;
if (site?.status !== 'running') throw new Error(`${runtime} deployment was not committed as running`);
if (!/^[a-z0-9.-]+$/.test(site.domain)) throw new Error('runtime site returned an unsafe domain');
if (!/^\/www\/wwwroot\/seavHost\/vHost\/sv[0-9a-f]{10}$/.test(project.path) || !/^sv[0-9a-f]{10}$/.test(project.hostName)) {
throw new Error('runtime project returned an unsafe host identity or path');
}
await localShellCheck(`Sea vHost ${runtimeSlug} live ${suffix}`, `curl --silent --show-error --fail --max-time 10 --header 'Host: ${site.domain}' http://127.0.0.1/ | grep -Fq '${marker}'`, `live-${suffix}`);
const runtimeRoot = `${project.path}${runPath}`;
await localShellCheck(`Sea vHost ${runtimeSlug} identity ${suffix}`, [
`runtime_root='${runtimeRoot}'`, `host_name='${project.hostName}'`, `runtime_port='${site.backendPort}'`,
'stage=listener; pid="$(fuser -n tcp "$runtime_port" 2>/dev/null | tr -s \' \' \'\\n\' | grep -E \'^[0-9]+$\' | head -n1)"; test -n "$pid"',
'stage=process_owner; test "$(stat -c %U "/proc/$pid")" = "$host_name"',
'stage=directory_owner; test "$(stat -c %U:%G "$runtime_root")" = "sea-vhost:$host_name"',
'stage=capabilities; test "$(grep -Ec \'^Cap(Prm|Eff|Amb):[[:space:]]+0+$\' "/proc/$pid/status")" -eq 3',
'stage=config_privacy; if runuser -u "$host_name" -- test -r /var/lib/sea-vhost/config.json; then exit 1; fi',
'stage=socket_privacy; if timeout 3 runuser -u "$host_name" -- curl --silent --unix-socket /run/sea-vhost/agent.sock http://localhost/v1/health >/dev/null 2>&1; then exit 1; fi',
].join('\n'), `identity-${suffix}`);
await api(`/api/v1/projects/${project.id}/sites/${site.id}/state`, { method: 'POST', cookie, body: { enabled: false } });
await localShellCheck(`Sea vHost ${runtimeSlug} stopped ${suffix}`, `if curl --silent --fail --max-time 3 http://127.0.0.1:${site.backendPort}/ >/dev/null 2>&1; then stage=still_listening; false; fi`, `stopped-${suffix}`);
const restarted = await api(`/api/v1/projects/${project.id}/sites/${site.id}/state`, { method: 'POST', cookie, body: { enabled: true } });
if (restarted.payload?.site?.status !== 'running') throw new Error(`${runtime} site restart did not return running`);
await localShellCheck(`Sea vHost ${runtimeSlug} restarted ${suffix}`, `curl --silent --show-error --fail --max-time 10 --header 'Host: ${site.domain}' http://127.0.0.1/ | grep -Fq '${marker}'`, `restarted-${suffix}`);
await api(`/api/v1/projects/${project.id}/sites/${site.id}`, { method: 'DELETE', cookie, expected: [204] });
await localShellCheck(`Sea vHost ${runtimeSlug} removed ${suffix}`, `if curl --silent --fail --max-time 3 http://127.0.0.1:${site.backendPort}/ >/dev/null 2>&1; then exit 1; fi`, `removed-${suffix}`);
site = undefined;
await api(`/api/v1/projects/${project.id}/files?path=${encodeURIComponent(runPath.slice(1))}`, { method: 'DELETE', cookie, expected: [204] });
await api(`/api/v1/projects/${project.id}/files?emptyTrash=1`, { method: 'DELETE', cookie, expected: [204] });
console.log(JSON.stringify({ runtime, version: runtimeVersion, lifecycle: ['create', 'upload', 'check', 'deploy', 'proxy', 'stop', 'start', 'delete'], cleanup: 'complete' }, null, 2));
} finally {
if (cookie && project?.id && site?.id) {
try { await api(`/api/v1/projects/${project.id}/sites/${site.id}`, { method: 'DELETE', cookie, expected: [204] }); } catch { /* best effort */ }
}
if (cookie && project?.id) {
try { await api(`/api/v1/projects/${project.id}/files?path=${encodeURIComponent(runPath.slice(1))}`, { method: 'DELETE', cookie, expected: [204] }); } catch { /* best effort */ }
try { await api(`/api/v1/projects/${project.id}/files?emptyTrash=1`, { method: 'DELETE', cookie, expected: [204] }); } catch { /* best effort */ }
}
}
+152
View File
@@ -0,0 +1,152 @@
const consoleURL = process.env.SEA_CONSOLE_URL?.trim();
const tenantLogin = process.env.SEA_TENANT_LOGIN?.trim();
const tenantPassword = process.env.SEA_TENANT_PASSWORD?.trim();
if (!consoleURL || !tenantLogin || !tenantPassword) {
console.error('SEA_CONSOLE_URL, SEA_TENANT_LOGIN and SEA_TENANT_PASSWORD are required.');
process.exit(2);
}
const consoleBase = new URL(consoleURL);
if (!['http:', 'https:'].includes(consoleBase.protocol) || consoleBase.username || consoleBase.password) {
console.error('SEA_CONSOLE_URL must be an HTTP(S) URL without embedded credentials.');
process.exit(2);
}
const checks = [];
async function request(pathname, { method = 'GET', body, cookie, origin, expected = [200] } = {}) {
const response = await fetch(new URL(pathname, consoleBase), {
method,
headers: {
Accept: 'application/json',
...(body === undefined ? {} : { 'Content-Type': 'application/json' }),
...(cookie ? { Cookie: cookie } : {}),
...(origin ? { Origin: origin } : {}),
},
body: body === undefined ? undefined : JSON.stringify(body),
redirect: 'manual',
signal: AbortSignal.timeout(10_000),
});
const text = await response.text();
let payload;
try { payload = text ? JSON.parse(text) : undefined; } catch { payload = undefined; }
if (!expected.includes(response.status)) {
throw new Error(`${method} ${pathname} returned HTTP ${response.status}: ${payload?.error?.message || 'unexpected response'}`);
}
return { response, payload };
}
async function check(name, callback) {
await callback();
checks.push(name);
}
function sessionCookie(response) {
const setCookie = typeof response.headers.getSetCookie === 'function' ? response.headers.getSetCookie()[0] : response.headers.get('set-cookie');
if (!setCookie?.startsWith('sea_session=')) throw new Error('login did not return the expected session cookie');
const lower = setCookie.toLowerCase();
if (!lower.includes('httponly') || !lower.includes('samesite=strict')) throw new Error('session cookie security attributes are incomplete');
if (consoleBase.protocol === 'https:' && !lower.includes('secure')) throw new Error('HTTPS console session cookie is missing Secure');
return setCookie.split(';', 1)[0];
}
function filePath(projectID, requested) {
const url = new URL(`/api/v1/projects/${projectID}/files`, consoleBase);
url.searchParams.set('path', requested);
return `${url.pathname}${url.search}`;
}
let cookie;
try {
await check('unauthenticated API denied', async () => {
await request('/api/v1/dashboard', { expected: [401] });
});
await check('cross-origin state request denied', async () => {
await request('/api/v1/auth/login', {
method: 'POST', origin: 'https://attacker.invalid', expected: [403],
body: { identifier: tenantLogin, password: tenantPassword },
});
});
await check('same-host wrong-scheme origin denied', async () => {
const wrongScheme = consoleBase.protocol === 'https:' ? 'http:' : 'https:';
await request('/api/v1/auth/login', {
method: 'POST', origin: `${wrongScheme}//${consoleBase.host}`, expected: [403],
body: { identifier: tenantLogin, password: tenantPassword },
});
});
await check('strict login JSON decoding', async () => {
await request('/api/v1/auth/login', {
method: 'POST', origin: consoleBase.origin, expected: [400],
body: { identifier: tenantLogin, password: tenantPassword, unexpected: true },
});
});
const login = await request('/api/v1/auth/login', {
method: 'POST', origin: consoleBase.origin,
body: { identifier: tenantLogin, password: tenantPassword },
});
cookie = sessionCookie(login.response);
checks.push('session cookie attributes');
const dashboard = await request('/api/v1/dashboard', { cookie });
const project = dashboard.payload?.projects?.[0];
if (!project?.id) throw new Error('tenant has no virtual host for security checks');
await check('tenant cannot use admin API', async () => {
await request('/api/v1/admin/plans', { cookie, expected: [403] });
});
await check('tenant project IDOR denied', async () => {
const missingProject = '9223372036854775807';
await request(`/api/v1/projects/${missingProject}/credentials`, { cookie, expected: [404] });
await request(`/api/v1/projects/${missingProject}/files`, { cookie, expected: [404] });
});
await check('authenticated CSRF denied before mutation', async () => {
await request(`/api/v1/projects/${project.id}/state`, {
method: 'POST', cookie, origin: 'https://attacker.invalid', expected: [403], body: { enabled: true },
});
});
await check('file traversal and ambiguous paths denied', async () => {
for (const candidate of ['../../etc/passwd', 'public/../outside', 'public//index.html', String.raw`..\..\secret`]) {
await request(filePath(project.id, candidate), { cookie, expected: [400] });
}
});
await check('internal trash path denied', async () => {
await request(filePath(project.id, '.sea-trash'), { cookie, expected: [400] });
await request(filePath(project.id, '.sea-trash/deleted.txt'), { cookie, expected: [400] });
});
await check('strict file-write JSON decoding', async () => {
await request(`/api/v1/projects/${project.id}/files`, {
method: 'PUT', cookie, origin: consoleBase.origin, expected: [400],
body: { path: 'security-probe.txt', content: '', overwrite: false, unexpected: true },
});
});
await check('setup and registration write routes closed', async () => {
await request('/api/v1/setup/install', { method: 'POST', origin: consoleBase.origin, body: {}, expected: [404] });
await request('/api/v1/auth/register', { method: 'POST', origin: consoleBase.origin, body: {}, expected: [404] });
});
await check('browser security headers present', async () => {
const response = await fetch(consoleBase, { redirect: 'manual', signal: AbortSignal.timeout(10_000) });
if (response.headers.get('x-content-type-options')?.toLowerCase() !== 'nosniff') throw new Error('missing X-Content-Type-Options');
if (response.headers.get('x-frame-options')?.toUpperCase() !== 'DENY') throw new Error('missing X-Frame-Options');
if (!response.headers.get('content-security-policy')) throw new Error('missing Content-Security-Policy');
});
console.log(JSON.stringify({ status: 'passed', checks, count: checks.length }, null, 2));
} finally {
if (cookie) {
try {
await request('/api/v1/auth/logout', { method: 'POST', cookie, origin: consoleBase.origin, expected: [204] });
} catch { /* best-effort session cleanup */ }
}
}
+61
View File
@@ -0,0 +1,61 @@
[Unit]
Description=Sea vHost privileged isolation agent
After=local-fs.target mysqld.service mysql.service mariadb.service
Before=sea-vhost-api.service
[Service]
Type=simple
User=root
Group=sea-vhost-agent-control
EnvironmentFile=/etc/sea-vhost/sea-vhost.env
ExecStart=/opt/sea-vhost/bin/sea-vhost-agent
Restart=on-failure
RestartSec=3
RuntimeDirectory=sea-vhost sea-vhost-php
RuntimeDirectoryMode=0755
StateDirectory=sea-vhost-agent
StateDirectoryMode=0711
UMask=0007
NoNewPrivileges=true
PrivateTmp=true
# A root-only directory view follows socket recreation after MySQL restarts.
# Tenant PHP processes cannot traverse this 0700 configuration directory.
ConfigurationDirectory=sea-vhost-mysql
ConfigurationDirectoryMode=0700
BindReadOnlyPaths=/tmp:/etc/sea-vhost-mysql/host-tmp
PrivateDevices=true
# PHP-FPM masters are launched by this service after dropping to each host
# UID/GID. They must retain host networking so ordinary PHP applications can
# reach the local MySQL listener and outbound APIs. The agent itself exposes
# only a token-authenticated Unix socket and does not listen on TCP.
# The privileged quota agent must enumerate processes owned by each isolated
# host UID. The unprivileged API keeps ProtectProc=invisible; this root-only,
# token-authenticated agent therefore retains the default /proc visibility.
ProcSubset=pid
ProtectClock=true
ProtectHostname=true
ProtectHome=true
ProtectSystem=strict
ReadOnlyPaths=/usr /boot /opt /var/lib/sea-vhost /var/lib/sea-vhost-panel /www/server
ReadWritePaths=/etc /www/wwwroot/seavHost/vHost /www/backup/sea-vhost /www/wwwlogs /www/server/panel/vhost/nginx /www/server/pure-ftpd/etc /www/server/nginx/logs/error.log /www/server/nginx/logs/nginx.pid -/www/server/nodejs/vhost/pids -/www/server/python_manager/versions -/www/server/php /var/lib/sea-vhost-agent /run/sea-vhost-php
ProtectKernelTunables=true
ProtectKernelModules=true
ProtectKernelLogs=true
ProtectControlGroups=true
# The agent creates locked per-host identities, applies ACLs and starts each
# PHP-FPM master after changing the forked child's UID/GID. The kernel clears
# ambient capabilities on that root-to-tenant UID transition, so tenant PHP
# processes do not inherit agent privileges. /etc remains writable because fixed useradd/usermod
# operations must update the host account databases; all other system paths
# stay read-only unless explicitly listed.
RestrictRealtime=true
LockPersonality=true
MemoryDenyWriteExecute=true
RestrictAddressFamilies=AF_UNIX AF_INET AF_INET6
CapabilityBoundingSet=CAP_CHOWN CAP_DAC_OVERRIDE CAP_FOWNER CAP_FSETID CAP_KILL CAP_LINUX_IMMUTABLE CAP_NET_BIND_SERVICE CAP_SETGID CAP_SETUID
AmbientCapabilities=CAP_SETGID CAP_SETUID
LimitCORE=0
SystemCallArchitectures=native
[Install]
WantedBy=multi-user.target
+45
View File
@@ -0,0 +1,45 @@
[Unit]
Description=Sea vHost API
After=network-online.target mysql.service sea-vhost-agent.service sea-vhost-panel-broker.service
Requires=sea-vhost-agent.service sea-vhost-panel-broker.service
Wants=network-online.target
[Service]
Type=simple
User=sea-vhost
Group=sea-vhost-control
SupplementaryGroups=sea-vhost-agent-control sea-vhost-panel-control
EnvironmentFile=/etc/sea-vhost/sea-vhost.env
ExecStart=/opt/sea-vhost/bin/sea-vhost-api
WorkingDirectory=/opt/sea-vhost
Restart=on-failure
RestartSec=3
UMask=0007
StateDirectory=sea-vhost
StateDirectoryMode=0700
NoNewPrivileges=true
PrivateTmp=true
PrivateDevices=true
ProtectProc=invisible
ProcSubset=pid
ProtectClock=true
ProtectHostname=true
ProtectSystem=strict
ProtectHome=true
ReadWritePaths=/www/wwwroot/seavHost/vHost /run/sea-vhost /var/lib/sea-vhost
ProtectKernelTunables=true
ProtectKernelModules=true
ProtectKernelLogs=true
ProtectControlGroups=true
RestrictSUIDSGID=true
RestrictRealtime=true
LockPersonality=true
MemoryDenyWriteExecute=true
RestrictAddressFamilies=AF_UNIX AF_INET AF_INET6
CapabilityBoundingSet=
AmbientCapabilities=
LimitCORE=0
SystemCallArchitectures=native
[Install]
WantedBy=multi-user.target
@@ -0,0 +1,34 @@
[Unit]
Description=Sea vHost controller
After=network-online.target
Wants=network-online.target
[Service]
User=sea-vhost
Group=sea-vhost-control
EnvironmentFile=/etc/sea-vhost/sea-vhost.env
ExecStart=/opt/sea-vhost/bin/sea-vhost-api
WorkingDirectory=/opt/sea-vhost
Restart=on-failure
RestartSec=3
StateDirectory=sea-vhost
StateDirectoryMode=0700
UMask=0077
NoNewPrivileges=true
PrivateTmp=true
PrivateDevices=true
ProtectSystem=strict
ProtectHome=true
ProtectProc=invisible
ProcSubset=pid
ProtectKernelTunables=true
ProtectKernelModules=true
ProtectControlGroups=true
RestrictSUIDSGID=true
RestrictAddressFamilies=AF_UNIX AF_INET AF_INET6
CapabilityBoundingSet=
AmbientCapabilities=
LimitCORE=0
[Install]
WantedBy=multi-user.target
+32
View File
@@ -0,0 +1,32 @@
[Unit]
Description=Sea vHost stateless execution node
After=network-online.target sea-vhost-agent.service sea-vhost-panel-broker.service
Requires=sea-vhost-agent.service sea-vhost-panel-broker.service
[Service]
User=sea-vhost
Group=sea-vhost-control
SupplementaryGroups=sea-vhost-agent-control sea-vhost-panel-control
EnvironmentFile=/etc/sea-vhost/sea-vhost.env
ExecStart=/opt/sea-vhost/bin/sea-vhost-node
Restart=on-failure
RestartSec=3
UMask=0007
NoNewPrivileges=true
PrivateTmp=true
PrivateDevices=true
ProtectSystem=strict
ProtectHome=true
ProtectProc=invisible
ProcSubset=pid
ProtectKernelTunables=true
ProtectKernelModules=true
ProtectControlGroups=true
RestrictSUIDSGID=true
RestrictAddressFamilies=AF_UNIX AF_INET AF_INET6
CapabilityBoundingSet=
AmbientCapabilities=
LimitCORE=0
[Install]
WantedBy=multi-user.target
@@ -0,0 +1,47 @@
[Unit]
Description=Sea vHost aaPanel capability broker
After=network-online.target
Before=sea-vhost-api.service
Wants=network-online.target
[Service]
Type=simple
User=sea-vhost-panel
Group=sea-vhost-panel-control
SupplementaryGroups=sea-vhost-control
EnvironmentFile=/etc/sea-vhost/sea-vhost.env
ExecStart=/opt/sea-vhost/bin/sea-vhost-panel-broker
Restart=on-failure
RestartSec=3
RuntimeDirectory=sea-vhost-panel
RuntimeDirectoryMode=0750
StateDirectory=sea-vhost-panel
StateDirectoryMode=0700
UMask=0077
NoNewPrivileges=true
PrivateTmp=true
PrivateDevices=true
ProtectProc=invisible
ProcSubset=pid
ProtectClock=true
ProtectHostname=true
ProtectSystem=strict
ProtectHome=true
ProtectKernelTunables=true
ProtectKernelModules=true
ProtectKernelLogs=true
ProtectControlGroups=true
RestrictSUIDSGID=true
RestrictRealtime=true
LockPersonality=true
MemoryDenyWriteExecute=true
RestrictAddressFamilies=AF_UNIX AF_INET AF_INET6
IPAddressDeny=any
IPAddressAllow=localhost
CapabilityBoundingSet=
AmbientCapabilities=
LimitCORE=0
SystemCallArchitectures=native
[Install]
WantedBy=multi-user.target
+223
View File
@@ -0,0 +1,223 @@
"""Installer safety/flow tests; no system commands or host provisioning."""
import contextlib
import importlib.util
import io
import json
import os
import subprocess
import tempfile
import unittest
from pathlib import Path
from unittest.mock import patch, Mock
spec = importlib.util.spec_from_file_location('install_wizard', Path(__file__).with_name('install-wizard.py'))
wizard = importlib.util.module_from_spec(spec)
spec.loader.exec_module(wizard)
class Answers:
def __init__(self, answers=(), confirmations=()):
self.answers = iter(answers)
self.confirmations = iter(confirmations)
def ask(self, label, default=''):
return next(self.answers)
def confirm(self, label, default=True):
return next(self.confirmations)
def secret(self, label):
return next(self.answers)
def paired():
return {'identity': {'nodeId': 2, 'caPem': 'CA', 'certificate': 'CERT', 'privateKey': 'PRIVATE', 'clientSpki': 'PIN'},
'tenantRoot': '/www/wwwroot/seavHost/vHost', 'address': ':9443',
'brokerSocket': '/run/sea-vhost-panel/broker.sock', 'agentSocket': '/run/sea-vhost/agent.sock'}
class WizardTests(unittest.TestCase):
def setUp(self):
self.temporary = tempfile.TemporaryDirectory()
self.addCleanup(self.temporary.cleanup)
self.root = Path(self.temporary.name)
for name in ('CONFIG', 'NODE_CONFIG', 'PANEL_CREDENTIALS', 'PANEL_REGISTRY', 'ENVIRONMENT'):
p = patch.object(wizard, name, self.root / name)
p.start()
self.addCleanup(p.stop)
self.output = io.StringIO()
p = contextlib.redirect_stdout(self.output)
p.__enter__()
self.addCleanup(p.__exit__, None, None, None)
def test_role_conversion_rejected_before_install(self):
for role, values in [('node', {'SEA_CONTROLLER_ONLY': 'true'}), ('controller', {'SEA_NODE_STATELESS': 'true'}),
('combined', {'SEA_CONTROLLER_ONLY': 'true'}), ('controller', {'SEA_ADDR': '127.0.0.1:8080'})]:
with self.subTest(role=role, values=values), self.assertRaises(wizard.InstallError):
wizard.check_role(role, values)
wizard.CONFIG.write_text('{}')
with self.assertRaises(wizard.InstallError):
wizard.check_role('node', {})
def test_existing_roles_allowed(self):
for role, values in [('combined', {'SEA_ADDR': '127.0.0.1:8080'}),
('controller', {'SEA_CONTROLLER_ONLY': 'true'}), ('node', {'SEA_NODE_STATELESS': 'true'})]:
wizard.check_role(role, values)
def test_panel_address_is_loopback_origin_only(self):
for value in ('https://evil.example:8888', 'https://localhost:8888/path', 'http://u:p@127.0.0.1:8888',
'https://127.0.0.1:99999', 'http://127.0.0.1:8888/?redirect=evil', 'file:///etc/passwd'):
with self.subTest(value=value), self.assertRaises(wizard.InstallError):
wizard.panel_url(value)
self.assertEqual(wizard.panel_url('https://127.0.0.1:7812/'), 'https://127.0.0.1:7812')
self.assertEqual(wizard.panel_url('http://[::1]:8888'), 'http://[::1]:8888')
def test_node_pair_identity_and_path(self):
self.assertEqual(wizard.validate_pair(paired()), (2, '/www/wwwroot/seavHost/vHost'))
for update in ({'tenantRoot': '/etc'}, {'tenantRoot': '/www/wwwroot/a/../b'}, {'address': ':22'},
{'address': 'localhost:9443'}, {'agentSocket': '/tmp/agent.sock'}, {'identity': {'nodeId': 1}}):
with self.subTest(update=update), self.assertRaises(wizard.InstallError):
wizard.validate_pair({**paired(), **update})
def test_missing_build_rejected_before_prompts(self):
with patch.object(wizard, 'SOURCE', self.root):
with self.assertRaisesRegex(wizard.InstallError, '安装包不完整'):
wizard.check_build('node')
def test_private_write_never_overwrites(self):
file = self.root / 'credentials.json'
wizard.private_json(file, {'api_key': 'secret'})
with self.assertRaises(FileExistsError):
wizard.private_json(file, {'api_key': 'changed'})
self.assertEqual(json.loads(file.read_text())['api_key'], 'secret')
if os.name == 'posix':
self.assertEqual(file.stat().st_mode & 0o777, 0o600)
def test_secret_prompt_and_credentials_not_printed(self):
key = 'sensitive-test-key-never-print'
with patch.object(wizard, 'detect_panel_url', return_value='https://127.0.0.1:7812'):
creds = wizard.credentials(Answers(['https://127.0.0.1:7812', key], [True]))
self.assertEqual(creds['api_key'], key)
self.assertTrue(creds['tls_insecure'])
self.assertNotIn(key, self.output.getvalue())
def test_node_flow_stages_credentials_and_cleans_even_on_failure(self):
# Real files, mocked privileged subprocess only. Assert no key in argv.
config = self.root / 'pair.json'
config.write_text(json.dumps(paired()))
creds = {'version': 1, 'url': 'https://127.0.0.1:7812', 'api_key': 'NEVER-PRINT-OR-ARGV', 'tls_insecure': True}
real_directory = tempfile.TemporaryDirectory
staged = []
def temporary_directory(**kwargs):
return real_directory(prefix=kwargs['prefix'], dir=self.root)
def command(args, **kwargs):
stage_pair, stage_creds = Path(args[-2]), Path(args[-1])
self.assertEqual(json.loads(stage_pair.read_text()), paired())
self.assertEqual(json.loads(stage_creds.read_text()), creds)
self.assertNotIn(creds['api_key'], ' '.join(str(a) for a in args))
staged.extend([stage_pair, stage_creds])
raise subprocess.CalledProcessError(2, args)
with patch.object(Path, 'is_dir', return_value=True), patch.object(Path, 'is_file', return_value=True), \
patch.object(wizard, 'credentials', return_value=creds), \
patch.object(wizard.os, 'fchmod', create=True), \
patch.object(wizard.tempfile, 'TemporaryDirectory', side_effect=temporary_directory), \
patch.object(wizard, 'run', side_effect=command), self.assertRaises(subprocess.CalledProcessError):
wizard.install_node(Answers([str(config)], [True]))
self.assertEqual(len(staged), 2)
self.assertTrue(all(not p.exists() for p in staged))
self.assertNotIn(creds['api_key'], self.output.getvalue())
def test_controller_uses_legacy_noninteractive_then_starts_services(self):
with patch.object(wizard, 'nginx_plan', return_value=None), patch.object(wizard, 'run') as command, \
patch.object(wizard, 'wait_services') as ready, patch.object(wizard, 'wait_api') as api_ready, patch.object(wizard, 'environment', return_value={'SEA_SETUP_TOKEN': 'install-token'}):
self.assertTrue(wizard.install_controller(Answers(confirmations=[True]), 'controller', {}))
self.assertEqual(command.call_args_list[0].args[0][-1], '--non-interactive')
self.assertEqual(command.call_args_list[2].args[0], ['systemctl', 'restart', 'sea-vhost-api'])
ready.assert_called_once_with(['sea-vhost-api'])
api_ready.assert_called_once_with({})
self.assertIn('install-token', self.output.getvalue())
def test_cancel_leaves_system_untouched(self):
with patch.object(wizard, 'nginx_plan', return_value=None), patch.object(wizard, 'run') as command:
self.assertFalse(wizard.install_controller(Answers(confirmations=[False]), 'controller', {}))
command.assert_not_called()
def test_cancel_node_upgrade_preserves_installed_config_permissions(self):
wizard.NODE_CONFIG.write_text(json.dumps(paired()))
with patch.object(Path, 'is_dir', return_value=True), patch.object(Path, 'is_file', return_value=True), \
patch.object(wizard, 'credentials', return_value={'url': 'https://127.0.0.1:7812'}), \
patch.object(wizard.os, 'fchmod', create=True) as chmod, patch.object(wizard, 'run') as command:
self.assertFalse(wizard.install_node(Answers([str(wizard.NODE_CONFIG)], [False])))
chmod.assert_not_called()
command.assert_not_called()
self.assertEqual(json.loads(wizard.NODE_CONFIG.read_text()), paired())
def test_nginx_failed_check_restores_existing_config(self):
file = self.root / 'console.conf'
file.write_bytes(b'previous')
plan = {'existing': False, 'target': file, 'text': 'replacement', 'nginx': '/test/nginx', 'reload': ['nginx', '-s', 'reload']}
with patch.object(wizard.os, 'fchmod', create=True), patch.object(wizard, 'run', side_effect=subprocess.CalledProcessError(1, ['nginx'])), \
patch.object(wizard.subprocess, 'run'):
with self.assertRaises(wizard.InstallError):
wizard.apply_nginx(plan)
self.assertEqual(file.read_bytes(), b'previous')
self.assertEqual(len(list(self.root.glob('console.conf.*.bak'))), 1)
def test_nginx_failed_reload_removes_new_config(self):
file = self.root / 'console.conf'
plan = {'existing': False, 'target': file, 'text': 'replacement', 'nginx': '/test/nginx', 'reload': ['nginx', '-s', 'reload']}
with patch.object(wizard.os, 'fchmod', create=True), \
patch.object(wizard, 'run', side_effect=[Mock(), subprocess.CalledProcessError(1, ['nginx'])]), \
patch.object(wizard.subprocess, 'run'):
with self.assertRaises(wizard.InstallError):
wizard.apply_nginx(plan)
self.assertFalse(file.exists())
def test_nginx_successful_atomic_write(self):
file = self.root / 'console.conf'
plan = {'existing': False, 'target': file, 'text': 'new config', 'nginx': '/test/nginx', 'reload': ['nginx', '-s', 'reload']}
with patch.object(wizard.os, 'fchmod', create=True), patch.object(wizard, 'run') as command:
wizard.apply_nginx(plan)
self.assertEqual(command.call_count, 2)
self.assertEqual(file.read_text(), 'new config')
self.assertFalse(list(self.root.glob('.sea-vhost-*')))
def test_runtime_readiness_failure_is_actionable(self):
with patch.object(wizard.subprocess, 'run', return_value=Mock(returncode=1)), patch.object(wizard.time, 'sleep'):
with self.assertRaisesRegex(wizard.InstallError, 'journalctl'):
wizard.wait_services(['sea-vhost-node'], attempts=2)
def test_runtime_readiness_requires_stable_active_service(self):
with patch.object(wizard.subprocess, 'run', side_effect=[Mock(returncode=0), Mock(returncode=1), Mock(returncode=0), Mock(returncode=0)]) as command, \
patch.object(wizard.time, 'sleep'):
wizard.wait_services(['sea-vhost-node'], attempts=4)
self.assertEqual(command.call_count, 4)
def test_api_readiness_does_not_accept_only_active_systemd(self):
with patch.object(wizard.time, 'monotonic', side_effect=[0, 1]):
with self.assertRaisesRegex(wizard.InstallError, 'API 健康检查未通过'):
wizard.wait_api({}, timeout=0)
def test_api_readiness_retries_connection_refused(self):
opener = Mock()
response = Mock(status=200)
response.read.return_value = b'{"status":"setup_required"}'
context = Mock()
context.__enter__ = Mock(return_value=response)
context.__exit__ = Mock(return_value=False)
opener.open.side_effect = [ConnectionRefusedError(), context]
with patch.object(wizard.urllib.request, 'build_opener', return_value=opener), patch.object(wizard.time, 'sleep'):
wizard.wait_api({})
self.assertEqual(opener.open.call_count, 2)
def test_domain_injection_rejected(self):
for value in ('example.com; root /etc;', 'a b.example.com', '*.example.com', 'https://example.com', 'a..example.com'):
self.assertFalse(wizard.valid_domain(value))
self.assertTrue(wizard.valid_domain('host.ser888.cn'))
if __name__ == '__main__':
unittest.main()
+63
View File
@@ -0,0 +1,63 @@
#!/usr/bin/env bash
set -euo pipefail
certificate_domain="${SEA_FTP_CERTIFICATE_DOMAIN:-}"
management_domain="${SEA_MANAGEMENT_DOMAIN:-}"
if [[ ! "${certificate_domain}" =~ ^[A-Za-z0-9.-]+$ ]] || [[ "${certificate_domain}" == .* ]] || [[ "${certificate_domain}" == *..* ]]; then
echo "SEA_FTP_CERTIFICATE_DOMAIN is invalid." >&2
exit 1
fi
if [[ ! "${management_domain}" =~ ^[A-Za-z0-9.-]+$ ]] || [[ "${management_domain}" == .* ]] || [[ "${management_domain}" == *..* ]]; then
echo "SEA_MANAGEMENT_DOMAIN is invalid." >&2
exit 1
fi
SEA_FTP_CERTIFICATE_DOMAIN="${certificate_domain}" /www/server/panel/pyenv/bin/python3 - <<'PY'
import json
import os
import stat
import tempfile
from pathlib import Path
path = Path('/var/lib/sea-vhost/config.json')
if not path.is_file() or path.is_symlink():
raise SystemExit('Sea vHost configuration is missing or unsafe')
metadata = path.stat()
payload = json.loads(path.read_text(encoding='utf-8'))
payload['ftp_domain'] = os.environ['SEA_FTP_CERTIFICATE_DOMAIN'].strip().lower()
handle, temporary_name = tempfile.mkstemp(prefix='.sea-vhost-config-', dir=str(path.parent), text=True)
try:
with os.fdopen(handle, 'w', encoding='utf-8') as output:
json.dump(payload, output, ensure_ascii=False, indent=2)
output.write('\n')
output.flush()
os.fsync(output.fileno())
os.chmod(temporary_name, stat.S_IMODE(metadata.st_mode))
os.chown(temporary_name, metadata.st_uid, metadata.st_gid)
os.replace(temporary_name, path)
finally:
try:
os.unlink(temporary_name)
except FileNotFoundError:
pass
PY
systemctl restart sea-vhost-agent sea-vhost-panel-broker sea-vhost-api
healthy=false
for _ in {1..30}; do
health="$(curl --fail --silent --show-error --max-time 3 --header "Host: ${management_domain}" http://127.0.0.1:8080/healthz 2>/dev/null || true)"
if [[ "${health}" == *'"status":"ok"'* ]]; then
healthy=true
break
fi
sleep 1
done
if [[ "${healthy}" == "true" ]]; then
echo "Sea vHost FTP host-reuse mode update: success"
# Do not exit here: panel-run-task appends its completion marker after this
# script, and an explicit exit would prevent the caller from observing it.
true
else
echo "Sea vHost API did not become healthy after the FTP mode update." >&2
exit 1
fi