185 lines
9.2 KiB
JavaScript
185 lines
9.2 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 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;
|
|
}
|