import crypto from 'node:crypto'; 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'; if (!baseURL || !apiKey) { console.error('SEA_PANEL_URL and SEA_PANEL_API_KEY are required.'); process.exit(2); } const base = new URL(baseURL); 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(apiKey)) }; } function formRequest(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; }); 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 requireSuccess(payload, operation) { if (!payload || (payload.status !== true && payload.status !== 'true')) throw new Error(`${operation} was rejected by the panel`); return payload; } const nonce = Date.now().toString().slice(-7); const taskName = `Sea vHost apt repair ${nonce}`; const source = '/etc/apt/sources.list.d/docker.list'; const disabled = `${source}.disabled`; const expected = 'deb [arch=amd64 signed-by=/usr/share/keyrings/docker-archive-keyring.gpg] mirrors.aliyun.com/docker-ce/linux/debian 13 stable'; const shell = [ // aaPanel appends a wrapper that reads $1 after the task body. 'set -eo pipefail', `source_file='${source}'`, `disabled_file='${disabled}'`, `expected='${expected}'`, 'test -f "$source_file" && test ! -L "$source_file"', 'test ! -e "$disabled_file"', 'actual="$(sed -e \"s/[[:space:]]*$//\" "$source_file")"', 'if [[ "$actual" != "$expected" ]]; then echo "Refusing to disable an unexpected apt source"; exit 1; fi', 'mv -- "$source_file" "$disabled_file"', 'rollback() { mv -- "$disabled_file" "$source_file" || true; }', 'trap rollback ERR', 'apt-get update', 'trap - ERR', "printf '%s\\n' 'Sea vHost apt source repair: success'", ].join('\n'); let taskID; try { 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: 'One-time guarded apt source repair', save: '0', backupTo: 'localhost', }), 'temporary repair 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 < 120; attempt += 1) { await new Promise((resolve) => setTimeout(resolve, 1000)); 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('Sea vHost apt source repair: success') || log.includes('Refusing to disable')) break; } if (!log.includes('Sea vHost apt source repair: success')) throw new Error(`apt source repair did not complete:\n${log.trim()}`); console.log(log.trim()); } finally { if (taskID) { try { await formRequest('/crontab', { action: 'DelCrontab', id: String(taskID) }); } catch { /* best effort */ } } }