Files
xiaowang 49be62e38b chore(p0/p1): 决策基线、协议实测样本与能力回归门禁
阶段 01(基线冻结与环境核验)
- 新增 docs/decision-baseline.md:DEC-001~408 决策登记、TBD 处置、
  GAP-01~18 文档同步清单、NEED-01~10 阻塞项闭环
- DEC-005 定稿:NapCat 维持 latest-stable,升级强制全量回归(选项 B)
- DEC-006 定稿:开发期接受 MinIO 明文 HTTP + root 凭据,正式环境
  TLS 与受限子账号列为部署前置条件
- 新增 .env.example(仅占位值)、.gitignore(排除 env-local.md 与 local/)
- 实测环境:JDK 21 / MySQL 8.0.46(lower_case_table_names=1 导致库名
  强制小写,影响首版初始化命名)/ MinIO 建桶读写全通

阶段 02(NapCat 4.18.41 协议实测,正向 WebSocket)
- 三证据矩阵(API retcode + 事件段 + history 回读段)覆盖 27 项能力
- 关键结论:retcode=0 不等于送达(poke/location/私聊 at 静默丢段);
  file 段成功但零事件回推;forward 容器无效须用并列 node 段且
  content 必须为段数组;get_forward_msg 读回为能力缺口;
  record 受上游解码能力限制;music 降级为 text;URL 形式媒体可用
  但 rkey 具时效;撤回只能用 delete_msg 且 history 不回显撤回状态;
  通知类事件无 real_seq,去重键需分类设计
- 安全发现:get_ai_record 名义查询实际会真实发送语音,已标 severity high
- 上游自检 API 不可信(can_send_record 返回 yes=true 与实测矛盾)

能力基线与回归门禁(DEC-005 落地)
- 新增 docs/capability-baseline.json:27 项能力机器可读基线 +
  8 条跨能力硬约束 GC-001~008,状态不得留空
- 新增 tools/probe/capability-check.mjs:离线结构校验 PASS(0 错误
  0 警告,探针覆盖 22/27);漂移比对 17 项自动一致、0 漂移、
  1 缺测、4 人工确认 → PASS;门禁有效性已做红/绿验证
- 新增/修复探测脚本 20 个,均默认 dry-run、写操作需 --yes、
  凭据仅从环境变量读取

未验证项保持未验证:反向 WS / HTTP 回调 / HTTP API 三条入站链路受阻于
网络拓扑;重复投递、乱序、断线重连补推及需 QQ 端人工操作的通知类事件
未采集,去重键与「结果未知」状态机不得定稿。
2026-10-29 15:09:56 +08:00

196 lines
8.8 KiB
JavaScript
Raw Permalink Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
// 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);
}