fix(bridge,common,onebot): reject phantom hook UINs + never crash logging (#162)

注入的竞态窗口里,native hook 偶发上报 13 位垃圾 UIN(时间戳型,读到 QQ 尚未落定
的内存)。TS 层防御缺失,导致两个连锁问题:

1) 幽灵账号:isRealUin 只查「纯数字且 ≥5 位」、无上限,垃圾值通过后建会话并把
   config/onebot_<垃圾>.json 落盘 → OneBot 节点配置里出现随机幽灵账号(跨重启残留)。
2) 进程崩溃:logger 彩色路径 ' '.repeat(SLOT - tagLen),UIN tag(含方括号)超宽 →
   负数 → RangeError: Invalid count value → uncaughtException。

跨平台(Win DLL / Linux .so 同逻辑)+「更新 QQ 后消失」都印证是 native 读到那块内存
的偶发垃圾;根修在 SnowLumaNative,此处补齐 TS 防御:

- 抽出唯一的 @snowluma/common/uin::isRealUin = /^\d{5,10}$/(真实 QQ ≤ uint32 →
  10 位)。删除 bridge/core 两处重复副本(重复正是这次漏加上限的温床)。等价旧逻辑,
  仅新增拒 11+ 位。
- logger.ts 加 Math.max(0, …),日志永不崩进程(独立健壮化)。
- 收紧 WebUI UIN_REGEX /^\d{5,12}$/ → /^\d{5,10}$/ 保持一致。
- 启动时 cleanupInvalidPerUinConfigs() 清掉已落盘的幽灵 onebot_<uin>.json(只删
  UIN 不合法的,绝不碰合法账号/全局配置)。

测试:common +8(uin 6 / logger 2)、onebot +3(cleanup)。typecheck 12 包干净;
common 58 / onebot 519 / core 471 / bridge 73 全绿。对抗性 Agent 逐输入核验等价性、
三层 gate 堵死幽灵入口、cleanup 安全时序,无回归。
This commit is contained in:
DrSmoothl committed 2026-07-01 20:37:02 +08:00
1 parent ade76d3d2f
commit 3932958c39
11 files changed
+209 -16

No files matched your search

+33
View File
@@ -1,4 +1,5 @@
import { createLogger } from '@snowluma/common/logger';
import { isRealUin } from '@snowluma/common/uin';
import { randomBytes } from 'crypto';
import fs from 'fs';
import path from 'path';
@@ -105,6 +106,38 @@ function ensureConfigDir(): void {
fs.mkdirSync(CONFIG_DIR, { recursive: true });
}
const PER_UIN_CONFIG = /^onebot_(\d+)\.json$/;
/**
* Remove per-UIN config files whose UIN is not a real QQ account — leftovers
* from the phantom-account bug where the native hook reported a garbage
* (timestamp-shaped) UIN and a `onebot_<garbage>.json` got persisted (issue
* #162). Only files matching `onebot_<digits>.json` are considered, and only
* those failing isRealUin (i.e. 11+ digits) are deleted — legitimate accounts
* are never touched. Returns the deleted file names. Safe to call at startup.
*/
export function cleanupInvalidPerUinConfigs(): string[] {
let entries: string[];
try {
entries = fs.readdirSync(CONFIG_DIR);
} catch {
return []; // config dir not created yet — nothing to clean
}
const removed: string[] = [];
for (const name of entries) {
const match = PER_UIN_CONFIG.exec(name);
if (!match || isRealUin(match[1])) continue;
try {
fs.unlinkSync(path.join(CONFIG_DIR, name));
removed.push(name);
log.warn('removed phantom per-UIN config (invalid UIN): %s', name);
} catch (err) {
log.warn('failed to remove phantom config %s: %s', name, err instanceof Error ? err.message : String(err));
}
}
return removed;
}
function toJsonObject(config: OneBotConfig): JsonObject {
const nets = config.networks;
return {