142 lines
7.0 KiB
JavaScript
142 lines
7.0 KiB
JavaScript
import crypto from 'node:crypto';
|
|
import { readFile } from 'node:fs/promises';
|
|
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 taskFile = process.env.SEA_PANEL_TASK_FILE?.trim();
|
|
const taskLabel = process.env.SEA_PANEL_TASK_NAME?.trim() || 'Sea vHost administrative task';
|
|
const taskEnvironmentJSON = process.env.SEA_PANEL_TASK_ENV_JSON?.trim() || '{}';
|
|
const taskTimeoutMinutes = Number(process.env.SEA_PANEL_TASK_TIMEOUT_MINUTES?.trim() || '10');
|
|
const insecureTLS = process.env.SEA_PANEL_TLS_INSECURE === 'true';
|
|
|
|
if (!panelURL || !panelAPIKey || !taskFile) {
|
|
console.error('SEA_PANEL_URL, SEA_PANEL_API_KEY and SEA_PANEL_TASK_FILE are required.');
|
|
process.exit(2);
|
|
}
|
|
if (!Number.isSafeInteger(taskTimeoutMinutes) || taskTimeoutMinutes < 1 || taskTimeoutMinutes > 120) {
|
|
console.error('SEA_PANEL_TASK_TIMEOUT_MINUTES must be an integer from 1 to 120.');
|
|
process.exit(2);
|
|
}
|
|
if (taskLabel.length > 80 || /[\r\n]/.test(taskLabel)) {
|
|
console.error('SEA_PANEL_TASK_NAME must be a single line of at most 80 characters.');
|
|
process.exit(2);
|
|
}
|
|
|
|
const base = new URL(panelURL);
|
|
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 shell = await readFile(taskFile, 'utf8');
|
|
if (!shell.trim() || shell.length > 512 * 1024 || shell.includes('\0')) {
|
|
console.error('The task file must contain 1 byte to 512 KiB of shell text without NUL bytes.');
|
|
process.exit(2);
|
|
}
|
|
let taskEnvironment;
|
|
try {
|
|
taskEnvironment = JSON.parse(taskEnvironmentJSON);
|
|
} catch {
|
|
console.error('SEA_PANEL_TASK_ENV_JSON must be a JSON object.');
|
|
process.exit(2);
|
|
}
|
|
if (!taskEnvironment || Array.isArray(taskEnvironment) || typeof taskEnvironment !== 'object') {
|
|
console.error('SEA_PANEL_TASK_ENV_JSON must be a JSON object.');
|
|
process.exit(2);
|
|
}
|
|
const shellQuote = (value) => `'${String(value).replaceAll("'", "'\\''")}'`;
|
|
const environmentLines = [];
|
|
for (const [name, value] of Object.entries(taskEnvironment)) {
|
|
if (!/^SEA_[A-Z0-9_]{1,80}$/.test(name) || typeof value !== 'string' || value.length > 4096 || value.includes('\0')) {
|
|
console.error('Task environment names must start with SEA_ and contain short string values.');
|
|
process.exit(2);
|
|
}
|
|
environmentLines.push(`export ${name}=${shellQuote(value)}`);
|
|
}
|
|
|
|
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 authFields() {
|
|
const requestTime = Math.floor(Date.now() / 1000).toString();
|
|
return { request_time: requestTime, request_token: md5(requestTime + md5(panelAPIKey)) };
|
|
}
|
|
function panelFormOnce(pathname, values) {
|
|
const body = Buffer.from(new URLSearchParams({ ...values, ...authFields() }).toString());
|
|
return new Promise((resolve, reject) => {
|
|
const request = client.request(new URL(pathname, base), {
|
|
method: 'POST', agent, timeout: 30_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;
|
|
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(`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);
|
|
});
|
|
}
|
|
async function panelForm(pathname,values){
|
|
for(let attempt=0;attempt<3;attempt++){
|
|
try{return await panelFormOnce(pathname,values)}catch(error){
|
|
if(attempt===2||!String(error.message).includes('before secure TLS connection was established'))throw error;
|
|
await new Promise(resolve=>setTimeout(resolve,1000*(attempt+1)));
|
|
}
|
|
}
|
|
}
|
|
function requireSuccess(payload, operation) {
|
|
if (payload === true || payload === 'true') return payload;
|
|
if (!payload || (payload.status !== true && payload.status !== 'true')) {
|
|
const reason=String(payload?.msg||payload?.message||"未提供原因").replaceAll(panelAPIKey,"[REDACTED]").slice(0,320); throw new Error(`${operation} was rejected by aaPanel: ${reason}`);
|
|
}
|
|
return payload;
|
|
}
|
|
|
|
const marker = `sea-vhost-task-complete-${crypto.randomBytes(12).toString('hex')}`;
|
|
const taskName = `${taskLabel} ${Date.now().toString().slice(-7)}`;
|
|
const body = `set +e\n(\n${environmentLines.join('\n')}\n${shell.trimEnd()}\n)\nsea_task_status=$?\nprintf '%s:%s\\n' '${marker}' "$sea_task_status"\nexit "$sea_task_status"\n`;
|
|
// These jobs are explicitly started once and removed in finally. Schedule the
|
|
// dormant cron date at least several days away so a long installer is not
|
|
// launched again every minute while its first execution is still running.
|
|
const dormantDay = String((new Date().getUTCDate() + 6) % 28 + 1);
|
|
let taskID;
|
|
try {
|
|
const task = requireSuccess(await panelForm('/crontab', {
|
|
action: 'AddCrontab', name: taskName, type: 'month', where1: dormantDay, where_hour: '0', where_minute: '0',
|
|
user: 'root', urladdress: 'http://', save_local: '0', sType: 'toShell', sBody: body,
|
|
sName: 'Temporary Sea vHost administrative task', save: '0', backupTo: 'localhost',
|
|
}), 'temporary task creation');
|
|
taskID = Number(task.id);
|
|
if (!Number.isSafeInteger(taskID) || taskID <= 0) throw new Error('aaPanel returned an invalid task id');
|
|
requireSuccess(await panelForm('/crontab', { action: 'StartTask', id: String(taskID) }), 'temporary task execution');
|
|
let log = '';
|
|
const deadline = Date.now() + taskTimeoutMinutes * 60_000;
|
|
while (Date.now() < deadline) {
|
|
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 + ':')) break;
|
|
}
|
|
if (!log.includes(marker + ':')) throw new Error(`the remote task did not complete within ${taskTimeoutMinutes} minutes`);
|
|
const statusMatch = log.match(new RegExp(`${marker}:(\\d+)`));
|
|
const cleanedLog = log.replace(new RegExp(`${marker}:\\d+`), '').trim();
|
|
if (cleanedLog) console.log(cleanedLog);
|
|
if (!statusMatch || statusMatch[1] !== '0') throw new Error(`the remote task failed with status ${statusMatch?.[1] ?? 'unknown'}`);
|
|
} finally {
|
|
if (taskID) {
|
|
try { await panelForm('/crontab', { action: 'DelCrontab', id: String(taskID) }); } catch { /* best effort */ }
|
|
}
|
|
}
|