Files
vHost/deploy/real-panel-smoke.mjs
T

316 lines
17 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 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;
}