import crypto from 'node:crypto'; import fs from 'node:fs'; import path from 'node:path'; import { execFileSync } from 'node:child_process'; import http from 'node:http'; import https from 'node:https'; const baseURL = process.env.SEA_PANEL_URL?.trim(); const apiKey = process.env.SEA_PANEL_API_KEY?.trim(); const insecureTLS = process.env.SEA_PANEL_TLS_INSECURE === 'true'; const cleanupOnly = process.argv.includes('--cleanup-only'); const installRequested = process.argv.includes('--install'); const productionDiagnose = process.argv.includes('--production-diagnose'); const diagnoseRequested = process.argv.includes('--diagnose') || productionDiagnose; const activationArgument = process.argv.find((value) => value.startsWith('--activate-http-test=')); const activationHost = activationArgument?.slice('--activate-http-test='.length) ?? ''; const packageArgument = process.argv.slice(2).find((value) => !value.startsWith('--')); const packagePath = path.resolve(packageArgument ?? 'build/sea-vhost-linux-amd64.tar.gz'); if (!baseURL || !apiKey) { console.error('SEA_PANEL_URL and SEA_PANEL_API_KEY are required.'); process.exit(2); } if (activationHost && (!installRequested || !/^[A-Za-z0-9.-]+$/.test(activationHost) || activationHost.startsWith('.') || activationHost.includes('..'))) { console.error('--activate-http-test requires --install and a valid host name or IP address.'); process.exit(2); } const base = new URL(baseURL); if (!['http:', 'https:'].includes(base.protocol) || base.username || base.password) { console.error('SEA_PANEL_URL must be an HTTP(S) URL without embedded credentials.'); process.exit(2); } const packageInfo = fs.statSync(packagePath); if (!packageInfo.isFile() || packageInfo.size < 1024 || packageInfo.size > 128 * 1024 * 1024) { throw new Error('deployment package must be a regular file between 1 KB and 128 MB'); } const entries = execFileSync('tar', ['-tzf', packagePath], { encoding: 'utf8', maxBuffer: 2 * 1024 * 1024 }) .split(/\r?\n/).filter(Boolean); if (!entries.includes('deploy/preflight.sh') || !entries.includes('deploy/install.sh') || !entries.includes('build/web/index.html') || entries.some((entry) => entry.startsWith('/') || entry.split('/').includes('..'))) { throw new Error('deployment archive has an unsafe or incomplete layout'); } if (activationHost && !entries.includes('deploy/activate-test.sh')) { throw new Error('standard release excludes the insecure HTTP test activator; use HTTPS installation'); } const archive = fs.readFileSync(packagePath); const hash = crypto.createHash('sha256').update(archive).digest('hex'); const shortHash = hash.slice(0, 12); const runID = Date.now().toString(); const remoteName = `sea-vhost-${shortHash}-${runID}.tar.gz`; const remotePath = `/tmp/${remoteName}`; const stagePath = `/opt/sea-vhost-staging-${shortHash}-${runID}`; const taskOperation = productionDiagnose ? 'production diagnose' : diagnoseRequested ? 'diagnose' : installRequested ? 'install' : 'preflight'; const taskName = `Sea vHost ${taskOperation} ${shortHash}-${runID.slice(-6)}`; const md5 = (value) => crypto.createHash('md5').update(value).digest('hex'); const client = base.protocol === 'https:' ? https : http; const agent = base.protocol === 'https:' ? new https.Agent({ rejectUnauthorized: !insecureTLS }) : undefined; function authFields() { const requestTime = Math.floor(Date.now() / 1000).toString(); return { request_time: requestTime, request_token: md5(requestTime + md5(apiKey)) }; } function send(method, pathname, body, contentType, timeoutMs = 30_000) { const url = new URL(pathname, base); return new Promise((resolve, reject) => { const request = client.request(url, { method, agent, timeout: timeoutMs, headers: { 'content-type': contentType, '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 formRequest(pathname, values) { const body = Buffer.from(new URLSearchParams({ ...values, ...authFields() }).toString()); return send('POST', pathname, body, 'application/x-www-form-urlencoded'); } async function cleanupStaleUploads() { const listing = await formRequest('/files', { action: 'GetDir', path: '/tmp', p: '1', search: `sea-vhost-${shortHash}` }); const pattern = new RegExp(`^sea-vhost-${shortHash}(?:-\\d+)?\\.tar\\.gz$`); const names = (Array.isArray(listing?.FILES) ? listing.FILES : []) .map((entry) => String(entry).split(';', 1)[0]) .filter((name) => pattern.test(name)); for (const name of names) { await formRequest('/files', { action: 'DeleteFile', path: `/tmp/${name}` }); } return names.length; } function multipartUpload() { const boundary = `----SeaVHost${crypto.randomBytes(12).toString('hex')}`; const chunks = []; const field = (name, value) => { chunks.push(Buffer.from(`--${boundary}\r\nContent-Disposition: form-data; name="${name}"\r\n\r\n${value}\r\n`)); }; const auth = authFields(); field('action', 'UploadFile'); field('path', '/tmp'); field('request_time', auth.request_time); field('request_token', auth.request_token); chunks.push(Buffer.from(`--${boundary}\r\nContent-Disposition: form-data; name="zunfile"; filename="${remoteName}"\r\nContent-Type: application/gzip\r\n\r\n`)); chunks.push(archive); chunks.push(Buffer.from(`\r\n--${boundary}--\r\n`)); return send('POST', '/files', Buffer.concat(chunks), `multipart/form-data; boundary=${boundary}`, 180_000); } function requireSuccess(payload, operation) { if (!payload || (payload.status !== true && payload.status !== 'true')) { throw new Error(`${operation} was rejected by the panel`); } return payload; } const shell = [ // aaPanel appends its own wrapper after the task body and references $1. // Enabling nounset here would make that trusted wrapper fail after a // successful preflight when the task is launched without arguments. 'set -eo pipefail', `test ! -e '${stagePath}'`, `printf '%s %s\\n' '${hash}' '${remotePath}' | sha256sum -c -`, `install -d -o root -g root -m 0700 '${stagePath}'`, `tar -xzf '${remotePath}' -C '${stagePath}'`, `bash '${stagePath}/deploy/preflight.sh'`, ...(installRequested ? [`bash '${stagePath}/deploy/install.sh'`, `printf '%s\n' 'Sea vHost install result: success'`] : []), ...(activationHost ? [`bash '${stagePath}/deploy/activate-test.sh' '${activationHost}'`] : []), ...(diagnoseRequested ? [ `SEA_DIAGNOSE_PRODUCTION=${productionDiagnose ? 'true' : 'false'} bash '${stagePath}/deploy/diagnose.sh'`, `printf '%s\n' 'Sea vHost diagnostic result: success'`, ] : []), ].join('\n'); let taskID; let uploadAttempted = false; let stageReady = false; try { const cleaned = await cleanupStaleUploads(); if (cleanupOnly) { console.log(`Removed ${cleaned} stale Sea vHost upload(s) from /tmp.`); process.exit(0); } uploadAttempted = true; requireSuccess(await multipartUpload(), 'package upload'); const task = requireSuccess(await formRequest('/crontab', { action: 'AddCrontab', name: taskName, 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: diagnoseRequested ? 'Temporary Sea vHost deployment diagnostics' : installRequested ? 'Temporary Sea vHost installer' : 'Temporary Sea vHost installation preflight', save: '0', backupTo: 'localhost', }), 'temporary task creation'); taskID = Number(task.id); if (!Number.isSafeInteger(taskID) || taskID <= 0) throw new Error('panel returned an invalid task id'); await formRequest('/crontab', { action: 'StartTask', id: String(taskID) }); let log = ''; for (let attempt = 0; attempt < 55; attempt += 1) { await new Promise((resolve) => setTimeout(resolve, 1500)); const result = await formRequest('/crontab', { action: 'GetLogs', id: String(taskID) }); log = typeof result?.msg === 'string' ? result.msg : typeof result === 'string' ? result : log; if (log.includes('当前日志为空')) log = ''; const successMarker = diagnoseRequested ? 'Sea vHost diagnostic result: success' : activationHost ? 'Sea vHost test activation result: success' : installRequested ? 'Sea vHost install result: success' : 'Result:'; if (log.includes(successMarker) || log.includes('SHA256SUMS') || log.includes('FAILED') || log.includes('★[')) break; } if (!log.trim()) throw new Error('remote deployment task produced no log output'); console.log(log.trim()); stageReady = log.includes('Result: 0 failure(s)'); const installed = log.includes('Sea vHost install result: success'); const activated = log.includes('Sea vHost test activation result: success'); const diagnosed = log.includes('Sea vHost diagnostic result: success'); if (stageReady) console.log(`Staged package: ${stagePath}`); if (installed && !activated) console.log('Sea vHost files and systemd units were installed; services were not started.'); if (activated) console.log(`Sea vHost test console was activated for host ${activationHost}.`); if (diagnosed) console.log(`Sea vHost ${productionDiagnose ? 'production ' : ''}diagnostics passed.`); if (!stageReady || (installRequested && !installed) || (activationHost && !activated) || (diagnoseRequested && !diagnosed)) process.exitCode = 1; } finally { if (taskID) { try { await formRequest('/crontab', { action: 'DelCrontab', id: String(taskID) }); } catch { /* best-effort cleanup */ } } if (uploadAttempted) { try { await formRequest('/files', { action: 'DeleteFile', path: remotePath }); } catch { /* best-effort cleanup */ } } if (!stageReady) { try { await formRequest('/files', { action: 'DeleteDir', path: stagePath }); } catch { /* best-effort cleanup */ } } }