feat(core): auto-inject hook on QQ process discovery
Headless / Docker deployments previously needed a human to click "Load" in WebUI for every newly-discovered QQ process. Add an opt-in HookManager.autoLoadOnDiscovery flag wired up through two layers: - SNOWLUMA_HOOK_AUTOLOAD env var (highest priority) - hookAutoLoad in runtime.json (persistent fallback) When enabled, every 'process-discovered' event from PipeWatcher fires session.load() fire-and-forget; failures stay scoped to the session via existing error-state handling and don't break the watcher loop. Default stays off, so non-Docker installs see no behaviour change.
This commit is contained in:
@@ -3,6 +3,10 @@ import path from 'path';
|
||||
|
||||
export interface RuntimeConfig {
|
||||
webuiPort?: number;
|
||||
/** When true, every newly-discovered QQ process gets auto-injected by
|
||||
* the HookManager. Also overridable at runtime via SNOWLUMA_HOOK_AUTOLOAD.
|
||||
* Defaults to false; the Docker image flips it on in supervisord.conf. */
|
||||
hookAutoLoad?: boolean;
|
||||
}
|
||||
|
||||
const CONFIG_DIR = 'config';
|
||||
@@ -10,6 +14,7 @@ const RUNTIME_CONFIG_PATH = path.join(CONFIG_DIR, 'runtime.json');
|
||||
|
||||
const DEFAULT_RUNTIME_CONFIG: RuntimeConfig = {
|
||||
webuiPort: 5099,
|
||||
hookAutoLoad: false,
|
||||
};
|
||||
|
||||
export function loadRuntimeConfig(): RuntimeConfig {
|
||||
@@ -23,10 +28,12 @@ export function loadRuntimeConfig(): RuntimeConfig {
|
||||
|
||||
const normalized: RuntimeConfig = {
|
||||
webuiPort: normalizePort(loaded.webuiPort ?? 5099, 5099),
|
||||
hookAutoLoad: normalizeBool(loaded.hookAutoLoad, false),
|
||||
};
|
||||
|
||||
if (
|
||||
normalized.webuiPort !== loaded.webuiPort
|
||||
|| normalized.hookAutoLoad !== loaded.hookAutoLoad
|
||||
) {
|
||||
saveRuntimeConfig(normalized);
|
||||
}
|
||||
@@ -44,6 +51,7 @@ function tryLoadRuntimeConfig(): RuntimeConfig | null {
|
||||
|
||||
return {
|
||||
webuiPort: normalizePort(parsed.webuiPort ?? 5099, 5099),
|
||||
hookAutoLoad: normalizeBool(parsed.hookAutoLoad, false),
|
||||
};
|
||||
} catch {
|
||||
return null;
|
||||
@@ -70,6 +78,17 @@ function normalizePort(value: unknown, fallback: number): number {
|
||||
return fallback;
|
||||
}
|
||||
|
||||
function normalizeBool(value: unknown, fallback: boolean): boolean {
|
||||
if (typeof value === 'boolean') return value;
|
||||
if (typeof value === 'number') return value !== 0;
|
||||
if (typeof value === 'string') {
|
||||
const v = value.trim().toLowerCase();
|
||||
if (v === 'true' || v === '1' || v === 'yes' || v === 'on') return true;
|
||||
if (v === 'false' || v === '0' || v === 'no' || v === 'off' || v === '') return false;
|
||||
}
|
||||
return fallback;
|
||||
}
|
||||
|
||||
function isObject(value: unknown): value is Record<string, unknown> {
|
||||
return typeof value === 'object' && value !== null && !Array.isArray(value);
|
||||
}
|
||||
|
||||
@@ -31,6 +31,10 @@ export type HookManagerDeps = {
|
||||
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;
|
||||
};
|
||||
|
||||
@@ -57,6 +61,7 @@ export class HookManager {
|
||||
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>;
|
||||
@@ -77,6 +82,7 @@ export class HookManager {
|
||||
};
|
||||
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;
|
||||
@@ -159,6 +165,15 @@ export class HookManager {
|
||||
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) {
|
||||
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;
|
||||
|
||||
@@ -15,7 +15,14 @@ async function main() {
|
||||
// HookManager defaults its packet sink to bridgeManager.onPacket, so
|
||||
// every parsed hook packet reaches the per-UIN bridge dispatcher with
|
||||
// no intermediate layer.
|
||||
const hookManager = new HookManager({ bridgeManager });
|
||||
// Env var SNOWLUMA_HOOK_AUTOLOAD wins over runtime.json so Docker /
|
||||
// headless deployments can flip auto-injection on without touching the
|
||||
// persisted user config volume.
|
||||
const autoLoadOnDiscovery = resolveAutoLoad(runtimeConfig.hookAutoLoad);
|
||||
const hookManager = new HookManager({ bridgeManager, autoLoadOnDiscovery });
|
||||
if (autoLoadOnDiscovery) {
|
||||
log.info('hook auto-load enabled: every discovered QQ process will be injected');
|
||||
}
|
||||
|
||||
oneBotManager.bind(bridgeManager);
|
||||
|
||||
@@ -40,6 +47,16 @@ async function main() {
|
||||
});
|
||||
}
|
||||
|
||||
function resolveAutoLoad(fromConfig: boolean | undefined): boolean {
|
||||
const envRaw = process.env.SNOWLUMA_HOOK_AUTOLOAD;
|
||||
if (typeof envRaw === 'string' && envRaw.trim()) {
|
||||
const v = envRaw.trim().toLowerCase();
|
||||
if (v === '1' || v === 'true' || v === 'yes' || v === 'on') return true;
|
||||
if (v === '0' || v === 'false' || v === 'no' || v === 'off') return false;
|
||||
}
|
||||
return fromConfig === true;
|
||||
}
|
||||
|
||||
main().catch((error) => {
|
||||
log.error(error instanceof Error ? (error.stack ?? error.message) : String(error));
|
||||
process.exit(1);
|
||||
|
||||
@@ -0,0 +1,104 @@
|
||||
import { describe, it, expect, vi } from 'vitest';
|
||||
import { EventEmitter } from 'events';
|
||||
import { HookManager } from '../src/hook/hook-manager';
|
||||
import { PipeWatcher } from '../src/hook/pipe-watcher';
|
||||
import type { ManualMapHandle } from '../src/hook/injector';
|
||||
import type { BridgeManager } from '../src/bridge/manager';
|
||||
import type { QqHookClient } from '../src/hook/qq-hook-client';
|
||||
|
||||
const DUMMY_HANDLE: ManualMapHandle = { base: 0n, entry: 0n, exceptionTable: 0n, size: 0 };
|
||||
const flush = () => new Promise<void>(r => setImmediate(r));
|
||||
|
||||
function makeManager(opts: {
|
||||
autoLoadOnDiscovery?: boolean;
|
||||
processes?: number[];
|
||||
}) {
|
||||
let pids = opts.processes ?? [];
|
||||
const live = new Set<number>();
|
||||
const inject = vi.fn(() => ({ method: 'loadModuleManual' as const, handle: DUMMY_HANDLE }));
|
||||
const unload = vi.fn();
|
||||
const pipeWatcher = new PipeWatcher({
|
||||
listProcesses: () => pids.map(pid => ({ pid, name: 'qq', path: '' })),
|
||||
listLivePipes: async () => new Set(live),
|
||||
intervalMs: 60_000, // disable internal timer; tests drive ticks manually
|
||||
});
|
||||
// FakeClient — never connected; just needs to satisfy EventEmitter +
|
||||
// a minimal subset of QqHookClient for HookSession.tearDownClient().
|
||||
const makeClient = vi.fn(() => {
|
||||
const c = new EventEmitter() as EventEmitter & Partial<QqHookClient>;
|
||||
(c as any).isClosed = false;
|
||||
(c as any).isLoggedIn = false;
|
||||
(c as any).getLoginState = () => ({ loggedIn: false, uin: '0', uinNumber: 0n });
|
||||
(c as any).connectAll = async () => { throw new Error('test: never really connect'); };
|
||||
(c as any).close = () => { (c as any).isClosed = true; };
|
||||
return c as unknown as QqHookClient;
|
||||
});
|
||||
const bridgeManager = {
|
||||
onPacket: vi.fn(),
|
||||
onHookLogin: vi.fn(),
|
||||
onPidDisconnected: vi.fn(),
|
||||
} as unknown as BridgeManager;
|
||||
const manager = new HookManager({
|
||||
bridgeManager,
|
||||
pipeWatcher,
|
||||
injector: { inject, unload },
|
||||
makeClient,
|
||||
autoLoadOnDiscovery: opts.autoLoadOnDiscovery,
|
||||
listProcesses: () => pids.map(pid => ({ pid, name: 'qq', path: '' })),
|
||||
});
|
||||
return {
|
||||
manager,
|
||||
inject,
|
||||
pipeWatcher,
|
||||
setProcesses: (next: number[]) => { pids = next; },
|
||||
};
|
||||
}
|
||||
|
||||
describe('HookManager.autoLoadOnDiscovery', () => {
|
||||
it('does NOT inject on process-discovered when flag is off', async () => {
|
||||
const ctx = makeManager({ autoLoadOnDiscovery: false, processes: [4242] });
|
||||
await ctx.pipeWatcher.start();
|
||||
await flush();
|
||||
expect(ctx.inject).not.toHaveBeenCalled();
|
||||
ctx.manager.dispose();
|
||||
});
|
||||
|
||||
it('injects every newly-discovered PID when flag is on', async () => {
|
||||
const ctx = makeManager({ autoLoadOnDiscovery: true, processes: [4242] });
|
||||
await ctx.pipeWatcher.start();
|
||||
// session.load() is queued via a per-session promise chain; flush twice
|
||||
// so the auto-load runs to completion before we assert.
|
||||
await flush();
|
||||
await flush();
|
||||
expect(ctx.inject).toHaveBeenCalledTimes(1);
|
||||
expect(ctx.inject).toHaveBeenCalledWith(4242);
|
||||
|
||||
// A second PID appearing mid-flight should also trigger an inject.
|
||||
ctx.setProcesses([4242, 9999]);
|
||||
await ctx.pipeWatcher.tickNow();
|
||||
await flush();
|
||||
await flush();
|
||||
expect(ctx.inject).toHaveBeenCalledTimes(2);
|
||||
expect(ctx.inject).toHaveBeenLastCalledWith(9999);
|
||||
|
||||
ctx.manager.dispose();
|
||||
});
|
||||
|
||||
it('swallows inject errors so the watcher keeps running', async () => {
|
||||
const ctx = makeManager({ autoLoadOnDiscovery: true, processes: [4242] });
|
||||
ctx.inject.mockImplementationOnce(() => { throw new Error('ptrace denied'); });
|
||||
await ctx.pipeWatcher.start();
|
||||
await flush();
|
||||
await flush();
|
||||
|
||||
// Second PID should still be auto-loaded — the failure on 4242 must
|
||||
// not leak out of the listener and break the watcher's emit loop.
|
||||
ctx.setProcesses([4242, 9999]);
|
||||
await ctx.pipeWatcher.tickNow();
|
||||
await flush();
|
||||
await flush();
|
||||
expect(ctx.inject).toHaveBeenCalledTimes(2);
|
||||
|
||||
ctx.manager.dispose();
|
||||
});
|
||||
});
|
||||
Reference in New Issue
Block a user