refactor: await native operations across the bridge lifecycle

This commit is contained in:
手瓜一十雪 committed 2026-10-18 13:19:21 +08:00
1 parent 1faa6c58fa
commit 9b165a8971
24 files changed
+241 -177

No files matched your search

+1 -7
View File
@@ -129,13 +129,7 @@ export class HookManager {
this.injector = deps.injector ?? { this.injector = deps.injector ?? {
inject: injectHookProcess, inject: injectHookProcess,
unload: (pid, handle) => { unload: unloadHookProcess,
if (!handle) {
return;
}
unloadHookProcess(pid, handle);
},
}; };
this.makeClient = deps.makeClient ?? ((pid: number) => new QqHookClient(pid)); this.makeClient = deps.makeClient ?? ((pid: number) => new QqHookClient(pid));
this.detectAccounts = deps.detectAccounts ?? detectAccountLoginsForPids; this.detectAccounts = deps.detectAccounts ?? detectAccountLoginsForPids;
+4 -4
View File
@@ -10,7 +10,7 @@ import type { PacketSink } from '@snowluma/common/protocol-types';
import { isRealUin } from '@snowluma/common/uin'; import { isRealUin } from '@snowluma/common/uin';
import { EventEmitter } from 'events'; import { EventEmitter } from 'events';
import { HookPacketClient } from './hook-packet-client'; import { HookPacketClient } from './hook-packet-client';
import type { HookInjectResult } from './injector'; import type { HookInjectResult, ManualMapHandle } from './injector';
import { detectUinForPid } from './qq-account'; import { detectUinForPid } from './qq-account';
import type { QqHookClient, QqHookLoginState, QqHookPacket } from './qq-hook-client'; import type { QqHookClient, QqHookLoginState, QqHookPacket } from './qq-hook-client';
import { statusFor } from './hook-status'; import { statusFor } from './hook-status';
@@ -33,8 +33,8 @@ const RECEIVE_STALE_CONFIRM_MS = 15_000;
export type HookSessionDeps = { export type HookSessionDeps = {
injector: { injector: {
inject: (pid: number) => HookInjectResult | Promise<HookInjectResult>; inject: (pid: number) => Promise<HookInjectResult>;
unload: (pid: number, handle: HookInjectResult['handle']) => void; unload: (pid: number, handle: ManualMapHandle) => Promise<void>;
}; };
makeClient: (pid: number) => QqHookClient; makeClient: (pid: number) => QqHookClient;
/** Account QQ's local data reports as signed in on `pid`, or null. Drives the /** Account QQ's local data reports as signed in on `pid`, or null. Drives the
@@ -440,7 +440,7 @@ export class HookSession extends EventEmitter {
const handle = this.injectResult?.handle; const handle = this.injectResult?.handle;
if (this.injected && handle) { if (this.injected && handle) {
this.injector.unload(this.pid, handle); await this.injector.unload(this.pid, handle);
this.log.info('SnowLuma unloaded from PID=%d', this.pid); this.log.info('SnowLuma unloaded from PID=%d', this.pid);
} }
+8 -8
View File
@@ -11,11 +11,11 @@ export interface ManualMapHandle {
} }
interface NativeHookAddon { interface NativeHookAddon {
getRuntimeIntegrity?(): unknown; getRuntimeIntegrityAsync(): Promise<unknown>;
getAllMainProcessAsync(): Promise<number[]>; getAllMainProcessAsync(): Promise<number[]>;
probeDbLock?(dbPath: string): { pid: number; name: string }[]; getFileHoldersAsync(path: string): Promise<{ pid: number; name: string }[]>;
loadModuleManual(pid: number, dylibPath: string): ManualMapHandle | Promise<ManualMapHandle>; loadModuleManualAsync(pid: number, dylibPath: string): Promise<ManualMapHandle>;
unloadModuleManual(pid: number, handle: ManualMapHandle): void; unloadModuleManualAsync(pid: number, handle: ManualMapHandle): Promise<void>;
} }
export interface HookProcessBaseInfo { export interface HookProcessBaseInfo {
@@ -26,7 +26,7 @@ export interface HookProcessBaseInfo {
export interface HookInjectResult { export interface HookInjectResult {
method: 'loadModuleManual'; method: 'loadModuleManual';
handle?: ManualMapHandle; handle: ManualMapHandle;
} }
let nativeAddon: NativeHookAddon | null = null; let nativeAddon: NativeHookAddon | null = null;
@@ -123,15 +123,15 @@ export async function injectHookProcess(pid: number): Promise<HookInjectResult>
throw new Error(`No hook ${injectableExt} found for ${process.platform}-${process.arch}`); throw new Error(`No hook ${injectableExt} found for ${process.platform}-${process.arch}`);
} }
return { method: 'loadModuleManual', handle: await addon.loadModuleManual(pid, dllPath) }; return { method: 'loadModuleManual', handle: await addon.loadModuleManualAsync(pid, dllPath) };
} }
export function unloadHookProcess(pid: number, handle: ManualMapHandle): void { export async function unloadHookProcess(pid: number, handle: ManualMapHandle): Promise<void> {
const addon = getNativeHookAddon(); const addon = getNativeHookAddon();
if (!addon) { if (!addon) {
throw new Error(getNativeHookLoadError() ?? 'hook native addon is not available'); throw new Error(getNativeHookLoadError() ?? 'hook native addon is not available');
} }
addon.unloadModuleManual(pid, handle); await addon.unloadModuleManualAsync(pid, handle);
} }
@@ -1,28 +1,27 @@
import fs from 'node:fs'; import fs from 'node:fs/promises';
import { getNativeHookAddon } from '../injector'; import { getNativeHookAddon } from '../injector';
export interface DbLockHolder { export interface DatabaseHolder {
pid: number; pid: number;
name: string; name: string;
} }
export function probeDbLock(dbPath: string): DbLockHolder[] { export async function getDatabaseHolders(dbPath: string): Promise<DatabaseHolder[]> {
if (process.platform === 'win32') { if (process.platform === 'win32') {
return probeWindowsHolders(dbPath); return getWindowsHolders(dbPath);
} }
return process.platform === 'linux' ? probeLinuxLocks(dbPath) : []; return process.platform === 'linux' ? getLinuxHolders(dbPath) : [];
} }
function probeWindowsHolders(dbPath: string): DbLockHolder[] { async function getWindowsHolders(dbPath: string): Promise<DatabaseHolder[]> {
const addon = getNativeHookAddon(); const addon = getNativeHookAddon();
if (!addon?.probeDbLock) { if (!addon?.getFileHoldersAsync) {
throw new Error('Windows account detection requires a hook addon with probeDbLock'); throw new Error('Windows account detection requires a hook addon with getFileHoldersAsync');
} }
const holders = addon.probeDbLock(dbPath); const holders = await addon.getFileHoldersAsync(dbPath);
if ( if (
!Array.isArray(holders) || !Array.isArray(holders) ||
@@ -50,16 +49,22 @@ export function isQqProcessName(name: string): boolean {
} }
/** Match POSIX locks by device and inode; the table does not contain file paths. */ /** Match POSIX locks by device and inode; the table does not contain file paths. */
function probeLinuxLocks(dbPath: string): DbLockHolder[] { async function getLinuxHolders(dbPath: string): Promise<DatabaseHolder[]> {
const stat = fs.statSync(dbPath, { throwIfNoEntry: false }); const stat = await fs.stat(dbPath).catch((error: NodeJS.ErrnoException) => {
if (error.code === 'ENOENT') {
return null;
}
throw error;
});
if (!stat) { if (!stat) {
return []; return [];
} }
const key = deviceInodeKey(stat.dev, stat.ino); const key = deviceInodeKey(stat.dev, stat.ino);
const table = fs.readFileSync('/proc/locks', 'utf8'); const table = await fs.readFile('/proc/locks', 'utf8');
const holders: DbLockHolder[] = []; const holders: DatabaseHolder[] = [];
const seen = new Set<number>(); const seen = new Set<number>();
for (const line of table.split('\n')) { for (const line of table.split('\n')) {
@@ -77,7 +82,7 @@ function probeLinuxLocks(dbPath: string): DbLockHolder[] {
} }
seen.add(pid); seen.add(pid);
holders.push({ pid, name: readProcessName(pid) }); holders.push({ pid, name: await readProcessName(pid) });
} }
return holders; return holders;
@@ -89,10 +94,14 @@ function deviceInodeKey(device: number, inode: number): string {
return `${major.toString(16).padStart(2, '0')}:${minor.toString(16).padStart(2, '0')}:${inode}`; return `${major.toString(16).padStart(2, '0')}:${minor.toString(16).padStart(2, '0')}:${inode}`;
} }
function readProcessName(pid: number): string { async function readProcessName(pid: number): Promise<string> {
try { try {
return fs.readFileSync(`/proc/${pid}/comm`, 'utf8').trim(); return (await fs.readFile(`/proc/${pid}/comm`, 'utf8')).trim();
} catch { } catch (error) {
return ''; if ((error as NodeJS.ErrnoException).code === 'ENOENT') {
return '';
}
throw error;
} }
} }
+3 -3
View File
@@ -1,5 +1,5 @@
import { createLogger } from '@snowluma/common/logger'; import { createLogger } from '@snowluma/common/logger';
import { isQqProcessName, probeDbLock } from './db-lock'; import { isQqProcessName, getDatabaseHolders } from './database-holders';
import { readLocalAccounts, type LocalAccount } from './login-db'; import { readLocalAccounts, type LocalAccount } from './login-db';
import { loginDbPaths, ntMsgDbPath, qqDataRoots, qqDataRootsForPid } from './paths'; import { loginDbPaths, ntMsgDbPath, qqDataRoots, qqDataRootsForPid } from './paths';
@@ -39,8 +39,8 @@ export async function detectAccountLogins(
} }
for (const account of report.accounts) { for (const account of report.accounts) {
const holder = probeDbLock(ntMsgDbPath(root, account)).find((candidate) => const holder = (await getDatabaseHolders(ntMsgDbPath(root, account))).find(
isQqProcessName(candidate.name), (candidate) => isQqProcessName(candidate.name),
); );
states.push({ ...account, pid: holder?.pid ?? null }); states.push({ ...account, pid: holder?.pid ?? null });
} }
+1 -1
View File
@@ -1,4 +1,4 @@
export { isQqProcessName, probeDbLock, type DbLockHolder } from './db-lock'; export { isQqProcessName, getDatabaseHolders, type DatabaseHolder } from './database-holders';
export { export {
detectAccountLogins, detectAccountLogins,
detectAccountLoginsForPids, detectAccountLoginsForPids,
+10 -12
View File
@@ -76,18 +76,18 @@ function isNativeRuntimeIntegrity(value: unknown): value is NativeRuntimeIntegri
); );
} }
let cached: RuntimeIntegrity | undefined; let cached: Promise<RuntimeIntegrity> | undefined;
/** One startup snapshot, shared by the startup log and the WebUI warning. */ /** One startup snapshot, shared by the startup log and the WebUI warning. */
export function getRuntimeIntegrity(): RuntimeIntegrity { export function getRuntimeIntegrity(): Promise<RuntimeIntegrity> {
return (cached ??= readRuntimeIntegrity());
}
async function readRuntimeIntegrity(): Promise<RuntimeIntegrity> {
if (process.platform !== 'win32') { if (process.platform !== 'win32') {
return { status: 'unsupported' }; return { status: 'unsupported' };
} }
if (cached) {
return cached;
}
try { try {
const addon = getNativeHookAddon(); const addon = getNativeHookAddon();
@@ -95,17 +95,17 @@ export function getRuntimeIntegrity(): RuntimeIntegrity {
throw new Error(getNativeHookLoadError() ?? '原生组件不可用'); throw new Error(getNativeHookLoadError() ?? '原生组件不可用');
} }
if (typeof addon.getRuntimeIntegrity !== 'function') { if (typeof addon.getRuntimeIntegrityAsync !== 'function') {
throw new Error('当前原生组件不支持完整性诊断,请更新原生组件'); throw new Error('当前原生组件不支持完整性诊断,请更新原生组件');
} }
const result = addon.getRuntimeIntegrity(); const result = await addon.getRuntimeIntegrityAsync();
if (!isNativeRuntimeIntegrity(result)) { if (!isNativeRuntimeIntegrity(result)) {
throw new Error('原生完整性诊断返回了无效数据'); throw new Error('原生完整性诊断返回了无效数据');
} }
cached = { return {
status: 'available', status: 'available',
pid: result.pid, pid: result.pid,
executablePath: result.executablePath, executablePath: result.executablePath,
@@ -113,11 +113,9 @@ export function getRuntimeIntegrity(): RuntimeIntegrity {
file: result.file, file: result.file,
}; };
} catch (error) { } catch (error) {
cached = { return {
status: 'unavailable', status: 'unavailable',
error: error instanceof Error ? error.message : String(error), error: error instanceof Error ? error.message : String(error),
}; };
} }
return cached;
} }
@@ -68,8 +68,11 @@ function makeManager(
bridgeManager, bridgeManager,
pipeWatcher, pipeWatcher,
injector: { injector: {
inject: vi.fn(() => ({ method: 'loadModuleManual' as const, handle: DUMMY_HANDLE })), inject: vi.fn(async () => ({
unload: vi.fn(), method: 'loadModuleManual' as const,
handle: DUMMY_HANDLE,
})),
unload: vi.fn(async () => {}),
}, },
makeClient: clientFactory, makeClient: clientFactory,
listProcesses: async () => pids.map((pid) => ({ pid, name: 'qq', path: '' })), listProcesses: async () => pids.map((pid) => ({ pid, name: 'qq', path: '' })),
@@ -174,11 +177,11 @@ describe('HookManager.onSessionsChanged', () => {
} as unknown as BridgeManagerSink, } as unknown as BridgeManagerSink,
pipeWatcher, pipeWatcher,
injector: { injector: {
inject: vi.fn(() => ({ inject: vi.fn(async () => ({
method: 'loadModuleManual' as const, method: 'loadModuleManual' as const,
handle: DUMMY_HANDLE, handle: DUMMY_HANDLE,
})), })),
unload: vi.fn(), unload: vi.fn(async () => {}),
}, },
makeClient: vi.fn(() => { makeClient: vi.fn(() => {
const c = new EventEmitter() as any; const c = new EventEmitter() as any;
+3 -3
View File
@@ -29,19 +29,19 @@ function makeManager(opts: {
autoLoadOnDiscovery?: boolean; autoLoadOnDiscovery?: boolean;
processes?: number[]; processes?: number[];
onSessionsChanged?: () => void; onSessionsChanged?: () => void;
inject?: (pid: number) => HookInjectResult | Promise<HookInjectResult>; inject?: (pid: number) => Promise<HookInjectResult>;
detectAccounts?: (pids: readonly number[]) => Promise<AccountLoginState[]>; detectAccounts?: (pids: readonly number[]) => Promise<AccountLoginState[]>;
}) { }) {
let pids = opts.processes ?? []; let pids = opts.processes ?? [];
const live = new Set<number>(); const live = new Set<number>();
const inject = vi.fn( const inject = vi.fn(
opts.inject ?? opts.inject ??
(() => ({ (async () => ({
method: 'loadModuleManual' as const, method: 'loadModuleManual' as const,
handle: DUMMY_HANDLE, handle: DUMMY_HANDLE,
})), })),
); );
const unload = vi.fn(); const unload = vi.fn(async () => {});
const pipeWatcher = new PipeWatcher({ const pipeWatcher = new PipeWatcher({
listProcesses: async () => pids.map((pid) => ({ pid, name: 'qq', path: '' })), listProcesses: async () => pids.map((pid) => ({ pid, name: 'qq', path: '' })),
listLivePipes: async () => new Set(live), listLivePipes: async () => new Set(live),
@@ -58,11 +58,11 @@ describe('HookManager — Docker reconnect-without-login leak guard', () => {
bridgeManager, bridgeManager,
pipeWatcher, pipeWatcher,
injector: { injector: {
inject: vi.fn(() => ({ inject: vi.fn(async () => ({
method: 'loadModuleManual' as const, method: 'loadModuleManual' as const,
handle: DUMMY_HANDLE, handle: DUMMY_HANDLE,
})), })),
unload: vi.fn(), unload: vi.fn(async () => {}),
}, },
makeClient: () => { makeClient: () => {
const c = new FakeClient(); const c = new FakeClient();
@@ -59,11 +59,11 @@ describe('HookSession — pipe reconnect with QQ never logging in', () => {
const session = new HookSession(61, { const session = new HookSession(61, {
detectLoginUin: async () => null, detectLoginUin: async () => null,
injector: { injector: {
inject: vi.fn(() => ({ inject: vi.fn(async () => ({
method: 'loadModuleManual' as const, method: 'loadModuleManual' as const,
handle: DUMMY_HANDLE, handle: DUMMY_HANDLE,
})), })),
unload: vi.fn(), unload: vi.fn(async () => {}),
}, },
makeClient: () => { makeClient: () => {
const c = new FakeClient(); const c = new FakeClient();
@@ -103,11 +103,11 @@ describe('HookSession — pipe reconnect with QQ never logging in', () => {
const session = new HookSession(61, { const session = new HookSession(61, {
detectLoginUin: async () => null, detectLoginUin: async () => null,
injector: { injector: {
inject: vi.fn(() => ({ inject: vi.fn(async () => ({
method: 'loadModuleManual' as const, method: 'loadModuleManual' as const,
handle: DUMMY_HANDLE, handle: DUMMY_HANDLE,
})), })),
unload: vi.fn(), unload: vi.fn(async () => {}),
}, },
makeClient: () => { makeClient: () => {
const c = new FakeClient(); const c = new FakeClient();
+57 -15
View File
@@ -112,8 +112,8 @@ function makeSession(
let pipeLive = opts.pipeLive ?? false; let pipeLive = opts.pipeLive ?? false;
const clients: FakeClient[] = []; const clients: FakeClient[] = [];
const injector = { const injector = {
inject: vi.fn(() => ({ method: 'loadModuleManual' as const, handle: DUMMY_HANDLE })), inject: vi.fn(async () => ({ method: 'loadModuleManual' as const, handle: DUMMY_HANDLE })),
unload: vi.fn(), unload: vi.fn(async () => {}),
}; };
// Default detection exposes no account so the reconcile safety net is inert // Default detection exposes no account so the reconcile safety net is inert
// unless a test opts into a known one. // unless a test opts into a known one.
@@ -200,10 +200,10 @@ describe('HookSession — runtime TRACE', () => {
try { try {
const injector = { const injector = {
inject: vi.fn(() => { inject: vi.fn(async () => {
throw new Error('fixture inject failure'); throw new Error('fixture inject failure');
}), }),
unload: vi.fn(), unload: vi.fn(async () => {}),
}; };
const failedLoad = new HookSession(7103, { const failedLoad = new HookSession(7103, {
injector, injector,
@@ -248,11 +248,11 @@ describe('HookSession — runtime TRACE', () => {
const clients: FakeClient[] = []; const clients: FakeClient[] = [];
const session = new HookSession(7108, { const session = new HookSession(7108, {
injector: { injector: {
inject: () => { inject: async () => {
pipeLive = true; pipeLive = true;
throw new Error('component loading failed [COMPONENT_LOAD_FAILED]'); throw new Error('component loading failed [COMPONENT_LOAD_FAILED]');
}, },
unload: () => undefined, unload: async () => undefined,
}, },
makeClient: () => { makeClient: () => {
const client = new FakeClient(); const client = new FakeClient();
@@ -451,8 +451,8 @@ describe('HookSession — load', () => {
}, },
); );
const injector = { const injector = {
inject: vi.fn(() => loading), inject: vi.fn(async () => loading),
unload: vi.fn(), unload: vi.fn(async () => {}),
}; };
const session = new HookSession(1234, { const session = new HookSession(1234, {
injector, injector,
@@ -474,10 +474,10 @@ describe('HookSession — load', () => {
it('inject failure → status error, error message captured', async () => { it('inject failure → status error, error message captured', async () => {
const injector = { const injector = {
inject: vi.fn(() => { inject: vi.fn(async () => {
throw new Error('inject boom'); throw new Error('inject boom');
}), }),
unload: vi.fn(), unload: vi.fn(async () => {}),
}; };
const session = new HookSession(1234, { const session = new HookSession(1234, {
injector, injector,
@@ -498,7 +498,7 @@ describe('HookSession — load', () => {
method: 'loadModuleManual' as const, method: 'loadModuleManual' as const,
handle: DUMMY_HANDLE, handle: DUMMY_HANDLE,
}), }),
unload: vi.fn(), unload: vi.fn(async () => {}),
}; };
const session = new HookSession(1234, { const session = new HookSession(1234, {
injector, injector,
@@ -678,11 +678,11 @@ describe('HookSession — unload', () => {
const session = new HookSession(pid, { const session = new HookSession(pid, {
injector: { injector: {
inject: vi.fn(() => ({ inject: vi.fn(async () => ({
method: 'loadModuleManual' as const, method: 'loadModuleManual' as const,
handle: DUMMY_HANDLE, handle: DUMMY_HANDLE,
})), })),
unload: vi.fn(), unload: vi.fn(async () => {}),
}, },
makeClient: () => new FakeClient() as unknown as QqHookClient, makeClient: () => new FakeClient() as unknown as QqHookClient,
pipeWatcher: { isPipeLive: () => pipeLive, tickNow }, pipeWatcher: { isPipeLive: () => pipeLive, tickNow },
@@ -699,6 +699,48 @@ describe('HookSession — unload', () => {
}); });
describe('HookSession — serialization', () => { describe('HookSession — serialization', () => {
it('waits for native unload before starting a queued load', async () => {
const ctx = makeSession();
await ctx.session.load();
let finish!: () => void;
ctx.injector.unload.mockReturnValueOnce(
new Promise<void>((resolve) => {
finish = resolve;
}),
);
const unloading = ctx.session.unload();
const loading = ctx.session.load();
await flush();
expect(ctx.injector.unload).toHaveBeenCalledOnce();
expect(ctx.injector.inject).toHaveBeenCalledTimes(1);
expect(ctx.session.toInfo().injected).toBe(true);
finish();
await unloading;
await loading;
expect(ctx.injector.inject).toHaveBeenCalledTimes(2);
ctx.session.dispose();
});
it('retains the handle when native unload rejects so it can be retried', async () => {
const ctx = makeSession();
await ctx.session.load();
ctx.injector.unload.mockRejectedValueOnce(new Error('unload rejected'));
await expect(ctx.session.unload()).resolves.toMatchObject({
status: 'error',
error: 'unload rejected',
injected: true,
});
await expect(ctx.session.unload()).resolves.toMatchObject({
status: 'available',
injected: false,
});
expect(ctx.injector.unload).toHaveBeenNthCalledWith(2, ctx.session.pid, DUMMY_HANDLE);
ctx.session.dispose();
});
it('user mashing load → unload → load runs in order, end state consistent', async () => { it('user mashing load → unload → load runs in order, end state consistent', async () => {
const ctx = makeSession({ pipeLive: false }); const ctx = makeSession({ pipeLive: false });
@@ -864,10 +906,10 @@ describe('HookSession — pipe-down must not clobber a settled error', () => {
it('onPipeDown after a failed load leaves the error status intact', async () => { it('onPipeDown after a failed load leaves the error status intact', async () => {
const injector = { const injector = {
inject: vi.fn(() => { inject: vi.fn(async () => {
throw new Error('inject boom'); throw new Error('inject boom');
}), }),
unload: vi.fn(), unload: vi.fn(async () => {}),
}; };
const session = new HookSession(1234, { const session = new HookSession(1234, {
injector, injector,
+31 -31
View File
@@ -62,14 +62,16 @@ function allowExisting(paths: readonly string[]): void {
function fakeAddon( function fakeAddon(
overrides: { overrides: {
getAllMainProcessAsync?: number[]; getAllMainProcessAsync?: number[];
loadModuleManual?: (pid: number, dylibPath: string) => unknown; loadModuleManualAsync?: (pid: number, dylibPath: string) => Promise<typeof HANDLE>;
unloadModuleManual?: (pid: number, handle: typeof HANDLE) => void; unloadModuleManualAsync?: (pid: number, handle: typeof HANDLE) => Promise<void>;
} = {}, } = {},
) { ) {
return { return {
getAllMainProcessAsync: vi.fn(async () => overrides.getAllMainProcessAsync ?? []), getAllMainProcessAsync: vi.fn(async () => overrides.getAllMainProcessAsync ?? []),
loadModuleManual: vi.fn(overrides.loadModuleManual ?? (() => HANDLE)), loadModuleManualAsync: vi.fn(overrides.loadModuleManualAsync ?? (async () => HANDLE)),
unloadModuleManual: vi.fn(overrides.unloadModuleManual ?? (() => undefined)), unloadModuleManualAsync: vi.fn(
overrides.unloadModuleManualAsync ?? (async () => undefined),
),
}; };
} }
@@ -335,13 +337,13 @@ describe('injectHookProcess', () => {
await expect(injectHookProcess(4242)).rejects.toThrow('No hook so found for linux-x64'); await expect(injectHookProcess(4242)).rejects.toThrow('No hook so found for linux-x64');
}); });
it('awaits a thenable loadModuleManual handle', async () => { it('awaits native asynchronous injection', async () => {
setPlatform('linux', 'x64'); setPlatform('linux', 'x64');
const nodePath = nativeCandidate('snowluma-linux-x64.node', 0); const nodePath = nativeCandidate('snowluma-linux-x64.node', 0);
const soPath = nativeCandidate('snowluma-linux-x64.so', 0); const soPath = nativeCandidate('snowluma-linux-x64.so', 0);
allowExisting([nodePath, soPath]); allowExisting([nodePath, soPath]);
const addon = fakeAddon({ const addon = fakeAddon({
loadModuleManual: () => Promise.resolve(HANDLE), loadModuleManualAsync: () => Promise.resolve(HANDLE),
}); });
installDlopen(addon); installDlopen(addon);
@@ -350,24 +352,8 @@ describe('injectHookProcess', () => {
method: 'loadModuleManual', method: 'loadModuleManual',
handle: HANDLE, handle: HANDLE,
}); });
expect(addon.loadModuleManual).toHaveBeenCalledTimes(1); expect(addon.loadModuleManualAsync).toHaveBeenCalledTimes(1);
expect(addon.loadModuleManual).toHaveBeenCalledWith(4242, soPath); expect(addon.loadModuleManualAsync).toHaveBeenCalledWith(4242, soPath);
});
it('accepts a synchronous loadModuleManual return value', async () => {
setPlatform('darwin', 'arm64');
const nodePath = nativeCandidate('snowluma-darwin-arm64.node', 1);
const soPath = nativeCandidate('snowluma-darwin-arm64.so', 1);
allowExisting([nodePath, soPath]);
const addon = fakeAddon({ loadModuleManual: () => HANDLE });
installDlopen(addon);
const { injectHookProcess } = await loadInjector();
await expect(injectHookProcess(77)).resolves.toEqual({
method: 'loadModuleManual',
handle: HANDLE,
});
expect(addon.loadModuleManual).toHaveBeenCalledWith(77, soPath);
}); });
it('injects snowluma-win32-x64.dll on win32 x64', async () => { it('injects snowluma-win32-x64.dll on win32 x64', async () => {
@@ -375,7 +361,7 @@ describe('injectHookProcess', () => {
const nodePath = nativeCandidate('snowluma-win32-x64.node', 0); const nodePath = nativeCandidate('snowluma-win32-x64.node', 0);
const dllPath = nativeCandidate('snowluma-win32-x64.dll', 0); const dllPath = nativeCandidate('snowluma-win32-x64.dll', 0);
allowExisting([nodePath, dllPath]); allowExisting([nodePath, dllPath]);
const addon = fakeAddon({ loadModuleManual: () => HANDLE }); const addon = fakeAddon({ loadModuleManualAsync: async () => HANDLE });
installDlopen(addon); installDlopen(addon);
const { injectHookProcess } = await loadInjector(); const { injectHookProcess } = await loadInjector();
@@ -383,7 +369,7 @@ describe('injectHookProcess', () => {
method: 'loadModuleManual', method: 'loadModuleManual',
handle: HANDLE, handle: HANDLE,
}); });
expect(addon.loadModuleManual).toHaveBeenCalledWith(5150, dllPath); expect(addon.loadModuleManualAsync).toHaveBeenCalledWith(5150, dllPath);
}); });
it('propagates a rejected loadModuleManual', async () => { it('propagates a rejected loadModuleManual', async () => {
@@ -394,7 +380,7 @@ describe('injectHookProcess', () => {
]); ]);
installDlopen( installDlopen(
fakeAddon({ fakeAddon({
loadModuleManual: () => Promise.reject(new Error('map failed')), loadModuleManualAsync: () => Promise.reject(new Error('map failed')),
}), }),
); );
@@ -404,10 +390,24 @@ describe('injectHookProcess', () => {
}); });
describe('unloadHookProcess', () => { describe('unloadHookProcess', () => {
it('propagates native unload rejection', async () => {
setPlatform('linux', 'x64');
allowExisting([nativeCandidate('snowluma-linux-x64.node', 0)]);
installDlopen(
fakeAddon({
unloadModuleManualAsync: async () => {
throw new Error('unload failed');
},
}),
);
const { unloadHookProcess } = await loadInjector();
await expect(unloadHookProcess(4242, HANDLE)).rejects.toThrow('unload failed');
});
it('throws the missing-addon load error', async () => { it('throws the missing-addon load error', async () => {
setPlatform('linux', 'x64'); setPlatform('linux', 'x64');
const { unloadHookProcess } = await loadInjector(); const { unloadHookProcess } = await loadInjector();
expect(() => unloadHookProcess(4242, HANDLE)).toThrow( await expect(unloadHookProcess(4242, HANDLE)).rejects.toThrow(
'No hook native addon found for linux-x64', 'No hook native addon found for linux-x64',
); );
}); });
@@ -419,8 +419,8 @@ describe('unloadHookProcess', () => {
installDlopen(addon); installDlopen(addon);
const { unloadHookProcess } = await loadInjector(); const { unloadHookProcess } = await loadInjector();
expect(unloadHookProcess(4242, HANDLE)).toBeUndefined(); await expect(unloadHookProcess(4242, HANDLE)).resolves.toBeUndefined();
expect(addon.unloadModuleManual).toHaveBeenCalledTimes(1); expect(addon.unloadModuleManualAsync).toHaveBeenCalledTimes(1);
expect(addon.unloadModuleManual).toHaveBeenCalledWith(4242, HANDLE); expect(addon.unloadModuleManualAsync).toHaveBeenCalledWith(4242, HANDLE);
}); });
}); });
@@ -3,7 +3,7 @@ import { mkdtemp, rm } from 'node:fs/promises';
import os from 'node:os'; import os from 'node:os';
import path from 'node:path'; import path from 'node:path';
import { SqliteDatabase } from '@snowluma/sqlite'; import { SqliteDatabase } from '@snowluma/sqlite';
import { isQqProcessName, probeDbLock } from '../src/qq-account/db-lock'; import { isQqProcessName, getDatabaseHolders } from '../src/qq-account/database-holders';
const native = vi.hoisted(() => ({ addon: vi.fn<() => unknown>(() => null) })); const native = vi.hoisted(() => ({ addon: vi.fn<() => unknown>(() => null) }));
@@ -12,13 +12,13 @@ vi.mock('../src/injector', () => ({ getNativeHookAddon: native.addon }));
const IS_LINUX = process.platform === 'linux'; const IS_LINUX = process.platform === 'linux';
const ORIGINAL_PLATFORM = process.platform; const ORIGINAL_PLATFORM = process.platform;
/** Run `probeDbLock` as if the host were Windows, with a stubbed addon. */ /** Run `getDatabaseHolders` as if the host were Windows, with a stubbed addon. */
function asWindows<T>(addon: unknown, run: () => T): T { async function asWindows<T>(addon: unknown, run: () => Promise<T>): Promise<T> {
Object.defineProperty(process, 'platform', { value: 'win32', configurable: true }); Object.defineProperty(process, 'platform', { value: 'win32', configurable: true });
native.addon.mockReturnValue(addon); native.addon.mockReturnValue(addon);
try { try {
return run(); return await run();
} finally { } finally {
Object.defineProperty(process, 'platform', { Object.defineProperty(process, 'platform', {
value: ORIGINAL_PLATFORM, value: ORIGINAL_PLATFORM,
@@ -33,9 +33,9 @@ afterEach(() => {
}); });
describe('database holder probe', () => { describe('database holder probe', () => {
it.runIf(IS_LINUX)('reports nothing for a file that is not there', () => { it.runIf(IS_LINUX)('reports nothing for a file that is not there', async () => {
const missing = path.join(os.tmpdir(), `snowluma-absent-${process.pid}.db`); const missing = path.join(os.tmpdir(), `snowluma-absent-${process.pid}.db`);
expect(probeDbLock(missing)).toEqual([]); expect(await getDatabaseHolders(missing)).toEqual([]);
}); });
it.runIf(IS_LINUX)('finds the process holding a database', async () => { it.runIf(IS_LINUX)('finds the process holding a database', async () => {
@@ -51,7 +51,7 @@ describe('database holder probe', () => {
await db.exec('CREATE TABLE t(value TEXT)'); await db.exec('CREATE TABLE t(value TEXT)');
await db.exec('BEGIN IMMEDIATE'); await db.exec('BEGIN IMMEDIATE');
const holders = probeDbLock(file); const holders = await getDatabaseHolders(file);
const self = holders.find((holder) => holder.pid === process.pid); const self = holders.find((holder) => holder.pid === process.pid);
expect(self).toBeDefined(); expect(self).toBeDefined();
// The holder is named from /proc/<pid>/comm, and that name is what // The holder is named from /proc/<pid>/comm, and that name is what
@@ -60,7 +60,9 @@ describe('database holder probe', () => {
expect(isQqProcessName(self!.name)).toBe(false); expect(isQqProcessName(self!.name)).toBe(false);
await db.exec('ROLLBACK'); await db.exec('ROLLBACK');
expect(probeDbLock(file).some((holder) => holder.pid === process.pid)).toBe(false); expect(
(await getDatabaseHolders(file)).some((holder) => holder.pid === process.pid),
).toBe(false);
} finally { } finally {
await db.close(); await db.close();
await rm(directory, { recursive: true, force: true }); await rm(directory, { recursive: true, force: true });
@@ -69,15 +71,28 @@ describe('database holder probe', () => {
}); });
describe('Windows holder probe', () => { describe('Windows holder probe', () => {
it('reports the holders the addon lists', () => { it('propagates rejected native queries instead of treating them as no login', async () => {
const holders = asWindows( await expect(
asWindows(
{
getFileHoldersAsync: async () => {
throw new Error('RmGetList failed: 5');
},
},
() => getDatabaseHolders('C:\\nt_msg.db'),
),
).rejects.toThrow('RmGetList failed: 5');
});
it('reports the holders the addon lists', async () => {
const holders = await asWindows(
{ {
probeDbLock: () => [ getFileHoldersAsync: async () => [
{ pid: 4242, name: 'QQ.exe' }, { pid: 4242, name: 'QQ.exe' },
{ pid: 7, name: 'weq' }, { pid: 7, name: 'weq' },
], ],
}, },
() => probeDbLock('C:\\Tencent Files\\10001\\nt_qq\\nt_db\\nt_msg.db'), () => getDatabaseHolders('C:\\Tencent Files\\10001\\nt_qq\\nt_db\\nt_msg.db'),
); );
expect(holders).toEqual([ expect(holders).toEqual([
@@ -88,22 +103,26 @@ describe('Windows holder probe', () => {
it.each([[{ pid: 0, name: 'QQ' }], [{ pid: 9 }], [null], 'not-an-array'])( it.each([[{ pid: 0, name: 'QQ' }], [{ pid: 9 }], [null], 'not-an-array'])(
'reports malformed native results: %j', 'reports malformed native results: %j',
(result) => { async (result) => {
expect(() => await expect(
asWindows({ probeDbLock: () => result }, () => probeDbLock('C:\\nt_msg.db')), asWindows({ getFileHoldersAsync: async () => result }, () =>
).toThrow('Invalid database holders'); getDatabaseHolders('C:\\nt_msg.db'),
),
).rejects.toThrow('Invalid database holders');
}, },
); );
it('accepts an empty holder list', () => { it('accepts an empty holder list', async () => {
expect(asWindows({ probeDbLock: () => [] }, () => probeDbLock('C:\\nt_msg.db'))).toEqual( expect(
[], await asWindows({ getFileHoldersAsync: async () => [] }, () =>
); getDatabaseHolders('C:\\nt_msg.db'),
),
).toEqual([]);
}); });
it.each([null, {}])('reports an unavailable native probe: %j', (addon) => { it.each([null, {}])('reports an unavailable native probe: %j', async (addon) => {
expect(() => asWindows(addon, () => probeDbLock('C:\\nt_msg.db'))).toThrow( await expect(asWindows(addon, () => getDatabaseHolders('C:\\nt_msg.db'))).rejects.toThrow(
'requires a hook addon with probeDbLock', 'requires a hook addon with getFileHoldersAsync',
); );
}); });
}); });
+15 -15
View File
@@ -7,15 +7,15 @@ import { getLogLevel, setLogLevel, subscribeLogs, type LogEntry } from '@snowlum
const mocks = vi.hoisted(() => ({ const mocks = vi.hoisted(() => ({
readLocalAccounts: vi.fn(), readLocalAccounts: vi.fn(),
probeDbLock: vi.fn(), getDatabaseHolders: vi.fn(),
})); }));
// The account list and the holder probe are covered on their own; this file is // The account list and the holder probe are covered on their own; this file is
// about how the two are joined. // about how the two are joined.
vi.mock('../src/qq-account/login-db', () => ({ readLocalAccounts: mocks.readLocalAccounts })); vi.mock('../src/qq-account/login-db', () => ({ readLocalAccounts: mocks.readLocalAccounts }));
vi.mock('../src/qq-account/db-lock', async (importOriginal) => ({ vi.mock('../src/qq-account/database-holders', async (importOriginal) => ({
...(await importOriginal<typeof import('../src/qq-account/db-lock')>()), ...(await importOriginal<typeof import('../src/qq-account/database-holders')>()),
probeDbLock: mocks.probeDbLock, getDatabaseHolders: mocks.getDatabaseHolders,
})); }));
import { detectAccountLogins, detectAccountLoginsForPids } from '../src/qq-account/detect'; import { detectAccountLogins, detectAccountLoginsForPids } from '../src/qq-account/detect';
@@ -29,7 +29,7 @@ const children: Array<ReturnType<typeof spawn>> = [];
afterEach(async () => { afterEach(async () => {
mocks.readLocalAccounts.mockReset(); mocks.readLocalAccounts.mockReset();
mocks.probeDbLock.mockReset(); mocks.getDatabaseHolders.mockReset();
for (const child of children.splice(0)) { for (const child of children.splice(0)) {
child.kill(); child.kill();
@@ -77,7 +77,7 @@ describe('local account detection', () => {
it('labels each account with the process holding its database', async () => { it('labels each account with the process holding its database', async () => {
const root = await makeRoot(); const root = await makeRoot();
mocks.readLocalAccounts.mockResolvedValue({ accounts: [ALICE, BOB], failures: [] }); mocks.readLocalAccounts.mockResolvedValue({ accounts: [ALICE, BOB], failures: [] });
mocks.probeDbLock.mockImplementation((dbPath: string) => { mocks.getDatabaseHolders.mockImplementation(async (dbPath: string) => {
if (dbPath === ntMsgDbPath(root, ALICE)) { if (dbPath === ntMsgDbPath(root, ALICE)) {
return [{ pid: 4242, name: 'qq' }]; return [{ pid: 4242, name: 'qq' }];
} }
@@ -98,7 +98,7 @@ describe('local account detection', () => {
mocks.readLocalAccounts.mockImplementation(async (root: string) => mocks.readLocalAccounts.mockImplementation(async (root: string) =>
root === own ? { accounts: [ALICE], failures: [] } : { accounts: [BOB], failures: [] }, root === own ? { accounts: [ALICE], failures: [] } : { accounts: [BOB], failures: [] },
); );
mocks.probeDbLock.mockImplementation((dbPath: string) => mocks.getDatabaseHolders.mockImplementation(async (dbPath: string) =>
dbPath === ntMsgDbPath(extra, BOB) ? [{ pid: 5151, name: 'qq' }] : [], dbPath === ntMsgDbPath(extra, BOB) ? [{ pid: 5151, name: 'qq' }] : [],
); );
@@ -109,7 +109,7 @@ describe('local account detection', () => {
// An account held under an instance's own HOME is still labelled, which // An account held under an instance's own HOME is still labelled, which
// is what a single-root lookup cannot do. // is what a single-root lookup cannot do.
expect(mocks.probeDbLock).toHaveBeenCalledWith(ntMsgDbPath(extra, BOB)); expect(mocks.getDatabaseHolders).toHaveBeenCalledWith(ntMsgDbPath(extra, BOB));
}); });
it('keeps account records with the same uin scoped to their own root', async () => { it('keeps account records with the same uin scoped to their own root', async () => {
@@ -120,7 +120,7 @@ describe('local account detection', () => {
? { accounts: [ALICE], failures: [] } ? { accounts: [ALICE], failures: [] }
: { accounts: [{ ...ALICE, nickname: 'Stale' }], failures: [] }, : { accounts: [{ ...ALICE, nickname: 'Stale' }], failures: [] },
); );
mocks.probeDbLock.mockImplementation((file: string) => mocks.getDatabaseHolders.mockImplementation(async (file: string) =>
file === ntMsgDbPath(second, ALICE) ? [{ pid: 5151, name: 'qq' }] : [], file === ntMsgDbPath(second, ALICE) ? [{ pid: 5151, name: 'qq' }] : [],
); );
@@ -152,7 +152,7 @@ describe('local account detection', () => {
}, },
], ],
}); });
mocks.probeDbLock.mockReturnValue([]); mocks.getDatabaseHolders.mockResolvedValue([]);
// An unreadable login.db must not look like "no accounts": an // An unreadable login.db must not look like "no accounts": an
// operator reading the log has to see why nothing was reported. // operator reading the log has to see why nothing was reported.
@@ -176,7 +176,7 @@ describe.runIf(process.platform === 'linux')('per-process data roots', () => {
const home = await makeRoot(); const home = await makeRoot();
const pid = await spawnWithHome(home); const pid = await spawnWithHome(home);
mocks.readLocalAccounts.mockResolvedValue({ accounts: [], failures: [] }); mocks.readLocalAccounts.mockResolvedValue({ accounts: [], failures: [] });
mocks.probeDbLock.mockReturnValue([]); mocks.getDatabaseHolders.mockResolvedValue([]);
await detectAccountLoginsForPids([pid]); await detectAccountLoginsForPids([pid]);
@@ -188,7 +188,7 @@ describe.runIf(process.platform === 'linux')('per-process data roots', () => {
const home = await makeRoot(); const home = await makeRoot();
const pids = [await spawnWithHome(home), await spawnWithHome(home)]; const pids = [await spawnWithHome(home), await spawnWithHome(home)];
mocks.readLocalAccounts.mockResolvedValue({ accounts: [], failures: [] }); mocks.readLocalAccounts.mockResolvedValue({ accounts: [], failures: [] });
mocks.probeDbLock.mockReturnValue([]); mocks.getDatabaseHolders.mockResolvedValue([]);
await detectAccountLoginsForPids(pids); await detectAccountLoginsForPids(pids);
@@ -200,7 +200,7 @@ describe.runIf(process.platform === 'linux')('per-process data roots', () => {
const configHome = await makeRoot(); const configHome = await makeRoot();
const pid = await spawnWithHome(home, { XDG_CONFIG_HOME: configHome }); const pid = await spawnWithHome(home, { XDG_CONFIG_HOME: configHome });
mocks.readLocalAccounts.mockResolvedValue({ accounts: [], failures: [] }); mocks.readLocalAccounts.mockResolvedValue({ accounts: [], failures: [] });
mocks.probeDbLock.mockReturnValue([]); mocks.getDatabaseHolders.mockResolvedValue([]);
await detectAccountLoginsForPids([pid]); await detectAccountLoginsForPids([pid]);
@@ -213,7 +213,7 @@ describe.runIf(process.platform === 'linux')('per-process data roots', () => {
const second = await makeRoot(); const second = await makeRoot();
const pids = [await spawnWithHome(first), await spawnWithHome(second)]; const pids = [await spawnWithHome(first), await spawnWithHome(second)];
mocks.readLocalAccounts.mockResolvedValue({ accounts: [], failures: [] }); mocks.readLocalAccounts.mockResolvedValue({ accounts: [], failures: [] });
mocks.probeDbLock.mockReturnValue([]); mocks.getDatabaseHolders.mockResolvedValue([]);
await detectAccountLoginsForPids(pids); await detectAccountLoginsForPids(pids);
@@ -225,7 +225,7 @@ describe.runIf(process.platform === 'linux')('per-process data roots', () => {
const home = await makeRoot(); const home = await makeRoot();
const pid = await spawnWithHome(home); const pid = await spawnWithHome(home);
mocks.readLocalAccounts.mockResolvedValue({ accounts: [], failures: [] }); mocks.readLocalAccounts.mockResolvedValue({ accounts: [], failures: [] });
mocks.probeDbLock.mockReturnValue([]); mocks.getDatabaseHolders.mockResolvedValue([]);
// The child exits, so its environment is no longer readable. // The child exits, so its environment is no longer readable.
await new Promise<void>((resolve) => { await new Promise<void>((resolve) => {
+20 -20
View File
@@ -56,20 +56,22 @@ describe('runtime integrity diagnostics', () => {
}); });
it('keeps one startup snapshot for logging and all WebUI polls', async () => { it('keeps one startup snapshot for logging and all WebUI polls', async () => {
const read = vi.fn().mockReturnValue(sample()); const read = vi.fn().mockResolvedValue(sample());
native.load.mockReturnValue({ getRuntimeIntegrity: read }); native.load.mockReturnValue({ getRuntimeIntegrityAsync: read });
const { getRuntimeIntegrity } = await import('../src/runtime-integrity'); const { getRuntimeIntegrity } = await import('../src/runtime-integrity');
const first = getRuntimeIntegrity(); const pending = getRuntimeIntegrity();
expect(getRuntimeIntegrity()).toBe(pending);
const first = await pending;
expect(first).toMatchObject({ expect(first).toMatchObject({
status: 'available', status: 'available',
process: { rid: 8192 }, process: { rid: 8192 },
file: { label: null }, file: { label: null },
}); });
read.mockReturnValue({ read.mockResolvedValue({
...sample(), ...sample(),
file: { status: 'ok', label: { rid: 4096, inherited: true, policy: 1 } }, file: { status: 'ok', label: { rid: 4096, inherited: true, policy: 1 } },
}); });
expect(getRuntimeIntegrity()).toBe(first); expect(await getRuntimeIntegrity()).toBe(first);
expect(read).toHaveBeenCalledTimes(1); expect(read).toHaveBeenCalledTimes(1);
}); });
@@ -77,13 +79,13 @@ describe('runtime integrity diagnostics', () => {
'retains %s query errors and the other successful result', 'retains %s query errors and the other successful result',
async (field) => { async (field) => {
native.load.mockReturnValue({ native.load.mockReturnValue({
getRuntimeIntegrity: () => ({ getRuntimeIntegrityAsync: async () => ({
...sample(), ...sample(),
[field]: { status: 'error', operation: 'Win32Query', code: 5 }, [field]: { status: 'error', operation: 'Win32Query', code: 5 },
}), }),
}); });
const { getRuntimeIntegrity } = await import('../src/runtime-integrity'); const { getRuntimeIntegrity } = await import('../src/runtime-integrity');
expect(getRuntimeIntegrity()).toMatchObject({ expect(await getRuntimeIntegrity()).toMatchObject({
status: 'available', status: 'available',
[field]: { status: 'error', operation: 'Win32Query', code: 5 }, [field]: { status: 'error', operation: 'Win32Query', code: 5 },
}); });
@@ -93,7 +95,7 @@ describe('runtime integrity diagnostics', () => {
it('reports old addons as unavailable rather than Medium', async () => { it('reports old addons as unavailable rather than Medium', async () => {
native.load.mockReturnValue({}); native.load.mockReturnValue({});
const { getRuntimeIntegrity } = await import('../src/runtime-integrity'); const { getRuntimeIntegrity } = await import('../src/runtime-integrity');
expect(getRuntimeIntegrity()).toMatchObject({ expect(await getRuntimeIntegrity()).toMatchObject({
status: 'unavailable', status: 'unavailable',
error: expect.stringContaining('不支持'), error: expect.stringContaining('不支持'),
}); });
@@ -103,7 +105,7 @@ describe('runtime integrity diagnostics', () => {
native.load.mockReturnValue(null); native.load.mockReturnValue(null);
native.error.mockReturnValue('dlopen failed: incompatible binary'); native.error.mockReturnValue('dlopen failed: incompatible binary');
const { getRuntimeIntegrity } = await import('../src/runtime-integrity'); const { getRuntimeIntegrity } = await import('../src/runtime-integrity');
expect(getRuntimeIntegrity()).toMatchObject({ expect(await getRuntimeIntegrity()).toMatchObject({
status: 'unavailable', status: 'unavailable',
error: 'dlopen failed: incompatible binary', error: 'dlopen failed: incompatible binary',
}); });
@@ -115,28 +117,26 @@ describe('runtime integrity diagnostics', () => {
{ ...sample(), process: { status: 'ok', rid: -1 } }, { ...sample(), process: { status: 'ok', rid: -1 } },
{ ...sample(), file: { status: 'ok', label: { rid: 4096, inherited: 'yes', policy: 1 } } }, { ...sample(), file: { status: 'ok', label: { rid: 4096, inherited: 'yes', policy: 1 } } },
])('rejects malformed or wrong-process native results', async (result) => { ])('rejects malformed or wrong-process native results', async (result) => {
native.load.mockReturnValue({ getRuntimeIntegrity: () => result }); native.load.mockReturnValue({ getRuntimeIntegrityAsync: async () => result });
const { getRuntimeIntegrity } = await import('../src/runtime-integrity'); const { getRuntimeIntegrity } = await import('../src/runtime-integrity');
expect(getRuntimeIntegrity()).toMatchObject({ expect(await getRuntimeIntegrity()).toMatchObject({
status: 'unavailable', status: 'unavailable',
error: expect.stringContaining('无效数据'), error: expect.stringContaining('无效数据'),
}); });
}); });
it('preserves thrown errors without repeatedly probing on WebUI polls', async () => { it('preserves rejected errors without repeatedly probing on WebUI polls', async () => {
const read = vi const read = vi
.fn() .fn()
.mockImplementationOnce(() => { .mockRejectedValueOnce(new Error('allocation failed'))
throw new Error('allocation failed'); .mockResolvedValue(sample());
}) native.load.mockReturnValue({ getRuntimeIntegrityAsync: read });
.mockReturnValue(sample());
native.load.mockReturnValue({ getRuntimeIntegrity: read });
const { getRuntimeIntegrity } = await import('../src/runtime-integrity'); const { getRuntimeIntegrity } = await import('../src/runtime-integrity');
expect(getRuntimeIntegrity()).toMatchObject({ expect(await getRuntimeIntegrity()).toMatchObject({
status: 'unavailable', status: 'unavailable',
error: 'allocation failed', error: 'allocation failed',
}); });
expect(getRuntimeIntegrity()).toMatchObject({ expect(await getRuntimeIntegrity()).toMatchObject({
status: 'unavailable', status: 'unavailable',
error: 'allocation failed', error: 'allocation failed',
}); });
@@ -146,7 +146,7 @@ describe('runtime integrity diagnostics', () => {
it('does not load the addon on non-Windows hosts', async () => { it('does not load the addon on non-Windows hosts', async () => {
Object.defineProperty(process, 'platform', { value: 'linux', configurable: true }); Object.defineProperty(process, 'platform', { value: 'linux', configurable: true });
const { getRuntimeIntegrity } = await import('../src/runtime-integrity'); const { getRuntimeIntegrity } = await import('../src/runtime-integrity');
expect(getRuntimeIntegrity()).toEqual({ status: 'unsupported' }); expect(await getRuntimeIntegrity()).toEqual({ status: 'unsupported' });
expect(native.load).not.toHaveBeenCalled(); expect(native.load).not.toHaveBeenCalled();
}); });
}); });
+1 -1
View File
@@ -59,7 +59,7 @@ async function main() {
perUinEnabled: runtimeConfig.logPerUin ?? DEFAULT_LOG_PER_UIN, perUinEnabled: runtimeConfig.logPerUin ?? DEFAULT_LOG_PER_UIN,
}); });
log.info('SnowLuma starting'); log.info('SnowLuma starting');
logRuntimeIntegrity(getRuntimeIntegrity()); logRuntimeIntegrity(await getRuntimeIntegrity());
const stopNativeStageSync = startNativeStageSync({ const stopNativeStageSync = startNativeStageSync({
version: APP_VERSION, version: APP_VERSION,
dataDir: 'data', dataDir: 'data',
+2 -2
View File
@@ -1364,7 +1364,7 @@ export async function initWebUI(
return usage; return usage;
} }
app.get('/api/system', (c) => { app.get('/api/system', async (c) => {
const cpus = os.cpus(); const cpus = os.cpus();
const usage = sampleCpuLoad(); const usage = sampleCpuLoad();
const totalMem = os.totalmem(); const totalMem = os.totalmem();
@@ -1397,7 +1397,7 @@ export async function initWebUI(
}, },
runtime: { runtime: {
pid: process.pid, pid: process.pid,
lowIntegrity: hasLowProcessIntegrity(getRuntimeIntegrity()), lowIntegrity: hasLowProcessIntegrity(await getRuntimeIntegrity()),
rss: runtimeMemory.rss, rss: runtimeMemory.rss,
heapTotal: runtimeMemory.heapTotal, heapTotal: runtimeMemory.heapTotal,
heapUsed: runtimeMemory.heapUsed, heapUsed: runtimeMemory.heapUsed,
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
+2 -3
View File
@@ -50,9 +50,8 @@ prove that QQ is signed out, and local detection alone never marks a bridge onli
The manual login probe and `/api/processes/:pid/probe-login` endpoint are removed. The manual login probe and `/api/processes/:pid/probe-login` endpoint are removed.
Linux resolves data roots from each QQ process's `XDG_CONFIG_HOME` or `HOME`. Linux resolves data roots from each QQ process's `XDG_CONFIG_HOME` or `HOME`.
Windows requires a hook addon with `probeDbLock`; the currently bundled addon does Windows uses the bundled addon’s `getFileHoldersAsync` to find the process holding
not provide it, so pre-injection account detection is unavailable there. A missing each account database. Query failures are reported instead of treated as no login.
interface is logged. Hook login events continue to report the online account.
## Account notification templates ## Account notification templates