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 端人工操作的通知类事件
未采集,去重键与「结果未知」状态机不得定稿。
This commit is contained in:
2026-10-29 15:09:56 +08:00
commit 49be62e38b
38 changed files with 36577 additions and 0 deletions
+66
View File
@@ -0,0 +1,66 @@
// 验证 get_ai_record 是否是「只读生成 URL」还是「会真实往群里发语音」。
// 起因:history 里出现 4 条 record 消息,而所有显式 record 段发送都返回 retcode=1200,
// 且这 4 条的 fileid 与历次 get_ai_record 返回的 URL fileid 逐一对应。
// 若成立,则 get_ai_record 名义上是查询接口、实际有外部副作用,QLinker 侧必须按写操作管控。
//
// 用法(会产生真实语音消息,属有副作用脚本):
// NAPCAT_WS_TOKEN=xxx node tools/probe/ai-record-sideeffect.mjs
import fs from 'node:fs';
const WS_URL = process.env.NAPCAT_WS_URL || 'ws://192.168.5.32:16099';
const TOKEN = process.env.NAPCAT_WS_TOKEN;
const GROUP = Number(process.env.PROBE_GROUP || 933280401);
if (!TOKEN) { console.error('缺少环境变量 NAPCAT_WS_TOKEN。凭据不得硬编码。'); process.exit(1); }
const pending = new Map();
let opened = false;
const ws = new WebSocket(`${WS_URL.replace(/\/$/, '')}/?access_token=${encodeURIComponent(TOKEN)}`);
ws.onopen = () => { opened = true; };
ws.onmessage = (ev) => {
let o; try { o = JSON.parse(String(ev.data)); } catch { return; }
if (o.echo && pending.has(o.echo)) { pending.get(o.echo).resolve(o); pending.delete(o.echo); }
};
for (let i = 0; i < 100 && !opened; i++) await new Promise((r) => setTimeout(r, 100));
if (!opened) { console.error('连接超时'); process.exit(1); }
const api = (action, params, ms = 40000) => new Promise((resolve) => {
const echo = `se-${action}-${Date.now()}-${Math.random().toString(36).slice(2, 6)}`;
const to = setTimeout(() => { pending.delete(echo); resolve({ __timeout: true }); }, ms);
pending.set(echo, { resolve: (o) => { clearTimeout(to); resolve(o); }, to });
ws.send(JSON.stringify({ action, params, echo }));
});
const fileIdOf = (u) => (String(u).match(/fileid=([^&]+)/) || [])[1] ?? null;
async function recordsInHistory() {
const r = await api('get_group_msg_history', { group_id: GROUP, count: 60 });
return (r?.data?.messages ?? [])
.filter((m) => (m.message ?? []).some((s) => s.type === 'record'))
.map((m) => ({ seq: m.real_seq, mid: m.message_id,
urlFileid: fileIdOf((m.message ?? []).find((s) => s.type === 'record')?.data?.url) }));
}
const before = await recordsInHistory();
console.log(`调用前 history 中 record 消息 ${before.length} 条: ` + before.map((x) => x.seq).join(','));
const r = await api('get_ai_record', { group_id: GROUP, character: 'lucy-voice-houge', text: '副作用验证' });
console.log(`get_ai_record retcode=${r.retcode} 返回类型=${typeof r.data} message_id=${JSON.stringify(r?.data?.message_id ?? null)}`);
const urlFileid = typeof r.data === 'string' ? fileIdOf(r.data) : null;
console.log('返回 URL fileid = ' + String(urlFileid).slice(0, 40));
await new Promise((x) => setTimeout(x, 12000));
const after = await recordsInHistory();
console.log(`调用后 history 中 record 消息 ${after.length} 条: ` + after.map((x) => x.seq).join(','));
const added = after.filter((a) => !before.some((b) => b.seq === a.seq));
console.log(`\n新增 ${added.length} 条: ` + JSON.stringify(added.map((a) => ({ seq: a.seq, mid: a.mid }))));
const matched = added.some((a) => a.urlFileid && a.urlFileid === urlFileid);
console.log(`新增消息的 url fileid 是否等于 get_ai_record 返回的 fileid: ${matched}`);
console.log(`\n结论候选: ${added.length === 1 && matched
? 'get_ai_record 会真实发送语音消息(名义查询接口实为写操作)'
: (added.length === 0 ? 'get_ai_record 未产生新消息(确为只读)' : '新增条数/指纹不匹配,需人工判读')}`);
fs.writeFileSync(`local/ai-record-sideeffect-${Date.now()}.jsonl`,
JSON.stringify({ before, after, added, matched, urlFileid, retcode: r.retcode }, null, 2) + '\n');
try { ws.close(); } catch {}
process.exit(0);
+160
View File
@@ -0,0 +1,160 @@
// NapCat 能力目录回归门禁(DEC-005:不锁版本,但升级必须跑全量回归)。
//
// 两种模式:
// 1) 离线结构校验(默认,可在 CI 直接跑,不联网)
// node tools/probe/capability-check.mjs
// 校验 docs/capability-baseline.json 的枚举合法性、状态完整性、证据存在性、
// 「结论与证据强度是否匹配」——防止把未验证项写成已验证。
//
// 2) 实测漂移比对(升级 NapCat 后必跑)
// node tools/probe/capability-check.mjs --against=local/matrix-result-x.jsonl,local/history-audit-x.jsonl
// 把实测结果与基线 regressionProbe 期望逐条比对,任何状态漂移即失败。
//
// 退出码:0 = 门禁通过;1 = 门禁失败。凭据不涉及(两种模式都不发请求)。
import fs from 'node:fs';
import path from 'node:path';
const ROOT = path.resolve(import.meta.dirname, '../..');
const BASELINE = path.join(ROOT, 'docs/capability-baseline.json');
const errors = [];
const warns = [];
const fail = (m) => errors.push(m);
const warn = (m) => warns.push(m);
if (!fs.existsSync(BASELINE)) { console.error('基线文件缺失: ' + BASELINE); process.exit(1); }
const base = JSON.parse(fs.readFileSync(BASELINE, 'utf8'));
const caps = base.capabilities ?? [];
const STATUS = Object.keys(base.enums?.status ?? {});
const REAL = Object.keys(base.enums?.realEnvTest ?? {});
const ADAPTER = Object.keys(base.enums?.adapterStatus ?? {});
console.log(`能力目录基线:${caps.length} 项,采集于 ${base.meta?.collectedAt},目标 NapCat ${base.meta?.targetNapCat?.version_observed}`);
// ---------- 模式 1:离线结构校验 ----------
function validateStructure() {
if (!base.meta?.evidenceRule) fail('meta.evidenceRule 缺失:三证据规则必须显式声明');
if (!(base.meta?.governance?.length >= 1)) fail('meta.governance 缺失:治理规则必须显式声明');
if (!base.globalConstraints?.length) warn('globalConstraints 为空:跨能力的坑未被固化');
const seen = new Set();
for (const c of caps) {
const tag = c.id ?? '(缺 id)';
if (!c.id) fail('存在无 id 的能力项');
else if (seen.has(c.id)) fail(`能力 id 重复: ${c.id}`);
seen.add(c.id);
if (!c.name) fail(`${tag}: 缺 name`);
if (!c.kind) fail(`${tag}: 缺 kind`);
// 状态不得留空
for (const f of ['sendStatus', 'eventStatus', 'historyStatus', 'parseStatus']) {
if (!c[f]) { fail(`${tag}: ${f} 为空。未采到必须显式标 untested 并写 todo。`); continue; }
const allowed = f === 'parseStatus' ? ADAPTER : STATUS;
if (!allowed.includes(c[f])) fail(`${tag}: ${f}='${c[f]}' 不在枚举内(合法值:${allowed.join('/')})`);
}
if (c.realEnvTest && !REAL.includes(c.realEnvTest)) fail(`${tag}: realEnvTest='${c.realEnvTest}' 不在枚举内`);
// 结论强度纪律:verified 必须有回归探针 + 真实环境验证 + 限制或证据说明
const positive = ['sendStatus', 'eventStatus', 'historyStatus'].filter((f) => c[f] === 'verified');
if (positive.length) {
if (!c.regressionProbe) fail(`${tag}: 标了 verified(${positive.join(',')})但没有 regressionProbe,升级后无法回归`);
if (c.realEnvTest === 'not_tested' || c.realEnvTest === 'blocked')
fail(`${tag}: 状态含 verified 但 realEnvTest=${c.realEnvTest},结论强度与证据不匹配`);
}
// 未验证项不得伪装
if ((c.realEnvTest === 'not_tested' || c.realEnvTest === 'blocked') && positive.length)
fail(`${tag}: 未做真实验证却存在 verified 状态`);
if (['untested', 'blocked'].includes(c.sendStatus) && !(c.todo?.length))
fail(`${tag}: 状态为 ${c.sendStatus} 但未写 todo,缺口无人认领`);
if (['readback_gap', 'silent_drop', 'downgraded', 'no_event', 'rejected'].includes(c.sendStatus)
&& !(c.limitations?.length))
fail(`${tag}: 记录了假成功/缺口类结论但 limitations 为空,后续无法理解判定依据`);
// 证据可追溯
const hasEvidence = (c.automationTest && String(c.automationTest).trim()) || (c.limitations?.length);
if (!hasEvidence) fail(`${tag}: 既无 automationTest 也无 limitations,结论不可追溯`);
}
// 覆盖度:矩阵里出现过的用例必须都能映射到某个能力的 regressionProbe
const probes = caps.flatMap((c) => (c.regressionProbe ? [c.regressionProbe] : []));
const covered = new Set(probes.map((p) => `${p.probe}:${p.case ?? '-'}`));
console.log(`\n结构校验:${errors.length} 个错误,${warns.length} 个警告`);
console.log(`回归探针覆盖:${probes.length}/${caps.length} 项能力带探针`);
const byStatus = {};
for (const c of caps) byStatus[c.sendStatus] = (byStatus[c.sendStatus] ?? 0) + 1;
console.log('发送侧状态分布:' + Object.entries(byStatus).map(([k, v]) => `${k}=${v}`).join(' '));
console.log('带探针的能力:' + [...covered].sort().join(', '));
}
// ---------- 模式 2:实测漂移比对 ----------
function readJsonl(f) {
return fs.readFileSync(f, 'utf8').trim().split('\n')
.map((l) => { try { return JSON.parse(l); } catch { return null; } }).filter(Boolean);
}
function validateAgainst(measureFiles) {
const rows = [];
for (const f of measureFiles) {
const p = path.resolve(ROOT, f);
if (!fs.existsSync(p)) { fail(`实测结果文件不存在: ${f}`); continue; }
for (const r of readJsonl(p)) rows.push({ ...r, __src: path.basename(f) });
}
console.log(`\n载入实测记录 ${rows.length} 条,来自 ${measureFiles.map((f) => path.basename(f)).join(', ')}`);
// 建立 case -> 实测行 的索引(matrix / url-media / record / followup 都是 id 字段)
const byCase = new Map();
for (const r of rows) if (r.id && !r.__summary) byCase.set(String(r.id), r);
// history-audit 提供 history_segs
const audit = new Map();
for (const r of rows) if (r.history_segs) audit.set(String(r.id), r);
// probe 名为 manual/any 的项无法从实测 jsonl 自动比对,单列为人工确认项
const AUTO = new Set(['matrix', 'segments', 'record', 'urlMedia', 'forwardFollowup']);
let checked = 0, drifted = 0, missing = 0, manual = 0;
for (const c of caps) {
const p = c.regressionProbe;
if (!p || !p.case || p.case === '-') continue;
if (!AUTO.has(p.probe)) { manual++; console.log(` [人工] ${c.id.padEnd(20)} ${p.probe}:${p.case} 无自动实测源,需人工确认`); continue; }
const actual = byCase.get(p.case) ?? audit.get(p.case);
if (!actual) { missing++; console.log(` [缺测] ${p.case.padEnd(22)} 本轮实测未覆盖,基线状态 ${c.sendStatus} 无法确认`); continue; }
checked++;
const exp = p.expect ?? {};
const diffs = [];
const actSegs = actual.event_segs ?? actual.history_segs;
const actRet = actual.retcode;
if (exp.retcode !== undefined && Number(actRet) !== Number(exp.retcode))
diffs.push(`retcode 期望 ${exp.retcode} 实测 ${actRet}`);
if (exp.eventSegs !== undefined) {
const a = byCase.get(p.case)?.event_segs;
if (a !== undefined && a !== exp.eventSegs) diffs.push(`事件段 期望 ${exp.eventSegs} 实测 ${a}`);
}
if (exp.historySegs !== undefined) {
const h = audit.get(p.case)?.history_segs;
if (h !== undefined && h !== exp.historySegs) diffs.push(`history段 期望 ${exp.historySegs} 实测 ${h}`);
}
if (exp.messageContains && !String(actual.message ?? '').includes(exp.messageContains))
diffs.push(`错误原文未包含 "${exp.messageContains}",实测 "${String(actual.message ?? '').slice(0, 60)}"`);
if (diffs.length) {
drifted++;
console.log(` [漂移] ${c.id.padEnd(20)} ${p.case.padEnd(22)} ${diffs.join(' ; ')}`);
console.log(` 基线状态 ${c.sendStatus} -> 需人工判定是能力变化还是采集环境问题,确认后更新基线并记录版本`);
} else {
console.log(` [一致] ${c.id.padEnd(20)} ${p.case.padEnd(22)} retcode=${actRet}`);
}
}
console.log(`\n漂移比对:自动比对 ${checked} 项,漂移 ${drifted} 项,缺测 ${missing} 项,人工确认 ${manual} 项`);
if (drifted) fail(`${drifted} 项能力行为相对基线漂移,DEC-005 要求升级后全量回归必须通过或显式确认`);
if (missing) warn(`${missing} 项基线探针本轮未采到,不得据此认为已回归通过`);
}
validateStructure();
const againstArg = process.argv.slice(2).find((a) => a.startsWith('--against='));
if (againstArg) validateAgainst(againstArg.slice(10).split(',').map((s) => s.trim()).filter(Boolean));
console.log('');
for (const w of warns) console.log('警告: ' + w);
for (const e of errors) console.log('错误: ' + e);
if (!againstArg) console.log('\n提示:升级 NapCat 后须跑 --against=<实测jsonl,...> 做漂移比对。');
console.log(errors.length ? `\n门禁结果:FAIL(${errors.length} 项)` : '\n门禁结果:PASS');
process.exit(errors.length ? 1 : 0);
+99
View File
@@ -0,0 +1,99 @@
// 采集真实收发样本:连接 NapCat 正向 WS → 发送一条测试消息 → 抓取回推事件原始 JSON
// 目的:为消息模型 / 消息段 / 去重键设计提供实测依据(decision-baseline 第 7 章样本采集)。
// 凭据只从环境变量读取。发送是真实外部副作用,必须显式 --send。
//
// 用法:
// NAPCAT_WS_TOKEN=xxx node tools/probe/capture-sample.mjs --send private <目标QQ>
// NAPCAT_WS_TOKEN=xxx node tools/probe/capture-sample.mjs --send group <群号>
// NAPCAT_WS_TOKEN=xxx node tools/probe/capture-sample.mjs # 只监听不发
const WS_URL = (process.env.NAPCAT_WS_URL || 'ws://192.168.5.32:16099').replace(/\/$/, '');
const TOKEN = process.env.NAPCAT_WS_TOKEN;
const WATCH_MS = Number(process.env.WATCH_MS || 45000);
if (!TOKEN) { console.error('缺少环境变量 NAPCAT_WS_TOKEN'); process.exit(1); }
const argv = process.argv.slice(2);
const doSend = argv[0] === '--send';
const kind = doSend ? argv[1] : null;
const target = doSend ? Number(argv[2]) : null;
if (doSend && !['private', 'group'].includes(kind)) {
console.error('kind 必须是 private 或 group'); process.exit(1);
}
if (doSend && !Number.isFinite(target)) {
console.error('缺少合法的目标 QQ 号 / 群号'); process.exit(1);
}
const MARK = `QLINKER-PROBE-${new Date().toISOString().slice(11, 19).replace(/:/g, '')}`;
const TEXT = `[QLinker 协议实测] 标记=${MARK} 这条消息由自动化探测脚本发出,用于采集消息结构样本,可忽略。`;
// SEGMENTS_JSON 允许传入任意消息段数组,用于采集不同段类型的真实结构
const SEGMENTS_JSON = process.env.SEGMENTS_JSON;
const events = [];
const ws = new WebSocket(`${WS_URL}/?access_token=${encodeURIComponent(TOKEN)}`);
const pending = new Map();
ws.onmessage = (ev) => {
let o;
try { o = JSON.parse(String(ev.data)); } catch { events.push({ __unparsed: String(ev.data).slice(0, 500) }); return; }
if (o.echo && pending.has(o.echo)) {
const p = pending.get(o.echo); pending.delete(o.echo); clearTimeout(p.to); p.resolve(o); return;
}
events.push(o);
const tag = o.post_type + '/' + (o.message_type || o.notice_type || o.meta_event_type || o.request_type || '-');
console.log(`[EVENT ${new Date().toISOString().slice(11, 23)}] ${tag}` +
(o.message_id ? ` message_id=${o.message_id}` : '') +
(o.user_id ? ` user_id=${o.user_id}` : '') +
(o.group_id ? ` group_id=${o.group_id}` : ''));
};
await new Promise((res, rej) => {
ws.onopen = res;
setTimeout(() => rej(new Error('连接超时')), 10000);
}).catch((e) => { console.error(e.message); process.exit(1); });
function call(action, params, ms = 20000) {
const echo = `${action}-${Date.now()}`;
return new Promise((resolve) => {
const to = setTimeout(() => { pending.delete(echo); resolve({ __timeout: true }); }, ms);
pending.set(echo, { resolve, to });
ws.send(JSON.stringify({ action, params, echo }));
});
}
const self = await call('get_login_info', {});
console.log(`已连接,登录号 = ${self?.data?.user_id} (${self?.data?.nickname})`);
if (doSend) {
const action = kind === 'private' ? 'send_private_msg' : 'send_group_msg';
let message = TEXT;
if (SEGMENTS_JSON) {
try { message = JSON.parse(SEGMENTS_JSON); } catch (e) { console.error('SEGMENTS_JSON 非法: ' + e.message); process.exit(1); }
console.log(`使用自定义消息段: ${JSON.stringify(message).slice(0, 200)}`);
}
const params = kind === 'private'
? { user_id: target, message }
: { group_id: target, message };
console.log(`\n发送 ${action} → ${target}`);
const r = await call(action, params);
if (r.__timeout) console.log('发送无响应(20s 超时)→ 需按「结果未知」处理');
else console.log('发送响应: ' + JSON.stringify({ status: r.status, retcode: r.retcode, message_id: r.data?.message_id }));
}
console.log(`\n监听事件 ${WATCH_MS / 1000}s(期间请在测试号上收/发消息)...`);
await new Promise(r => setTimeout(r, WATCH_MS));
try { ws.close(); } catch {}
const counts = {};
for (const e of events) {
const k = e.post_type ? `${e.post_type}/${e.message_type || e.notice_type || e.meta_event_type || e.request_type || '-'}` : 'unparsed';
counts[k] = (counts[k] || 0) + 1;
}
console.log('\n=== 事件类型统计 ===');
Object.entries(counts).sort().forEach(([k, v]) => console.log(` ${k}: ${v}`));
// message_sent 是 NapCat 扩展的 post_type,标准 OneBot11 无此类型,必须一并采集
const interesting = events.filter(e => ['message', 'message_sent', 'notice', 'request'].includes(e.post_type));
console.log(`\n=== 业务事件原始样本 ${interesting.length} 条 ===`);
interesting.forEach((e, i) => console.log(`--- sample[${i}] ---\n${JSON.stringify(e, null, 2)}`));
+116
View File
@@ -0,0 +1,116 @@
// 长时间挂机的 OneBot11 事件采集器(正向 WebSocket)。
// 每条事件原样追加为一行 JSON,另写一份人类可读的时间线,用于:
// 1) 消息段样本采集;2) 断线重连与补推行为观测;3) 重复投递/乱序观测。
// 凭据只从环境变量读取。
//
// 用法:
// NAPCAT_WS_TOKEN=xxx LOG_FILE=local/events-$(date +%H%M%S).jsonl \
// node tools/probe/event-listener.mjs
// 可选:
// NAPCAT_WS_URL 默认 ws://192.168.5.32:16099
// LOG_FILE 默认 local/events.jsonl
// DROP_HEARTBEAT 默认 true,心跳不落盘(否则文件被 3s 一条刷屏)
// MAX_MS 默认 0(不限时)
const WS_URL = process.env.NAPCAT_WS_URL || 'ws://192.168.5.32:16099';
const TOKEN = process.env.NAPCAT_WS_TOKEN;
const LOG_FILE = process.env.LOG_FILE || 'local/events.jsonl';
const DROP_HEARTBEAT = process.env.DROP_HEARTBEAT !== 'false';
const MAX_MS = Number(process.env.MAX_MS || 0);
import fs from 'node:fs';
import path from 'node:path';
if (!TOKEN) {
console.error('缺少环境变量 NAPCAT_WS_TOKEN。凭据不得硬编码。');
process.exit(1);
}
fs.mkdirSync(path.dirname(LOG_FILE), { recursive: true });
const T0 = Date.now();
const elapsed = () => Date.now() - T0;
const line = (kind, obj) => {
const rec = { t: new Date().toISOString(), el: elapsed(), kind, ...obj };
fs.appendFileSync(LOG_FILE, JSON.stringify(rec) + '\n');
return rec;
};
const say = (...a) => console.log(`[+${(elapsed() / 1000).toFixed(1)}s]`, ...a);
let ws = null;
let connSeq = 0;
let closedByUs = false;
let events = 0;
let reconnects = 0;
function connect() {
connSeq += 1;
const seq = connSeq;
const url = `${WS_URL.replace(/\/$/, '')}/?access_token=${encodeURIComponent(TOKEN)}`;
say(`连接 #${seq} -> ${WS_URL}`);
ws = new WebSocket(url);
let sawLifecycle = false;
ws.onopen = () => {
// 握手成功不等于认证成功,这里只记录,不当作可用
line('client', { event: 'ws_open', conn: seq, note: '握手成功,等待 lifecycle' });
say(`#${seq} 握手成功(尚未确认认证)`);
};
ws.onmessage = (ev) => {
let o;
try { o = JSON.parse(String(ev.data)); } catch {
line('unparsed', { raw: String(ev.data).slice(0, 4000) });
return;
}
const postType = o.post_type ?? o.meta_event_type ?? '(no post_type)';
const isHeartbeat = o.post_type === 'meta_event' && o.meta_event_type === 'heartbeat';
if (o.post_type === 'meta_event' && o.meta_event_type === 'lifecycle') {
sawLifecycle = true;
say(`#${seq} 收到 lifecycle(${o.sub_type}) —— 认证已确认`);
}
if (isHeartbeat && DROP_HEARTBEAT) return;
events += 1;
const brief = o.post_type === 'message' || o.post_type === 'message_sent'
? `${o.message_type}/${o.message_id}/seq=${o.real_seq ?? '-'}`
: (o.notice_type || o.request_type || o.meta_event_type || '');
line('event', { conn: seq, brief, data: o });
say(`事件 #${events} ${postType} ${brief}`);
};
ws.onerror = (e) => {
line('client', { event: 'ws_error', conn: seq, message: String(e?.message ?? e) });
say(`#${seq} error`);
};
ws.onclose = (e) => {
line('client', {
event: 'ws_close', conn: seq, code: e?.code, reason: String(e?.reason ?? ''),
sawLifecycle,
});
say(`#${seq} 关闭 code=${e?.code} reason=${e?.reason || '(空)'} 曾认证=${sawLifecycle}`);
if (closedByUs) return;
reconnects += 1;
line('client', { event: 'reconnect_scheduled', conn: seq, reconnects });
say(`非主动关闭,1s 后重连(第 ${reconnects} 次)`);
setTimeout(connect, 1000);
};
}
connect();
const stop = (why) => {
say(`停止:${why}`);
line('client', { event: 'listener_stop', why, events, reconnects });
closedByUs = true;
try { ws?.close(); } catch {}
say(`累计事件 ${events} 条,重连 ${reconnects} 次,日志 ${LOG_FILE}`);
process.exit(0);
};
process.on('SIGINT', () => stop('SIGINT'));
process.on('SIGTERM', () => stop('SIGTERM'));
if (MAX_MS > 0) setTimeout(() => stop('MAX_MS 到期'), MAX_MS);
say(`采集开始 -> ${LOG_FILE}(心跳落盘=${!DROP_HEARTBEAT})`);
line('client', { event: 'listener_start', url: WS_URL, dropHeartbeat: DROP_HEARTBEAT });
+156
View File
@@ -0,0 +1,156 @@
// 矩阵跑完后的定向补测,只针对三个悬而未决的点:
// 1) 服务端合并转发的 node.content 形态(段数组 vs JSON 字符串)——上一轮传字符串被当字面文本渲染
// 2) get_forward_msg 的正确参数名(穷举常见命名,拿到成功结构或全部失败证据)
// 3) 语音能力旁证:send_group_ai_record(NapCat 官方 TTS)能否成功,用于区分
// 「record 段不可用」与「NapCat 运行环境缺解码器」
// 默认 dry-run,--yes 才真实发送。凭据只从环境变量读取。
import fs from 'node:fs';
import path from 'node:path';
const WS_URL = process.env.NAPCAT_WS_URL || 'ws://192.168.5.32:16099';
const TOKEN = process.env.NAPCAT_WS_TOKEN;
const GROUP = Number(process.env.PROBE_GROUP || 933280401);
const FRIEND = Number(process.env.PROBE_FRIEND || 2161656029);
const SELF = Number(process.env.PROBE_SELF || 3575608514);
const DO_WRITE = process.argv.includes('--yes');
const OUT_DIR = process.env.PROBE_OUT || 'local';
if (!TOKEN) { console.error('缺少环境变量 NAPCAT_WS_TOKEN。凭据不得硬编码。'); process.exit(1); }
const stamp = new Date().toISOString().replace(/[:.]/g, '-');
fs.mkdirSync(OUT_DIR, { recursive: true });
const OUT = path.join(OUT_DIR, `followup-${stamp}.jsonl`);
const say = (...a) => console.log(...a);
const pending = new Map();
let opened = false;
let authed = false;
const events = [];
const ws = new WebSocket(`${WS_URL.replace(/\/$/, '')}/?access_token=${encodeURIComponent(TOKEN)}`);
ws.onopen = () => { opened = true; };
ws.onmessage = (ev) => {
let o; try { o = JSON.parse(String(ev.data)); } catch { return; }
if (o.echo && pending.has(o.echo)) { pending.get(o.echo).resolve(o); pending.delete(o.echo); return; }
if (o.post_type === 'meta_event' && o.meta_event_type === 'lifecycle') { authed = true; return; }
if (o.post_type === 'meta_event') return;
events.push({ el: Date.now(), data: o });
fs.appendFileSync(OUT, JSON.stringify({ kind: 'event', t: new Date().toISOString(), data: o }) + '\n');
};
for (let i = 0; i < 100 && !opened; i++) await new Promise((r) => setTimeout(r, 100));
if (!opened) { console.error('连接超时'); process.exit(1); }
for (let i = 0; i < 100 && !authed; i++) await new Promise((r) => setTimeout(r, 100));
say('认证=' + authed);
if (!authed && DO_WRITE) { console.error('未确认认证,中止。'); process.exit(2); }
const api = (action, params, ms = 30000) => new Promise((resolve) => {
const echo = `fu-${action}-${Date.now()}-${Math.random().toString(36).slice(2, 6)}`;
const to = setTimeout(() => { pending.delete(echo); resolve({ __timeout: true }); }, ms);
pending.set(echo, { resolve: (o) => { clearTimeout(to); resolve(o); }, to });
ws.send(JSON.stringify({ action, params, echo }));
});
const nodeArr = (label) => [
{ type: 'node', data: { type: 'node', user_id: String(SELF), nickname: '雪珂',
content: [{ type: 'text', data: { text: `${label}-A` } }] } },
{ type: 'node', data: { type: 'node', user_id: String(FRIEND), nickname: '小王',
content: [{ type: 'text', data: { text: `${label}-B` } }] } },
];
const JOBS = [
{ id: 'fwd_group_content_arr', desc: 'send_group_forward_msg + node.content 为段数组',
action: 'send_group_forward_msg', params: () => ({ group_id: GROUP, messages: nodeArr('数组形') }) },
{ id: 'fwd_seg_parallel', desc: '并列 node 段(第19章已证明生效,作为对照基准)',
action: 'send_group_msg', params: () => ({ group_id: GROUP, message: [
...nodeArr('并列段'), { type: 'text', data: { text: '[QLf:fwd_seg_parallel]' } }] }) },
{ id: 'ai_record_group', desc: 'send_group_ai_record(官方 TTS 语音,群)',
action: 'send_group_ai_record', params: () => ({ group_id: GROUP, character: 'lucy-voice-houge', text: 'QLinker 语音能力旁证' }) },
];
say(`\n模式=${DO_WRITE ? '真实发送' : 'DRY-RUN'}\n`);
const sent = {};
for (const j of JOBS) {
if (!DO_WRITE) { say(`${j.id.padEnd(22)} [计划] ${j.desc}`); continue; }
const t0 = Date.now();
const r = await api(j.action, j.params());
if (j.action.includes('ai_record')) {
const rec = { id: j.id, desc: j.desc, retcode: r.__timeout ? 'TIMEOUT' : r.retcode,
message: r.message ?? r.wording ?? '', data_preview: typeof r.data === 'string' ? r.data.slice(0, 90) : JSON.stringify(r.data)?.slice(0, 120) };
fs.appendFileSync(OUT, JSON.stringify({ kind: 'result', ...rec }) + '\n');
say(`${j.id.padEnd(22)} retcode=${String(rec.retcode).padEnd(7)} ${String(rec.message).slice(0, 50)} data=${String(rec.data_preview).slice(0, 70)}`);
continue;
}
const mid = r?.data?.message_id;
sent[j.id] = mid;
await new Promise((r2) => setTimeout(r2, 5000));
const hasArrLabel = (e) => (Array.isArray(e.data.message) ? e.data.message : [])
.some((s) => s.type === 'json' && String(s.data?.data || '').includes('数组形'));
const hasMark = (e) => String(e.data.raw_message || '').includes('[QLf:' + j.id + ']');
const ev = events.find((e) => e.el >= t0 && (hasArrLabel(e) || hasMark(e)));
const jsonSeg = (Array.isArray(ev?.data?.message) ? ev.data.message : []).find((s) => s.type === 'json');
let detail = {};
try { detail = JSON.parse(jsonSeg.data.data)?.meta?.detail || {}; } catch {}
const rec = { id: j.id, desc: j.desc, retcode: r.__timeout ? 'TIMEOUT' : r.retcode,
message: r.message ?? r.wording ?? '', message_id: mid ?? null,
real_seq: ev?.data?.real_seq ?? null, tsum: detail.tsum ?? null,
news: JSON.stringify(detail.news ?? '').slice(0, 300), resid: detail.resid ?? null,
uniseq: detail.uniseq ?? null };
fs.appendFileSync(OUT, JSON.stringify({ kind: 'result', ...rec }) + '\n');
say(`${j.id.padEnd(22)} retcode=${String(rec.retcode).padEnd(6)} seq=${String(rec.real_seq ?? '-').padEnd(6)} tsum=${rec.tsum ?? '-'} news=${rec.news.slice(0, 110)}`);
}
// get_forward_msg 参数名穷举(只读)
say('\n--- get_forward_msg 参数穷举 ---');
const MID = sent.fwd_seg_parallel || 497853103;
const PARAM_SETS = [
{ message_id: MID },
{ message_id: String(MID) },
{ message_id: MID, group_id: GROUP },
{ id: String(MID) },
];
for (const p of PARAM_SETS) {
const r = await api('get_forward_msg', p);
const okFlag = r.retcode === 0;
say(`${JSON.stringify(p).slice(0, 60).padEnd(62)} retcode=${String(r.retcode).padEnd(6)} ${okFlag ? 'OK ' + JSON.stringify(r.data).slice(0, 120) : String(r.message).slice(0, 60)}`);
fs.appendFileSync(OUT, JSON.stringify({ kind: 'get_forward_msg', id: 'get_forward_msg',
retcode: r.retcode, message: r.message ?? '', params: p, resp: r }) + '\n');
}
// resid/uniseq 形式:从刚采到的事件里取
let resid = null, uniseq = null;
for (const e of events) {
const j = (e.data.message || []).find?.((s) => s.type === 'json');
if (!j) continue;
try {
const d = JSON.parse(j.data.data)?.meta?.detail || {};
if (d.resid) { resid = d.resid; uniseq = d.uniseq; break; }
} catch {}
}
if (resid) {
for (const p of [
{ resid, uniseq },
{ id: uniseq, resid },
{ message_id: MID, resid, uniseq, group_id: GROUP },
]) {
const r = await api('get_forward_msg', p);
say(`${'resid/uniseq:' + JSON.stringify(p).slice(0, 45).padEnd(50)} retcode=${String(r.retcode).padEnd(6)} ${r.retcode === 0 ? 'OK ' + JSON.stringify(r.data).slice(0, 120) : String(r.message).slice(0, 55)}`);
fs.appendFileSync(OUT, JSON.stringify({ kind: 'get_forward_msg', id: 'get_forward_msg',
retcode: r.retcode, message: r.message ?? '', params: p, resp: r }) + '\n');
}
} else say('未从事件里取到 resid,跳过 resid/uniseq 组合');
// 文件上传通知:延长等待,确认是否真的完全无通知事件
say('\n--- 群文件上传后的通知观测(等待 20s)---');
if (DO_WRITE) {
const t0 = Date.now();
const up = await api('upload_group_file', { group_id: GROUP,
file: 'base64://' + Buffer.from('QLinker 通知观测文件\n', 'utf8').toString('base64'),
name: `qlinker-notify-${stamp}.txt` });
say(`upload_group_file retcode=${up.retcode} ${String(up.message).slice(0, 60)}`);
fs.appendFileSync(OUT, JSON.stringify({ kind: 'upload', resp: up }) + '\n');
await new Promise((r) => setTimeout(r, 20000));
const during = events.filter((e) => e.el >= t0);
say(`20s 内收到事件 ${during.length} 条:` + (during.map((e) => e.data.notice_type || e.data.request_type || e.data.post_type).join(',') || '(无)'));
}
say('\n结果 -> ' + OUT);
try { ws.close(); } catch {}
process.exit(0);
+95
View File
@@ -0,0 +1,95 @@
// 用 message_id 精确回读 history,补齐「API + 事件 + history」第三条证据。
// 矩阵脚本靠 raw_message 里的标记文本匹配会失败:history 的 raw_message 把
// [ ] , 等字符做了实体转义(&#91; &#93; &#44;),文本匹配不可靠,改用 message_id 关联。
// 只读接口,无副作用。凭据只从环境变量读取。
//
// 用法:
// NAPCAT_WS_TOKEN=xxx node tools/probe/history-audit.mjs local/matrix-result-xxx.jsonl
import fs from 'node:fs';
import path from 'node:path';
const WS_URL = process.env.NAPCAT_WS_URL || 'ws://192.168.5.32:16099';
const TOKEN = process.env.NAPCAT_WS_TOKEN;
const GROUP = Number(process.env.PROBE_GROUP || 933280401);
const FRIEND = Number(process.env.PROBE_FRIEND || 2161656029);
if (!TOKEN) { console.error('缺少环境变量 NAPCAT_WS_TOKEN。凭据不得硬编码。'); process.exit(1); }
const src = process.argv.slice(2).find((a) => !a.startsWith('--'));
if (!src || !fs.existsSync(src)) { console.error('用法: node history-audit.mjs <matrix-result.jsonl>'); process.exit(1); }
const rows = fs.readFileSync(src, 'utf8').trim().split('\n')
.map((l) => { try { return JSON.parse(l); } catch { return null; } })
.filter((r) => r && r.message_id);
const want = new Map(rows.map((r) => [Number(r.message_id), r]));
console.log(`待回读 message_id ${want.size} 个(来自 ${src})`);
const pending = new Map();
let opened = false;
const ws = new WebSocket(`${WS_URL.replace(/\/$/, '')}/?access_token=${encodeURIComponent(TOKEN)}`);
ws.onopen = () => { opened = true; };
ws.onmessage = (ev) => {
let o; try { o = JSON.parse(String(ev.data)); } catch { return; }
if (o.echo && pending.has(o.echo)) { pending.get(o.echo).resolve(o); pending.delete(o.echo); }
};
for (let i = 0; i < 100 && !opened; i++) await new Promise((r) => setTimeout(r, 100));
if (!opened) { console.error('连接超时'); process.exit(1); }
const api = (action, params, ms = 30000) => new Promise((resolve) => {
const echo = `ha-${action}-${Date.now()}-${Math.random().toString(36).slice(2, 6)}`;
const to = setTimeout(() => { pending.delete(echo); resolve({ __timeout: true }); }, ms);
pending.set(echo, { resolve: (o) => { clearTimeout(to); resolve(o); }, to });
ws.send(JSON.stringify({ action, params, echo }));
});
const segTypes = (m) => Array.isArray(m) ? m.map((s) => s.type).join('+') : '(无)';
const found = new Map();
const rawOf = new Map();
async function pull(action, key, val, rounds = 8) {
let params = { [key]: val, count: 100 };
let pages = 0;
for (let i = 0; i < rounds; i++) {
const r = await api(action, params);
const list = r?.data?.messages ?? [];
pages += 1;
if (!list.length) break;
for (const m of list) {
const id = Number(m.message_id);
if (want.has(id) && !found.has(id)) {
found.set(id, { segs: segTypes(m.message), real_seq: m.real_seq,
empty: Array.isArray(m.message) && m.message.length === 0 });
rawOf.set(id, m);
}
}
if ([...want.keys()].every((id) => found.has(id))) break;
const oldest = list[list.length - 1];
if (!oldest?.message_id) break;
params = { [key]: val, count: 100, message_id: Number(oldest.message_id) };
}
return pages;
}
const pg = await pull('get_group_msg_history', 'group_id', GROUP);
const pf = await pull('get_friend_msg_history', 'user_id', FRIEND);
console.log(`翻页:群 ${pg} 页 / 私聊 ${pf} 页`);
const out = [];
console.log('\n' + '用例'.padEnd(4) + 'id'.padEnd(20) + '事件段'.padEnd(20) + 'history段'.padEnd(20) + 'seq');
for (const r of rows) {
const h = found.get(Number(r.message_id));
const line = { id: r.id, event_segs: r.event_segs, retcode: r.retcode, message_id: r.message_id,
history_segs: h ? h.segs : 'NOT_IN_HISTORY', history_seq: h?.real_seq ?? null,
history_empty: h?.empty ?? null };
out.push(line);
console.log(String(out.length).padEnd(4) + String(r.id).padEnd(20)
+ String(r.event_segs).padEnd(20) + String(line.history_segs).padEnd(20)
+ String(line.history_seq ?? '-'));
}
const dst = path.join(path.dirname(src), `history-audit-${Date.now()}.jsonl`);
fs.writeFileSync(dst, out.map((o) => JSON.stringify(o)).join('\n') + '\n');
fs.writeFileSync(path.join(path.dirname(src), `history-raw-${Date.now()}.jsonl`),
[...rawOf.entries()].map(([id, m]) => JSON.stringify({ message_id: id, msg: m })).join('\n') + '\n');
console.log(`\n命中 ${found.size}/${want.size} -> ${dst}`);
try { ws.close(); } catch {}
process.exit(0);
+87
View File
@@ -0,0 +1,87 @@
// 只读导出群/私聊 history 的段结构,便于人工核对「事件段 vs history 段」差异。
// 无副作用。凭据只从环境变量读取。
//
// 用法:
// NAPCAT_WS_TOKEN=xxx node tools/probe/history-dump.mjs # 群 + 私聊各 25 条
// NAPCAT_WS_TOKEN=xxx node tools/probe/history-dump.mjs group 60
// NAPCAT_WS_TOKEN=xxx node tools/probe/history-dump.mjs --grep=record # 只看含某段的
import fs from 'node:fs';
const WS_URL = process.env.NAPCAT_WS_URL || 'ws://192.168.5.32:16099';
const TOKEN = process.env.NAPCAT_WS_TOKEN;
const GROUP = Number(process.env.PROBE_GROUP || 933280401);
const FRIEND = Number(process.env.PROBE_FRIEND || 2161656029);
if (!TOKEN) { console.error('缺少环境变量 NAPCAT_WS_TOKEN。凭据不得硬编码。'); process.exit(1); }
const args = process.argv.slice(2);
const grep = (args.find((a) => a.startsWith('--grep=')) || '').slice(7);
const count = Number(args.find((a) => /^\d+$/.test(a)) || 25);
const which = args.find((a) => a === 'group' || a === 'private') || 'both';
const pending = new Map();
let opened = false;
const ws = new WebSocket(`${WS_URL.replace(/\/$/, '')}/?access_token=${encodeURIComponent(TOKEN)}`);
ws.onopen = () => { opened = true; };
ws.onmessage = (ev) => {
let o; try { o = JSON.parse(String(ev.data)); } catch { return; }
if (o.echo && pending.has(o.echo)) { pending.get(o.echo).resolve(o); pending.delete(o.echo); }
};
for (let i = 0; i < 100 && !opened; i++) await new Promise((r) => setTimeout(r, 100));
if (!opened) { console.error('连接超时'); process.exit(1); }
const api = (action, params, ms = 30000) => new Promise((resolve) => {
const echo = `hd-${action}-${Date.now()}-${Math.random().toString(36).slice(2, 6)}`;
const to = setTimeout(() => { pending.delete(echo); resolve({ __timeout: true }); }, ms);
pending.set(echo, { resolve: (o) => { clearTimeout(to); resolve(o); }, to });
ws.send(JSON.stringify({ action, params, echo }));
});
const brief = (x) => {
const d = x.data || {};
switch (x.type) {
case 'text': return `text<${String(d.text ?? '').replace(/\s+/g, ' ').slice(0, 46)}>`;
case 'record': return `record<file=${String(d.file ?? '').slice(0, 26)} url=${d.url ? 'Y' : 'N'} size=${d.file_size ?? '-'} format=${d.format ?? '-'}>`;
case 'image': return `image<size=${d.file_size ?? '-'} sub=${d.sub_type ?? '-'} url=${d.url ? 'Y' : 'N'}>`;
case 'video': return `video<url=${d.url ? 'Y' : 'N'} size=${d.file_size ?? '-'}>`;
case 'file': return `file<name=${d.file_name ?? d.name ?? '-'} id=${String(d.file_id ?? '-').slice(0, 14)}>`;
case 'at': return `at<qq=${d.qq}>`;
case 'music': return `music<type=${d.type ?? '-'} url=${d.url ? 'Y' : 'N'}>`;
case 'reply': return `reply<id=${d.id}>`;
case 'location': return `location<${d.lat},${d.lon}>`;
case 'node': return `node<${d.nickname ?? '-'}>`;
case 'json': {
let t = 'json<?>';
try { const o = JSON.parse(d.data); t = `json<app=${o.app ?? '-'} tsum=${o.meta?.detail?.tsum ?? '-'}>`;
const n = o.meta?.detail?.news;
if (n) t += JSON.stringify(n).slice(0, 100);
} catch { t = 'json<unparsable>'; }
return t;
}
default: return `${x.type}<${JSON.stringify(d).slice(0, 60)}>`;
}
};
async function dump(action, key, val, label) {
const r = await api(action, { [key]: val, count });
const list = (r?.data?.messages ?? []).slice().reverse();
console.log(`\n===== ${label}(${list.length} 条,retcode=${r.retcode})=====`);
for (const m of list) {
const segs = (m.message ?? []).map(brief);
const types = (m.message ?? []).map((x) => x.type);
if (grep && !types.includes(grep) && !JSON.stringify(m).includes(grep)) continue;
console.log(`${String(m.real_seq ?? '-').padEnd(6)}${(m.message ?? []).length === 0 ? '[空消息/已撤回]' : segs.join(' | ').slice(0, 210)}`);
}
return list;
}
const out = [];
if (which !== 'private') out.push(...await dump('get_group_msg_history', 'group_id', GROUP, '群 ' + GROUP));
if (which !== 'group') out.push(...await dump('get_friend_msg_history', 'user_id', FRIEND, '私聊 ' + FRIEND));
if (process.env.DUMP_RAW) {
fs.writeFileSync(process.env.DUMP_RAW, out.map((m) => JSON.stringify(m)).join('\n') + '\n');
console.log('\n原始 -> ' + process.env.DUMP_RAW);
}
try { ws.close(); } catch {}
process.exit(0);
+126
View File
@@ -0,0 +1,126 @@
// 本地事件接收端(HTTP 回调 / 反向 WS 实测用)。
// 打印 NapCat 实际推送的路径、请求头、鉴权方式与原始 body,用于确定 QLinker 接收端契约。
// 用法: PORT=8080 TOKEN=<期望token> node tools/probe/ingress-sink.mjs
import { createServer } from 'node:http';
import crypto from 'node:crypto';
import { appendFileSync, mkdirSync } from 'node:fs';
import path from 'node:path';
const PORT = Number(process.env.PORT || 8080);
const EXPECT_TOKEN = process.env.TOKEN || '';
// 后台运行时 stdout 会丢失,用 LOG_FILE 保留实测证据(默认 local/ 已被 gitignore)
const LOG_FILE = process.env.LOG_FILE || 'local/ingress-sink.log';
let count = 0;
try { mkdirSync(path.dirname(LOG_FILE), { recursive: true }); } catch {}
const log = (...a) => {
const line = a.join(' ');
console.log(line);
try { appendFileSync(LOG_FILE, line + '\n', 'utf-8'); } catch {}
};
// 令牌出现在日志里必须脱敏(AGENTS.md 11.2)
const mask = (v) => (typeof v === 'string' && v.length > 6 ? v.slice(0, 4) + '***' + v.slice(-2) : String(v ?? ''));
const describe = (req) => JSON.stringify({
authorization: req.headers.authorization ? mask(req.headers.authorization) : undefined,
'content-type': req.headers['content-type'],
'user-agent': req.headers['user-agent'],
'x-onebot-appid': req.headers['x-onebot-appid'],
'x-onebot-bot-id': req.headers['x-onebot-bot-id'],
});
const tokenOrigin = (req, u) => {
const q = u.searchParams.get('access_token');
const got = q || req.headers.authorization || '';
return 'token 来源: ' + (q ? 'access_token 查询参数' : (req.headers.authorization ? 'Authorization 头' : '未携带'))
+ (got ? ` = ${mask(got)}` : '');
};
const server = createServer((req, res) => {
const u = new URL(req.url, 'http://x');
if (req.method === 'GET') {
// 探活端点:用于从 NapCat 侧验证「它能否访问到本机」,不产生任何业务副作用
log(`[GET ${req.url}] from ${req.socket.remoteAddress} ua=${req.headers['user-agent'] || '-'}`);
res.writeHead(200, { 'Content-Type': 'application/json' });
res.end(JSON.stringify({ ok: true, role: 'qlinker-ingress-sink', time: new Date().toISOString() }));
return;
}
const chunks = [];
req.on('data', c => chunks.push(c));
req.on('end', () => {
const body = Buffer.concat(chunks).toString('utf-8');
count++;
log(`\n===== [HTTP #${count}] ${new Date().toISOString()} ${req.method} ${req.url} from ${req.socket.remoteAddress} =====`);
log('headers: ' + describe(req));
log(tokenOrigin(req, u));
let obj; try { obj = JSON.parse(body); } catch {}
if (obj) {
log(`post_type=${obj.post_type} detail=${obj.message_type || obj.notice_type || obj.meta_event_type || '-'}`
+ ` self_id=${obj.self_id} message_id=${obj.message_id ?? '-'} seq=${obj.message_seq ?? '-'}`);
}
log(`body(${body.length}B): ` + body.slice(0, 700));
res.writeHead(200, { 'Content-Type': 'application/json' });
res.end(JSON.stringify({ status: 'ok', retcode: 0 }));
});
});
// 反向 WebSocket:NapCat 主动连入。不依赖第三方 ws 库,手写 RFC6455 握手与帧解析。
const WS_GUID = '258EAFA5-E914-47DA-95CA-C5AB0DC85B11';
function decodeFrames(buf, onText) {
let off = 0;
while (off + 2 <= buf.length) {
const b1 = buf[off + 1];
const masked = (b1 & 0x80) !== 0;
let len = b1 & 0x7f;
let p = off + 2;
if (len === 126) { if (p + 2 > buf.length) break; len = buf.readUInt16BE(p); p += 2; }
else if (len === 127) { if (p + 8 > buf.length) break; len = Number(buf.readBigUInt64BE(p)); p += 8; }
let key;
if (masked) { if (p + 4 > buf.length) break; key = buf.subarray(p, p + 4); p += 4; }
if (p + len > buf.length) break;
const payload = Buffer.from(buf.subarray(p, p + len));
if (masked) for (let i = 0; i < payload.length; i++) payload[i] ^= key[i % 4];
onText(payload);
off = p + len;
}
return off;
}
server.on('upgrade', (req, socket) => {
const u = new URL(req.url, 'http://x');
const got = u.searchParams.get('access_token') || req.headers.authorization || '';
count++;
log(`\n===== [WS #${count}] ${new Date().toISOString()} upgrade ${req.url} from ${req.socket.remoteAddress} =====`);
log('headers: ' + describe(req));
log(tokenOrigin(req, u));
if (EXPECT_TOKEN && got !== EXPECT_TOKEN && !String(got).endsWith(EXPECT_TOKEN)) {
log(' → token 不匹配,拒绝握手');
socket.destroy();
return;
}
const accept = crypto.createHash('sha1').update(req.headers['sec-websocket-key'] + WS_GUID).digest('base64');
socket.write('HTTP/1.1 101 Switching Protocols\r\n'
+ 'Upgrade: websocket\r\n'
+ 'Connection: Upgrade\r\n'
+ `Sec-WebSocket-Accept: ${accept}\r\n\r\n`);
log(' → 握手完成,等待事件');
let acc = Buffer.alloc(0);
socket.on('data', (d) => {
acc = Buffer.concat([acc, d]);
acc = acc.subarray(decodeFrames(acc, (payload) => {
const s = payload.toString('utf-8');
let o; try { o = JSON.parse(s); } catch {}
log(o
? ` 事件 post_type=${o.post_type} detail=${o.message_type || o.notice_type || o.meta_event_type || '-'} message_id=${o.message_id ?? '-'} seq=${o.message_seq ?? '-'}`
: ` 原文: ${s.slice(0, 400)}`);
}));
});
socket.on('close', () => log(' → 反向 WS 连接关闭'));
socket.on('error', () => {});
});
server.listen(PORT, '0.0.0.0', () => {
log(`ingress sink 已监听 0.0.0.0:${PORT}(HTTP + 反向 WS 共用端口;期望 token=${EXPECT_TOKEN ? mask(EXPECT_TOKEN) : '未校验'})`);
});
+449
View File
@@ -0,0 +1,449 @@
// 阶段 02 补充矩阵探测:正向 WS 内可自动触发的消息段 / 事件样本。
// 默认 dry-run,只有显式 --yes 才产生真实外部副作用(真实发消息/上传文件)。
// 凭据只从环境变量读取,脚本内不留明文。
//
// 用法:
// NAPCAT_WS_TOKEN=xxx node tools/probe/matrix-probe.mjs # dry-run,仅打印计划
// NAPCAT_WS_TOKEN=xxx node tools/probe/matrix-probe.mjs --yes # 真实执行
// NAPCAT_WS_TOKEN=xxx node tools/probe/matrix-probe.mjs --yes --only=g_record_url,g_image_url
// 可选:
// NAPCAT_WS_URL 默认 ws://192.168.5.32:16099
// PROBE_GROUP 默认 933280401
// PROBE_FRIEND 默认 2161656029
// PROBE_SELF 默认 3575608514(转发节点署名用)
// SETTLE_MS 每条用例发送后等待事件的时间,默认 5000
// ALLOW_ADMIN=1 允许尝试 set_group_admin(会改群状态,默认跳过)
import fs from 'node:fs';
import path from 'node:path';
const WS_URL = process.env.NAPCAT_WS_URL || 'ws://192.168.5.32:16099';
const TOKEN = process.env.NAPCAT_WS_TOKEN;
const GROUP = Number(process.env.PROBE_GROUP || 933280401);
const FRIEND = Number(process.env.PROBE_FRIEND || 2161656029);
const SELF = Number(process.env.PROBE_SELF || 3575608514);
const SETTLE_MS = Number(process.env.SETTLE_MS || 5000);
const OUT_DIR = process.env.PROBE_OUT || 'local';
const argv = process.argv.slice(2);
const DO_WRITE = argv.includes('--yes');
const only = (argv.find((a) => a.startsWith('--only=')) || '').slice(7);
const ONLY = only ? new Set(only.split(',')) : null;
if (!TOKEN) { console.error('缺少环境变量 NAPCAT_WS_TOKEN。凭据不得硬编码。'); process.exit(1); }
// 1x1 PNG,用于图片段
const PNG_B64 =
'iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mP8z8BQDwAEhQGAhKmMIQAAAABJRU5ErkJggg==';
// 明显不是 MP4 的内容,用于观察上游是否校验媒体内容
const FAKE_MP4_B64 = Buffer.from('NOTAREALMP4FILE-QLINKER-PROBE').toString('base64');
const TXT_B64 = Buffer.from('QLinker 阶段02 探测文件内容\n第二行\n', 'utf8').toString('base64');
const ts = Date.now();
const stamp = new Date(ts).toISOString().replace(/[:.]/g, '-');
fs.mkdirSync(OUT_DIR, { recursive: true });
const EV_FILE = path.join(OUT_DIR, `matrix-ev-${stamp}.jsonl`);
const RS_FILE = path.join(OUT_DIR, `matrix-result-${stamp}.jsonl`);
const API_FILE = path.join(OUT_DIR, `matrix-api-${stamp}.jsonl`);
const writeLine = (f, o) => fs.appendFileSync(f, JSON.stringify(o) + '\n');
const T0 = Date.now();
const say = (...a) => console.log(`[+${((Date.now() - T0) / 1000).toFixed(1)}s]`, ...a);
// ---------- WS 客户端:同一连接既收事件又调 API ----------
const pending = new Map();
let ws = null;
let authenticated = false;
const events = [];
function api(action, params, timeoutMs = 25000) {
const echo = `mp-${action}-${Date.now()}-${Math.random().toString(36).slice(2, 7)}`;
return new Promise((resolve) => {
const to = setTimeout(() => {
pending.delete(echo);
resolve({ __timeout: true, action });
}, timeoutMs);
pending.set(echo, { resolve: (o) => { clearTimeout(to); resolve(o); }, to });
ws.send(JSON.stringify({ action, params, echo }));
});
}
function waitLifecycle(ms = 15000) {
return new Promise((resolve) => {
const t = setTimeout(() => resolve(false), ms);
const iv = setInterval(() => {
if (authenticated) { clearTimeout(t); clearInterval(iv); resolve(true); }
}, 100);
});
}
function open() {
return new Promise((resolve, reject) => {
ws = new WebSocket(`${WS_URL.replace(/\/$/, '')}/?access_token=${encodeURIComponent(TOKEN)}`);
// 处理器必须在 resolve 之前挂好,否则握手到挂载之间的事件会丢
ws.onmessage = (ev) => {
let o;
try { o = JSON.parse(String(ev.data)); } catch { return; }
if (o.echo && pending.has(o.echo)) {
const p = pending.get(o.echo);
pending.delete(o.echo);
p.resolve(o);
return;
}
if (o.post_type === 'meta_event' && o.meta_event_type === 'lifecycle') {
authenticated = true;
say(`收到 lifecycle(${o.sub_type}) —— 认证确认`);
return;
}
if (o.post_type === 'meta_event') return;
const rec = { t: new Date().toISOString(), el: Date.now() - T0, data: o };
events.push(rec);
writeLine(EV_FILE, rec);
};
ws.onopen = () => resolve();
ws.onerror = (e) => reject(new Error('ws error: ' + String(e?.message ?? e)));
setTimeout(() => reject(new Error('ws 连接超时')), 15000);
});
}
await open();
say('握手成功,等待 lifecycle 以确认认证');
const ok = await waitLifecycle();
say(ok ? '认证已确认,可以安全发送' : '!! 未收到 lifecycle,API 可能全部 1403');
if (!ok && DO_WRITE) { console.error('未确认认证,中止真实发送。'); try { ws.close(); } catch {} process.exit(2); }
// ---------- 素材准备 ----------
const ctx = { group: GROUP, friend: FRIEND, self: SELF, mid: {}, url: {}, b64: {} };
async function prepRecord() {
const r = await api('get_ai_record', { group_id: GROUP, character: 'lucy-voice-houge', text: 'QLinker 语音探测' });
if (r.retcode !== 0 || typeof r.data !== 'string') {
say('get_ai_record 失败:' + JSON.stringify(r).slice(0, 200));
return;
}
ctx.url.record = r.data;
writeLine(path.join(OUT_DIR, `matrix-material-${stamp}.jsonl`), { kind: 'ai_record_url', url: r.data });
try {
const resp = await fetch(r.data);
const buf = Buffer.from(await resp.arrayBuffer());
const magic = buf.subarray(0, 12).toString('hex');
ctx.b64.record = buf.toString('base64');
ctx.recordBytes = buf.length;
ctx.recordMagic = magic;
say(`语音素材下载完成 ${buf.length} 字节 magic=${magic} ascii=${JSON.stringify(buf.subarray(0, 6).toString('latin1'))}`);
writeLine(path.join(OUT_DIR, `matrix-material-${stamp}.jsonl`),
{ kind: 'ai_record_bin', bytes: buf.length, magic, ascii: buf.subarray(0, 12).toString('latin1') });
} catch (e) { say('语音素材下载失败:' + e.message); }
}
async function prepMediaUrl() {
// 用一条真实 base64 图片换回 CDN url,再用该 url 测 URL 形式
const r = await api('send_group_msg', {
group_id: GROUP,
message: [{ type: 'image', data: { file: 'base64://' + PNG_B64 } },
{ type: 'text', data: { text: '[QLm:prep_img]' } }],
});
if (r.retcode !== 0) { say('prep 图片发送失败:' + JSON.stringify(r).slice(0, 200)); return; }
ctx.mid.prep_img = r.data?.message_id;
const t = Date.now();
while (Date.now() - t < SETTLE_MS) {
const hit = events.find((e) => e.data.post_type === 'message_sent'
&& String(e.data.raw_message || '').includes('[QLm:prep_img]')
&& (e.data.message || []).some((s) => s.type === 'image' && s.data.url));
if (hit) {
const seg = hit.data.message.find((s) => s.type === 'image');
ctx.url.image = seg.data.url;
ctx.url.imageFileId = seg.data.file;
say('拿到图片 CDN url: ' + String(seg.data.url).slice(0, 80));
return;
}
await new Promise((r2) => setTimeout(r2, 200));
}
say('未从事件里拿到图片 url');
}
// ---------- 用例定义 ----------
const mark = (id) => ({ type: 'text', data: { text: `[QLm:${id}]` } });
const segs = (...s) => s;
// node.content 有两种可能形态:OneBot 段数组,或段数组的 JSON 字符串。
// 上游对两者的接受度必须实测,不能猜。
function fwdNodes(list, form) {
return list.map((n) => ({
type: 'node',
data: {
user_id: String(n.uid),
nickname: n.nick,
content: form === 'str' ? JSON.stringify(n.content) : n.content,
},
}));
}
const CASES = [
{ id: 'g_text', kind: 'msg', desc: '群纯文本(作为后续 reply 的目标)',
build: () => ({ action: 'send_group_msg', params: { group_id: GROUP, message: segs(mark('g_text')) } }) },
{ id: 'g_at_all', kind: 'msg', desc: '群 @全体',
build: () => ({ action: 'send_group_msg', params: { group_id: GROUP,
message: segs({ type: 'at', data: { qq: 'all' } }, mark('g_at_all')) } }) },
{ id: 'g_face', kind: 'msg', desc: '群 face 段(无文本)',
build: () => ({ action: 'send_group_msg', params: { group_id: GROUP,
message: segs({ type: 'face', data: { id: '178' } }, mark('g_face')) } }) },
{ id: 'g_record_url', kind: 'msg', desc: '群语音:真实 QQ 语音 CDN URL 形式',
need: () => ctx.url.record,
build: () => ({ action: 'send_group_msg', params: { group_id: GROUP,
message: segs({ type: 'record', data: { file: ctx.url.record } }, mark('g_record_url')) } }) },
{ id: 'g_record_b64', kind: 'msg', desc: '群语音:真实语音 base64 形式',
need: () => ctx.b64.record,
build: () => ({ action: 'send_group_msg', params: { group_id: GROUP,
message: segs({ type: 'record', data: { file: 'base64://' + ctx.b64.record } }, mark('g_record_b64')) } }) },
{ id: 'g_image_url', kind: 'msg', desc: '群图片:URL 形式(非 base64)',
need: () => ctx.url.image,
build: () => ({ action: 'send_group_msg', params: { group_id: GROUP,
message: segs({ type: 'image', data: { file: ctx.url.image } }, mark('g_image_url')) } }) },
{ id: 'g_video_url', kind: 'msg', desc: '群视频:URL 形式',
need: () => ctx.url.video,
build: () => ({ action: 'send_group_msg', params: { group_id: GROUP,
message: segs({ type: 'video', data: { file: ctx.url.video } }, mark('g_video_url')) } }) },
{ id: 'g_video_b64', kind: 'msg', desc: '群视频:base64(非合法 MP4 内容)',
build: () => ({ action: 'send_group_msg', params: { group_id: GROUP,
message: segs({ type: 'video', data: { file: 'base64://' + FAKE_MP4_B64 } }, mark('g_video_b64')) } }) },
{ id: 'g_reply_1', kind: 'msg', desc: '群引用第一层(reply -> g_text)',
need: () => ctx.mid.g_text,
build: () => ({ action: 'send_group_msg', params: { group_id: GROUP,
message: segs({ type: 'reply', data: { id: String(ctx.mid.g_text) } }, mark('g_reply_1')) } }) },
{ id: 'g_reply_nested', kind: 'msg', desc: '群引用嵌套(reply -> 一条本身就带 reply 的消息)',
need: () => ctx.mid.g_reply_1,
build: () => ({ action: 'send_group_msg', params: { group_id: GROUP,
message: segs({ type: 'reply', data: { id: String(ctx.mid.g_reply_1) } }, mark('g_reply_nested')) } }) },
{ id: 'g_forward_api', kind: 'msg', desc: '服务端合并转发 send_group_forward_msg',
nodes: [
{ uid: SELF, nick: '雪珂', content: [{ type: 'text', data: { text: '转发条目A' } }] },
{ uid: FRIEND, nick: '小王', content: [{ type: 'text', data: { text: '转发条目B' } }] },
{ uid: SELF, nick: '雪珂', content: [{ type: 'image', data: { file: 'base64://' + PNG_B64 } }] },
],
build: function () { return { action: 'send_group_forward_msg', params: { group_id: GROUP, messages: fwdNodes(this.nodes, 'str') } }; },
alt: function () { return { group_id: GROUP, messages: fwdNodes(this.nodes, 'arr') }; } },
{ id: 'g_forward_read', kind: 'api', desc: 'get_forward_msg 读回上一步的合并转发',
need: () => ctx.mid.g_forward_api,
build: () => ({ action: 'get_forward_msg', params: { message_id: ctx.mid.g_forward_api } }) },
{ id: 'g_forward_read_self', kind: 'api', desc: 'get_forward_msg 读回 node 段自发合并转发',
build: () => ({ action: 'get_forward_msg', params: { message_id: 497853103 } }) },
{ id: 'g_forward_read_resid', kind: 'api', desc: 'get_forward_msg 用 resid/uniseq 读回 node 段转发',
build: () => ({ action: 'get_forward_msg', params: {
message_id: 497853103,
resid: '2Fxh/sSm2xg93V25/m929koqkzXAguVg0YQ5H7KoKwAgU5MIzx3yAJzNACKfCOls',
uniseq: '55ba6c8c-d10f-4e02-ad78-9e43e30e2436' } }) },
{ id: 'g_music_url', kind: 'msg', desc: '音乐分享 {type,url} 形式(163 之外)',
build: () => ({ action: 'send_group_msg', params: { group_id: GROUP,
message: segs({ type: 'music', data: { type: '163', url: 'https://music.163.com/song?id=186016',
audio: 'https://music.163.com/song/media/outer/url?id=186016.mp3', title: 'QLinker探测', singer: '未知' } }, mark('g_music_url')) } }) },
{ id: 'g_ark', kind: 'msg', desc: 'ARK 段',
build: () => ({ action: 'send_group_msg', params: { group_id: GROUP,
message: segs({ type: 'ark', data: { descriptor: { function: '1', msg: 'QLinker 探测' },
prompt: '[{"app":"com.tencent.miniapp","desc":"QLinker","prompt":"QLinker 探测"}]',
meta: { detail: { appid: '1109935564', appType: 1, title: 'QLinker 探测', desc: '探测',
ctime: String(Math.floor(Date.now() / 1000)) } } } }, mark('g_ark')) } }) },
{ id: 'g_location', kind: 'msg', desc: '群位置段(复测:第19章为静默丢弃)',
build: () => ({ action: 'send_group_msg', params: { group_id: GROUP,
message: segs({ type: 'location', data: { lat: '31.230416', lon: '121.473701', title: '外滩', content: '上海市黄浦区' } }, mark('g_location')) } }) },
{ id: 'p_text', kind: 'msg', desc: '私聊文本',
build: () => ({ action: 'send_private_msg', params: { user_id: FRIEND, message: segs(mark('p_text')) } }) },
{ id: 'p_face', kind: 'msg', desc: '私聊 face 段',
build: () => ({ action: 'send_private_msg', params: { user_id: FRIEND,
message: segs({ type: 'face', data: { id: '178' } }, mark('p_face')) } }) },
{ id: 'p_image_b64', kind: 'msg', desc: '私聊图片 base64',
build: () => ({ action: 'send_private_msg', params: { user_id: FRIEND,
message: segs({ type: 'image', data: { file: 'base64://' + PNG_B64 } }, mark('p_image_b64')) } }) },
{ id: 'p_record_url', kind: 'msg', desc: '私聊语音 URL 形式',
need: () => ctx.url.record,
build: () => ({ action: 'send_private_msg', params: { user_id: FRIEND,
message: segs({ type: 'record', data: { file: ctx.url.record } }, mark('p_record_url')) } }) },
{ id: 'p_json', kind: 'msg', desc: '私聊 json 段',
build: () => ({ action: 'send_private_msg', params: { user_id: FRIEND,
message: segs({ type: 'json', data: { data: JSON.stringify({ app: 'com.tencent.subbubble',
view: 'news', config: { autosize: true, forward: 1 },
extra: { serviceId: '1600000203', templateId: '1', refstrain: 'news' },
meta: { detail: { news: [{ text: 'QLinker 私聊 json 探测' }] } } }) } }, mark('p_json')) } }) },
{ id: 'p_reply', kind: 'msg', desc: '私聊引用(reply -> p_text)',
need: () => ctx.mid.p_text,
build: () => ({ action: 'send_private_msg', params: { user_id: FRIEND,
message: segs({ type: 'reply', data: { id: String(ctx.mid.p_text) } }, mark('p_reply')) } }) },
{ id: 'p_forward_api', kind: 'msg', desc: '私聊服务端合并转发 send_private_forward_msg',
nodes: [
{ uid: SELF, nick: '雪珂', content: [{ type: 'text', data: { text: '私聊转发条目A' } }] },
{ uid: FRIEND, nick: '小王', content: [{ type: 'text', data: { text: '私聊转发条目B' } }] },
],
build: function () { return { action: 'send_private_forward_msg', params: { user_id: FRIEND, messages: fwdNodes(this.nodes, 'str') } }; },
alt: function () { return { user_id: FRIEND, messages: fwdNodes(this.nodes, 'arr') }; } },
{ id: 'p_at', kind: 'msg', desc: '私聊 at 段(观察是否被丢弃)',
build: () => ({ action: 'send_private_msg', params: { user_id: FRIEND,
message: segs({ type: 'at', data: { qq: String(FRIEND) } }, mark('p_at')) } }) },
{ id: 'g_upload_file', kind: 'file', desc: '群文件上传(观察 upload_file / group_upload_file 通知)',
build: () => ({ action: 'upload_group_file', params: { group_id: GROUP,
file: 'base64://' + TXT_B64, name: `qlinker-probe-${stamp}.txt` } }) },
{ id: 'p_upload_file', kind: 'file', desc: '私聊文件上传',
build: () => ({ action: 'upload_private_file', params: { user_id: FRIEND,
file: 'base64://' + TXT_B64, name: `qlinker-probe-p-${stamp}.txt` } }) },
{ id: 'g_admin', kind: 'risky', desc: '群管理员变动(会改群状态,需 ALLOW_ADMIN=1)',
gate: () => process.env.ALLOW_ADMIN === '1',
build: () => ({ action: 'set_group_admin', params: { group_id: GROUP, user_id: FRIEND, enable: true } }) },
];
const results = [];
function eventsFor(t0, t1, id) {
return events
.filter((e) => e.el >= t0 && e.el <= t1)
.filter((e) => {
const d = e.data;
if (d.post_type === 'message' || d.post_type === 'message_sent') {
return String(d.raw_message || '').includes(`[QLm:${id}]`)
|| (ctx.mid[id] && d.message_id === ctx.mid[id]);
}
return true;
});
}
function segTypes(msg) {
return Array.isArray(msg) ? msg.map((s) => s.type).join('+') : '(无)';
}
const planned = CASES.filter((c) => (!ONLY || ONLY.has(c.id)) && (c.gate ? c.gate() : true));
say(`模式=${DO_WRITE ? '真实发送' : 'DRY-RUN'} 用例=${planned.length}/${CASES.length} 事件文件=${EV_FILE}`);
if (!DO_WRITE) {
for (const c of planned) console.log(` [计划] ${c.id.padEnd(20)} ${c.desc}`);
for (const c of CASES.filter((x) => x.gate && !x.gate())) {
console.log(` [跳过] ${c.id.padEnd(20)} 门禁未开启(需 ALLOW_ADMIN=1)`);
}
console.log('\nDRY-RUN 未产生任何外部调用。加 --yes 执行真实发送。');
try { ws.close(); } catch {}
process.exit(0);
}
await prepRecord();
await prepMediaUrl();
for (const c of planned) {
if (c.need && !c.need()) {
say(`跳过 ${c.id}:前置素材缺失`);
results.push({ id: c.id, desc: c.desc, status: 'skipped', reason: '前置素材缺失' });
continue;
}
const { action, params } = c.build();
const t0 = Date.now() - T0;
let r = await api(action, params);
let attempts = [{ params, resp: r }];
// node.content 的形态(JSON 字符串 / 段数组)在不同版本上不一致,失败时用备用形态重试一次
if (c.alt && (r.__timeout || r.retcode !== 0)) {
const altParams = c.alt();
const r2 = await api(action, altParams);
attempts.push({ params: altParams, resp: r2 });
if (!r2.__timeout && r2.retcode === 0) r = r2;
}
if (r.__timeout) r = { __timeout: true };
const mid = r?.data?.message_id;
if (mid) ctx.mid[c.id] = mid;
if (c.id === 'g_video_b64' && r?.retcode === 0) {
// 视频段回推里取 url 供 g_video_url 使用
const t = Date.now();
while (Date.now() - t < SETTLE_MS) {
const hit = events.find((e) => String(e.data.raw_message || '').includes('[QLm:g_video_b64]')
&& (e.data.message || []).some((s) => s.type === 'video' && s.data.url));
if (hit) { ctx.url.video = hit.data.message.find((s) => s.type === 'video').data.url; break; }
await new Promise((r2) => setTimeout(r2, 200));
}
}
await new Promise((r2) => setTimeout(r2, SETTLE_MS));
const t1 = Date.now() - T0;
const evs = eventsFor(t0, t1, c.id);
const msgEv = evs.find((e) => e.data.post_type === 'message_sent');
if (c.kind === 'api' || attempts.length > 1) {
writeLine(API_FILE, { id: c.id, desc: c.desc, action, attempts: attempts.map((a) => ({ params: a.params, resp: a.resp })) });
}
const rec = {
id: c.id, desc: c.desc, action,
retcode: r.__timeout ? 'TIMEOUT' : r.retcode,
message: r.message ?? r.wording ?? '',
message_id: mid ?? null,
real_seq: msgEv?.data?.real_seq ?? null,
event_segs: msgEv ? segTypes(msgEv.data.message) : (evs.length ? `(非消息事件 ${evs.length} 条)` : 'NO_EVENT'),
notice_types: [...new Set(evs.filter((e) => e.data.post_type === 'notice').map((e) => e.data.notice_type))],
request_types: [...new Set(evs.filter((e) => e.data.post_type === 'request').map((e) => e.data.request_type))],
event_count: evs.length,
retcode_trail: attempts.map((a) => (a.resp?.__timeout ? 'TIMEOUT' : a.resp?.retcode)).join('/'),
status: r.__timeout ? 'timeout' : (r.retcode === 0 ? 'sent' : 'rejected'),
};
results.push(rec);
writeLine(RS_FILE, rec);
say(`${rec.id.padEnd(20)} retcode=${String(rec.retcode).padEnd(7)} seq=${String(rec.real_seq ?? '-').padEnd(5)} 事件段=${rec.event_segs}${rec.notice_types.length ? ' notice=' + rec.notice_types.join(',') : ''}`);
}
// ---------- history 回读 ----------
async function readHistory(action, key, val) {
const r = await api(action, { [key]: val, count: 60 });
const list = r?.data?.messages ?? [];
const map = new Map();
for (const m of list) {
const raw = String(m.raw_message ?? '');
const hit = results.find((x) => raw.includes(`[QLm:${x.id}]`));
if (hit && !map.has(hit.id)) map.set(hit.id, { segs: segTypes(m.message), real_seq: m.real_seq, message_id: m.message_id });
}
return map;
}
say('history 回读中…');
const hg = await readHistory('get_group_msg_history', 'group_id', GROUP);
const hp = await readHistory('get_friend_msg_history', 'user_id', FRIEND);
const hm = new Map([...hg, ...hp]);
for (const r of results) {
const h = hm.get(r.id);
r.history_segs = h ? h.segs : (r.kind === 'msg' ? 'NOT_IN_HISTORY' : '-');
r.history_seq = h?.real_seq ?? null;
}
// ---------- 摘要 ----------
console.log('\n================ 矩阵结果 ================');
console.log('用例'.padEnd(20) + 'retcode'.padEnd(9) + 'seq'.padEnd(7) + '事件段'.padEnd(26) + 'history段');
for (const r of results) {
console.log(String(r.id).padEnd(20) + String(r.retcode ?? r.status).padEnd(9)
+ String(r.real_seq ?? '-').padEnd(7) + String(r.event_segs).padEnd(26) + String(r.history_segs));
}
console.log('\n语音素材: ' + (ctx.recordBytes ? `${ctx.recordBytes} 字节 magic=${ctx.recordMagic}` : '未取得'));
console.log('事件 ' + events.length + ' 条 -> ' + EV_FILE);
console.log('结果 -> ' + RS_FILE);
writeLine(RS_FILE, { __summary: true, record_magic: ctx.recordMagic ?? null,
record_bytes: ctx.recordBytes ?? null, image_url: ctx.url.image ?? null,
video_url: ctx.url.video ?? null, record_url: ctx.url.record ?? null, events: events.length });
try { ws.close(); } catch {}
process.exit(0);
+69
View File
@@ -0,0 +1,69 @@
// 通过 NapCat 正向 WebSocket 调用 OneBot11 接口(默认只读,写操作需显式 --write)
// 凭据只从环境变量 NAPCAT_WS_TOKEN 读取,不写死在脚本里。
// 用法:
// NAPCAT_WS_TOKEN=xxx node tools/probe/napcat-call.mjs <action> [jsonParams]
// NAPCAT_WS_TOKEN=xxx node tools/probe/napcat-call.mjs get_group_list
// NAPCAT_WS_TOKEN=xxx node tools/probe/napcat-call.mjs --write send_group_msg '{"group_id":1,"message":"hi"}'
const WS_URL = process.env.NAPCAT_WS_URL || 'ws://192.168.5.32:16099';
const TOKEN = process.env.NAPCAT_WS_TOKEN;
// 未经 --write 显式声明时,一律拒绝,避免误触发真实外部副作用
const WRITE_PREFIX_OK = new Set([
'send_private_msg', 'send_group_msg', 'send_msg',
'set_group_ban', 'set_group_card', 'set_group_name',
'delete_msg', 'recall_msg', 'set_essence_msg',
'send_poke', 'group_poke', 'friend_poke',
]);
const argv = process.argv.slice(2);
const isWrite = argv[0] === '--write';
if (isWrite) argv.shift();
const action = argv[0];
const paramsRaw = argv[1] || '{}';
if (!TOKEN) {
console.error('缺少环境变量 NAPCAT_WS_TOKEN。凭据不得硬编码。');
process.exit(1);
}
if (!action) {
console.error('缺少 action 参数。');
process.exit(1);
}
let params;
try { params = JSON.parse(paramsRaw); } catch (e) { console.error('params 不是合法 JSON: ' + e.message); process.exit(1); }
if (isWrite && !WRITE_PREFIX_OK.has(action)) {
console.error(`拒绝:${action} 不在允许的写操作清单内。`);
process.exit(1);
}
if (!isWrite && WRITE_PREFIX_OK.has(action)) {
console.error(`拒绝:${action} 是写操作,需要显式加 --write。`);
process.exit(1);
}
const ws = new WebSocket(`${WS_URL.replace(/\/$/, '')}/?access_token=${encodeURIComponent(TOKEN)}`);
const pending = new Map();
ws.onmessage = (ev) => {
let o; try { o = JSON.parse(String(ev.data)); } catch { return; }
if (o.echo && pending.has(o.echo)) {
const p = pending.get(o.echo);
pending.delete(o.echo);
clearTimeout(p.to);
p.resolve(o);
}
};
await new Promise((res, rej) => {
ws.onopen = res;
setTimeout(() => rej(new Error('连接超时')), 10000);
}).catch((e) => { console.error(e.message); process.exit(1); });
const echo = `call-${action}-${Date.now()}`;
const out = await new Promise((resolve) => {
const to = setTimeout(() => { pending.delete(echo); resolve({ __timeout: true }); }, 20000);
pending.set(echo, { resolve, to });
ws.send(JSON.stringify({ action, params, echo }));
});
try { ws.close(); } catch {}
if (out.__timeout) { console.error('20s 无响应'); process.exit(1); }
console.log(JSON.stringify(out, null, 2));
+195
View File
@@ -0,0 +1,195 @@
// 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);
}
+70
View File
@@ -0,0 +1,70 @@
// NapCat WebUI 网络配置管理(默认只读;写操作需显式 --apply)
// 密码只从环境变量 NAPCAT_WEBUI_PASSWORD 读取,脚本内不留任何凭据或哈希。
//
// 用法:
// NAPCAT_WEBUI_PASSWORD=xxx node tools/probe/napcat-webui.mjs list
// NAPCAT_WEBUI_PASSWORD=xxx node tools/probe/napcat-webui.mjs version
// NAPCAT_WEBUI_PASSWORD=xxx node tools/probe/napcat-webui.mjs scheme
// NAPCAT_WEBUI_PASSWORD=xxx node tools/probe/napcat-webui.mjs apply <jsonFile> # 需 --apply
const BASE = (process.env.NAPCAT_WEBUI_URL || 'http://192.168.5.32:6099').replace(/\/$/, '');
const PASSWORD = process.env.NAPCAT_WEBUI_PASSWORD;
if (!PASSWORD) {
console.error('缺少环境变量 NAPCAT_WEBUI_PASSWORD。凭据不得硬编码在脚本或仓库中。');
process.exit(1);
}
// NapCat WebUI 登录方式:hash = SHA256(password + ".napcat"),实测确认
const hash = await sha256Hex(`${PASSWORD}.napcat`);
async function sha256Hex(s) {
const buf = await crypto.subtle.digest('SHA-256', new TextEncoder().encode(s));
return [...new Uint8Array(buf)].map(b => b.toString(16).padStart(2, '0')).join('');
}
async function api(path, { method = 'GET', body, cred } = {}) {
const headers = { 'Content-Type': 'application/json' };
if (cred) headers.Authorization = `Bearer ${cred}`;
const res = await fetch(`${BASE}/api${path}`, {
method, headers, body: body ? JSON.stringify(body) : undefined,
});
const text = await res.text();
let json; try { json = JSON.parse(text); } catch { json = { __raw: text.slice(0, 400) }; }
return { http: res.status, ...json };
}
const login = await api('/auth/login', { method: 'POST', body: { hash } });
if (login.code !== 0) {
console.error(`WebUI 登录失败: code=${login.code} message=${login.message}`);
process.exit(1);
}
const CRED = login.data?.Credential;
console.error(`WebUI 登录成功(credential 长度 ${CRED?.length})`);
const cmd = process.argv[2];
switch (cmd) {
case 'version': {
const r = await api('/webui/version', { cred: CRED });
console.log(JSON.stringify(r, null, 2));
break;
}
case 'scheme': {
const r = await api('/webui/scheme', { cred: CRED });
console.log(JSON.stringify(r, null, 2));
break;
}
case 'list': {
const r = await api('/network/list', { method: 'POST', cred: CRED, body: {} });
console.log(JSON.stringify(r, null, 2));
break;
}
case 'apply': {
console.error('apply 未启用:修改 NapCat 网络配置属于对外部运行实例的写操作,');
console.error('需先人工确认新增项与影响范围,再显式实现。');
process.exit(1);
}
default:
console.error('用法: list | version | scheme | apply');
process.exit(1);
}
+100
View File
@@ -0,0 +1,100 @@
// NapCat 正向 WebSocket 探测:鉴权行为 + 是否可通过 WS 调用 OneBot11 API
// 只调用只读接口,不发送任何消息、不执行任何有副作用的动作。
// 用法: node tools/probe/probe-ws-api.mjs <wsUrl> <access_token>
const base = (process.argv[2] || 'ws://192.168.5.32:16099').replace(/\/$/, '');
const token = process.argv[3];
if (!token) {
console.error('缺少 access_token 参数。凭据不得硬编码在脚本中,请通过命令行参数传入。');
process.exit(1);
}
const READ_ONLY_ACTIONS = [
['get_version_info', {}],
['get_login_info', {}],
['get_status', {}],
['get_friend_list', {}],
['get_group_list', {}],
['get_group_system_msg', {}],
['get_online_clients', {}],
];
function connect(target, authHeader) {
return new WebSocket(target, authHeader ? { headers: { Authorization: `Bearer ${authHeader}` } } : {});
}
function probe(label, target, authHeader) {
return new Promise((resolve) => {
const out = { label, target, open: false, closeCode: null, reason: '', events: [] };
let ws;
try { ws = connect(target, authHeader); } catch (e) { resolve({ ...out, err: String(e) }); return; }
const done = () => { try { ws.close(); } catch {} ; resolve(out); };
const timer = setTimeout(done, 10000);
ws.onopen = () => { out.open = true; };
ws.onmessage = (ev) => {
const s = String(ev.data);
if (s.length < 400) out.events.push(s);
else out.events.push(s.slice(0, 400) + `...(+${s.length - 400})`);
if (out.events.length >= 2) { clearTimeout(timer); done(); }
};
ws.onclose = (e) => { out.closeCode = e.code; out.reason = e.reason || ''; clearTimeout(timer); resolve(out); };
ws.onerror = () => {};
});
}
console.log('### 1. 鉴权行为验证(无 token / 错 token / 正确 token 是否都能连上)');
for (const [label, t, auth] of [
['bare-no-token', base, null],
['query-wrong-token', `${base}/?access_token=WRONG_TOKEN_123456`, null],
['header-wrong-token', base, 'WRONG_TOKEN_123456'],
['query-correct-token', `${base}/?access_token=${token}`, null],
['header-correct-token', base, token],
]) {
const r = await probe(label, t, auth);
console.log(`- ${label}: open=${r.open} close=${r.closeCode} reason="${r.reason}" events=${r.events.length}`);
}
console.log('\n### 2. 通过 WS 调用 OneBot11 API(action + echo)');
const ws = connect(`${base}/?access_token=${token}`);
await new Promise((res, rej) => {
ws.onopen = res;
ws.onerror = (e) => rej(new Error('ws error ' + (e.message || '')));
setTimeout(() => rej(new Error('connect timeout')), 10000);
}).catch((e) => { console.log('连接失败: ' + e.message); process.exit(0); });
const pending = new Map();
ws.onmessage = (ev) => {
let obj;
try { obj = JSON.parse(String(ev.data)); } catch { return; }
if (obj.echo && pending.has(obj.echo)) {
const { resolve } = pending.get(obj.echo);
pending.delete(obj.echo);
resolve(obj);
}
};
function call(action, params, ms = 12000) {
const echo = `probe-${action}-${Date.now()}`;
return new Promise((resolve) => {
const to = setTimeout(() => {
pending.delete(echo);
resolve({ __timeout: true, action });
}, ms);
pending.set(echo, {
resolve: (o) => { clearTimeout(to); resolve(o); },
});
ws.send(JSON.stringify({ action, params, echo }));
});
}
for (const [action, params] of READ_ONLY_ACTIONS) {
const r = await call(action, params);
if (r.__timeout) {
console.log(`- ${action}: 无响应(12s 超时)→ 该 WS 通道不支持 API 调用`);
} else {
const s = JSON.stringify(r);
console.log(`- ${action}: status=${r.status} retcode=${r.retcode} → ${s.slice(0, 300)}`);
}
}
try { ws.close(); } catch {}
console.log('\n探测结束');
+50
View File
@@ -0,0 +1,50 @@
// 精确验证:不带 token 的客户端在 12 秒窗口内能收到多少条事件推送
// 与带正确 token 的客户端做对照。只读,不调用任何 API。
// 用法: node tools/probe/probe-ws-event-leak.mjs <wsUrl> <access_token>
const base = (process.argv[2] || 'ws://192.168.5.32:16099').replace(/\/$/, '');
const token = process.argv[3];
if (!token) {
console.error('缺少 access_token 参数。凭据不得硬编码在脚本中,请通过命令行参数传入。');
process.exit(1);
}
const WINDOW_MS = 12000;
function observe(label, target, authHeader) {
return new Promise((resolve) => {
const msgs = [];
const t0 = Date.now();
let opened = false, closedBy = 'none', closeCode = null;
const ws = new WebSocket(target, authHeader ? { headers: { Authorization: `Bearer ${authHeader}` } } : {});
ws.onopen = () => { opened = true; };
ws.onmessage = (ev) => {
const s = String(ev.data);
let kind = 'unparsed';
try {
const o = JSON.parse(s);
kind = `${o.post_type}/${o.meta_event_type || o.message_type || o.notice_type || o.request_type || '-'}`;
} catch {}
msgs.push({ at: Date.now() - t0, kind, len: s.length, raw: s.slice(0, 200) });
};
ws.onclose = (e) => { if (!closedBy.startsWith('客户端')) { closedBy = '服务端'; closeCode = e.code; } };
ws.onerror = () => {};
setTimeout(() => {
closedBy = closedBy === 'none' ? '客户端主动关闭(测试窗口结束)' : closedBy;
try { ws.close(); } catch {}
resolve({ label, opened, closedBy, closeCode, msgs });
}, WINDOW_MS);
});
}
console.log(`每种情况观察 ${WINDOW_MS / 1000}s。NapCat 心跳间隔 3s,正常应收到约 3-4 条心跳。\n`);
for (const [label, t, auth] of [
['A. 完全不带凭据 ', base, null],
['B. 带错误 access_token ', `${base}/?access_token=clearly_wrong_token`, null],
['C. 带错误 Authorization 头 ', base, 'clearly_wrong_token'],
['D. 带正确 access_token ', `${base}/?access_token=${token}`, null],
]) {
const r = await observe(label, t, auth);
const kinds = r.msgs.map(m => m.kind);
console.log(`${label} 握手=${r.opened ? '成功' : '失败'} 关闭方=${r.closedBy}${r.closeCode ? '(' + r.closeCode + ')' : ''} 收到 ${r.msgs.length} 条`);
console.log(` 事件类型: ${kinds.length ? kinds.join(' | ') : '(无)'}`);
r.msgs.forEach(m => console.log(` [${m.at}ms] ${m.raw}`));
}
+59
View File
@@ -0,0 +1,59 @@
// 安全验证:未授权客户端能否通过 NapCat WebSocket 调用 API(只调用只读接口)
// 用法: node tools/probe/probe-ws-unauth.mjs <wsUrl>
const base = (process.argv[2] || 'ws://192.168.5.32:16099').replace(/\/$/, '');
function run(label, target) {
return new Promise((resolve) => {
const res = { label, open: false, apiWorked: null, detail: '' };
const ws = new WebSocket(target);
const pending = new Map();
const finish = () => { try { ws.close(); } catch {} ; resolve(res); };
const hardTimer = setTimeout(finish, 20000);
ws.onopen = () => { res.open = true; };
ws.onmessage = (ev) => {
let o; try { o = JSON.parse(String(ev.data)); } catch { return; }
if (o.echo && pending.has(o.echo)) {
const p = pending.get(o.echo); pending.delete(o.echo);
res.apiWorked = o.status === 'ok';
res.detail = `retcode=${o.retcode} data=${JSON.stringify(o.data).slice(0, 160)}`;
clearTimeout(p.to); clearTimeout(hardTimer);
finish();
}
};
ws.onclose = () => {
if (!res.open) { res.detail = `握手即被关闭 close`; clearTimeout(hardTimer); resolve(res); }
};
ws.onerror = () => {};
ws.addEventListener?.('open', () => {
const echo = `unauth-${Date.now()}`;
const to = setTimeout(() => {
pending.delete(echo);
res.apiWorked = false;
res.detail = '发送 action 后 15s 无任何响应';
clearTimeout(hardTimer);
finish();
}, 15000);
pending.set(echo, { to });
try {
ws.send(JSON.stringify({ action: 'get_version_info', params: {}, echo }));
} catch (e) {
res.detail = 'send 失败: ' + e.message;
}
});
});
}
console.log('测试:完全不带任何凭据的客户端,能否调用 NapCat API');
console.log('(若返回 status=ok,说明该 WebSocket 端口对任意内网主机开放全部 QQ 账号操作能力)\n');
for (const [label, t] of [
['bare', base],
['wrong-token', `${base}/?access_token=definitely_wrong`],
]) {
const r = await run(label, t);
console.log(`- ${label}`);
console.log(` 握手成功 : ${r.open}`);
console.log(` API 可调用 : ${r.apiWorked}`);
console.log(` 详情 : ${r.detail}`);
}
+54
View File
@@ -0,0 +1,54 @@
// NapCat 反向/正向 WebSocket 握手探测(只读,不发送任何业务消息)
// 用法: node tools/probe/probe-ws.mjs <wsUrl> [access_token]
const url = process.argv[2] || 'ws://192.168.5.32:16099';
const token = process.argv[3] || '';
function attempt(target) {
return new Promise((resolve) => {
const t0 = Date.now();
let ws;
try {
ws = new WebSocket(target, { headers: token ? { Authorization: `Bearer ${token}` } : {} });
} catch (e) {
resolve({ target, ok: false, err: String(e) });
return;
}
const logs = [];
const timer = setTimeout(() => {
try { ws.close(); } catch {}
resolve({ target, ok: false, err: 'timeout 12s', logs });
}, 12000);
ws.onopen = () => logs.push(`OPEN at ${Date.now() - t0}ms`);
ws.onmessage = (ev) => {
const s = typeof ev.data === 'string' ? ev.data : `<binary ${ev.data.byteLength}B>`;
logs.push(`MSG(${s.length}): ${s.slice(0, 600)}`);
if (logs.filter(l => l.startsWith('MSG')).length >= 3) {
clearTimeout(timer);
try { ws.close(); } catch {}
}
};
ws.onerror = (e) => logs.push(`ERROR: ${e.message || e.type || 'unknown'}`);
ws.onclose = (e) => {
clearTimeout(timer);
logs.push(`CLOSE code=${e.code} reason="${e.reason}" clean=${e.wasClean}`);
resolve({ target, ok: logs.some(l => l.startsWith('OPEN')), logs });
};
});
}
const candidates = [];
const base = url.replace(/\/$/, '');
candidates.push(`${base}/`);
if (token) {
candidates.push(`${base}/?access_token=${token}`);
candidates.push(`${base}?access_token=${token}`);
}
for (const c of candidates) {
const r = await attempt(c);
console.log('===============================================');
console.log(`TARGET ${c}`);
console.log(`RESULT ok=${r.ok}${r.err ? ' err=' + r.err : ''}`);
(r.logs || []).forEach(l => console.log(' ' + l));
}
+115
View File
@@ -0,0 +1,115 @@
// 语音段(record)可用性专项探测。
// 第 19 章用 WAV 得到 "No decodable audio stream: Decoder not found",
// 本轮改用 NapCat 自己 get_ai_record 产出的真实 QQ 语音(magic = \x03#!SILK_V3),
// 排除「素材非法」这一变量,再用多种 file 传法定位到底是素材、参数还是解码器问题。
// 默认 dry-run,--yes 才真实发送。凭据只从环境变量读取。
//
// 用法:
// NAPCAT_WS_TOKEN=xxx node tools/probe/record-probe.mjs
// NAPCAT_WS_TOKEN=xxx node tools/probe/record-probe.mjs --yes
import fs from 'node:fs';
import path from 'node:path';
const WS_URL = process.env.NAPCAT_WS_URL || 'ws://192.168.5.32:16099';
const TOKEN = process.env.NAPCAT_WS_TOKEN;
const GROUP = Number(process.env.PROBE_GROUP || 933280401);
const FRIEND = Number(process.env.PROBE_FRIEND || 2161656029);
const DO_WRITE = process.argv.includes('--yes');
const OUT_DIR = process.env.PROBE_OUT || 'local';
if (!TOKEN) { console.error('缺少环境变量 NAPCAT_WS_TOKEN。凭据不得硬编码。'); process.exit(1); }
const stamp = new Date().toISOString().replace(/[:.]/g, '-');
fs.mkdirSync(OUT_DIR, { recursive: true });
const OUT = path.join(OUT_DIR, `record-probe-${stamp}.jsonl`);
const say = (...a) => console.log(...a);
const pending = new Map();
let authenticated = false;
const ws = new WebSocket(`${WS_URL.replace(/\/$/, '')}/?access_token=${encodeURIComponent(TOKEN)}`);
ws.onmessage = (ev) => {
let o; try { o = JSON.parse(String(ev.data)); } catch { return; }
if (o.echo && pending.has(o.echo)) { pending.get(o.echo).resolve(o); pending.delete(o.echo); return; }
if (o.post_type === 'meta_event' && o.meta_event_type === 'lifecycle') authenticated = true;
};
await new Promise((res, rej) => { ws.onopen = res; setTimeout(() => rej(new Error('连接超时')), 15000); })
.catch((e) => { console.error(e.message); process.exit(1); });
for (let i = 0; i < 60 && !authenticated; i++) await new Promise((r) => setTimeout(r, 100));
say('认证=' + authenticated);
const api = (action, params, ms = 30000) => new Promise((resolve) => {
const echo = `rp-${action}-${Date.now()}-${Math.random().toString(36).slice(2, 6)}`;
const to = setTimeout(() => { pending.delete(echo); resolve({ __timeout: true }); }, ms);
pending.set(echo, { resolve: (o) => { clearTimeout(to); resolve(o); }, to });
ws.send(JSON.stringify({ action, params, echo }));
});
// 素材:让 NapCat 自己生成语音,拿到官方 CDN URL,再下载成 silk 字节
let silkB64 = null, silkUrl = null, magic = null, bytes = 0;
const ai = await api('get_ai_record', { group_id: GROUP, character: 'lucy-voice-houge', text: 'QLinker 语音可用性探测' });
if (ai.retcode === 0 && typeof ai.data === 'string') {
silkUrl = ai.data;
try {
const buf = Buffer.from(await (await fetch(silkUrl)).arrayBuffer());
bytes = buf.length;
magic = buf.subarray(0, 16).toString('hex');
silkB64 = buf.toString('base64');
say(`素材: ${bytes} 字节 magic=${magic} ascii=${JSON.stringify(buf.subarray(0, 12).toString('latin1'))}`);
fs.writeFileSync(path.join(OUT_DIR, `record-silk-${stamp}.bin`), buf);
} catch (e) { say('素材下载失败: ' + e.message); }
} else {
say('get_ai_record 失败: ' + JSON.stringify(ai).slice(0, 200));
}
const VARIANTS = [
{ id: 'b64_plain', desc: 'record.file = base64://<silk>', need: silkB64,
data: () => ({ file: 'base64://' + silkB64 }) },
{ id: 'b64_format_silk', desc: 'record.file = base64://<silk> + format=silk', need: silkB64,
data: () => ({ file: 'base64://' + silkB64, format: 'silk' }) },
{ id: 'b64_name_silk', desc: 'record.file = base64://<silk> + file_name=a.silk', need: silkB64,
data: () => ({ file: 'base64://' + silkB64, file_name: 'a.silk' }) },
{ id: 'url_plain', desc: 'record.file = <QQ CDN url>', need: silkUrl,
data: () => ({ file: silkUrl }) },
{ id: 'url_field', desc: 'record.url = <QQ CDN url>(不放 file)', need: silkUrl,
data: () => ({ url: silkUrl }) },
{ id: 'url_format_silk', desc: 'record.file = <url> + format=silk + path', need: silkUrl,
data: () => ({ file: silkUrl, format: 'silk', path: '/tmp/qlinker-probe.silk' }) },
{ id: 'b64_url_both', desc: 'record.file = base64 + url 同时给', need: silkB64 && silkUrl,
data: () => ({ file: 'base64://' + silkB64, url: silkUrl }) },
{ id: 'ai_record_api', desc: 'send_group_ai_record(官方 TTS 语音,作为语音能力旁证)', api: 'send_group_ai_record',
params: () => ({ group_id: GROUP, character: 'lucy-voice-houge', text: 'QLinker 语音可用性探测' }) },
];
const results = [];
say(`\n模式=${DO_WRITE ? '真实发送' : 'DRY-RUN'}\n`);
for (const v of VARIANTS) {
// 只有显式声明 need 的变体才受素材门禁约束
if ('need' in v && !v.need) { say(`${v.id.padEnd(18)} 跳过:素材缺失`); results.push({ id: v.id, status: 'skipped' }); continue; }
if (!DO_WRITE) { say(`${v.id.padEnd(18)} [计划] ${v.desc}`); continue; }
let r;
if (v.api) r = await api(v.api, v.params());
else r = await api('send_group_msg', { group_id: GROUP, message: [
{ type: 'record', data: v.data() }, { type: 'text', data: { text: `[QLr:${v.id}]` } }] });
const rec = { id: v.id, desc: v.desc, retcode: r.__timeout ? 'TIMEOUT' : r.retcode,
message: r.message ?? r.wording ?? '', message_id: r?.data?.message_id ?? null,
status: r.__timeout ? 'timeout' : (r.retcode === 0 ? 'sent' : 'rejected') };
results.push(rec);
fs.appendFileSync(OUT, JSON.stringify(rec) + '\n');
say(`${v.id.padEnd(18)} retcode=${String(rec.retcode).padEnd(7)} ${String(rec.message).slice(0, 70)}`);
await new Promise((r2) => setTimeout(r2, 2500));
}
if (DO_WRITE) {
say('\nhistory 回读:');
const h = await api('get_group_msg_history', { group_id: GROUP, count: 40 });
for (const m of h?.data?.messages ?? []) {
const raw = String(m.raw_message ?? '');
const hit = raw.match(/\[QLr:([a-z_0-9]+)\]/);
if (hit) say(` ${hit[1].padEnd(18)} seq=${m.real_seq} 段=${(m.message ?? []).map((s) => s.type).join('+')}`);
}
fs.appendFileSync(OUT, JSON.stringify({ __summary: true, magic, bytes, silk_url: silkUrl }) + '\n');
say('\n结果 -> ' + OUT);
}
try { ws.close(); } catch {}
process.exit(0);
+309
View File
@@ -0,0 +1,309 @@
// OneBot11 消息段发送矩阵探测。
// 目的: 逐段类型实测 NapCat 4.18.41 是否接受、返回什么 retcode/字段、事件回推长什么样。
// 默认 dry-run 只打印将要发送的内容;加 --yes 才真实发送到测试群/测试号。
//
// 用法:
// NAPCAT_WS_TOKEN=xxx node tools/probe/seg-probe.mjs # dry-run 全量
// NAPCAT_WS_TOKEN=xxx node tools/probe/seg-probe.mjs --yes poke # 真发指定用例
// NAPCAT_WS_TOKEN=xxx node tools/probe/seg-probe.mjs --yes --all
// 目标: KIND=group TARGET=933280401(默认)/ KIND=private TARGET=<qq>
// 事件侧: LOG_FILE=local/seg-events.jsonl 可把发送期间收到的事件原样落盘,供结构分析
// 发送后等待: SETTLE_MS 默认 4000,用于等事件回推
//
// ⚠ 会产生真实外部副作用(向真实 QQ 群/号发消息),仅在已授权的测试群/测试号上使用。
import fs from 'node:fs';
import path from 'node:path';
const WS_URL = process.env.NAPCAT_WS_URL || 'ws://192.168.5.32:16099';
const TOKEN = process.env.NAPCAT_WS_TOKEN;
const KIND = process.env.KIND || 'group';
const TARGET = Number(process.env.TARGET || (KIND === 'group' ? 933280401 : 2161656029));
const SELF_QQ = Number(process.env.SELF_QQ || 3575608514);
const LOG_FILE = process.env.LOG_FILE || '';
const RESULT_DIR = process.env.RESULT_DIR || 'local';
const STAMP = new Date().toISOString().replace(/[:.]/g, '-');
const SETTLE_MS = Number(process.env.SETTLE_MS || 4000);
// 上一轮实测得到的真实 message_id,用于 reply 引用
const REPLY_TO = process.env.REPLY_TO || '';
const argv = process.argv.slice(2);
const DO_WRITE = argv.includes('--yes');
const names = argv.filter((a) => !a.startsWith('--'));
const RUN_ALL = names.includes('--all') || names.length === 0;
if (!TOKEN) { console.error('缺少 NAPCAT_WS_TOKEN'); process.exit(1); }
if (LOG_FILE) fs.mkdirSync(path.dirname(LOG_FILE), { recursive: true });
const logEvent = (caseName, o) => {
if (!LOG_FILE) return;
fs.appendFileSync(LOG_FILE, JSON.stringify({ t: new Date().toISOString(), case: caseName, data: o }) + '\n');
};
const TAG = (n) => `[QLinker段探测:${n}]`;
const arr = (...segs) => segs;
// 1x1 透明 PNG
const PNG_1PX = 'iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mNk+M9QDwADhgGAWjR9awAAAABJRU5ErkJggg==';
// 最小合法 WAV: 8kHz / 8bit / 单声道 / 8 字节静音,共 52 字节
const u32 = (v) => { const b = Buffer.alloc(4); b.writeUInt32LE(v, 0); return b; };
const u16 = (v) => { const b = Buffer.alloc(2); b.writeUInt16LE(v, 0); return b; };
const WAV_DATA = Buffer.alloc(8, 128);
const WAV_MIN = Buffer.concat([
Buffer.from('RIFF', 'ascii'), u32(36 + WAV_DATA.length), Buffer.from('WAVE', 'ascii'),
Buffer.from('fmt ', 'ascii'), u32(16),
u16(1), u16(1), u32(8000), u32(8000), u16(1), u16(8),
Buffer.from('data', 'ascii'), u32(WAV_DATA.length), WAV_DATA,
]).toString('base64');
// 每个用例: { name, desc, message, expect }
// expect: 'ok' 预期被接受;'reject' 预期被拒绝(拒绝本身也是有价值的结论)
const CASES = [
{
name: 'poke',
desc: '戳一戳(群内 @ 目标成员)',
message: arr(
{ type: 'text', data: { text: `${TAG('poke')} 文本段` } },
{ type: 'poke', data: { type: 'qq', id: String(TARGET === 933280401 ? 2161656029 : TARGET) } },
),
expect: 'ok',
},
{
name: 'location',
desc: '位置分享',
message: arr(
{ type: 'text', data: { text: `${TAG('location')} 文本段` } },
{ type: 'location', data: { lat: '39.90469', lon: '116.40717', title: '测试地点', content: 'QLinker 探测' } },
),
expect: 'ok',
},
{
name: 'json',
desc: 'JSON 卡片(未注册业务 appid,预期可能被拒)',
message: arr({ type: 'json', data: { data: JSON.stringify({ app: 'com.example.unknown', view: 'library', config: { width: 600, height: 400 }, prompt: '探测', summary: '探测', meta: { detail: { title: { title: 'QLinker 段探测' } } } }) } }),
expect: 'unknown',
},
{
name: 'music',
desc: '音乐分享(id 形式)',
message: arr({ type: 'music', data: { type: '163', id: '1408551584' } }),
expect: 'unknown',
},
{
name: 'image_base64',
desc: '图片段 base64(1x1 PNG,走 base64:// 协议,不依赖外部 URL)',
message: arr(
{ type: 'text', data: { text: `${TAG('image_base64')} 文本段` } },
{ type: 'image', data: { file: 'base64://' + PNG_1PX } },
),
expect: 'ok',
},
{
name: 'record_base64',
desc: '语音段 base64(WAV 头,QQ 语音通常为 silk/amr,观察是否接受)',
message: arr({ type: 'record', data: { file: 'base64://' + WAV_MIN } }),
expect: 'unknown',
},
{
name: 'video_base64',
desc: '视频段 base64(非合法 MP4 内容,观察校验强度)',
message: arr({ type: 'video', data: { file: 'base64://' + PNG_1PX } }),
expect: 'unknown',
},
{
name: 'file_base64',
desc: '文件段 base64(群文件上传路径)',
message: arr({ type: 'file', data: { file: 'base64://' + Buffer.from('QLinker seg probe file payload\n').toString('base64'), name: 'qlinker-probe.txt' } }),
expect: 'unknown',
},
{
name: 'forward',
desc: '转发节点(forward + node 数组,自定义节点)',
message: arr(
{ type: 'text', data: { text: `${TAG('forward')} 文本段` } },
{
type: 'forward',
data: {
forward: true,
nodes: JSON.stringify([
{ type: 'node', user_id: String(SELF_QQ), nickname: '雪珂', content: [{ type: 'text', data: { text: '转发的第一条' } }] },
{ type: 'node', user_id: '2161656029', nickname: '小王', content: [{ type: 'text', data: { text: '转发的第二条' } }] },
]),
},
},
),
expect: 'unknown',
},
{
name: 'forward_array',
desc: '转发变体:nodes 传真正的数组而非 JSON 字符串',
message: arr(
{ type: 'text', data: { text: `${TAG('forward_array')} 文本段` } },
{
type: 'forward',
data: {
nodes: [
{ type: 'node', user_id: String(SELF_QQ), nickname: '雪珂', content: [{ type: 'text', data: { text: '数组节点第一条' } }] },
{ type: 'node', user_id: '2161656029', nickname: '小王', content: [{ type: 'text', data: { text: '数组节点第二条' } }] },
],
},
},
),
expect: 'unknown',
},
{
name: 'node_single',
desc: '转发变体:单个 node 段(非 forward 容器)',
message: arr({
type: 'node',
data: { type: 'node', user_id: String(SELF_QQ), nickname: '雪珂', content: [{ type: 'text', data: { text: '单节点内容' } }] },
}),
expect: 'unknown',
},
{
name: 'node_multi',
desc: '转发变体:message 数组里并列多个 node 段(node_single 已证明单节点生效)',
message: arr(
{ type: 'node', data: { type: 'node', user_id: String(SELF_QQ), nickname: '雪珂', content: [{ type: 'text', data: { text: '并列节点一' } }] } },
{ type: 'node', data: { type: 'node', user_id: '2161656029', nickname: '小王', content: [{ type: 'text', data: { text: '并列节点二' } }] } },
{ type: 'node', data: { type: 'node', user_id: String(SELF_QQ), nickname: '雪珂', content: [{ type: 'text', data: { text: '并列节点三' } }] } },
),
expect: 'unknown',
},
{
name: 'reply',
desc: '引用回复(reply + 文本,引用上一条真实 message_id)',
skipIf: !REPLY_TO,
skipWhy: '未提供 REPLY_TO 环境变量(需真实 message_id)',
message: arr(
{ type: 'reply', data: { id: String(REPLY_TO) } },
{ type: 'text', data: { text: `${TAG('reply')} 引用回复文本` } },
),
expect: 'ok',
},
{
name: 'unknown_type',
desc: '未知段类型(验证是否会污染或整条失败)',
message: arr(
{ type: 'text', data: { text: `${TAG('unknown_type')} 文本段` } },
{ type: 'qlinker_nonexistent_segment', data: { foo: 'bar' } },
),
expect: 'reject',
},
{
name: 'empty_seg',
desc: '空消息段数组',
message: [],
expect: 'reject',
},
{
name: 'long_text',
desc: '超长文本(5000 字符,观察截断/拒绝阈值)',
message: arr({ type: 'text', data: { text: TAG('long_text') + '甲'.repeat(5000) } }),
expect: 'unknown',
},
];
const ws = new WebSocket(`${WS_URL.replace(/\/$/, '')}/?access_token=${encodeURIComponent(TOKEN)}`);
const pending = new Map();
let n = 0;
let currentCase = '(idle)';
let sawLifecycle = false;
const lifecycle = new Promise((resolve) => {
const to = setTimeout(() => resolve(false), 10000);
ws.__onLifecycle = resolve;
ws.__lifecycleTimeout = to;
});
ws.onmessage = (ev) => {
let o; try { o = JSON.parse(String(ev.data)); } catch { return; }
if (o.post_type) {
if (o.post_type === 'meta_event' && o.meta_event_type === 'lifecycle') {
sawLifecycle = true;
ws.__onLifecycle?.(true);
clearTimeout(ws.__lifecycleTimeout);
}
if (o.post_type === 'meta_event' && o.meta_event_type === 'heartbeat') return;
const brief = o.message_id ?? o.notice_type ?? o.meta_event_type ?? '';
console.log(` · 事件 ${o.post_type}/${brief}`);
logEvent(currentCase, o);
return;
}
if (o.echo && pending.has(o.echo)) {
const p = pending.get(o.echo); pending.delete(o.echo); clearTimeout(p.to); p.resolve(o);
}
};
ws.onerror = (e) => { console.error('WS 错误:', e?.message ?? e); process.exit(1); };
await new Promise((res, rej) => { ws.onopen = res; setTimeout(() => rej(new Error('连接超时')), 10000); })
.catch((e) => { console.error(e.message); process.exit(1); });
// 握手成功不等于认证成功,等 lifecycle 再动手
const authed = await lifecycle;
console.log(`握手完成,认证确认=${authed}(未确认时发送可能全部 1403)`);
const call = (action, params, ms = 30000) => new Promise((resolve) => {
const echo = `seg-${++n}-${Date.now()}`;
const to = setTimeout(() => { pending.delete(echo); resolve({ __timeout: true }); }, ms);
pending.set(echo, { resolve, to });
ws.send(JSON.stringify({ action, params, echo }));
});
const action = KIND === 'group' ? 'send_group_msg' : 'send_private_msg';
const targetKey = KIND === 'group' ? 'group_id' : 'user_id';
console.log(`模式: ${DO_WRITE ? '*** 真实发送 ***' : 'dry-run(不发)'} 目标: ${KIND} ${TARGET} 通道: ${action}`);
console.log('='.repeat(90));
const results = [];
for (const c of CASES) {
if (!RUN_ALL && !names.includes(c.name)) continue;
console.log(`\n【${c.name}】${c.desc} (预期 ${c.expect})`);
console.log(' message =', JSON.stringify(c.message).slice(0, 320));
if (c.skipIf) {
console.log(` → 跳过: ${c.skipWhy}`);
results.push({ name: c.name, verdict: 'SKIPPED' });
continue;
}
if (!DO_WRITE) { results.push({ name: c.name, verdict: 'DRYRUN' }); continue; }
currentCase = c.name;
const t0 = Date.now();
const r = await call(action, { [targetKey]: TARGET, message: c.message });
const ms = Date.now() - t0;
if (r.__timeout) {
console.log(` → ${ms}ms 无响应(超时,属「结果未知」场景)`);
results.push({ name: c.name, verdict: 'TIMEOUT', ms });
} else {
const mid = r?.data?.message_id;
console.log(` → ${ms}ms retcode=${r.retcode} status=${r.status} message_id=${mid ?? '-'}`);
if (r.retcode !== 0) console.log(' errmsg:', JSON.stringify(r).slice(0, 400));
results.push({ name: c.name, verdict: r.retcode === 0 ? 'ACCEPTED' : 'REJECTED', retcode: r.retcode, ms, message_id: mid });
}
await new Promise((r) => setTimeout(r, SETTLE_MS));
}
currentCase = '(done)';
console.log('\n' + '='.repeat(90));
console.log('汇总:');
for (const r of results) console.log(` ${r.verdict.padEnd(9)} ${r.name}${r.retcode !== undefined ? ` retcode=${r.retcode} ${r.ms}ms` : ''}`);
// 结果落盘,字段名与 capability-check 的回归比对对齐(id / retcode / event_segs)
fs.mkdirSync(RESULT_DIR, { recursive: true });
const resultFile = path.join(RESULT_DIR, `seg-result-${STAMP}.jsonl`);
const evByCase = new Map();
if (LOG_FILE && fs.existsSync(LOG_FILE)) {
for (const l of fs.readFileSync(LOG_FILE, 'utf8').trim().split('\n')) {
let o; try { o = JSON.parse(l); } catch { continue; }
if (!o.case || o.case === '(idle)' || o.case === '(done)') continue;
const segs = Array.isArray(o.data?.message) ? o.data.message.map((s) => s.type).join('+') : null;
if (segs && !evByCase.has(o.case)) evByCase.set(o.case, segs);
}
}
fs.writeFileSync(resultFile, results.map((r) => JSON.stringify({
id: r.name, status: r.verdict, retcode: r.retcode ?? null,
message_id: r.message_id ?? null, event_segs: evByCase.get(r.name) ?? null, ms: r.ms ?? null,
})).join('\n') + '\n');
console.log('结果 -> ' + resultFile);
console.log(LOG_FILE ? `事件侧结构见 ${LOG_FILE},按 case 字段检索。` : '提示: 设 LOG_FILE 可采集事件侧结构。');
try { ws.close(); } catch {}
process.exit(0);
+110
View File
@@ -0,0 +1,110 @@
// 补采 URL 形式的图片/视频(矩阵里 g_image_url / g_video_url 被 skipped)。
// 上一轮失败原因:复用了历史 CDN URL,其 rkey 已过期。媒体 CDN URL 具时效,必须现发现用。
// 做法:先从 history 找一条自己发过的 image/video,取其**当前新鲜**的 url 字段,
// 立刻用于 send_group_msg 的 file=<url>,再比对事件段与 history 段。
// 默认 dry-run,--yes 才真实发送。凭据只从环境变量读取。
import fs from 'node:fs';
import path from 'node:path';
const WS_URL = process.env.NAPCAT_WS_URL || 'ws://192.168.5.32:16099';
const TOKEN = process.env.NAPCAT_WS_TOKEN;
const GROUP = Number(process.env.PROBE_GROUP || 933280401);
const DO_WRITE = process.argv.includes('--yes');
const OUT_DIR = process.env.PROBE_OUT || 'local';
if (!TOKEN) { console.error('缺少环境变量 NAPCAT_WS_TOKEN。凭据不得硬编码。'); process.exit(1); }
const stamp = new Date().toISOString().replace(/[:.]/g, '-');
fs.mkdirSync(OUT_DIR, { recursive: true });
const OUT = path.join(OUT_DIR, `url-media-${stamp}.jsonl`);
const say = (...a) => console.log(...a);
const pending = new Map();
let opened = false, authed = false;
const events = [];
const ws = new WebSocket(`${WS_URL.replace(/\/$/, '')}/?access_token=${encodeURIComponent(TOKEN)}`);
ws.onopen = () => { opened = true; };
ws.onmessage = (ev) => {
let o; try { o = JSON.parse(String(ev.data)); } catch { return; }
if (o.echo && pending.has(o.echo)) { pending.get(o.echo).resolve(o); pending.delete(o.echo); return; }
if (o.post_type === 'meta_event') { if (o.meta_event_type === 'lifecycle') authed = true; return; }
events.push({ el: Date.now(), data: o });
fs.appendFileSync(OUT, JSON.stringify({ kind: 'event', data: o }) + '\n');
};
for (let i = 0; i < 100 && !opened; i++) await new Promise((r) => setTimeout(r, 100));
if (!opened) { console.error('连接超时'); process.exit(1); }
for (let i = 0; i < 100 && !authed; i++) await new Promise((r) => setTimeout(r, 100));
say('认证=' + authed);
if (!authed && DO_WRITE) { console.error('未确认认证,中止。'); process.exit(2); }
const api = (action, params, ms = 40000) => new Promise((resolve) => {
const echo = `um-${action}-${Date.now()}-${Math.random().toString(36).slice(2, 6)}`;
const to = setTimeout(() => { pending.delete(echo); resolve({ __timeout: true }); }, ms);
pending.set(echo, { resolve: (o) => { clearTimeout(to); resolve(o); }, to });
ws.send(JSON.stringify({ action, params, echo }));
});
// 现场取新鲜 URL
const h = await api('get_group_msg_history', { group_id: GROUP, count: 60 });
const fresh = {};
for (const m of h?.data?.messages ?? []) {
for (const s of m.message ?? []) {
if ((s.type === 'image' || s.type === 'video') && s.data?.url && !fresh[s.type]) {
fresh[s.type] = s.data.url;
}
}
}
say('现场取到 URL: ' + Object.keys(fresh).map((k) => k + '=' + fresh[k].slice(0, 55) + '...').join(' / '));
// 先验证 URL 当下是否可下载,避免把「URL 过期」误判成「NapCat 不支持 URL 形式」
for (const [k, u] of Object.entries(fresh)) {
try { const r = await fetch(u); const b = await r.arrayBuffer();
say(` ${k} URL 可达性: HTTP ${r.status} ${b.byteLength} 字节`);
fresh[k + '_ok'] = r.ok && b.byteLength > 0;
} catch (e) { say(` ${k} URL 下载异常: ${e.message}`); fresh[k + '_ok'] = false; }
}
const CASES = [
{ id: 'g_image_url', seg: 'image', text: '[QLu:image_url]' },
{ id: 'g_video_url', seg: 'video', text: '[QLu:video_url]' },
];
const results = [];
say(`\n模式=${DO_WRITE ? '真实发送' : 'DRY-RUN'}\n`);
for (const c of CASES) {
const url = fresh[c.seg];
if (!url || !fresh[c.seg + '_ok']) {
say(`${c.id.padEnd(14)} 跳过:${!url ? 'history 无该类型新鲜 URL' : 'URL 已不可下载'}`);
results.push({ id: c.id, status: 'skipped', reason: !url ? 'no_fresh_url' : 'url_not_downloadable' });
continue;
}
if (!DO_WRITE) { say(`${c.id.padEnd(14)} [计划] ${c.seg} file=<新鲜 CDN url>`); continue; }
const t0 = Date.now();
const r = await api('send_group_msg', { group_id: GROUP,
message: [{ type: c.seg, data: { file: url } }, { type: 'text', data: { text: c.text } }] });
await new Promise((x) => setTimeout(x, 7000));
// 注意:raw_message 里 [ ] , 会被转义成 &#91; &#93; &#44;,文本匹配不可靠,必须用 message_id 关联
const midNum = Number(r?.data?.message_id);
const ev = events.find((e) => e.el >= t0 && Number(e.data.message_id) === midNum);
const rec = { id: c.id, seg: c.seg, retcode: r.__timeout ? 'TIMEOUT' : r.retcode,
message: r.message ?? '', message_id: r?.data?.message_id ?? null,
event_segs: ev ? (ev.data.message || []).map((s) => s.type).join('+') : 'NO_EVENT',
event_seq: ev?.data?.real_seq ?? null,
event_seg_detail: ev ? JSON.stringify((ev.data.message || []).map((s) => ({
t: s.type, size: s.data?.file_size ?? null, url: s.data?.url ? 'Y' : 'N' }))) : null,
status: r.__timeout ? 'timeout' : (r.retcode === 0 ? 'sent' : 'rejected') };
results.push(rec);
fs.appendFileSync(OUT, JSON.stringify({ kind: 'result', ...rec }) + '\n');
say(`${c.id.padEnd(14)} retcode=${String(rec.retcode).padEnd(6)} seq=${String(rec.event_seq ?? '-').padEnd(6)} 事件段=${rec.event_segs} ${rec.event_seg_detail ?? ''}`);
}
const hist = await api('get_group_msg_history', { group_id: GROUP, count: 12 });
say('\nhistory 回读:');
for (const m of hist?.data?.messages ?? []) {
const raw = String(m.raw_message ?? '');
const hit = raw.match(/\[QLu:([a-z_]+)\]/);
if (hit) say(` ${hit[1].padEnd(12)} seq=${m.real_seq} 段=${(m.message ?? []).map((s) => s.type).join('+')}`);
}
fs.appendFileSync(OUT, JSON.stringify({ __summary: true, results }) + '\n');
say('\n结果 -> ' + OUT);
try { ws.close(); } catch {}
process.exit(0);
+37
View File
@@ -0,0 +1,37 @@
// 只读分析:递归抓取 NapCat WebUI 所有前端 chunk(含懒加载),提取后端路由。
// 不发送写请求,不修改任何配置。
const BASE = (process.env.NAPCAT_WEBUI_URL || 'http://192.168.5.32:6099').replace(/\/$/, '');
const seen = new Set();
const queue = [];
const routes = new Map();
function collect(src, from) {
for (const m of src.matchAll(/\.(post|get|put|delete)\(\s*"([^"]{2,70})"/g)) {
const key = `${m[1].toUpperCase()} ${m[2]}`;
if (!routes.has(key)) routes.set(key, from);
}
for (const m of src.matchAll(/assets\/[A-Za-z0-9_.-]+\.js/g)) queue.push(m[0]);
}
async function fetchText(url) {
try { return await fetch(url, { signal: AbortSignal.timeout(20000) }).then(r => r.ok ? r.text() : ''); }
catch { return ''; }
}
const entry = await fetchText(`${BASE}/webui/`);
collect(entry, 'index.html');
let round = 0;
while (queue.length && round < 400) {
const c = queue.shift();
if (seen.has(c)) continue;
seen.add(c);
round++;
const src = await fetchText(`${BASE}/webui/${c}`);
if (src) collect(src, c.split('/').pop());
}
console.log(`扫描 ${seen.size} 个 chunk`);
console.log(`\n=== ${routes.size} 个路由 ===`);
[...routes.entries()].sort().forEach(([k, v]) => console.log(` ${k} <- ${v}`));