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 insecureTLS = process.env.SEA_PANEL_TLS_INSECURE === 'true'; if (!panelURL || !panelAPIKey) 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 = {}) { 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: 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; }); response.on('end', () => { if (response.statusCode < 200 || response.statusCode > 299) return reject(new Error(`panel returned HTTP ${response.statusCode}`)); 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 rows(payload) { if (Array.isArray(payload?.data)) return payload.data; if (Array.isArray(payload?.data?.data)) return payload.data.data; return []; } const nodeList = rows(await panelForm('/project/nodejs/get_project_list/stype', { search: 'sv', p: '1', limit: '100' })); if (nodeList.some((item) => /^sv[0-9a-f]{10}(?:_[0-9]+)?$/.test(item.name ?? item.project_name ?? ''))) { throw new Error('managed-looking Node.js panel records still exist; refusing process-only cleanup'); } const marker = `runtime-cleanup-${Date.now()}`; const shell = [ 'set -euo pipefail', 'host_dir="$(find /www/wwwroot/seavHost/vHost -xdev -mindepth 1 -maxdepth 1 -type d -name \'sv??????????\' -print -quit)"; test -n "$host_dir"; host_name="${host_dir##*/}"', `listener_pid="$(ss -lntp | sed -n '/127\\.0\\.0\\.1:20021[[:space:]]/s/.*pid=\\([0-9][0-9]*\\).*/\\1/p' | head -n1)"; if [[ -z "$listener_pid" ]]; then printf "terminated_orphan_processes=0\\n%s\\n" '${marker}'; exit 0; fi; test "$(stat -c %U "/proc/$listener_pid")" = "$host_name"; tr '\\0' ' ' <"/proc/$listener_pid/cmdline" | grep -Fq "node server.js"`, 'kill -TERM "$listener_pid"; pkill -TERM -u "$host_name" -f "npm run start" 2>/dev/null || true; sleep 2; if ss -lntp | grep -qE \'127\\.0\\.0\\.1:20021\\b\'; then exit 1; fi; printf "terminated_orphan_processes=2\\n"', `printf '%s\n' '${marker}'`, ].join('\n'); const task = await panelForm('/crontab', { action: 'AddCrontab', name: `Sea vHost runtime cleanup ${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: shell, sName: 'Temporary Sea vHost orphan runtime cleanup', save: '0', backupTo: 'localhost' }); const taskID = Number(task?.id); if ((task?.status !== true && task?.status !== 'true') || !Number.isSafeInteger(taskID)) throw new Error('panel rejected cleanup task'); let cleanupLog = ''; try { await panelForm('/crontab', { action: 'StartTask', id: String(taskID) }); for (let attempt = 0; attempt < 90; attempt += 1) { await new Promise((resolve) => setTimeout(resolve, 1000)); const result = await panelForm('/crontab', { action: 'GetLogs', id: String(taskID) }); cleanupLog = typeof result?.msg === 'string' ? result.msg : typeof result === 'string' ? result : cleanupLog; if (cleanupLog.includes(marker)) break; } if (!cleanupLog.includes(marker)) throw new Error('orphan process cleanup did not complete'); } finally { try { await panelForm('/crontab', { action: 'DelCrontab', id: String(taskID) }); } catch { /* best effort */ } } const pythonPayload = await panelForm('/project/python/GetProjectList/stype', { search: 'sv', p: '1', limit: '100' }); const stalePython = rows(pythonPayload).filter((item) => /^sv[0-9a-f]{10}_[0-9]+$/.test(item.name ?? '') && /^\/www\/wwwroot\/seavHost\/vHost\/sv[0-9a-f]{10}\/python-[a-z0-9]+$/.test(item.path ?? '')); for (const item of stalePython) { const removed = await panelForm('/project/python/remove_project/stype', { project_name: item.name, name: item.name }); if (removed?.status === false || removed?.status === 'false') throw new Error(`panel rejected stale Python test cleanup for ${item.name}`); } console.log(JSON.stringify({ status: 'passed', orphanProcessesTerminated: Number(cleanupLog.match(/terminated_orphan_processes=(\d+)/)?.[1] ?? 0), stalePythonProjectsRemoved: stalePython.map((item) => item.name) }, null, 2));