feat: import Sea vHost single-server testing release
This commit is contained in:
commit
248badd33e
441 files changed
+63221
No files matched your search
@@ -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));
|
||||
Reference in new issue
Block a user