199 lines
13 KiB
JavaScript
199 lines
13 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 = `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; }
|
|
}
|
|
}
|