189 lines
11 KiB
JavaScript
189 lines
11 KiB
JavaScript
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; }
|
|
}
|
|
}
|