Files
vHost/deploy/panel-project-source-probe.mjs
T

152 lines
6.1 KiB
JavaScript

import crypto from 'node:crypto';
import http from 'node:http';
import https from 'node:https';
// Read-only compatibility probe for aaPanel's built-in language project
// modules. It deliberately uses only the Files API and never prints secrets.
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) {
console.error('SEA_PANEL_URL and SEA_PANEL_API_KEY are required.');
process.exit(2);
}
const panelBase = new URL(panelURL);
const panelClient = panelBase.protocol === 'https:' ? https : http;
const panelAgent = panelBase.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 requestToken = md5(requestTime + md5(panelAPIKey));
const body = Buffer.from(new URLSearchParams({ ...values, request_time: requestTime, request_token: requestToken }).toString());
const url = new URL(pathname, panelBase);
return new Promise((resolve, reject) => {
const request = panelClient.request(url, {
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 > 8 * 1024 * 1024) request.destroy(new Error('panel response exceeded 8 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 fileText(payload) {
if (typeof payload === 'string') return payload;
for (const key of ['data', 'msg', 'content']) {
if (typeof payload?.[key] === 'string') return payload[key];
}
return '';
}
function directoryNames(payload) {
const rows = Array.isArray(payload) ? payload
: Array.isArray(payload?.files) ? payload.files
: Array.isArray(payload?.data) ? payload.data
: [...(Array.isArray(payload?.DIR) ? payload.DIR : []), ...(Array.isArray(payload?.FILES) ? payload.FILES : [])];
return rows.map((row) => {
const value = typeof row === 'string' ? row : row?.filename || row?.name || row?.path;
return typeof value === 'string' ? value.split(';', 1)[0] : value;
}).filter(Boolean);
}
const candidateDirectories = [
'/www/server/panel/class/projectModel',
'/www/server/panel/mod/project',
'/www/server/panel/mod/project/java',
'/www/server/panel/BTPanel',
];
const discovered = new Set();
for (const path of candidateDirectories) {
try {
const payload = await panelForm('/files', { action: 'GetDir', path });
const names = directoryNames(payload);
console.log(`${path}: ${names.length ? names.join(', ') : '(no recognized entries)'}`);
for (const name of names) {
if (/^(nodejs|python|go|java).*\.py$/i.test(name)) discovered.add(`${path}/${name}`);
}
} catch (error) {
console.log(`${path}: unavailable (${error.message})`);
}
}
const explicitFiles = [
'/www/server/panel/class/projectModel/nodejsModel.py',
'/www/server/panel/class/projectModel/pythonModel.py',
'/www/server/panel/class/projectModel/goModel.py',
'/www/server/panel/class/projectModel/javaModel.py',
'/www/server/panel/mod/project/nodejs.py',
'/www/server/panel/mod/project/python.py',
'/www/server/panel/mod/project/python/serviceMod.py',
'/www/server/panel/mod/project/go.py',
'/www/server/panel/mod/project/java/projectMod.py',
];
for (const file of explicitFiles) discovered.add(file);
const wantedFunctions = new Set((process.env.SEA_PROBE_FUNCTIONS || [
'create_project', 'start_project', 'stop_project', 'restart_project',
'remove_project', 'delete_project', 'get_project_list',
].join(',')).split(',').map((value) => value.trim()).filter(Boolean));
const linePattern = process.env.SEA_PROBE_MATCH ? new RegExp(process.env.SEA_PROBE_MATCH, 'i') : null;
for (const path of discovered) {
try {
const text = fileText(await panelForm('/files', { action: 'GetFileBody', path }));
if (!text) continue;
const lines = text.split(/\r?\n/);
const matches = [];
if (linePattern) {
for (let index = 0; index < lines.length; index += 1) {
if (linePattern.test(lines[index])) {
const start = Math.max(0, index - 2);
const end = Math.min(lines.length, index + 3);
matches.push(`L${start + 1}-${end}:\n${lines.slice(start, end).join('\n')}`);
}
}
}
for (let index = 0; index < lines.length; index += 1) {
const definition = lines[index].match(/^ def\s+([A-Za-z_][A-Za-z0-9_]*)\s*\(/);
if (!definition || !wantedFunctions.has(definition[1])) continue;
let end = index + 1;
while (end < lines.length && !/^ def\s+[A-Za-z_][A-Za-z0-9_]*\s*\(/.test(lines[end])) end += 1;
matches.push(`L${index + 1}-${end}:\n${lines.slice(index, end).join('\n')}`);
}
if (matches.length) {
console.log(`\n=== ${path} (${lines.length} lines, ${matches.length} functions) ===`);
console.log(matches.join('\n---\n'));
}
} catch {
// Missing candidates are expected across aaPanel versions.
}
}
if (process.env.SEA_PROBE_RUNTIME_LOGS === 'true') {
for (const path of ['/www/server/panel/logs/npm-exec.log']) {
try {
const lines = fileText(await panelForm('/files', { action: 'GetFileBody', path })).split(/\r?\n/);
console.log(`\n=== ${path} (last 120 lines) ===`);
console.log(lines.slice(-120).join('\n'));
} catch {
console.log(`\n=== ${path}: unavailable ===`);
}
}
}