refactor(packages): extract @snowluma/bridge (hook + QQ lifecycle)

Split the QQ NT client lifecycle / hook injection layer out of
@snowluma/core into its own self-contained package. The new bridge
package owns:
  - native hook addon loader (injector)
  - HookManager + per-PID HookSession orchestration
  - PipeWatcher for QQ process discovery
  - QqHookClient pipe protocol
  - qq-port-probe for early UIN sniffing

The hook layer used to type its main collaborator as
`BridgeManager` directly. To keep the new package free of any
dependency on @snowluma/core, the cross-package coupling is now
expressed via a 3-method `BridgeManagerSink` interface that lives
in the bridge package. BridgeManager (in core) satisfies the
interface structurally with no source changes; the top-level
app/webui still inject it the same way.

Pure file relocation otherwise: git mv preserves history at 100%
on every file, the only logic edit is the interface introduction
in hook-manager.ts and an updated `nativeSearchDirs()` offset
(one fewer `..` since hook now lives at packages/bridge/src
instead of packages/core/src/hook).
This commit is contained in:
DrSmoothl committed 2026-05-23 23:40:57 +08:00
1 parent c16064d7e3
commit f53df5e313
22 files changed
+161 -30

No files matched your search

+313
View File
@@ -0,0 +1,313 @@
import fs from 'fs';
import type { PacketSender } from '@snowluma/common/packet-sender';
import type { PacketInfo, PacketSink } from '@snowluma/common/protocol-types';
import { createLogger, type Logger } from '@snowluma/common/logger';
import {
injectHookProcess,
listHookProcesses,
unloadHookProcess,
type HookProcessBaseInfo,
} from './injector';
import { HookSession, type HookSessionDeps } from './hook-session';
import { PipeWatcher } from './pipe-watcher';
import { QqHookClient } from './qq-hook-client';
import type { HookProcessInfo } from './types';
import { probeQqLoginInfo, type QqPortLoginInfo } from './qq-port-probe';
export type { HookProcessInfo, HookProcessStatus } from './types';
export type { HookProcessBaseInfo } from './injector';
export type { QqPortLoginInfo } from './qq-port-probe';
/**
* Sink that the hook layer calls back into when it observes a new login,
* a parsed packet, or a PID disconnect. The concrete implementation lives
* in @snowluma/core (`BridgeManager`), which is wired in by the top-level
* app entry. Declaring it here keeps @snowluma/bridge free of any
* dependency on @snowluma/core — the hook package is self-contained.
*/
export interface BridgeManagerSink {
onHookLogin(pid: number, uin: string, packetClient: PacketSender): void;
onPacket(pkt: PacketInfo): void;
onPidDisconnected(pid: number): void;
}
export type HookManagerDeps = {
bridgeManager: BridgeManagerSink;
/** Sink for parsed packets from any live HookSession. Defaults to
* `bridgeManager.onPacket` — every packet flows straight into the
* per-UIN bridge dispatcher with no intermediate event emitter. */
onPacket?: PacketSink;
/** Native injector entrypoints. Defaults to the real native addon. */
injector?: HookSessionDeps['injector'];
/** Hook pipe-client factory. Defaults to `new QqHookClient(pid)`. */
makeClient?: HookSessionDeps['makeClient'];
/** Pre-built watcher. Defaults to a PipeWatcher wrapping the native listings. */
pipeWatcher?: PipeWatcher;
/** Polling interval for the default watcher. Ignored if `pipeWatcher` is provided. */
watcherIntervalMs?: number;
/** Native process lister used by `listProcesses()`. Defaults to the native addon. */
listProcesses?: () => HookProcessBaseInfo[];
/** When true, every newly-discovered QQ process is auto-injected (fires
* `loadProcess(pid)` from the watcher's 'process-discovered' handler).
* Failed loads are logged and leave the session in the 'error' state. */
autoLoadOnDiscovery?: boolean;
log?: Logger;
};
/**
* HookManager — thin orchestrator over a per-PID HookSession map and a
* singleton PipeWatcher.
*
* Responsibilities:
* - Route user commands (load/unload/refresh) to the matching session.
* - Route watcher diff events to the matching session.
* - Forward session events ('login' / 'disconnected') to BridgeManager.
* - Retry stuck-in-connecting sessions on every watcher tick (so a
* failed connect eventually recovers without a manual refresh).
*
* The native injector, native pipe-client, and native process/pipe
* listings are all swappable dependencies so tests can run without a
* real QQ.exe or a native addon.
*/
export class HookManager {
private readonly bridgeManager: BridgeManagerSink;
private readonly onPacket: PacketSink;
private readonly injector: HookSessionDeps['injector'];
private readonly makeClient: HookSessionDeps['makeClient'];
private readonly pipeWatcher: PipeWatcher;
private readonly ownsPipeWatcher: boolean;
private readonly listProcessesNative: () => HookProcessBaseInfo[];
private readonly autoLoadOnDiscovery: boolean;
private readonly log: Logger;
private readonly sessions = new Map<number, HookSession>();
private readonly startPromise: Promise<void>;
private disposed = false;
constructor(deps: HookManagerDeps) {
this.bridgeManager = deps.bridgeManager;
this.onPacket = deps.onPacket ?? ((pkt) => deps.bridgeManager.onPacket(pkt));
this.log = deps.log ?? createLogger('Hook');
this.injector = deps.injector ?? {
inject: injectHookProcess,
unload: (pid, handle) => {
if (!handle) return;
unloadHookProcess(pid, handle);
},
};
this.makeClient = deps.makeClient ?? ((pid: number) => new QqHookClient(pid));
this.listProcessesNative = deps.listProcesses ?? listHookProcesses;
this.autoLoadOnDiscovery = deps.autoLoadOnDiscovery ?? false;
if (deps.pipeWatcher) {
this.pipeWatcher = deps.pipeWatcher;
this.ownsPipeWatcher = false;
} else {
this.pipeWatcher = new PipeWatcher({
listProcesses: this.listProcessesNative,
listLivePipes: () => QqHookClient.listLivePipes(),
intervalMs: deps.watcherIntervalMs,
log: this.log,
});
this.ownsPipeWatcher = true;
}
this.bindWatcher();
this.startPromise = this.pipeWatcher.start();
}
// ─────────────── public API (unchanged from prior HookManager) ───────────────
async listProcesses(): Promise<HookProcessInfo[]> {
await this.startPromise;
let processes: HookProcessBaseInfo[];
try {
processes = this.listProcessesNative();
} catch (error) {
this.log.warn('listProcesses failed: %s', errMsg(error));
processes = [];
}
const result: HookProcessInfo[] = [];
for (const proc of processes) {
const session = this.ensureSession(proc.pid);
session.attachProcessInfo(proc);
result.push(session.toInfo());
}
return result.sort((a, b) => a.pid - b.pid);
}
async loadProcess(pid: number): Promise<HookProcessInfo> {
this.assertValidPid(pid);
await this.startPromise;
const session = this.ensureSession(pid);
const info = await session.load();
// Pull the next tick forward so a freshly-injected pipe gets noticed
// within the next event-loop turn instead of after the full interval.
this.pipeWatcher.wake();
return info;
}
async unloadProcess(pid: number): Promise<HookProcessInfo> {
this.assertValidPid(pid);
await this.startPromise;
const session = this.ensureSession(pid);
return session.unload();
}
async refreshProcess(pid: number): Promise<HookProcessInfo> {
this.assertValidPid(pid);
await this.startPromise;
const session = this.ensureSession(pid);
return session.refresh();
}
async probeProcessLoginInfo(pid: number): Promise<QqPortLoginInfo | null> {
this.assertValidPid(pid);
return probeQqLoginInfo(pid);
}
dispose(): void {
if (this.disposed) return;
this.disposed = true;
for (const session of this.sessions.values()) {
session.dispose();
}
this.sessions.clear();
if (this.ownsPipeWatcher) {
this.pipeWatcher.dispose();
}
}
// ─────────────── wiring ───────────────
private bindWatcher(): void {
this.pipeWatcher.on('process-discovered', (info: HookProcessBaseInfo) => {
if (this.disposed) return;
const session = this.ensureSession(info.pid);
session.attachProcessInfo(info);
// Headless/Docker deployments enable autoLoadOnDiscovery so QQ gets
// injected without a human clicking "Load" in WebUI. Fire-and-forget:
// failures are already captured inside loadInternal and surfaced via
// the session's status field.
if (this.autoLoadOnDiscovery && shouldAutoLoadPid(info.pid, this.log)) {
void session.load().catch((err) => {
this.log.warn('auto-load failed: PID=%d err=%s', info.pid, errMsg(err));
});
}
});
this.pipeWatcher.on('process-gone', (pid: number) => {
if (this.disposed) return;
const session = this.sessions.get(pid);
if (session) session.notifyProcessGone();
});
this.pipeWatcher.on('pipe-up', (pid: number) => {
if (this.disposed) return;
const session = this.sessions.get(pid);
if (session) session.onPipeUp();
});
this.pipeWatcher.on('pipe-down', (pid: number) => {
if (this.disposed) return;
const session = this.sessions.get(pid);
if (session) session.onPipeDown();
});
// After every tick, retry sessions that are stuck in 'connecting' OR
// 'disconnected' while the pipe is up. Mirrors the original
// tickWatcher's per-tick reconcileConnect pass; onPipeUp is idempotent
// so calling it for an already-connected session is harmless.
//
// The 'disconnected' branch matters on Windows: when the QQ-NT side of
// the named pipe stays alive but the SnowLuma-side socket dies (read
// EPIPE / idle-timeout / similar transient I/O fault), the watcher
// sees the pipe as still-live (the OS-level pipe is still listed by
// `listLivePipes`) so it never fires another `pipe-up`. Without
// retrying 'disconnected' sessions here the session is stranded
// forever — a real-world symptom users reported as "Windows running
// for a while then stops" with logs `pipe error: read EPIPE` →
// `session closed: UIN=…`.
this.pipeWatcher.on('tick', () => {
if (this.disposed) return;
for (const session of this.sessions.values()) {
if ((session.status === 'connecting' || session.status === 'disconnected')
&& this.pipeWatcher.isPipeLive(session.pid)) {
session.onPipeUp();
}
}
});
}
private ensureSession(pid: number): HookSession {
let session = this.sessions.get(pid);
if (session) return session;
session = new HookSession(pid, {
injector: this.injector,
makeClient: this.makeClient,
pipeWatcher: this.pipeWatcher,
onPacket: this.onPacket,
log: this.log,
});
session.attachProcessInfo({ name: defaultProcessName() });
session.on('login', (uin: string, sender) => {
this.bridgeManager.onHookLogin(pid, uin, sender);
});
session.on('disconnected', (wasLoggedIn: boolean) => {
if (wasLoggedIn) this.bridgeManager.onPidDisconnected(pid);
});
session.on('disposed', () => {
this.sessions.delete(pid);
});
this.sessions.set(pid, session);
return session;
}
private assertValidPid(pid: number): void {
if (!Number.isInteger(pid) || pid <= 0) throw new Error('invalid pid');
}
}
function defaultProcessName(): string {
return process.platform === 'win32' ? 'QQ.exe' : 'qq';
}
function errMsg(value: unknown): string {
return value instanceof Error ? value.message : String(value);
}
/**
* Filter for auto-load only. Returns false for Linux Electron child
* processes (zygote/renderer/gpu/utility), which the native enumerator
* mis-classifies as "main QQ" because their cmdline contains "qq" and
* they transiently inherit wrapper.node via fork copy-on-write.
*
* Injecting into a zygote spawns the hook's resolver thread inside it;
* every renderer Electron later forks then inherits that thread + the
* partially-init'd hook state, which breaks QQ's IPC and login UI.
*
* Manual loadProcess() bypasses this gate — the operator is responsible
* for picking the right PID from WebUI.
*/
export function shouldAutoLoadPid(pid: number, log: Logger): boolean {
if (process.platform !== 'linux') return true;
// Escape hatch: operators who explicitly want auto-load on every
// enumerated PID can set this to opt out of the filter.
if (process.env.SNOWLUMA_HOOK_AUTOLOAD_ALL === '1') return true;
let cmdline: string;
try {
cmdline = fs.readFileSync(`/proc/${pid}/cmdline`, 'utf8');
} catch {
// Can't read cmdline (process gone, permission, etc.) — let the
// existing load() path handle it; if the process is dead the load
// will fail with a clear error.
return true;
}
if (cmdline.includes('--type=')) {
const type = (/--type=([^\0\s]+)/.exec(cmdline)?.[1]) ?? 'unknown';
log.info('auto-load skip: PID=%d is an Electron child process (--type=%s)', pid, type);
return false;
}
return true;
}
+34
View File
@@ -0,0 +1,34 @@
import type { PacketSender, SendPacketResult } from '@snowluma/common/packet-sender';
import { QqHookClient, type QqHookSendReply } from './qq-hook-client';
export class HookPacketClient implements PacketSender {
constructor(private readonly client: QqHookClient) {}
async sendPacket(serviceCmd: string, body: Buffer, timeoutMs = 15000): Promise<SendPacketResult> {
if (!this.client.isLoggedIn) {
return { success: false, gotResponse: false, errorCode: -1, errorMessage: 'qq_hook client is not logged in', responseData: null };
}
try {
const reply = await this.client.send(serviceCmd, body, {
wantReply: true,
replyTimeoutMs: timeoutMs,
}) as QqHookSendReply;
return {
success: reply.error === 0,
gotResponse: true,
errorCode: reply.error,
errorMessage: reply.message || '',
responseData: reply.body,
};
} catch (error) {
return {
success: false,
gotResponse: false,
errorCode: -1,
errorMessage: error instanceof Error ? error.message : String(error),
responseData: null,
};
}
}
}
+439
View File
@@ -0,0 +1,439 @@
import { EventEmitter } from 'events';
import type { PacketSink } from '@snowluma/common/protocol-types';
import { createLogger, type Logger } from '@snowluma/common/logger';
import { HookPacketClient } from './hook-packet-client';
import type { HookInjectResult } from './injector';
import type { QqHookClient, QqHookLoginState, QqHookPacket } from './qq-hook-client';
import type { HookProcessInfo, HookProcessStatus } from './types';
export type HookSessionDeps = {
injector: {
inject: (pid: number) => HookInjectResult;
unload: (pid: number, handle: HookInjectResult['handle']) => void;
};
makeClient: (pid: number) => QqHookClient;
/** Sync fast-path check used by load() to skip re-injection when a
* prior SnowLuma run left a working pipe behind. `tickNow` forces a
* fresh poll — used after unload to dodge the up-to-1500ms cache
* staleness that would otherwise false-flag a successful unload. */
pipeWatcher: {
isPipeLive: (pid: number) => boolean;
tickNow?: () => Promise<void>;
};
/** Sink for parsed packets. Called with the BridgeManager-shaped
* PacketInfo for every packet received while logged in. If omitted,
* packets are dropped (useful in unit tests that don't care). */
onPacket?: PacketSink;
log?: Logger;
};
/**
* HookSession — owns the lifecycle of one QQ.exe process: injection,
* pipe client, login state, and the public status field.
*
* Concurrency: every state-mutating method goes through a per-session
* promise chain so user clicks (load/unload/refresh) and watcher-driven
* events (onPipeUp/onPipeDown) never interleave.
*
* Communication: emits high-level events instead of calling BridgeManager
* directly, so HookManager forwards them and tests can attach spies.
*
* Emitted events:
* 'login' (uin, packetSender) — real-UIN login detected
* 'disconnected' (wasLoggedIn) — connection dropped or torn down
* 'status-changed' (status, error) — status field mutated
* 'disposed' () — session stopped tracking this PID
*/
export class HookSession extends EventEmitter {
readonly pid: number;
private readonly injector: HookSessionDeps['injector'];
private readonly makeClient: HookSessionDeps['makeClient'];
private readonly pipeWatcher: HookSessionDeps['pipeWatcher'];
private readonly onPacket: PacketSink | null;
private readonly log: Logger;
private _status: HookProcessStatus = 'available';
private _error = '';
private _uin = '0';
private _method = '';
private _name = '';
private _path = '';
private injected = false;
private connected = false;
private loggedIn = false;
private injectResult: HookInjectResult | null = null;
private client: QqHookClient | null = null;
private sender: HookPacketClient | null = null;
private bound = false;
private opChain: Promise<unknown> = Promise.resolve();
private disposed = false;
constructor(pid: number, deps: HookSessionDeps) {
super();
this.pid = pid;
this.injector = deps.injector;
this.makeClient = deps.makeClient;
this.pipeWatcher = deps.pipeWatcher;
this.onPacket = deps.onPacket ?? null;
this.log = deps.log ?? createLogger('HookSession');
}
// ─────────────── readonly public surface ───────────────
get status(): HookProcessStatus { return this._status; }
get error(): string { return this._error; }
get uin(): string { return this._uin; }
get method(): string { return this._method; }
get isDisposed(): boolean { return this.disposed; }
attachProcessInfo(info: { name?: string; path?: string }): void {
if (info.name) this._name = info.name;
if (info.path) this._path = info.path;
}
toInfo(): HookProcessInfo {
return {
pid: this.pid,
name: this._name,
path: this._path,
injected: this.injected,
connected: this.connected,
loggedIn: this.loggedIn,
uin: this._uin,
status: this._status,
error: this._error,
method: this._method,
};
}
// ─────────────── user-facing commands ───────────────
load(): Promise<HookProcessInfo> {
return this.serialize(() => this.loadInternal());
}
unload(): Promise<HookProcessInfo> {
return this.serialize(() => this.unloadInternal());
}
refresh(): Promise<HookProcessInfo> {
return this.serialize(() => this.refreshInternal());
}
// ─────────────── watcher-driven events (called by manager) ───────────────
/** Pipe came up (or stayed up across a SnowLuma restart). Drives connect
* attempts and adopts pre-existing hooks. Idempotent; safe to call on
* every watcher tick where the pipe is live. */
onPipeUp(): void {
if (this.disposed) return;
void this.serialize(async () => {
if (this.disposed) return;
// Adopt a DLL that survived a SnowLuma restart.
if (!this.injected) {
this.injected = true;
if (!this._method) this._method = 'reconnect';
}
if (this.client?.isClosed) this.tearDownClient();
if (!this.connected) {
await this.attemptConnect();
} else {
this.setStatus(this.loggedIn ? 'online' : 'loaded', '');
}
}).catch(err => this.log.warn('onPipeUp failed: PID=%d err=%s', this.pid, errMsg(err)));
}
onPipeDown(): void {
if (this.disposed) return;
void this.serialize(async () => {
if (this.disposed) return;
if (!this.connected) {
// Nothing to tear down; just keep status visible.
if (this.injected) this.setStatus('connecting', this._error);
return;
}
const wasLoggedIn = this.loggedIn;
this.tearDownClient();
this.setStatus(
this.injected ? (wasLoggedIn ? 'disconnected' : 'connecting') : 'available',
'',
);
if (wasLoggedIn) this.emit('disconnected', true);
}).catch(err => this.log.warn('onPipeDown failed: PID=%d err=%s', this.pid, errMsg(err)));
}
/** Called by the manager when the watcher reports the QQ.exe process is
* gone. Cleans up and signals the manager to remove this session. */
notifyProcessGone(): void {
if (this.disposed) return;
void this.serialize(async () => {
if (this.disposed) return;
const wasLoggedIn = this.loggedIn;
this.tearDownClient();
this.injected = false;
this.injectResult = null;
this._method = '';
this.setStatus('available', '');
if (wasLoggedIn) this.emit('disconnected', true);
this.disposed = true;
this.emit('disposed');
this.removeAllListeners();
}).catch(err => this.log.warn('notifyProcessGone failed: PID=%d err=%s', this.pid, errMsg(err)));
}
dispose(): void {
if (this.disposed) return;
this.disposed = true;
this.tearDownClient();
this.removeAllListeners();
}
// ─────────────── per-session serialization ───────────────
private serialize<T>(op: () => Promise<T>): Promise<T> {
const previous = this.opChain;
let release!: () => void;
const completion = new Promise<void>(resolve => { release = resolve; });
this.opChain = previous.then(() => completion);
return (async () => {
try {
await previous.catch(() => undefined);
return await op();
} finally {
release();
}
})();
}
// ─────────────── internal transitions ───────────────
private async loadInternal(): Promise<HookProcessInfo> {
this._error = '';
this.setStatus('loading', '');
try {
if (!this.injected) {
// Fast path: a previous SnowLuma run may have left the hook DLL
// resident in QQ.exe. If the watcher already sees a live pipe,
// skip re-injection and let onPipeUp drive the reconnect.
if (this.pipeWatcher.isPipeLive(this.pid)) {
this.injected = true;
this._method = this._method || 'reconnect';
this.log.info('PID=%d already has SnowLuma pipe; will reconnect', this.pid);
} else {
this.injectResult = this.injector.inject(this.pid);
this.injected = true;
this._method = this.injectResult.method;
}
}
this.setStatus(
this.connected ? (this.loggedIn ? 'online' : 'loaded') : 'connecting',
'',
);
} catch (error) {
this._error = errMsg(error);
this.setStatus('error', this._error);
this.log.error('load failed: PID=%d err=%s', this.pid, this._error);
}
return this.toInfo();
}
private async unloadInternal(): Promise<HookProcessInfo> {
this._error = '';
try {
const wasLoggedIn = this.loggedIn;
this.tearDownClient();
if (wasLoggedIn) this.emit('disconnected', true);
const handle = this.injectResult?.handle;
if (this.injected && handle) {
this.injector.unload(this.pid, handle);
this.log.info('SnowLuma unloaded from PID=%d', this.pid);
}
this.injected = false;
this.injectResult = null;
this._method = '';
this._uin = '0';
// Verify the unload took: if the pipe is still up the DLL is still
// resident. The cached snapshot is up to 1500ms stale and we just
// changed the world, so force a fresh poll first — otherwise even
// a successful unload reads as "pipe still live" until the next
// background tick runs and we'd report a spurious failure.
await this.pipeWatcher.tickNow?.();
if (this.pipeWatcher.isPipeLive(this.pid)) {
this._error = 'DLL卸载失败:命名管道仍然存在,watcher将自动重连';
this.setStatus('connecting', this._error);
this.log.warn('unload verification failed: PID=%d pipe still up', this.pid);
} else {
this.setStatus('available', '');
}
} catch (error) {
this._error = errMsg(error);
this.setStatus('error', this._error);
this.log.error('unload failed: PID=%d err=%s', this.pid, this._error);
}
return this.toInfo();
}
private async refreshInternal(): Promise<HookProcessInfo> {
this._error = '';
try {
const pipeUp = this.pipeWatcher.isPipeLive(this.pid);
if (pipeUp) {
// Adopt an unknown DLL the same way onPipeUp would.
if (!this.injected) {
this.injected = true;
this._method = this._method || 'reconnect';
}
if (this.client?.isClosed) this.tearDownClient();
if (!this.connected) {
await this.attemptConnect();
} else {
this.setStatus(this.loggedIn ? 'online' : 'loaded', '');
}
} else {
const wasLoggedIn = this.loggedIn;
this.tearDownClient();
this.setStatus(this.injected ? 'disconnected' : 'available', '');
if (wasLoggedIn) this.emit('disconnected', true);
}
} catch (error) {
this._error = errMsg(error);
this.setStatus(this.injected ? 'disconnected' : 'error', this._error);
this.log.warn('refresh failed: PID=%d err=%s', this.pid, this._error);
}
return this.toInfo();
}
// ─────────────── client plumbing ───────────────
private async attemptConnect(): Promise<void> {
if (this.connected) return;
if (this.client?.isClosed) this.tearDownClient();
if (!this.client) {
this.client = this.makeClient(this.pid);
this.sender = new HookPacketClient(this.client);
this.bound = false;
}
if (!this.bound) {
this.bindClient(this.client);
this.bound = true;
}
const client = this.client;
try {
await client.connectAll({ recv: true });
this.connected = true;
this.setStatus(client.isLoggedIn ? 'online' : 'loaded', '');
const loginState = client.getLoginState();
if (loginState.loggedIn) this.handleLoginState(loginState);
this.log.info('pipe connected: PID=%d', this.pid);
} catch (error) {
this._error = errMsg(error);
// Drop the client so the next attempt builds a fresh socket pair.
this.tearDownClient();
this.setStatus(this.injected ? 'connecting' : 'available', this._error);
}
}
private bindClient(client: QqHookClient): void {
client.on('packet', packet => this.handlePacket(packet));
client.on('loginState', state => this.handleLoginState(state));
client.on('error', error => {
const msg = errMsg(error);
this._error = msg;
this.log.warn('pipe error: PID=%d err=%s', this.pid, msg);
});
client.on('close', () => {
if (this.disposed) return;
// Only the currently-registered client should drive a reconcile;
// listeners may fire for an already-replaced client.
if (this.client !== client) return;
void this.serialize(async () => {
if (this.disposed) return;
if (this.client !== client) return;
const wasLoggedIn = this.loggedIn;
this.tearDownClient();
if (!this.injected) {
this.setStatus('available', '');
} else if (wasLoggedIn) {
this.setStatus('disconnected', '');
} else {
this.setStatus('connecting', '');
}
if (wasLoggedIn) this.emit('disconnected', true);
}).catch(err => this.log.warn('close reconcile failed: PID=%d err=%s', this.pid, errMsg(err)));
});
}
private tearDownClient(): void {
const client = this.client;
if (client) {
client.removeAllListeners();
try { client.close(); } catch { /* ignore */ }
}
this.client = null;
this.sender = null;
this.bound = false;
this.connected = false;
this.loggedIn = false;
}
private handleLoginState(state: QqHookLoginState): void {
const wasLoggedIn = this.loggedIn;
const previousUin = this._uin;
this._uin = state.uin || state.uinNumber.toString();
this.loggedIn = state.loggedIn && isRealUin(this._uin);
if (this.loggedIn) {
this.setStatus('online', '');
} else if (this.connected) {
this.setStatus('loaded', this._error);
}
if (!this.loggedIn || !this.sender) return;
if (wasLoggedIn && previousUin === this._uin) return;
this.emit('login', this._uin, this.sender);
this.log.success('login detected: PID=%d UIN=%s', this.pid, this._uin);
}
private handlePacket(packet: QqHookPacket): void {
if (!this.loggedIn) return;
const uin = packet.uin || this._uin;
if (!isRealUin(uin)) return;
if (!this.onPacket) return;
// Re-shape the hook-client wire packet into BridgeManager's PacketInfo
// shape. Used to live in the deleted NtqqHandler.onHookPacket; field
// renaming was that module's entire purpose, so it lives at the source
// now (no need for a single-listener event-emitter in between).
this.onPacket({
pid: this.pid,
uin,
serviceCmd: packet.cmd,
seqId: packet.seq,
retCode: packet.error,
fromClient: false,
body: Buffer.from(packet.body),
});
}
private setStatus(status: HookProcessStatus, error: string): void {
if (this._status === status && this._error === error) return;
this._status = status;
this._error = error;
this.emit('status-changed', status, error);
}
}
function isRealUin(uin: string): boolean {
if (!uin || uin === '0') return false;
return /^\d+$/.test(uin) && uin.length >= 5;
}
function errMsg(value: unknown): string {
return value instanceof Error ? value.message : String(value);
}
+13
View File
@@ -0,0 +1,13 @@
// Public entry — re-exports the hook orchestration surface that the
// top-level app (and webui readers) consume. Everything else is
// internal to the package.
export {
HookManager,
type HookManagerDeps,
type BridgeManagerSink,
type HookProcessInfo,
type HookProcessStatus,
type HookProcessBaseInfo,
type QqPortLoginInfo,
} from './hook-manager';
+128
View File
@@ -0,0 +1,128 @@
import { existsSync } from 'fs';
import path from 'path';
import { fileURLToPath } from 'url';
const __dirname = path.dirname(fileURLToPath(import.meta.url));
export interface ManualMapHandle {
base: bigint;
entry: bigint;
exceptionTable: bigint;
size: number;
}
interface NativeHookAddon {
getAllMainProcess(): number[];
loadModuleManual(pid: number, dylibPath: string): ManualMapHandle;
unloadModuleManual(pid: number, handle: ManualMapHandle): void;
}
export interface HookProcessBaseInfo {
pid: number;
name: string;
path: string;
}
export interface HookInjectResult {
method: 'loadModuleManual';
handle?: ManualMapHandle;
}
let nativeAddon: NativeHookAddon | null = null;
let nativeLoadError: string | null = null;
function loadNativeAddon(addonPath: string): NativeHookAddon {
const mod = { exports: {} as Record<string, unknown> };
process.dlopen(mod, addonPath);
return mod.exports as unknown as NativeHookAddon;
}
type HookBinaryExt = 'node' | 'dll' | 'so';
function platformBinaryName(ext: HookBinaryExt): string {
if (process.platform === 'win32' && process.arch === 'x64') return `snowluma-win32-x64.${ext}`;
return `snowluma-${process.platform}-${process.arch}.${ext}`;
}
function platformInjectableExt(): 'dll' | 'so' {
return process.platform === 'win32' ? 'dll' : 'so';
}
function defaultProcessName(): string {
return process.platform === 'win32' ? 'QQ.exe' : 'qq';
}
function nativeSearchDirs(): string[] {
// Several layouts must be supported:
// 1. Released zip (flattened dist/): __dirname=<extracted>/, native at <extracted>/native
// 2. Dev via tsx (packages/bridge/src/injector.ts): __dirname=<root>/packages/bridge/src
// → walk up to <root>/packages and append runtime/native
// Same offset works for `packages/bridge/dist/index.mjs` after build.
// 3. cwd-based fallback when neither __dirname-relative path resolves.
return [
path.resolve(__dirname, 'native'),
path.resolve(__dirname, '..', '..', 'runtime', 'native'),
path.resolve(process.cwd(), 'dist', 'native'),
path.resolve(process.cwd(), 'packages', 'runtime', 'native'),
];
}
export function resolveHookNativePath(ext: HookBinaryExt): string | null {
const fileName = platformBinaryName(ext);
for (const dir of nativeSearchDirs()) {
const fullPath = path.join(dir, fileName);
if (existsSync(fullPath)) return fullPath;
}
return null;
}
export function getNativeHookAddon(): NativeHookAddon | null {
if (nativeAddon) return nativeAddon;
const addonPath = resolveHookNativePath('node');
if (!addonPath) {
nativeLoadError = `No hook native addon found for ${process.platform}-${process.arch}`;
return null;
}
try {
nativeAddon = loadNativeAddon(addonPath);
nativeLoadError = null;
return nativeAddon;
} catch (error) {
nativeLoadError = error instanceof Error ? error.message : String(error);
return null;
}
}
export function getNativeHookLoadError(): string | null {
return nativeLoadError;
}
export function listHookProcesses(): HookProcessBaseInfo[] {
const addon = getNativeHookAddon();
if (!addon) return [];
return [...new Set(addon.getAllMainProcess())]
.filter(pid => Number.isInteger(pid) && pid > 0)
.sort((a, b) => a - b)
.map(pid => ({ pid, name: defaultProcessName(), path: '' }));
}
export function injectHookProcess(pid: number): HookInjectResult {
const addon = getNativeHookAddon();
if (!addon) {
throw new Error(getNativeHookLoadError() ?? 'hook native addon is not available');
}
const injectableExt = platformInjectableExt();
const dllPath = resolveHookNativePath(injectableExt);
if (!dllPath) {
throw new Error(`No hook ${injectableExt} found for ${process.platform}-${process.arch}`);
}
return { method: 'loadModuleManual', handle: addon.loadModuleManual(pid, dllPath) };
}
export function unloadHookProcess(pid: number, handle: ManualMapHandle): void {
const addon = getNativeHookAddon();
if (!addon) {
throw new Error(getNativeHookLoadError() ?? 'hook native addon is not available');
}
addon.unloadModuleManual(pid, handle);
}
+208
View File
@@ -0,0 +1,208 @@
import { EventEmitter } from 'events';
import { createLogger, type Logger } from '@snowluma/common/logger';
import type { HookProcessBaseInfo } from './injector';
const DEFAULT_INTERVAL_MS = 1500;
const MIN_INTERVAL_MS = 250;
export type PipeWatcherDeps = {
/** Native: list QQ.exe processes currently running. */
listProcesses: () => HookProcessBaseInfo[];
/** Native: PIDs that currently have a live SnowLuma named pipe. */
listLivePipes: () => Promise<Set<number>>;
/** Polling interval in ms. Defaults to 1500, floored to 250. */
intervalMs?: number;
log?: Logger;
};
/**
* PipeWatcher — the only module that polls the OS for QQ.exe processes
* and live SnowLuma named pipes. Subscribers consume diffs as events.
*
* Lifecycle: start() runs one tick synchronously, then schedules a poll
* every `intervalMs`. tickNow() drains a single tick on demand. wake()
* pulls the next scheduled tick forward to the next event-loop turn.
*
* Emitted events:
* 'process-discovered' (info: HookProcessBaseInfo) — a QQ.exe appeared
* 'process-gone' (pid: number) — a QQ.exe disappeared
* 'pipe-up' (pid: number) — named pipe came up
* 'pipe-down' (pid: number) — named pipe dropped
* 'tick' () — fired after every poll
*
* Within a single tick the order is: process-discovered, pipe-up,
* pipe-down, process-gone, tick. That ordering lets HookManager create
* a session before it gets a pipe event and run disconnect logic before
* dispose logic when QQ.exe is killed with a live pipe.
*/
export class PipeWatcher extends EventEmitter {
private readonly listProcesses: PipeWatcherDeps['listProcesses'];
private readonly listLivePipes: PipeWatcherDeps['listLivePipes'];
private readonly intervalMs: number;
private readonly log: Logger;
private livePipes = new Set<number>();
private knownPids = new Set<number>();
private timer: NodeJS.Timeout | null = null;
private ticking = false;
private pendingWake = false;
private startPromise: Promise<void> | null = null;
private stopped = false;
constructor(deps: PipeWatcherDeps) {
super();
this.listProcesses = deps.listProcesses;
this.listLivePipes = deps.listLivePipes;
this.intervalMs = Math.max(MIN_INTERVAL_MS, deps.intervalMs ?? DEFAULT_INTERVAL_MS);
this.log = deps.log ?? createLogger('PipeWatcher');
}
/** Was this PID's pipe live as of the last completed tick? */
isPipeLive(pid: number): boolean {
return this.livePipes.has(pid);
}
/** Was this PID alive as of the last completed tick? */
isProcessAlive(pid: number): boolean {
return this.knownPids.has(pid);
}
/**
* Run an initial tick (so isPipeLive/isProcessAlive return real data)
* and begin the polling loop. Idempotent.
*/
start(): Promise<void> {
if (this.startPromise) return this.startPromise;
this.startPromise = (async () => {
try {
await this.tickOnce();
} finally {
this.scheduleNext(this.intervalMs);
}
})();
return this.startPromise;
}
/** Pull the next scheduled tick forward to the next event-loop turn. */
wake(): void {
if (this.stopped) return;
this.scheduleNext(0);
}
/** Force a single tick now. Resolves after diff events have been emitted. */
tickNow(): Promise<void> {
return this.tickOnce();
}
stop(): void {
this.stopped = true;
if (this.timer) {
clearTimeout(this.timer);
this.timer = null;
}
}
dispose(): void {
this.stop();
this.removeAllListeners();
}
private scheduleNext(delayMs: number): void {
if (this.stopped) return;
if (this.timer) {
clearTimeout(this.timer);
this.timer = null;
}
this.timer = setTimeout(() => {
this.timer = null;
void this.tickAndReschedule();
}, Math.max(0, delayMs));
}
private async tickAndReschedule(): Promise<void> {
try {
await this.tickOnce();
} finally {
this.scheduleNext(this.intervalMs);
}
}
/**
* Read processes + live pipes, emit diff events. If another tick is
* already running, mark a follow-up tick so we don't lose a wake().
*/
private async tickOnce(): Promise<void> {
if (this.ticking) {
this.pendingWake = true;
return;
}
this.ticking = true;
try {
let processes: HookProcessBaseInfo[];
try {
processes = this.listProcesses();
} catch (error) {
this.log.warn('listProcesses failed: %s', errMsg(error));
processes = [];
}
let livePipes: Set<number>;
try {
livePipes = await this.listLivePipes();
} catch (error) {
this.log.warn('listLivePipes failed: %s', errMsg(error));
livePipes = new Set();
}
const newKnownPids = new Set<number>();
for (const proc of processes) newKnownPids.add(proc.pid);
// 1. Newly discovered processes.
for (const proc of processes) {
if (!this.knownPids.has(proc.pid)) {
this.emit('process-discovered', proc);
}
}
// 2. Pipes that came up. Ignore pipes for processes we don't know
// about (would race against an out-of-order tick).
const newLivePipes = new Set<number>();
for (const pid of livePipes) {
if (!newKnownPids.has(pid)) continue;
newLivePipes.add(pid);
if (!this.livePipes.has(pid)) {
this.emit('pipe-up', pid);
}
}
// 3. Pipes that dropped. Emit pipe-down BEFORE process-gone so
// subscribers can run disconnect logic before dispose logic.
for (const pid of this.livePipes) {
if (!newLivePipes.has(pid)) {
this.emit('pipe-down', pid);
}
}
// 4. Processes that disappeared.
for (const pid of this.knownPids) {
if (!newKnownPids.has(pid)) {
this.emit('process-gone', pid);
}
}
this.knownPids = newKnownPids;
this.livePipes = newLivePipes;
this.emit('tick');
} finally {
this.ticking = false;
if (this.pendingWake) {
this.pendingWake = false;
// Defer to break sync recursion if a listener calls wake().
setImmediate(() => { void this.tickOnce(); });
}
}
}
}
function errMsg(value: unknown): string {
return value instanceof Error ? value.message : String(value);
}
+775
View File
@@ -0,0 +1,775 @@
import net from 'net';
import os from 'os';
import path from 'path';
import { promises as fs } from 'fs';
import { EventEmitter } from 'events';
export const PIPE_MAGIC = 0x31504851;
export const PIPE_VERSION = 1;
export const HEADER_SIZE = 40;
export const DEFAULT_ACK_TIMEOUT_MS = 5000;
export const DEFAULT_REPLY_TIMEOUT_MS = 30000;
const DEFAULT_PIPE_PROBE_TIMEOUT_MS = 250;
export enum PipeOp {
hello = 1,
sendRequest = 2,
sendAck = 3,
sendReply = 4,
error = 5,
recvPacket = 6,
loginState = 7,
}
const PipeFlagWantReply = 1 << 0;
const PipeFlagLoggedIn = 1 << 2;
export interface QqHookLoginState {
loggedIn: boolean;
uin: string;
uinNumber: bigint;
}
export interface QqHookPacket {
seq: number;
error: number;
cmd: string;
uin: string;
body: Buffer;
}
export interface QqHookHello {
pipeName: string;
pid: number;
recvPipe: boolean;
}
export interface QqHookSendReply {
requestId: number;
error: number;
message: string;
body: Buffer;
}
export interface QqHookClientOptions {
ackTimeoutMs?: number;
replyTimeoutMs?: number;
}
export interface QqHookSendOptions {
wantReply?: boolean;
ackTimeoutMs?: number;
replyTimeoutMs?: number;
}
interface PipeFrame {
op: number;
requestId: number;
status: number;
flags: number;
value0: bigint;
cmd: string;
msg: string;
body: Buffer;
}
interface Deferred<T> {
promise: Promise<T>;
resolve: (value: T | PromiseLike<T>) => void;
reject: (reason?: unknown) => void;
}
interface PendingAck {
resolve: (value: { requestId: number; wantReply: boolean }) => void;
reject: (reason?: unknown) => void;
wantReply: boolean;
}
function linuxRuntimeDir(): string {
const explicit = process.env.SNOWLUMA_HOOK_RUNTIME_DIR;
if (explicit && explicit.length > 0) return explicit;
const xdg = process.env.XDG_RUNTIME_DIR;
if (xdg && xdg.length > 0) return xdg;
// Mirrors hook_stub.cpp runtime_dir() fallback.
// process.geteuid is POSIX-only; cast to allow non-Linux type checks.
const uid = typeof process.geteuid === 'function' ? process.geteuid() : os.userInfo().uid;
return `/tmp/snowluma-${uid}`;
}
function mojoPipeName(pid: number, suffix: string): string {
if (process.platform === 'win32') {
return `\\\\.\\pipe\\mojo.${pid}.${suffix}`;
}
return path.join(linuxRuntimeDir(), `mojo.${pid}.${suffix}.sock`);
}
type LinuxPipeProbe = (socketPath: string) => Promise<boolean>;
async function isConnectableUnixSocket(socketPath: string): Promise<boolean> {
try {
const stat = await fs.stat(socketPath);
if (!stat.isSocket()) return false;
} catch {
return false;
}
return new Promise<boolean>((resolve) => {
let socket: net.Socket;
try {
socket = net.createConnection(socketPath);
} catch {
resolve(false);
return;
}
let done = false;
let timer: NodeJS.Timeout;
const finish = (ok: boolean) => {
if (done) return;
done = true;
clearTimeout(timer);
socket.removeAllListeners();
socket.destroy();
resolve(ok);
};
timer = setTimeout(() => finish(false), DEFAULT_PIPE_PROBE_TIMEOUT_MS);
socket.once('connect', () => finish(true));
socket.once('error', () => finish(false));
});
}
export async function listLiveLinuxPipePids(
runtimeDir = linuxRuntimeDir(),
probe: LinuxPipeProbe = isConnectableUnixSocket,
): Promise<Set<number>> {
const result = new Set<number>();
let names: string[];
try {
names = await fs.readdir(runtimeDir);
} catch {
return result;
}
await Promise.all(names.map(async (name) => {
const m = /^mojo\.(\d+)\.control\.sock$/.exec(name);
if (!m) return;
const pid = Number(m[1]);
if (!Number.isInteger(pid) || pid <= 0) return;
if (await probe(path.join(runtimeDir, name))) result.add(pid);
}));
return result;
}
function toBuffer(body: Buffer | Uint8Array | string | null | undefined): Buffer {
if (Buffer.isBuffer(body)) return body;
if (body instanceof Uint8Array) return Buffer.from(body);
if (typeof body === 'string') return Buffer.from(body, 'utf8');
if (body == null) return Buffer.alloc(0);
throw new TypeError('body must be Buffer, Uint8Array, string, or null');
}
function createDeferred<T>(): Deferred<T> {
let resolve!: (value: T | PromiseLike<T>) => void;
let reject!: (reason?: unknown) => void;
const promise = new Promise<T>((res, rej) => {
resolve = res;
reject = rej;
});
return { promise, resolve, reject };
}
function withTimeout<T>(promise: Promise<T>, timeoutMs: number, label: string): Promise<T> {
if (!timeoutMs || timeoutMs <= 0) return promise;
return new Promise<T>((resolve, reject) => {
const timer = setTimeout(() => {
reject(new Error(`${label} timed out after ${timeoutMs} ms`));
}, timeoutMs);
promise.then(
value => {
clearTimeout(timer);
resolve(value);
},
error => {
clearTimeout(timer);
reject(error);
});
});
}
function encodeFrame({
op,
requestId = 0,
status = 0,
flags = 0,
value0 = 0n,
cmd = '',
msg = '',
body = Buffer.alloc(0),
}: {
op: number;
requestId?: number;
status?: number;
flags?: number;
value0?: bigint | number;
cmd?: string;
msg?: string;
body?: Buffer | Uint8Array | string | null;
}): Buffer {
const cmdBuf = Buffer.from(cmd, 'utf8');
const msgBuf = Buffer.from(msg, 'utf8');
const bodyBuf = toBuffer(body);
const header = Buffer.alloc(HEADER_SIZE);
header.writeUInt32LE(PIPE_MAGIC, 0);
header.writeUInt16LE(PIPE_VERSION, 4);
header.writeUInt16LE(op, 6);
header.writeUInt32LE(requestId >>> 0, 8);
header.writeInt32LE(status | 0, 12);
header.writeUInt32LE(flags >>> 0, 16);
header.writeUInt32LE(cmdBuf.length >>> 0, 20);
header.writeUInt32LE(msgBuf.length >>> 0, 24);
header.writeUInt32LE(bodyBuf.length >>> 0, 28);
header.writeBigUInt64LE(BigInt(value0), 32);
return Buffer.concat([header, cmdBuf, msgBuf, bodyBuf]);
}
class FrameReader {
private buffer = Buffer.alloc(0);
constructor(private readonly onFrame: (frame: PipeFrame) => void) {}
push(chunk: Buffer): void {
this.buffer = Buffer.concat([this.buffer, chunk]);
while (this.buffer.length >= HEADER_SIZE) {
const magic = this.buffer.readUInt32LE(0);
const version = this.buffer.readUInt16LE(4);
if (magic !== PIPE_MAGIC || version !== PIPE_VERSION) {
throw new Error(`bad frame header magic=0x${magic.toString(16)} version=${version}`);
}
const cmdLen = this.buffer.readUInt32LE(20);
const msgLen = this.buffer.readUInt32LE(24);
const bodyLen = this.buffer.readUInt32LE(28);
const total = HEADER_SIZE + cmdLen + msgLen + bodyLen;
if (this.buffer.length < total) return;
const frame: PipeFrame = {
op: this.buffer.readUInt16LE(6),
requestId: this.buffer.readUInt32LE(8),
status: this.buffer.readInt32LE(12),
flags: this.buffer.readUInt32LE(16),
value0: this.buffer.readBigUInt64LE(32),
cmd: '',
msg: '',
body: Buffer.alloc(0),
};
let offset = HEADER_SIZE;
frame.cmd = this.buffer.subarray(offset, offset + cmdLen).toString('utf8');
offset += cmdLen;
frame.msg = this.buffer.subarray(offset, offset + msgLen).toString('utf8');
offset += msgLen;
frame.body = Buffer.from(this.buffer.subarray(offset, offset + bodyLen));
this.buffer = this.buffer.subarray(total);
this.onFrame(frame);
}
}
}
export class QqHookClient extends EventEmitter {
readonly pid: number;
readonly defaultAckTimeoutMs: number;
readonly defaultReplyTimeoutMs: number;
private controlSocket: net.Socket | null = null;
private recvSocket: net.Socket | null = null;
private controlConnectPromise: Promise<QqHookHello> | null = null;
private recvConnectPromise: Promise<QqHookHello> | null = null;
private nextRequestId = 1;
private pendingAcks = new Map<number, PendingAck>();
private pendingReplies = new Map<number, Deferred<QqHookSendReply>>();
private controlHello: QqHookHello | null = null;
private recvHello: QqHookHello | null = null;
private controlHelloResolver: Deferred<QqHookHello> | null = null;
private recvHelloResolver: Deferred<QqHookHello> | null = null;
private controlWriteChain: Promise<unknown> = Promise.resolve();
private closed = false;
private loginState: QqHookLoginState = { loggedIn: false, uin: '0', uinNumber: 0n };
private loginWaiters: Deferred<QqHookLoginState>[] = [];
constructor(pid: number, {
ackTimeoutMs = DEFAULT_ACK_TIMEOUT_MS,
replyTimeoutMs = DEFAULT_REPLY_TIMEOUT_MS,
}: QqHookClientOptions = {}) {
super();
this.pid = pid;
this.defaultAckTimeoutMs = ackTimeoutMs;
this.defaultReplyTimeoutMs = replyTimeoutMs;
}
get isLoggedIn(): boolean {
return this.loginState.loggedIn;
}
get isClosed(): boolean {
return this.closed;
}
get currentUin(): string {
return this.loginState.uin;
}
get currentUinNumber(): bigint {
return this.loginState.uinNumber;
}
getLoginState(): QqHookLoginState {
return { ...this.loginState };
}
async waitForLogin({ timeoutMs = 0 } = {}): Promise<QqHookLoginState> {
await this.connect();
if (this.loginState.loggedIn) {
return this.getLoginState();
}
const deferred = createDeferred<QqHookLoginState>();
this.loginWaiters.push(deferred);
return withTimeout(deferred.promise, timeoutMs, 'waitForLogin');
}
static controlPipeName(pid: number): string {
return mojoPipeName(pid, 'control');
}
static recvPipeName(pid: number): string {
return mojoPipeName(pid, 'recv');
}
/**
* Lightweight liveness check for the control pipe. Used to detect whether an
* existing SnowLuma hook is still hosted inside the QQ.exe process without
* opening the pipe, so probing cannot disturb the first real client connect.
*/
static async probePipe(pid: number): Promise<boolean> {
const live = await QqHookClient.listLivePipes();
return live.has(pid);
}
/**
* Enumerate every PID currently hosting a SnowLuma `mojo.<pid>.control` pipe
* in a single filesystem listing. The HookManager's pipe-watcher uses this
* to drive connect/reconnect decisions without per-PID stat calls.
*/
static async listLivePipes(): Promise<Set<number>> {
const result = new Set<number>();
try {
if (process.platform === 'win32') {
const names = await fs.readdir('\\\\.\\pipe\\');
for (const name of names) {
const m = /^mojo\.(\d+)\.control$/i.exec(name);
if (m) result.add(Number(m[1]));
}
} else {
return await listLiveLinuxPipePids();
}
} catch {
/* directory missing or inaccessible — treat as no live pipes */
}
return result;
}
async connect(): Promise<QqHookHello> {
if (this.closed) {
throw new Error('qq_hook client is closed');
}
if (this.controlSocket && this.controlHello) {
return this.controlHello;
}
if (this.controlConnectPromise) {
return this.controlConnectPromise;
}
this.controlConnectPromise = (async () => {
this.controlSocket = await this.connectSocket(
QqHookClient.controlPipeName(this.pid),
'control',
frame => this.handleControlFrame(frame));
this.controlHello = await this.waitForHello(false);
return this.controlHello;
})();
try {
return await this.controlConnectPromise;
} finally {
this.controlConnectPromise = null;
}
}
async startRecv(onPacket?: (packet: QqHookPacket) => void): Promise<QqHookHello> {
if (this.closed) {
throw new Error('qq_hook client is closed');
}
if (typeof onPacket === 'function') {
this.on('packet', onPacket);
}
if (this.recvSocket && this.recvHello) {
return this.recvHello;
}
if (this.recvConnectPromise) {
return this.recvConnectPromise;
}
this.recvConnectPromise = (async () => {
this.recvSocket = await this.connectSocket(
QqHookClient.recvPipeName(this.pid),
'recv',
frame => this.handleRecvFrame(frame));
this.recvHello = await this.waitForHello(true);
return this.recvHello;
})();
try {
return await this.recvConnectPromise;
} finally {
this.recvConnectPromise = null;
}
}
async connectAll({ recv = true } = {}): Promise<{ control: QqHookHello; recv: QqHookHello | null }> {
const control = await this.connect();
const recvInfo = recv ? await this.startRecv() : null;
return { control, recv: recvInfo };
}
async send(cmd: string, body: Buffer | Uint8Array | string | null | undefined, {
wantReply = true,
ackTimeoutMs = this.defaultAckTimeoutMs,
replyTimeoutMs = this.defaultReplyTimeoutMs,
}: QqHookSendOptions = {}): Promise<QqHookSendReply | { requestId: number }> {
await this.connect();
// Wrap inside uint32 explicitly. `nextRequestId++ >>> 0` would
// misbehave once the integer exceeds Number.MAX_SAFE_INTEGER (the
// postfix increment loses precision before the shift), letting two
// distinct requests collide on the same id. Skip 0 because zero is
// used as a sentinel by the wire protocol.
let requestId = this.nextRequestId;
while (this.pendingAcks.has(requestId) || this.pendingReplies.has(requestId)) {
requestId = (requestId + 1) >>> 0;
if (requestId === 0) requestId = 1;
}
this.nextRequestId = (requestId + 1) >>> 0;
if (this.nextRequestId === 0) this.nextRequestId = 1;
const payload = encodeFrame({
op: PipeOp.sendRequest,
requestId,
flags: wantReply ? PipeFlagWantReply : 0,
cmd,
body,
});
const ackDeferred = createDeferred<{ requestId: number; wantReply: boolean }>();
this.pendingAcks.set(requestId, {
resolve: ackDeferred.resolve,
reject: ackDeferred.reject,
wantReply,
});
let replyDeferred: Deferred<QqHookSendReply> | null = null;
if (wantReply) {
replyDeferred = createDeferred<QqHookSendReply>();
this.pendingReplies.set(requestId, replyDeferred);
}
try {
await this.writeControl(payload);
await withTimeout(ackDeferred.promise, ackTimeoutMs, `send ack ${requestId}`);
if (!wantReply) {
return { requestId };
}
return await withTimeout(
replyDeferred!.promise,
replyTimeoutMs,
`send reply ${requestId}`);
} catch (error) {
this.pendingAcks.delete(requestId);
this.pendingReplies.delete(requestId);
throw error;
}
}
async sendNoReply(cmd: string, body: Buffer | Uint8Array | string | null | undefined, options: Omit<QqHookSendOptions, 'wantReply'> = {}): Promise<{ requestId: number }> {
return this.send(cmd, body, { ...options, wantReply: false }) as Promise<{ requestId: number }>;
}
async sendAndWait(cmd: string, body: Buffer | Uint8Array | string | null | undefined, options: Omit<QqHookSendOptions, 'wantReply'> = {}): Promise<QqHookSendReply> {
return this.send(cmd, body, { ...options, wantReply: true }) as Promise<QqHookSendReply>;
}
async sendMany(items: Array<{ cmd: string; body?: Buffer | Uint8Array | string | null; wantReply?: boolean; ackTimeoutMs?: number; replyTimeoutMs?: number }>, {
concurrency = 64,
wantReply = true,
ackTimeoutMs = this.defaultAckTimeoutMs,
replyTimeoutMs = this.defaultReplyTimeoutMs,
}: QqHookSendOptions & { concurrency?: number } = {}): Promise<Array<QqHookSendReply | { requestId: number }>> {
const results = new Array<QqHookSendReply | { requestId: number }>(items.length);
let nextIndex = 0;
const workerCount = Math.max(1, Math.min(concurrency | 0, items.length || 1));
const worker = async () => {
for (;;) {
const index = nextIndex;
nextIndex += 1;
if (index >= items.length) return;
const item = items[index];
const itemWantReply = item.wantReply ?? wantReply;
results[index] = await this.send(item.cmd, item.body, {
wantReply: itemWantReply,
ackTimeoutMs: item.ackTimeoutMs ?? ackTimeoutMs,
replyTimeoutMs: item.replyTimeoutMs ?? replyTimeoutMs,
});
}
};
await Promise.all(Array.from({ length: workerCount }, () => worker()));
return results;
}
waitForPacket(predicate: (packet: QqHookPacket) => boolean = () => true, { timeoutMs = 0 } = {}): Promise<QqHookPacket> {
return new Promise((resolve, reject) => {
let timer: NodeJS.Timeout | null = null;
const cleanup = () => {
this.off('packet', onPacket);
if (timer) {
clearTimeout(timer);
timer = null;
}
};
const onPacket = (packet: QqHookPacket) => {
try {
if (!predicate(packet)) return;
cleanup();
resolve(packet);
} catch (error) {
cleanup();
reject(error);
}
};
this.on('packet', onPacket);
if (timeoutMs > 0) {
timer = setTimeout(() => {
cleanup();
reject(new Error(`recv packet timed out after ${timeoutMs} ms`));
}, timeoutMs);
}
});
}
close(): void {
if (this.closed) return;
this.closed = true;
this.rejectControlPending(new Error('qq_hook client closed'));
this.rejectRecvPending(new Error('qq_hook client closed'));
this.rejectLoginWaiters(new Error('qq_hook client closed'));
if (this.controlSocket) {
this.controlSocket.destroy();
this.controlSocket = null;
}
if (this.recvSocket) {
this.recvSocket.destroy();
this.recvSocket = null;
}
this.controlHello = null;
this.recvHello = null;
this.controlWriteChain = Promise.resolve();
}
private rejectLoginWaiters(error: Error): void {
const waiters = this.loginWaiters;
this.loginWaiters = [];
for (const waiter of waiters) waiter.reject(error);
}
private rejectControlPending(error: Error): void {
for (const pending of this.pendingAcks.values()) {
pending.reject(error);
}
for (const pending of this.pendingReplies.values()) {
pending.reject(error);
}
this.pendingAcks.clear();
this.pendingReplies.clear();
if (this.controlHelloResolver) {
this.controlHelloResolver.reject(error);
this.controlHelloResolver = null;
}
}
private rejectRecvPending(error: Error): void {
if (this.recvHelloResolver) {
this.recvHelloResolver.reject(error);
this.recvHelloResolver = null;
}
}
private writeControl(payload: Buffer): Promise<void> {
const socket = this.controlSocket;
if (!socket || socket.destroyed) {
return Promise.reject(new Error('control pipe is not connected'));
}
const writePromise = this.controlWriteChain.then(() => new Promise<void>((resolve, reject) => {
if (!this.controlSocket || this.controlSocket.destroyed) {
reject(new Error('control pipe is not connected'));
return;
}
socket.write(payload, error => {
if (error) reject(error);
else resolve();
});
}));
this.controlWriteChain = writePromise.catch(() => {});
return writePromise;
}
private connectSocket(pipeName: string, kind: 'control' | 'recv', onFrame: (frame: PipeFrame) => void): Promise<net.Socket> {
return new Promise((resolve, reject) => {
const socket = net.createConnection(pipeName);
const reader = new FrameReader(onFrame);
const onInitialError = (error: Error) => reject(error);
socket.once('error', onInitialError);
socket.once('connect', () => {
socket.off('error', onInitialError);
socket.on('data', chunk => {
try {
reader.push(chunk);
} catch (error) {
this.emit('error', error);
socket.destroy(error instanceof Error ? error : undefined);
}
});
socket.on('error', error => {
this.emit('error', error);
});
socket.on('close', () => {
this.handleSocketClose(kind);
this.emit('close', kind);
});
resolve(socket);
});
});
}
private waitForHello(recvPipe: boolean): Promise<QqHookHello> {
const deferred = createDeferred<QqHookHello>();
if (recvPipe) {
this.recvHelloResolver = deferred;
} else {
this.controlHelloResolver = deferred;
}
return deferred.promise;
}
private resolveHello(frame: PipeFrame, recvPipe: boolean): void {
const resolver = recvPipe ? this.recvHelloResolver : this.controlHelloResolver;
if (!resolver) return;
if (recvPipe) this.recvHelloResolver = null;
else this.controlHelloResolver = null;
resolver.resolve({
pipeName: frame.msg,
pid: Number(frame.value0),
recvPipe,
});
}
private handleSocketClose(kind: 'control' | 'recv'): void {
if (kind === 'control') {
this.controlSocket = null;
this.controlHello = null;
this.rejectControlPending(new Error('control pipe closed'));
return;
}
this.recvSocket = null;
this.recvHello = null;
this.rejectRecvPending(new Error('recv pipe closed'));
}
private applyLoginStateFrame(frame: PipeFrame): void {
const flaggedLoggedIn = (frame.flags & PipeFlagLoggedIn) !== 0;
const statusLoggedIn = frame.status !== 0;
const loggedIn = flaggedLoggedIn || statusLoggedIn;
const uinNumber = BigInt(frame.value0);
const uin = frame.msg || uinNumber.toString();
const previous = this.loginState;
const next = { loggedIn, uin, uinNumber };
this.loginState = next;
this.emit('loginState', next);
if (previous.loggedIn !== next.loggedIn || previous.uin !== next.uin) {
if (next.loggedIn) {
const waiters = this.loginWaiters;
this.loginWaiters = [];
for (const waiter of waiters) waiter.resolve({ ...next });
}
}
}
private handleControlFrame(frame: PipeFrame): void {
if (frame.op === PipeOp.hello) {
this.resolveHello(frame, false);
return;
}
if (frame.op === PipeOp.loginState) {
this.applyLoginStateFrame(frame);
return;
}
if (frame.op === PipeOp.sendAck) {
const pending = this.pendingAcks.get(frame.requestId);
if (!pending) return;
this.pendingAcks.delete(frame.requestId);
pending.resolve({ requestId: frame.requestId, wantReply: pending.wantReply });
return;
}
if (frame.op === PipeOp.sendReply) {
const pending = this.pendingReplies.get(frame.requestId);
if (!pending) return;
this.pendingReplies.delete(frame.requestId);
pending.resolve({
requestId: frame.requestId,
error: frame.status,
message: frame.msg,
body: Buffer.from(frame.body),
});
return;
}
if (frame.op === PipeOp.error) {
const error = new Error(frame.msg || `pipe error ${frame.status}`);
const ack = this.pendingAcks.get(frame.requestId);
if (ack) {
this.pendingAcks.delete(frame.requestId);
ack.reject(error);
}
const reply = this.pendingReplies.get(frame.requestId);
if (reply) {
this.pendingReplies.delete(frame.requestId);
reply.reject(error);
}
}
}
private handleRecvFrame(frame: PipeFrame): void {
if (frame.op === PipeOp.hello) {
this.resolveHello(frame, true);
return;
}
if (frame.op === PipeOp.loginState) {
this.applyLoginStateFrame(frame);
return;
}
if (frame.op !== PipeOp.recvPacket) return;
this.emit('packet', {
seq: Number(frame.value0),
error: frame.status,
cmd: frame.cmd,
uin: frame.msg,
body: Buffer.from(frame.body),
} satisfies QqHookPacket);
}
}
export { mojoPipeName };
+168
View File
@@ -0,0 +1,168 @@
import net from 'net';
import { exec } from 'child_process';
import { promisify } from 'util';
const execAsync = promisify(exec);
const PORT_RANGE_START = 9210;
const PORT_RANGE_END = 9219;
const PROBE_TIMEOUT_MS = 1000;
const CONNECTION_TIMEOUT_MS = 500;
export interface QqPortLoginInfo {
port: number;
uin: string;
uid?: string;
nickName?: string;
loggedIn: boolean;
}
interface JwtPayload {
errCode: number;
errMsg: string;
port: number;
uin?: string;
uid?: string;
nickName?: string;
data?: {
uin?: string;
url?: string;
};
iat: number;
}
function decodeJwt(token: string): JwtPayload | null {
try {
const parts = token.split('.');
if (parts.length !== 3) return null;
const payload = Buffer.from(parts[1], 'base64').toString('utf8');
return JSON.parse(payload);
} catch {
return null;
}
}
async function probePort(port: number): Promise<QqPortLoginInfo | null> {
return new Promise((resolve) => {
const client = new net.Socket();
const link = 'tencent://';
const payload = `POST /tencent HTTP/1.1\r\nHost: 127.0.0.1:${port}\r\nConnection: close\r\nContent-Length: ${link.length}\r\n\r\n${link}`;
let responseData = '';
let timer: NodeJS.Timeout;
const cleanup = () => {
clearTimeout(timer);
client.removeAllListeners();
client.destroy();
};
timer = setTimeout(() => {
cleanup();
resolve(null);
}, PROBE_TIMEOUT_MS);
client.setTimeout(CONNECTION_TIMEOUT_MS);
client.connect(port, '127.0.0.1', () => {
client.write(payload);
});
client.on('data', (data) => {
responseData += data.toString();
});
client.on('close', () => {
cleanup();
const jwtMatch = responseData.match(/eyJ[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+/);
if (!jwtMatch) {
resolve(null);
return;
}
const decoded = decodeJwt(jwtMatch[0]);
if (!decoded || decoded.errCode !== 0) {
resolve(null);
return;
}
const uin = decoded.uin || decoded.data?.uin || '';
resolve({
port,
uin,
uid: decoded.uid,
nickName: decoded.nickName,
loggedIn: uin.length > 0,
});
});
client.on('error', () => {
cleanup();
resolve(null);
});
client.on('timeout', () => {
cleanup();
resolve(null);
});
});
}
async function getProcessPorts(pid: number): Promise<number[]> {
try {
if (process.platform === 'win32') {
const { stdout } = await execAsync(`netstat -ano | findstr ${pid}`);
const ports = new Set<number>();
const lines = stdout.split('\n');
for (const line of lines) {
const parts = line.trim().split(/\s+/);
if (parts.length < 5) continue;
const owningPid = parts[parts.length - 1];
if (owningPid !== String(pid)) continue;
const localAddr = parts[1];
const portMatch = localAddr.match(/:(\d+)$/);
if (!portMatch) continue;
const port = Number(portMatch[1]);
if (port >= PORT_RANGE_START && port <= PORT_RANGE_END) {
ports.add(port);
}
}
return Array.from(ports);
} else {
const { stdout } = await execAsync(`ss -tlnp | grep pid=${pid}`);
const ports = new Set<number>();
const lines = stdout.split('\n');
for (const line of lines) {
const match = line.match(/:(\d+)\s/);
if (match) {
const port = Number(match[1]);
if (port >= PORT_RANGE_START && port <= PORT_RANGE_END) {
ports.add(port);
}
}
}
return Array.from(ports);
}
} catch {
return [];
}
}
export async function probeQqLoginInfo(pid: number): Promise<QqPortLoginInfo | null> {
const ports = await getProcessPorts(pid);
if (ports.length === 0) {
for (let port = PORT_RANGE_START; port <= PORT_RANGE_END; port++) {
const info = await probePort(port);
if (info) return info;
}
return null;
}
for (const port of ports) {
const info = await probePort(port);
if (info) return info;
}
return null;
}
+21
View File
@@ -0,0 +1,21 @@
import type { HookProcessBaseInfo } from './injector';
export type HookProcessStatus =
| 'available'
| 'loading'
| 'connecting'
| 'loaded'
| 'online'
| 'error'
| 'disconnected';
/** Public-facing snapshot of a per-PID HookSession. */
export interface HookProcessInfo extends HookProcessBaseInfo {
injected: boolean;
connected: boolean;
loggedIn: boolean;
uin: string;
status: HookProcessStatus;
error: string;
method: string;
}