196 lines
8.8 KiB
JavaScript
196 lines
8.8 KiB
JavaScript
// NapCat OB11 网络配置管理(对应 WebUI「网络协议配置」)
|
||||
|
|
//
|
|||
|
|
// 安全约束:
|
|||
|
|
// 1. WebUI 密码只从环境变量 NAPCAT_WEBUI_PASSWORD 读取,脚本与仓库内不留凭据。
|
|||
|
|
// 2. 任何写操作必须显式 --yes,否则只打印将要提交的内容(dry-run)。
|
|||
|
|
// 3. 写入前自动备份到 local/(已 gitignore)。
|
|||
|
|
// 4. 写入后强制校验:原有 websocketServers 不得丢失。丢失则立即自动回滚,防止把自己锁在外面。
|
|||
|
|
//
|
|||
|
|
// 用法:
|
|||
|
|
// node tools/probe/napcat-net.mjs get
|
|||
|
|
// node tools/probe/napcat-net.mjs backup
|
|||
|
|
// node tools/probe/napcat-net.mjs restore <backupFile> --yes
|
|||
|
|
// node tools/probe/napcat-net.mjs add-ws-server --name X --port 16100 --token-env VAR --yes
|
|||
|
|
// node tools/probe/napcat-net.mjs add-http-server --name X --port 3000 --token-env VAR --yes
|
|||
|
|
// node tools/probe/napcat-net.mjs add-http-client --name X --url http://IP:8080/onebot/v11/ --token-env VAR --yes
|
|||
|
|
// node tools/probe/napcat-net.mjs add-ws-client --name X --url ws://IP:8081/onebot/v11/ws --token-env VAR --yes
|
|||
|
|
// node tools/probe/napcat-net.mjs restart --yes
|
|||
|
|
import { readFileSync, writeFileSync, mkdirSync, readdirSync } from 'node:fs';
|
|||
|
|
|
|||
|
|
const BASE = (process.env.NAPCAT_WEBUI_URL || 'http://192.168.5.32:6099').replace(/\/$/, '');
|
|||
|
|
const PASSWORD = process.env.NAPCAT_WEBUI_PASSWORD;
|
|||
|
|
const BACKUP_DIR = 'local';
|
|||
|
|
|
|||
|
|
if (!PASSWORD) { console.error('缺少环境变量 NAPCAT_WEBUI_PASSWORD'); process.exit(1); }
|
|||
|
|
|
|||
|
|
const sha256Hex = async (s) =>
|
|||
|
|
[...new Uint8Array(await crypto.subtle.digest('SHA-256', new TextEncoder().encode(s)))]
|
|||
|
|
.map(b => b.toString(16).padStart(2, '0')).join('');
|
|||
|
|
|
|||
|
|
async function api(path, body, cred) {
|
|||
|
|
const res = await fetch(`${BASE}/api${path}`, {
|
|||
|
|
method: body === undefined ? 'GET' : 'POST',
|
|||
|
|
headers: { 'Content-Type': 'application/json', ...(cred ? { Authorization: `Bearer ${cred}` } : {}) },
|
|||
|
|
body: body === undefined ? undefined : JSON.stringify(body),
|
|||
|
|
signal: AbortSignal.timeout(20000),
|
|||
|
|
});
|
|||
|
|
const t = await res.text();
|
|||
|
|
let j; try { j = JSON.parse(t); } catch { j = { __raw: t.slice(0, 300) }; }
|
|||
|
|
return { http: res.status, ...j };
|
|||
|
|
}
|
|||
|
|
|
|||
|
|
const loginRes = await api('/auth/login', { hash: await sha256Hex(`${PASSWORD}.napcat`) });
|
|||
|
|
if (loginRes.code !== 0) { console.error(`WebUI 登录失败: ${loginRes.message}`); process.exit(1); }
|
|||
|
|
const CRED = loginRes.data.Credential;
|
|||
|
|
|
|||
|
|
// 登录号不写死,从 WebUI 动态取(RestartNapCat 等接口以 uin 为键)
|
|||
|
|
const usersRes = await api('/QQLogin/GetQuickLoginListNew', {}, CRED);
|
|||
|
|
const userList = Array.isArray(usersRes.data) ? usersRes.data : [];
|
|||
|
|
const UIN = process.env.NAPCAT_UIN || String(userList[0]?.uin ?? '');
|
|||
|
|
if (!UIN) { console.error('无法确定 NapCat 登录号 uin,可用 NAPCAT_UIN 指定'); process.exit(1); }
|
|||
|
|
console.error(`NapCat 登录号 uin = ${UIN}${userList[0]?.nickName ? ' (' + userList[0].nickName + ')' : ''}`);
|
|||
|
|
|
|||
|
|
const argv = process.argv.slice(2);
|
|||
|
|
const YES = argv.includes('--yes');
|
|||
|
|
const cmd = argv[0];
|
|||
|
|
const opt = (name, dflt) => { const i = argv.indexOf(`--${name}`); return i >= 0 ? argv[i + 1] : dflt; };
|
|||
|
|
|
|||
|
|
async function getConfig() {
|
|||
|
|
const r = await api('/OB11Config/GetConfig', { uin: UIN }, CRED);
|
|||
|
|
if (r.code !== 0) throw new Error(`GetConfig 失败: ${r.message}`);
|
|||
|
|
return r.data;
|
|||
|
|
}
|
|||
|
|
|
|||
|
|
function snapshot(cfg) {
|
|||
|
|
mkdirSync(BACKUP_DIR, { recursive: true });
|
|||
|
|
const f = `${BACKUP_DIR}/napcat-ob11-${new Date().toISOString().replace(/[:.]/g, '-')}.json`;
|
|||
|
|
writeFileSync(f, JSON.stringify(cfg, null, 2), 'utf-8');
|
|||
|
|
return f;
|
|||
|
|
}
|
|||
|
|
|
|||
|
|
// 写操作统一入口:备份 → 提交 → 校验 → 失败回滚
|
|||
|
|
async function commit(next, label) {
|
|||
|
|
const before = await getConfig();
|
|||
|
|
const file = snapshot(before);
|
|||
|
|
console.log(`已备份原配置 → ${file}`);
|
|||
|
|
console.log(`变更项: ${label}`);
|
|||
|
|
if (!YES) {
|
|||
|
|
console.log('\n[dry-run] 未提交。确认后加 --yes 执行。');
|
|||
|
|
console.log(JSON.stringify(next.network, null, 2));
|
|||
|
|
return;
|
|||
|
|
}
|
|||
|
|
const r = await api('/OB11Config/SetConfig', { config: JSON.stringify(next) }, CRED);
|
|||
|
|
console.log(`SetConfig: code=${r.code} message=${r.message}`);
|
|||
|
|
if (r.code !== 0) { console.error('写入失败,未做改动。'); process.exit(1); }
|
|||
|
|
|
|||
|
|
const after = await getConfig();
|
|||
|
|
const lost = before.network.websocketServers.filter(
|
|||
|
|
o => o.enable && !after.network.websocketServers.some(n => n.name === o.name && n.port === o.port && n.enable)
|
|||
|
|
);
|
|||
|
|
if (lost.length) {
|
|||
|
|
console.error(`校验失败:原有 WS Server 丢失 ${lost.map(o => `${o.name}:${o.port}`).join(', ')},正在回滚...`);
|
|||
|
|
const rb = await api('/OB11Config/SetConfig', { config: JSON.stringify(before) }, CRED);
|
|||
|
|
console.log(`回滚结果: code=${rb.code} message=${rb.message}`);
|
|||
|
|
console.error(`备份文件保留在 ${file},可人工 restore。`);
|
|||
|
|
process.exit(1);
|
|||
|
|
}
|
|||
|
|
console.log('校验通过:原有 WS Server 仍在,新配置已落地。');
|
|||
|
|
console.log('注意:网络配置通常需要重启 NapCat 才生效(restart 子命令,需单独 --yes)。');
|
|||
|
|
}
|
|||
|
|
|
|||
|
|
const tokenFromEnv = () => {
|
|||
|
|
const v = opt('token-env');
|
|||
|
|
if (!v) throw new Error('缺少 --token-env <环境变量名>,token 不得写在命令行参数里');
|
|||
|
|
const t = process.env[v];
|
|||
|
|
if (!t) throw new Error(`环境变量 ${v} 未设置`);
|
|||
|
|
return t;
|
|||
|
|
};
|
|||
|
|
|
|||
|
|
const baseServer = (name, token) => ({
|
|||
|
|
enable: true, name, token, messagePostFormat: 'array',
|
|||
|
|
reportSelfMessage: true, enableForcePushEvent: true, debug: false, heartInterval: 3000,
|
|||
|
|
});
|
|||
|
|
|
|||
|
|
const cfg = await getConfig();
|
|||
|
|
const net = cfg.network;
|
|||
|
|
|
|||
|
|
switch (cmd) {
|
|||
|
|
case 'get':
|
|||
|
|
console.log(JSON.stringify(net, null, 2));
|
|||
|
|
break;
|
|||
|
|
|
|||
|
|
case 'backup':
|
|||
|
|
console.log('已备份 → ' + snapshot(cfg));
|
|||
|
|
break;
|
|||
|
|
|
|||
|
|
case 'restore': {
|
|||
|
|
const f = argv[1];
|
|||
|
|
if (!f || f === '--yes') { console.error('用法: restore <backupFile> --yes'); process.exit(1); }
|
|||
|
|
const data = JSON.parse(readFileSync(f, 'utf-8'));
|
|||
|
|
if (!data?.network) { console.error('备份文件结构不合法'); process.exit(1); }
|
|||
|
|
if (!YES) { console.log(`[dry-run] 将从 ${f} 还原,加 --yes 执行。`); break; }
|
|||
|
|
const r = await api('/OB11Config/SetConfig', { config: JSON.stringify(data) }, CRED);
|
|||
|
|
console.log(`restore: code=${r.code} message=${r.message}`);
|
|||
|
|
break;
|
|||
|
|
}
|
|||
|
|
|
|||
|
|
case 'add-ws-server': {
|
|||
|
|
const name = opt('name'), port = Number(opt('port'));
|
|||
|
|
if (!name || !Number.isFinite(port)) { console.error('缺少 --name / --port'); process.exit(1); }
|
|||
|
|
if (net.websocketServers.some(s => s.name === name || s.port === port)) { console.error('同名或同端口已存在'); process.exit(1); }
|
|||
|
|
const next = structuredClone(cfg);
|
|||
|
|
next.network.websocketServers.push({ ...baseServer(name, tokenFromEnv()), host: '0.0.0.0', port, });
|
|||
|
|
await commit(next, `新增 websocketServer ${name}:${port}`);
|
|||
|
|
break;
|
|||
|
|
}
|
|||
|
|
|
|||
|
|
case 'add-http-server': {
|
|||
|
|
const name = opt('name'), port = Number(opt('port'));
|
|||
|
|
if (!name || !Number.isFinite(port)) { console.error('缺少 --name / --port'); process.exit(1); }
|
|||
|
|
if (net.httpServers.some(s => s.name === name || s.port === port)) { console.error('同名或同端口已存在'); process.exit(1); }
|
|||
|
|
const next = structuredClone(cfg);
|
|||
|
|
next.network.httpServers.push({ ...baseServer(name, tokenFromEnv()), host: '0.0.0.0', port });
|
|||
|
|
await commit(next, `新增 httpServer ${name}:${port}`);
|
|||
|
|
break;
|
|||
|
|
}
|
|||
|
|
|
|||
|
|
case 'add-http-client': {
|
|||
|
|
const name = opt('name'), url = opt('url');
|
|||
|
|
if (!name || !url) { console.error('缺少 --name / --url'); process.exit(1); }
|
|||
|
|
if (net.httpClients.some(s => s.name === name)) { console.error('同名已存在'); process.exit(1); }
|
|||
|
|
const next = structuredClone(cfg);
|
|||
|
|
next.network.httpClients.push({
|
|||
|
|
...baseServer(name, tokenFromEnv()),
|
|||
|
|
url,
|
|||
|
|
async: false, secret: '', retryInterval: 5, timeout: 10, httpInterval: 0,
|
|||
|
|
});
|
|||
|
|
await commit(next, `新增 httpClient ${name} → ${url}`);
|
|||
|
|
break;
|
|||
|
|
}
|
|||
|
|
|
|||
|
|
case 'add-ws-client': {
|
|||
|
|
const name = opt('name'), url = opt('url');
|
|||
|
|
if (!name || !url) { console.error('缺少 --name / --url'); process.exit(1); }
|
|||
|
|
if (net.websocketClients.some(s => s.name === name)) { console.error('同名已存在'); process.exit(1); }
|
|||
|
|
const next = structuredClone(cfg);
|
|||
|
|
next.network.websocketClients.push({
|
|||
|
|
...baseServer(name, tokenFromEnv()),
|
|||
|
|
url,
|
|||
|
|
accessToken: '', heartbeatInterval: 3000, reverseHeartbeatInterval: 30000,
|
|||
|
|
reconnectInterval: 5000,
|
|||
|
|
});
|
|||
|
|
await commit(next, `新增 websocketClient ${name} → ${url}`);
|
|||
|
|
break;
|
|||
|
|
}
|
|||
|
|
|
|||
|
|
case 'restart':
|
|||
|
|
if (!YES) { console.log('[dry-run] 将重启 NapCat 进程,加 --yes 执行。'); break; }
|
|||
|
|
console.log('提醒:重启会中断该 QQ 号登录会话与所有 NapCat 连接。');
|
|||
|
|
console.log(JSON.stringify(await api('/QQLogin/RestartNapCat', { uin: UIN }, CRED), null, 2));
|
|||
|
|
break;
|
|||
|
|
|
|||
|
|
default:
|
|||
|
|
console.error('用法: get | backup | restore | add-ws-server | add-http-server | add-http-client | add-ws-client | restart');
|
|||
|
|
process.exit(1);
|
|||
|
|
}
|