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:
11 files changed
+209
-16
No files matched your search
@@ -1,5 +1,6 @@
|
|||||||
import { createLogger, type Logger } from '@snowluma/common/logger';
|
import { createLogger, type Logger } from '@snowluma/common/logger';
|
||||||
import type { PacketSink } from '@snowluma/common/protocol-types';
|
import type { PacketSink } from '@snowluma/common/protocol-types';
|
||||||
|
import { isRealUin } from '@snowluma/common/uin';
|
||||||
import { EventEmitter } from 'events';
|
import { EventEmitter } from 'events';
|
||||||
import { HookPacketClient } from './hook-packet-client';
|
import { HookPacketClient } from './hook-packet-client';
|
||||||
import type { HookInjectResult } from './injector';
|
import type { HookInjectResult } from './injector';
|
||||||
@@ -518,11 +519,6 @@ export class HookSession extends EventEmitter {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
function isRealUin(uin: string): boolean {
|
|
||||||
if (!uin || uin === '0') return false;
|
|
||||||
return /^\d+$/.test(uin) && uin.length >= 5;
|
|
||||||
}
|
|
||||||
|
|
||||||
function errMsg(value: unknown): string {
|
function errMsg(value: unknown): string {
|
||||||
return value instanceof Error ? value.message : String(value);
|
return value instanceof Error ? value.message : String(value);
|
||||||
}
|
}
|
||||||
@@ -55,6 +55,10 @@
|
|||||||
"./runtime": {
|
"./runtime": {
|
||||||
"types": "./src/runtime.ts",
|
"types": "./src/runtime.ts",
|
||||||
"default": "./src/runtime.ts"
|
"default": "./src/runtime.ts"
|
||||||
|
},
|
||||||
|
"./uin": {
|
||||||
|
"types": "./src/uin.ts",
|
||||||
|
"default": "./src/uin.ts"
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
"scripts": {
|
"scripts": {
|
||||||
|
|||||||
@@ -175,7 +175,7 @@ function render(level: LogLevel, options: LogOptions, args: unknown[], reqId?: n
|
|||||||
// Pad first, then color only the visible tag so escape codes don't eat
|
// Pad first, then color only the visible tag so escape codes don't eat
|
||||||
// into the alignment width.
|
// into the alignment width.
|
||||||
const cUin = uinTag
|
const cUin = uinTag
|
||||||
? ansi(COLOR_DIM, uinTag) + ' '.repeat(UIN_SLOT_WIDTH - uinTag.length)
|
? ansi(COLOR_DIM, uinTag) + ' '.repeat(Math.max(0, UIN_SLOT_WIDTH - uinTag.length))
|
||||||
: ' '.repeat(UIN_SLOT_WIDTH);
|
: ' '.repeat(UIN_SLOT_WIDTH);
|
||||||
const cScope = ansi(COLOR_SCOPE, `[${options.scope}]`);
|
const cScope = ansi(COLOR_SCOPE, `[${options.scope}]`);
|
||||||
const cReq = reqTag ? `${ansi(COLOR_DIM, reqTag)} ` : '';
|
const cReq = reqTag ? `${ansi(COLOR_DIM, reqTag)} ` : '';
|
||||||
|
|||||||
@@ -0,0 +1,11 @@
|
|||||||
|
// Shared QQ UIN validity check. A "real" UIN is a live QQ account number, not
|
||||||
|
// a garbage value the native hook can emit during the probe→inject race — e.g.
|
||||||
|
// a 13-digit millisecond timestamp read from not-yet-populated QQ memory
|
||||||
|
// (issue #162). No real QQ UIN exceeds 10 digits (they fit in uint32, max
|
||||||
|
// 4294967295), so a pure digit string of 5..10 chars is the accept window.
|
||||||
|
//
|
||||||
|
// Callers rely on a `true` result guaranteeing a BigInt()-safe pure-digit
|
||||||
|
// string. Keep that contract if the pattern ever changes.
|
||||||
|
export function isRealUin(uin: string): boolean {
|
||||||
|
return /^\d{5,10}$/.test(uin);
|
||||||
|
}
|
||||||
@@ -0,0 +1,45 @@
|
|||||||
|
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
|
||||||
|
|
||||||
|
// The file transport writes to disk; stub it so the test has no side effects.
|
||||||
|
vi.mock('../src/log-file-transport', () => ({
|
||||||
|
getFileTransport: () => ({ write: () => {} }),
|
||||||
|
}));
|
||||||
|
|
||||||
|
import { createLogger } from '../src/logger';
|
||||||
|
|
||||||
|
// Regression for issue #162: a hook-reported garbage UIN (13-digit, timestamp
|
||||||
|
// shaped) produced a `[…]` tag wider than the fixed UIN slot, and the colored
|
||||||
|
// render path did `' '.repeat(slot - tagLen)` → RangeError: Invalid count value
|
||||||
|
// → uncaughtException. The padding must clamp at zero.
|
||||||
|
describe('logger UIN slot padding', () => {
|
||||||
|
let prevTTY: boolean | undefined;
|
||||||
|
let prevNoColor: string | undefined;
|
||||||
|
|
||||||
|
beforeEach(() => {
|
||||||
|
prevTTY = process.stdout.isTTY;
|
||||||
|
prevNoColor = process.env.NO_COLOR;
|
||||||
|
// Force the colored render path (the only one that used .repeat()).
|
||||||
|
(process.stdout as unknown as { isTTY: boolean }).isTTY = true;
|
||||||
|
delete process.env.NO_COLOR;
|
||||||
|
vi.spyOn(process.stdout, 'write').mockReturnValue(true);
|
||||||
|
vi.spyOn(process.stderr, 'write').mockReturnValue(true);
|
||||||
|
});
|
||||||
|
|
||||||
|
afterEach(() => {
|
||||||
|
(process.stdout as unknown as { isTTY: boolean | undefined }).isTTY = prevTTY;
|
||||||
|
if (prevNoColor === undefined) delete process.env.NO_COLOR;
|
||||||
|
else process.env.NO_COLOR = prevNoColor;
|
||||||
|
vi.restoreAllMocks();
|
||||||
|
});
|
||||||
|
|
||||||
|
it('does not throw when the UIN tag exceeds the slot width', () => {
|
||||||
|
const log = createLogger('Test').child({ uin: '1701414379536' }); // 13-digit → [..] = 15 chars
|
||||||
|
expect(() => log.info('phantom account line')).not.toThrow();
|
||||||
|
expect(() => log.error('phantom error line')).not.toThrow();
|
||||||
|
});
|
||||||
|
|
||||||
|
it('still renders a normal-width UIN and a no-UIN logger', () => {
|
||||||
|
expect(() => createLogger('Test').child({ uin: '10001' }).info('ok')).not.toThrow();
|
||||||
|
expect(() => createLogger('Test').info('no uin')).not.toThrow();
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -0,0 +1,40 @@
|
|||||||
|
import { describe, expect, it } from 'vitest';
|
||||||
|
import { isRealUin } from '../src/uin';
|
||||||
|
|
||||||
|
describe('isRealUin', () => {
|
||||||
|
it('accepts real QQ UINs (5..10 digits)', () => {
|
||||||
|
expect(isRealUin('10001')).toBe(true); // 5-digit floor
|
||||||
|
expect(isRealUin('123456789')).toBe(true);
|
||||||
|
expect(isRealUin('4294967295')).toBe(true); // uint32 max, 10 digits
|
||||||
|
});
|
||||||
|
|
||||||
|
it('rejects the empty string and "0"', () => {
|
||||||
|
expect(isRealUin('')).toBe(false);
|
||||||
|
expect(isRealUin('0')).toBe(false);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('rejects too-short UINs (< 5 digits)', () => {
|
||||||
|
expect(isRealUin('1')).toBe(false);
|
||||||
|
expect(isRealUin('1234')).toBe(false);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('rejects the garbage timestamp-shaped UINs from issue #162 (11+ digits)', () => {
|
||||||
|
expect(isRealUin('1701414379536')).toBe(false); // 13-digit ms timestamp
|
||||||
|
expect(isRealUin('1614019567632')).toBe(false);
|
||||||
|
expect(isRealUin('2014024115056')).toBe(false);
|
||||||
|
expect(isRealUin('12345678901')).toBe(false); // 11 digits — first rejected width
|
||||||
|
});
|
||||||
|
|
||||||
|
it('rejects non-digit strings (path traversal / injection guards)', () => {
|
||||||
|
expect(isRealUin('12345a')).toBe(false);
|
||||||
|
expect(isRealUin('12 345')).toBe(false);
|
||||||
|
expect(isRealUin('../etc')).toBe(false);
|
||||||
|
expect(isRealUin('123456\n')).toBe(false);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('guarantees a BigInt-safe pure-digit string on accept', () => {
|
||||||
|
const uin = '123456789';
|
||||||
|
expect(isRealUin(uin)).toBe(true);
|
||||||
|
expect(() => BigInt(uin)).not.toThrow();
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -1,6 +1,7 @@
|
|||||||
import { createLogger } from '@snowluma/common/logger';
|
import { createLogger } from '@snowluma/common/logger';
|
||||||
import type { PacketSender } from '@snowluma/common/packet-sender';
|
import type { PacketSender } from '@snowluma/common/packet-sender';
|
||||||
import type { PacketInfo } from '@snowluma/common/protocol-types';
|
import type { PacketInfo } from '@snowluma/common/protocol-types';
|
||||||
|
import { isRealUin } from '@snowluma/common/uin';
|
||||||
import { IdentityService } from '@snowluma/protocol/identity-service';
|
import { IdentityService } from '@snowluma/protocol/identity-service';
|
||||||
import { Bridge } from './bridge';
|
import { Bridge } from './bridge';
|
||||||
|
|
||||||
@@ -72,13 +73,8 @@ export class BridgeManager {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
private static isRealUin(uin: string): boolean {
|
|
||||||
if (!uin || uin === '0') return false;
|
|
||||||
return /^\d+$/.test(uin) && uin.length >= 5;
|
|
||||||
}
|
|
||||||
|
|
||||||
onHookLogin(pid: number, uin: string, packetClient: PacketSender): void {
|
onHookLogin(pid: number, uin: string, packetClient: PacketSender): void {
|
||||||
if (!BridgeManager.isRealUin(uin)) return;
|
if (!isRealUin(uin)) return;
|
||||||
|
|
||||||
this.pidPacketClients_.set(pid, packetClient);
|
this.pidPacketClients_.set(pid, packetClient);
|
||||||
|
|
||||||
@@ -94,7 +90,7 @@ export class BridgeManager {
|
|||||||
}
|
}
|
||||||
|
|
||||||
onPacket(pkt: PacketInfo): void {
|
onPacket(pkt: PacketInfo): void {
|
||||||
if (!pkt.uin || !BridgeManager.isRealUin(pkt.uin)) return;
|
if (!pkt.uin || !isRealUin(pkt.uin)) return;
|
||||||
const uin = pkt.uin;
|
const uin = pkt.uin;
|
||||||
|
|
||||||
// Ensure session exists
|
// Ensure session exists
|
||||||
|
|||||||
@@ -3,6 +3,7 @@ import { closeLogger, createLogger } from '@snowluma/common/logger';
|
|||||||
import { loadRuntimeConfig } from '@snowluma/common/runtime';
|
import { loadRuntimeConfig } from '@snowluma/common/runtime';
|
||||||
import { OneBotManager } from '@snowluma/onebot/manager';
|
import { OneBotManager } from '@snowluma/onebot/manager';
|
||||||
import { migrateGlobalSettings } from '@snowluma/onebot/global-config';
|
import { migrateGlobalSettings } from '@snowluma/onebot/global-config';
|
||||||
|
import { cleanupInvalidPerUinConfigs } from '@snowluma/onebot/config';
|
||||||
import { BridgeManager } from './bridge/manager';
|
import { BridgeManager } from './bridge/manager';
|
||||||
import { createNotificationManager } from './notifications/manager';
|
import { createNotificationManager } from './notifications/manager';
|
||||||
import { createStateWiring } from './webui/state-wiring';
|
import { createStateWiring } from './webui/state-wiring';
|
||||||
@@ -33,6 +34,10 @@ async function main() {
|
|||||||
// any session (and thus any per-UIN config rewrite) can drop it.
|
// any session (and thus any per-UIN config rewrite) can drop it.
|
||||||
migrateGlobalSettings();
|
migrateGlobalSettings();
|
||||||
|
|
||||||
|
// One-shot: purge any persisted phantom accounts (onebot_<garbage>.json) the
|
||||||
|
// native hook may have created with a timestamp-shaped UIN (issue #162).
|
||||||
|
cleanupInvalidPerUinConfigs();
|
||||||
|
|
||||||
const bridgeManager = new BridgeManager();
|
const bridgeManager = new BridgeManager();
|
||||||
const oneBotManager = new OneBotManager();
|
const oneBotManager = new OneBotManager();
|
||||||
const autoLoadOnDiscovery = resolveAutoLoad(runtimeConfig.hookAutoLoad);
|
const autoLoadOnDiscovery = resolveAutoLoad(runtimeConfig.hookAutoLoad);
|
||||||
|
|||||||
@@ -101,9 +101,12 @@ export const SSE_TOKEN_QUERY_PATHS: ReadonlySet<string> = new Set([
|
|||||||
]);
|
]);
|
||||||
const TOKEN_QUERY_ALLOWLIST = SSE_TOKEN_QUERY_PATHS;
|
const TOKEN_QUERY_ALLOWLIST = SSE_TOKEN_QUERY_PATHS;
|
||||||
|
|
||||||
// uin = QQ number; 5–12 digits. Used to construct config file paths,
|
// uin = QQ number; 5–10 digits (real QQ UINs fit in uint32, max 4294967295).
|
||||||
// so we MUST refuse anything else (path traversal, NUL bytes, etc.).
|
// Used to construct config file paths, so we MUST refuse anything else (path
|
||||||
const UIN_REGEX = /^\d{5,12}$/;
|
// traversal, NUL bytes, etc.) — and the 10-digit cap also rejects the garbage
|
||||||
|
// timestamp-shaped UINs the native hook can emit (issue #162). Mirrors
|
||||||
|
// isRealUin in @snowluma/common/uin.
|
||||||
|
const UIN_REGEX = /^\d{5,10}$/;
|
||||||
|
|
||||||
const avatarCache = new Map<string, { body: Uint8Array; contentType: string; expiresAt: number }>();
|
const avatarCache = new Map<string, { body: Uint8Array; contentType: string; expiresAt: number }>();
|
||||||
|
|
||||||
|
|||||||
@@ -1,4 +1,5 @@
|
|||||||
import { createLogger } from '@snowluma/common/logger';
|
import { createLogger } from '@snowluma/common/logger';
|
||||||
|
import { isRealUin } from '@snowluma/common/uin';
|
||||||
import { randomBytes } from 'crypto';
|
import { randomBytes } from 'crypto';
|
||||||
import fs from 'fs';
|
import fs from 'fs';
|
||||||
import path from 'path';
|
import path from 'path';
|
||||||
@@ -105,6 +106,38 @@ function ensureConfigDir(): void {
|
|||||||
fs.mkdirSync(CONFIG_DIR, { recursive: true });
|
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 {
|
function toJsonObject(config: OneBotConfig): JsonObject {
|
||||||
const nets = config.networks;
|
const nets = config.networks;
|
||||||
return {
|
return {
|
||||||
|
|||||||
@@ -0,0 +1,60 @@
|
|||||||
|
import { afterEach, beforeEach, describe, expect, it } from 'vitest';
|
||||||
|
import fs from 'fs';
|
||||||
|
import os from 'os';
|
||||||
|
import path from 'path';
|
||||||
|
import { cleanupInvalidPerUinConfigs } from '../src/config';
|
||||||
|
|
||||||
|
// Issue #162: phantom accounts (garbage timestamp-shaped UIN) got persisted as
|
||||||
|
// config/onebot_<garbage>.json. Startup cleanup must delete exactly those and
|
||||||
|
// never touch legitimate per-UIN configs or the global onebot.json.
|
||||||
|
describe('cleanupInvalidPerUinConfigs', () => {
|
||||||
|
let tempDir: string;
|
||||||
|
let prevCwd: string;
|
||||||
|
|
||||||
|
beforeEach(() => {
|
||||||
|
tempDir = fs.mkdtempSync(path.join(os.tmpdir(), 'snowluma-config-cleanup-'));
|
||||||
|
prevCwd = process.cwd();
|
||||||
|
process.chdir(tempDir);
|
||||||
|
fs.mkdirSync('config', { recursive: true });
|
||||||
|
});
|
||||||
|
|
||||||
|
afterEach(() => {
|
||||||
|
process.chdir(prevCwd);
|
||||||
|
fs.rmSync(tempDir, { recursive: true, force: true });
|
||||||
|
});
|
||||||
|
|
||||||
|
const write = (name: string) => fs.writeFileSync(path.join('config', name), '{}');
|
||||||
|
const exists = (name: string) => fs.existsSync(path.join('config', name));
|
||||||
|
|
||||||
|
it('deletes only per-UIN files whose UIN fails validation', () => {
|
||||||
|
write('onebot.json'); // global — must survive
|
||||||
|
write('onebot_123456789.json'); // legit 9-digit — must survive
|
||||||
|
write('onebot_4294967295.json'); // legit 10-digit — must survive
|
||||||
|
write('onebot_1701414379536.json'); // 13-digit phantom — must go
|
||||||
|
write('onebot_12345678901.json'); // 11-digit phantom — must go
|
||||||
|
write('snowluma.json'); // unrelated global — must survive
|
||||||
|
|
||||||
|
const removed = cleanupInvalidPerUinConfigs().sort();
|
||||||
|
|
||||||
|
expect(removed).toEqual(['onebot_12345678901.json', 'onebot_1701414379536.json']);
|
||||||
|
expect(exists('onebot.json')).toBe(true);
|
||||||
|
expect(exists('onebot_123456789.json')).toBe(true);
|
||||||
|
expect(exists('onebot_4294967295.json')).toBe(true);
|
||||||
|
expect(exists('snowluma.json')).toBe(true);
|
||||||
|
expect(exists('onebot_1701414379536.json')).toBe(false);
|
||||||
|
expect(exists('onebot_12345678901.json')).toBe(false);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('is a no-op when there are no phantom files', () => {
|
||||||
|
write('onebot.json');
|
||||||
|
write('onebot_123456789.json');
|
||||||
|
expect(cleanupInvalidPerUinConfigs()).toEqual([]);
|
||||||
|
expect(exists('onebot_123456789.json')).toBe(true);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('does not throw when the config dir is absent', () => {
|
||||||
|
fs.rmSync('config', { recursive: true, force: true });
|
||||||
|
expect(() => cleanupInvalidPerUinConfigs()).not.toThrow();
|
||||||
|
expect(cleanupInvalidPerUinConfigs()).toEqual([]);
|
||||||
|
});
|
||||||
|
});
|
||||||
Reference in new issue
Block a user