Migrate project to pnpm monorepo
Restructure the repository into a pnpm workspace under packages/ (core, webui, runtime). Move source files for core and webui into packages/*, add package manifests for @snowluma/core and @snowluma/runtime, and remove the old launcher package.json. Update root package.json to be a monorepo controller (scripts delegate to pnpm filters, set packageManager and Node engine). Configure build outputs to emit into the repo-root dist/ (vite config changes) so the existing release pipeline continues to work. Add .npmrc with mirrors, expand .gitignore for monorepo layout, add tsconfig base and package-level tsconfigs, and add vitest config for the core package. Adjust injector native search paths and update tests import paths to the new package layout. Small CI/workflow comment added to clarify build behavior and README updated with monorepo structure and common commands.
This commit is contained in:
1 parent
6bba36bba6
commit
39f1672b29
122 files changed
+279
-85
No files matched your search
@@ -0,0 +1,291 @@
|
||||
import type { BridgeManager } from '../bridge/manager';
|
||||
import type { NtqqHandler } from '../protocol/ntqq-handler';
|
||||
import { createLogger } from '../utils/logger';
|
||||
import { HookPacketClient } from './hook-packet-client';
|
||||
import { injectHookProcess, listHookProcesses, unloadHookProcess, type HookInjectResult, type HookProcessBaseInfo } from './injector';
|
||||
import { QqHookClient, type QqHookLoginState, type QqHookPacket } from './qq-hook-client';
|
||||
|
||||
const log = createLogger('Hook');
|
||||
const CONNECT_RETRY_COUNT = 30;
|
||||
const CONNECT_RETRY_INTERVAL_MS = 1000;
|
||||
|
||||
export type HookProcessStatus = 'available' | 'loading' | 'loaded' | 'online' | 'error' | 'disconnected';
|
||||
|
||||
export interface HookProcessInfo extends HookProcessBaseInfo {
|
||||
injected: boolean;
|
||||
connected: boolean;
|
||||
loggedIn: boolean;
|
||||
uin: string;
|
||||
status: HookProcessStatus;
|
||||
error: string;
|
||||
method: string;
|
||||
}
|
||||
|
||||
interface HookProcessState extends HookProcessInfo {
|
||||
client: QqHookClient | null;
|
||||
sender: HookPacketClient | null;
|
||||
injectResult: HookInjectResult | null;
|
||||
connectTask: Promise<void> | null;
|
||||
bound: boolean;
|
||||
}
|
||||
|
||||
export class HookManager {
|
||||
private readonly states = new Map<number, HookProcessState>();
|
||||
private readonly loadTasks = new Map<number, Promise<HookProcessInfo>>();
|
||||
private readonly unloadTasks = new Map<number, Promise<HookProcessInfo>>();
|
||||
|
||||
constructor(
|
||||
private readonly ntqq: NtqqHandler,
|
||||
private readonly bridgeManager: BridgeManager,
|
||||
) {}
|
||||
|
||||
async listProcesses(): Promise<HookProcessInfo[]> {
|
||||
const processes = await listHookProcesses();
|
||||
for (const proc of processes) {
|
||||
const state = this.ensureState(proc.pid);
|
||||
state.name = proc.name;
|
||||
state.path = proc.path;
|
||||
}
|
||||
|
||||
const seen = new Set(processes.map(proc => proc.pid));
|
||||
const result: HookProcessInfo[] = [];
|
||||
for (const proc of processes) {
|
||||
result.push(this.toPublicInfo(this.ensureState(proc.pid)));
|
||||
}
|
||||
for (const state of this.states.values()) {
|
||||
if (!seen.has(state.pid) && state.injected) {
|
||||
result.push(this.toPublicInfo(state));
|
||||
}
|
||||
}
|
||||
return result.sort((a, b) => a.pid - b.pid);
|
||||
}
|
||||
|
||||
async loadProcess(pid: number): Promise<HookProcessInfo> {
|
||||
if (!Number.isInteger(pid) || pid <= 0) {
|
||||
throw new Error('invalid pid');
|
||||
}
|
||||
const runningTask = this.loadTasks.get(pid);
|
||||
if (runningTask) return runningTask;
|
||||
|
||||
const task = this.loadProcessInternal(pid);
|
||||
this.loadTasks.set(pid, task);
|
||||
try {
|
||||
return await task;
|
||||
} finally {
|
||||
this.loadTasks.delete(pid);
|
||||
}
|
||||
}
|
||||
|
||||
async unloadProcess(pid: number): Promise<HookProcessInfo> {
|
||||
if (!Number.isInteger(pid) || pid <= 0) {
|
||||
throw new Error('invalid pid');
|
||||
}
|
||||
const runningTask = this.unloadTasks.get(pid);
|
||||
if (runningTask) return runningTask;
|
||||
|
||||
const task = this.unloadProcessInternal(pid);
|
||||
this.unloadTasks.set(pid, task);
|
||||
try {
|
||||
return await task;
|
||||
} finally {
|
||||
this.unloadTasks.delete(pid);
|
||||
}
|
||||
}
|
||||
|
||||
dispose(): void {
|
||||
for (const state of this.states.values()) {
|
||||
state.client?.close();
|
||||
state.client = null;
|
||||
state.connected = false;
|
||||
state.loggedIn = false;
|
||||
state.status = state.injected ? 'disconnected' : 'available';
|
||||
}
|
||||
}
|
||||
|
||||
private async loadProcessInternal(pid: number): Promise<HookProcessInfo> {
|
||||
const state = this.ensureState(pid);
|
||||
state.status = 'loading';
|
||||
state.error = '';
|
||||
|
||||
try {
|
||||
if (!state.injected) {
|
||||
state.injectResult = injectHookProcess(pid);
|
||||
state.injected = true;
|
||||
state.method = state.injectResult.method;
|
||||
log.info('SnowLuma loaded into PID=%d via %s', pid, state.method);
|
||||
}
|
||||
state.status = state.connected ? (state.loggedIn ? 'online' : 'loaded') : 'loaded';
|
||||
this.startClient(state);
|
||||
} catch (error) {
|
||||
state.status = 'error';
|
||||
state.error = error instanceof Error ? error.message : String(error);
|
||||
log.error('load failed: PID=%d err=%s', pid, state.error);
|
||||
}
|
||||
|
||||
return this.toPublicInfo(state);
|
||||
}
|
||||
|
||||
private async unloadProcessInternal(pid: number): Promise<HookProcessInfo> {
|
||||
const state = this.ensureState(pid);
|
||||
state.error = '';
|
||||
|
||||
try {
|
||||
state.client?.close();
|
||||
state.client = null;
|
||||
state.sender = null;
|
||||
state.connectTask = null;
|
||||
state.bound = false;
|
||||
state.connected = false;
|
||||
state.loggedIn = false;
|
||||
this.bridgeManager.onPidDisconnected(pid);
|
||||
|
||||
const handle = state.injectResult?.handle;
|
||||
if (state.injected && handle) {
|
||||
unloadHookProcess(pid, handle);
|
||||
log.info('SnowLuma unloaded from PID=%d via unloadModuleManual', pid);
|
||||
}
|
||||
|
||||
state.injected = false;
|
||||
state.injectResult = null;
|
||||
state.method = '';
|
||||
state.uin = '0';
|
||||
state.status = 'available';
|
||||
} catch (error) {
|
||||
state.status = 'error';
|
||||
state.error = error instanceof Error ? error.message : String(error);
|
||||
log.error('unload failed: PID=%d err=%s', pid, state.error);
|
||||
}
|
||||
|
||||
return this.toPublicInfo(state);
|
||||
}
|
||||
|
||||
private ensureState(pid: number): HookProcessState {
|
||||
let state = this.states.get(pid);
|
||||
if (!state) {
|
||||
state = {
|
||||
pid,
|
||||
name: 'QQ.exe',
|
||||
path: '',
|
||||
injected: false,
|
||||
connected: false,
|
||||
loggedIn: false,
|
||||
uin: '0',
|
||||
status: 'available',
|
||||
error: '',
|
||||
method: '',
|
||||
client: null,
|
||||
sender: null,
|
||||
injectResult: null,
|
||||
connectTask: null,
|
||||
bound: false,
|
||||
};
|
||||
this.states.set(pid, state);
|
||||
}
|
||||
return state;
|
||||
}
|
||||
|
||||
private startClient(state: HookProcessState): void {
|
||||
if (!state.client) {
|
||||
state.client = new QqHookClient(state.pid);
|
||||
state.sender = new HookPacketClient(state.client);
|
||||
}
|
||||
if (!state.bound) {
|
||||
this.bindClient(state, state.client);
|
||||
state.bound = true;
|
||||
}
|
||||
if (!state.connectTask) {
|
||||
state.connectTask = this.connectClient(state).finally(() => {
|
||||
state.connectTask = null;
|
||||
});
|
||||
void state.connectTask;
|
||||
}
|
||||
}
|
||||
|
||||
private bindClient(state: HookProcessState, client: QqHookClient): void {
|
||||
client.on('packet', packet => this.handlePacket(state, packet));
|
||||
client.on('loginState', loginState => this.handleLoginState(state, loginState));
|
||||
client.on('error', error => {
|
||||
state.error = error instanceof Error ? error.message : String(error);
|
||||
if (!state.connected) state.status = 'error';
|
||||
log.warn('pipe error: PID=%d err=%s', state.pid, state.error);
|
||||
});
|
||||
client.on('close', () => {
|
||||
state.connected = false;
|
||||
if (state.loggedIn) {
|
||||
state.loggedIn = false;
|
||||
state.status = 'disconnected';
|
||||
this.bridgeManager.onPidDisconnected(state.pid);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
private async connectClient(state: HookProcessState): Promise<void> {
|
||||
const client = state.client;
|
||||
if (!client) return;
|
||||
|
||||
for (let attempt = 1; attempt <= CONNECT_RETRY_COUNT; attempt++) {
|
||||
try {
|
||||
await client.connectAll({ recv: true });
|
||||
state.connected = true;
|
||||
state.status = client.isLoggedIn ? 'online' : 'loaded';
|
||||
state.error = '';
|
||||
const loginState = client.getLoginState();
|
||||
if (loginState.loggedIn) {
|
||||
this.handleLoginState(state, loginState);
|
||||
}
|
||||
log.info('pipe connected: PID=%d', state.pid);
|
||||
return;
|
||||
} catch (error) {
|
||||
state.error = error instanceof Error ? error.message : String(error);
|
||||
if (attempt >= CONNECT_RETRY_COUNT) {
|
||||
state.status = 'error';
|
||||
log.error('pipe connect failed: PID=%d err=%s', state.pid, state.error);
|
||||
return;
|
||||
}
|
||||
await delay(CONNECT_RETRY_INTERVAL_MS);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private handleLoginState(state: HookProcessState, loginState: QqHookLoginState): void {
|
||||
state.uin = loginState.uin || loginState.uinNumber.toString();
|
||||
state.loggedIn = loginState.loggedIn && isRealUin(state.uin);
|
||||
state.status = state.loggedIn ? 'online' : (state.connected ? 'loaded' : state.status);
|
||||
|
||||
if (!state.loggedIn || !state.sender) return;
|
||||
|
||||
this.bridgeManager.onHookLogin(state.pid, state.uin, state.sender);
|
||||
log.success('login detected: PID=%d UIN=%s', state.pid, state.uin);
|
||||
}
|
||||
|
||||
private handlePacket(state: HookProcessState, packet: QqHookPacket): void {
|
||||
if (!state.loggedIn) return;
|
||||
const uin = packet.uin || state.uin;
|
||||
if (!isRealUin(uin)) return;
|
||||
this.ntqq.onHookPacket(state.pid, { ...packet, uin });
|
||||
}
|
||||
|
||||
private toPublicInfo(state: HookProcessState): HookProcessInfo {
|
||||
return {
|
||||
pid: state.pid,
|
||||
name: state.name,
|
||||
path: state.path,
|
||||
injected: state.injected,
|
||||
connected: state.connected,
|
||||
loggedIn: state.loggedIn,
|
||||
uin: state.uin,
|
||||
status: state.status,
|
||||
error: state.error,
|
||||
method: state.method,
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
function isRealUin(uin: string): boolean {
|
||||
if (!uin || uin === '0') return false;
|
||||
return /^\d+$/.test(uin) && uin.length >= 5;
|
||||
}
|
||||
|
||||
function delay(ms: number): Promise<void> {
|
||||
return new Promise(resolve => setTimeout(resolve, ms));
|
||||
}
|
||||
@@ -0,0 +1,34 @@
|
||||
import type { PacketSender, SendPacketResult } from '../protocol/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,
|
||||
};
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,116 @@
|
||||
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;
|
||||
}
|
||||
|
||||
function platformBinaryName(ext: 'node' | 'dll'): string {
|
||||
if (process.platform === 'win32' && process.arch === 'x64') return `snowluma-win32-x64.${ext}`;
|
||||
return `snowluma-${process.platform}-${process.arch}.${ext}`;
|
||||
}
|
||||
|
||||
function nativeSearchDirs(): string[] {
|
||||
// Several layouts must be supported:
|
||||
// 1. Released zip (flattened dist/): __dirname=<extracted>/, native at <extracted>/native
|
||||
// 2. Repo bundled build (dist/index.mjs): __dirname=<root>/dist, native at <root>/dist/native
|
||||
// 3. Dev via tsx (packages/core/src/hook/injector.ts): __dirname=<root>/packages/core/src/hook
|
||||
// → walk up to <root>/packages and append runtime/native
|
||||
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: 'node' | 'dll'): 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: 'QQ.exe', path: '' }));
|
||||
}
|
||||
|
||||
export function injectHookProcess(pid: number): HookInjectResult {
|
||||
const addon = getNativeHookAddon();
|
||||
if (!addon) {
|
||||
throw new Error(getNativeHookLoadError() ?? 'hook native addon is not available');
|
||||
}
|
||||
const dllPath = resolveHookNativePath('dll');
|
||||
if (!dllPath) {
|
||||
throw new Error(`No hook DLL 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);
|
||||
}
|
||||
@@ -0,0 +1,652 @@
|
||||
import net from 'net';
|
||||
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;
|
||||
|
||||
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 mojoPipeName(pid: number, suffix: string): string {
|
||||
return `\\\\.\\pipe\\mojo.${pid}.${suffix}`;
|
||||
}
|
||||
|
||||
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 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');
|
||||
}
|
||||
|
||||
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();
|
||||
|
||||
const requestId = this.nextRequestId++ >>> 0;
|
||||
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;
|
||||
if (previous.loggedIn !== next.loggedIn || previous.uin !== next.uin) {
|
||||
this.emit('loginState', next);
|
||||
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 };
|
||||
Reference in new issue
Block a user