feat(bridge): detect local QQ accounts with shared process snapshots (#525)

Read QQ account databases and attribute identities to their owning processes. Share snapshots across REST, watcher updates and login reconciliation, discard stale results, and report detection failures.
This commit is contained in:
H3CoF6 authored and GitHub committed 2026-10-18 12:10:37 +08:00
1 parent 8e24995fc3
commit f6ca9d5f65
38 files changed
+2979 -1534

No files matched your search

@@ -5,6 +5,7 @@ import { PipeWatcher } from '../src/pipe-watcher';
import type { ManualMapHandle } from '../src/injector';
import type { BridgeManagerSink } from '../src/hook-manager';
import type { QqHookClient } from '../src/qq-hook-client';
import type { AccountLoginState } from '../src/qq-account';
// Regression cover for the WebUI SSE wiring: HookManager must call its
// optional `onSessionsChanged` callback every time the observable set of
@@ -25,7 +26,14 @@ interface Harness {
clientFactory: ReturnType<typeof vi.fn>;
}
function makeManager(opts: { processes?: number[]; livePipes?: number[] } = {}): Harness {
function makeManager(
opts: {
processes?: number[];
livePipes?: number[];
detectAccounts?: (pids: readonly number[]) => Promise<AccountLoginState[]>;
accountReprobeIntervalMs?: number;
} = {},
): Harness {
let pids = opts.processes ?? [];
let live = new Set<number>(opts.livePipes ?? []);
const pipeWatcher = new PipeWatcher({
@@ -65,6 +73,8 @@ function makeManager(opts: { processes?: number[]; livePipes?: number[] } = {}):
},
makeClient: clientFactory,
listProcesses: () => pids.map((pid) => ({ pid, name: 'qq', path: '' })),
detectAccounts: opts.detectAccounts ?? (async () => []),
accountReprobeIntervalMs: opts.accountReprobeIntervalMs,
onSessionsChanged,
});
return {
@@ -184,6 +194,7 @@ describe('HookManager.onSessionsChanged', () => {
return c;
}),
listProcesses: () => pids.map((pid) => ({ pid, name: 'qq', path: '' })),
detectAccounts: async () => [],
// onSessionsChanged deliberately omitted
});
await pipeWatcher.start();
@@ -196,6 +207,202 @@ describe('HookManager.onSessionsChanged', () => {
});
});
describe('HookManager periodic account re-probe', () => {
it('shares one account probe between watcher ticks and concurrent snapshots', async () => {
const probe = Promise.withResolvers<AccountLoginState[]>();
const detectAccounts = vi.fn(() => probe.promise);
const ctx = makeManager({ processes: [4242], detectAccounts });
try {
await ctx.pipeWatcher.start();
const first = ctx.manager.listProcesses();
const second = ctx.manager.listProcesses();
await flush();
expect(detectAccounts).toHaveBeenCalledTimes(1);
probe.resolve([{ uin: '10001', uid: 'u_a', nickname: 'Alice', pid: 4242 }]);
const snapshots = await Promise.all([first, second]);
expect(snapshots.map((list) => list[0]!.account)).toEqual([
{ uin: '10001', nickname: 'Alice' },
{ uin: '10001', nickname: 'Alice' },
]);
} finally {
probe.resolve([]);
ctx.manager.dispose();
}
});
it('keeps all process labels when an operation reads just one process', async () => {
const accounts: AccountLoginState[] = [
{ uin: '10001', uid: 'u_a', nickname: 'Alice', pid: 4242 },
{ uin: '10002', uid: 'u_b', nickname: 'Bob', pid: 5151 },
];
const detectAccounts = vi.fn(async (pids: readonly number[]) =>
accounts.filter((account) => pids.includes(account.pid!)),
);
const ctx = makeManager({ processes: [4242, 5151], detectAccounts });
try {
await ctx.manager.listProcesses();
const baseline = detectAccounts.mock.calls.length;
expect((await ctx.manager.refreshProcess(4242)).account?.uin).toBe('10001');
ctx.onSessionsChanged.mockClear();
await ctx.pipeWatcher.tickNow();
await flush();
expect(detectAccounts).toHaveBeenCalledTimes(baseline);
expect(ctx.onSessionsChanged).not.toHaveBeenCalled();
expect((await ctx.manager.listProcesses())[1]!.account?.uin).toBe('10002');
} finally {
ctx.manager.dispose();
}
});
it('does not publish a late account result for an exited process', async () => {
const probe = Promise.withResolvers<AccountLoginState[]>();
const ctx = makeManager({ processes: [4242], detectAccounts: () => probe.promise });
try {
await ctx.pipeWatcher.start();
const snapshot = ctx.manager.listProcesses();
await flush();
ctx.setProcesses([]);
await ctx.pipeWatcher.tickNow();
await flush();
ctx.onSessionsChanged.mockClear();
probe.resolve([{ uin: '10001', uid: 'u_a', nickname: 'Alice', pid: 4242 }]);
await flush();
expect(await snapshot).toEqual([]);
expect(ctx.onSessionsChanged).not.toHaveBeenCalled();
expect(await ctx.manager.listProcesses()).toEqual([]);
} finally {
probe.resolve([]);
ctx.manager.dispose();
}
});
// A login can happen with no hook edge at all (QQ signs in after SnowLuma
// started, or before the hook was injected), so no session status changes
// and nothing pushes a fresh processes snapshot. These cover the watcher
// pass that re-reads the account labels and invalidates when they move.
it('publishes when a process gains an account label', async () => {
let accounts: AccountLoginState[] = [{ uin: '1', uid: 'u1', nickname: 'A', pid: null }];
const ctx = makeManager({
processes: [4242],
detectAccounts: async () => accounts,
accountReprobeIntervalMs: 0,
});
await ctx.pipeWatcher.start();
await flush();
ctx.onSessionsChanged.mockClear();
// QQ finished signing in: the account's nt_msg.db is now held by 4242.
accounts = [{ uin: '1', uid: 'u1', nickname: 'A', pid: 4242 }];
await ctx.pipeWatcher.tickNow();
await flush();
await flush();
expect(ctx.onSessionsChanged).toHaveBeenCalled();
const list = await ctx.manager.listProcesses();
expect(list[0]!.account).toEqual({ uin: '1', nickname: 'A' });
ctx.manager.dispose();
});
it('stays silent while the labels are unchanged', async () => {
const accounts: AccountLoginState[] = [{ uin: '1', uid: 'u1', nickname: 'A', pid: 4242 }];
const detectAccounts = vi.fn(async () => accounts);
const ctx = makeManager({
processes: [4242],
detectAccounts,
accountReprobeIntervalMs: 0,
});
await ctx.pipeWatcher.start();
await flush();
ctx.onSessionsChanged.mockClear();
await ctx.pipeWatcher.tickNow();
await ctx.pipeWatcher.tickNow();
await flush();
await flush();
// Detection did run again — it just had nothing new to report.
expect(detectAccounts.mock.calls.length).toBeGreaterThan(1);
expect(ctx.onSessionsChanged).not.toHaveBeenCalled();
ctx.manager.dispose();
});
it('ignores accounts that are not signed in on any process', async () => {
let accounts: AccountLoginState[] = [{ uin: '1', uid: 'u1', nickname: 'A', pid: null }];
const ctx = makeManager({
processes: [4242],
detectAccounts: async () => accounts,
accountReprobeIntervalMs: 0,
});
await ctx.pipeWatcher.start();
await flush();
ctx.onSessionsChanged.mockClear();
// Only the cached-account set changed (another account signed in on
// another machine/user); no process label moved.
accounts = [
{ uin: '1', uid: 'u1', nickname: 'A', pid: null },
{ uin: '2', uid: 'u2', nickname: 'B', pid: null },
];
await ctx.pipeWatcher.tickNow();
await flush();
await flush();
expect(ctx.onSessionsChanged).not.toHaveBeenCalled();
ctx.manager.dispose();
});
it('throttles the probe to the configured interval', async () => {
const detectAccounts = vi.fn(async () => [] as AccountLoginState[]);
const ctx = makeManager({
processes: [4242],
detectAccounts,
accountReprobeIntervalMs: 60_000,
});
await ctx.pipeWatcher.start();
await flush();
const baseline = detectAccounts.mock.calls.length;
await ctx.pipeWatcher.tickNow();
await ctx.pipeWatcher.tickNow();
await flush();
expect(detectAccounts.mock.calls.length).toBe(baseline);
ctx.manager.dispose();
});
it('keeps working when detection fails, and reports the failure once', async () => {
const ctx = makeManager({
processes: [4242],
detectAccounts: async () => {
throw new Error('login.db unreadable');
},
accountReprobeIntervalMs: 0,
});
await ctx.pipeWatcher.start();
await flush();
ctx.onSessionsChanged.mockClear();
await expect(ctx.pipeWatcher.tickNow()).resolves.not.toThrow();
await expect(ctx.pipeWatcher.tickNow()).resolves.not.toThrow();
await flush();
await flush();
// Detection failing is not a label change, so nothing is published.
expect(ctx.onSessionsChanged).not.toHaveBeenCalled();
expect((await ctx.manager.listProcesses())[0]!.account).toBeNull();
ctx.manager.dispose();
});
});
describe('HookManager receive-health wiring (#233)', () => {
it('forwards stale and recovered receive health for the owning PID', async () => {
const ctx = makeManager({ processes: [4242], livePipes: [4242] });
@@ -7,6 +7,7 @@ import { HookManager, shouldAutoLoadPid } from '../src/hook-manager';
import { PipeWatcher } from '../src/pipe-watcher';
import type { HookInjectResult, ManualMapHandle } from '../src/injector';
import type { BridgeManagerSink } from '../src/hook-manager';
import type { AccountLoginState } from '../src/qq-account';
import type { QqHookClient } from '../src/qq-hook-client';
import {
createLogger,
@@ -29,6 +30,7 @@ function makeManager(opts: {
processes?: number[];
onSessionsChanged?: () => void;
inject?: (pid: number) => HookInjectResult | Promise<HookInjectResult>;
detectAccounts?: (pids: readonly number[]) => Promise<AccountLoginState[]>;
}) {
let pids = opts.processes ?? [];
const live = new Set<number>();
@@ -76,6 +78,8 @@ function makeManager(opts: {
autoLoadOnDiscovery: opts.autoLoadOnDiscovery,
onSessionsChanged: opts.onSessionsChanged,
listProcesses: () => pids.map((pid) => ({ pid, name: 'qq', path: '' })),
// Detection reads QQ's own data directories; tests stay off the host.
detectAccounts: opts.detectAccounts ?? (async () => []),
});
return {
manager,
@@ -469,3 +473,41 @@ describe('shouldAutoLoadPid', () => {
expect(shouldAutoLoadPid(99999, log)).toBe(true);
});
});
describe('HookManager — signed-in account labelling', () => {
it('labels each process with the account detected on it', async () => {
const ctx = makeManager({
processes: [4242, 5151],
detectAccounts: async () => [
{ uin: '10001', uid: 'u_a', nickname: 'Alice', pid: 4242 },
{ uin: '10002', uid: 'u_b', nickname: 'Bob', pid: null },
],
});
try {
const list = await ctx.manager.listProcesses();
expect(list.map((info) => [info.pid, info.account])).toEqual([
[4242, { uin: '10001', nickname: 'Alice' }],
[5151, null],
]);
} finally {
ctx.manager.dispose();
}
});
it('leaves processes unlabelled when detection fails', async () => {
const ctx = makeManager({
processes: [4242],
detectAccounts: async () => {
throw new Error('login.db unreadable');
},
});
try {
const list = await ctx.manager.listProcesses();
expect(list[0]!.account).toBeNull();
} finally {
ctx.manager.dispose();
}
});
});
@@ -71,6 +71,7 @@ describe('HookManager — Docker reconnect-without-login leak guard', () => {
},
autoLoadOnDiscovery: true,
listProcesses: () => [{ pid: PID, name: 'qq', path: '' }],
detectAccounts: async () => [],
});
// Initial discovery + first connect.
+56 -33
View File
@@ -8,7 +8,6 @@ import {
type QqHookClient,
type QqHookPacket,
} from '../src/qq-hook-client';
import type { QqPortLoginInfo } from '../src/qq-port-probe';
import type { PacketSender } from '@snowluma/common/packet-sender';
import type { PacketSink } from '@snowluma/common/protocol-types';
import { getLogLevel, setLogLevel, subscribeLogs, type LogEntry } from '@snowluma/common/logger';
@@ -104,7 +103,7 @@ function makeSession(
pipeLive?: boolean;
clientFailsConnect?: boolean;
onPacket?: PacketSink;
probeLogin?: (pid: number) => Promise<QqPortLoginInfo | null>;
detectLoginUin?: (pid: number) => Promise<string | null>;
nativeReadyOnIdentityHint?: boolean;
identityHintFailures?: number;
} = {},
@@ -116,10 +115,9 @@ function makeSession(
inject: vi.fn(() => ({ method: 'loadModuleManual' as const, handle: DUMMY_HANDLE })),
unload: vi.fn(),
};
// Default probe exposes no identity so the reconcile safety net is inert
// unless a test opts into a known account.
const probeLogin =
opts.probeLogin ?? (async () => ({ port: 0, uin: '', identityKnown: false }));
// Default detection exposes no account so the reconcile safety net is inert
// unless a test opts into a known one.
const detectLoginUin = opts.detectLoginUin ?? (async () => null);
const session = new HookSession(pid, {
injector,
@@ -136,7 +134,7 @@ function makeSession(
// Cast: FakeClient mirrors only the surface HookSession touches.
return c as unknown as QqHookClient;
},
probeLogin,
detectLoginUin,
pipeWatcher: { isPipeLive: () => pipeLive },
onPacket: opts.onPacket,
});
@@ -1003,10 +1001,35 @@ describe('HookSession — packet forwarding', () => {
});
describe('HookSession — login reconcile (Docker auto-login safety net)', () => {
it('discards an identity read started before a pipe reconnect', async () => {
const detection = Promise.withResolvers<string | null>();
const ctx = makeSession({ pipeLive: true, detectLoginUin: () => detection.promise });
try {
await ctx.session.load();
ctx.session.onPipeUp();
await flush();
const previous = ctx.currentClient();
previous.close();
await flush();
ctx.session.onPipeUp();
await flush();
const current = ctx.currentClient();
expect(current).not.toBe(previous);
detection.resolve('10001');
await flush();
expect(current.loginIdentityHints).toEqual([]);
expect(previous.loginIdentityHints).toEqual([]);
} finally {
detection.resolve(null);
ctx.session.dispose();
}
});
it('keeps the packet sender usable only after native readiness confirms the identity hint', async () => {
const ctx = makeSession({
pipeLive: true,
probeLogin: async () => ({ port: 4301, uin: '10001', identityKnown: true }),
detectLoginUin: async () => '10001',
nativeReadyOnIdentityHint: true,
});
let sender: PacketSender | undefined;
@@ -1033,12 +1056,12 @@ describe('HookSession — login reconcile (Docker auto-login safety net)', () =>
]);
});
it('treats a port-probed account as an identity hint, not native login proof', async () => {
it('treats a locally detected account as an identity hint, not native login proof', async () => {
// Account identity does not prove request readiness. The bridge must wait
// for a login-state confirmation instead of synthesizing one.
const ctx = makeSession({
pipeLive: true,
probeLogin: async () => ({ port: 4301, uin: '10001', identityKnown: true }),
detectLoginUin: async () => '10001',
});
const loginSpy = vi.fn();
ctx.session.on('login', loginSpy);
@@ -1058,7 +1081,7 @@ describe('HookSession — login reconcile (Docker auto-login safety net)', () =>
vi.useFakeTimers();
const ctx = makeSession({
pipeLive: true,
probeLogin: async () => ({ port: 4301, uin: '10001', identityKnown: true }),
detectLoginUin: async () => '10001',
});
try {
@@ -1079,7 +1102,7 @@ describe('HookSession — login reconcile (Docker auto-login safety net)', () =>
let uin = '10001';
const ctx = makeSession({
pipeLive: true,
probeLogin: async () => ({ port: 4301, uin, identityKnown: true }),
detectLoginUin: async () => uin,
});
try {
@@ -1104,7 +1127,7 @@ describe('HookSession — login reconcile (Docker auto-login safety net)', () =>
vi.useFakeTimers();
const ctx = makeSession({
pipeLive: true,
probeLogin: async () => ({ port: 4301, uin: '10001', identityKnown: true }),
detectLoginUin: async () => '10001',
identityHintFailures: 3,
});
@@ -1128,10 +1151,10 @@ describe('HookSession — login reconcile (Docker auto-login safety net)', () =>
}
});
it('does not log in when the probe reports not-logged-in', async () => {
it('does not log in when no account is detected', async () => {
const ctx = makeSession({
pipeLive: true,
probeLogin: async () => ({ port: 0, uin: '', identityKnown: false }),
detectLoginUin: async () => null,
});
const loginSpy = vi.fn();
ctx.session.on('login', loginSpy);
@@ -1144,10 +1167,10 @@ describe('HookSession — login reconcile (Docker auto-login safety net)', () =>
expect(ctx.session.status).toBe('loaded');
});
it('ignores a probe with a non-real uin (0)', async () => {
it('ignores a detected account with a non-real uin (0)', async () => {
const ctx = makeSession({
pipeLive: true,
probeLogin: async () => ({ port: 4301, uin: '0', identityKnown: true }),
detectLoginUin: async () => '0',
});
const loginSpy = vi.fn();
ctx.session.on('login', loginSpy);
@@ -1159,11 +1182,11 @@ describe('HookSession — login reconcile (Docker auto-login safety net)', () =>
expect(loginSpy).not.toHaveBeenCalled();
});
it('tolerates a throwing probe (best-effort, no crash/login)', async () => {
it('tolerates a throwing detection (best-effort, no crash/login)', async () => {
const ctx = makeSession({
pipeLive: true,
probeLogin: async () => {
throw new Error('port scan failed');
detectLoginUin: async () => {
throw new Error('account detection unavailable');
},
});
const loginSpy = vi.fn();
@@ -1177,14 +1200,14 @@ describe('HookSession — login reconcile (Docker auto-login safety net)', () =>
expect(ctx.session.status).toBe('loaded');
});
it('detects a login that lands on a LATER interval probe', async () => {
it('detects a login that lands on a LATER interval check', async () => {
vi.useFakeTimers();
try {
let identityKnown = false;
let signedIn = false;
const ctx = makeSession({
pipeLive: true,
probeLogin: async () => ({ port: 4301, uin: '10001', identityKnown }),
detectLoginUin: async () => (signedIn ? '10001' : null),
nativeReadyOnIdentityHint: true,
});
const loginSpy = vi.fn();
@@ -1195,8 +1218,8 @@ describe('HookSession — login reconcile (Docker auto-login safety net)', () =>
await vi.advanceTimersByTimeAsync(0); // connect + immediate probe (not logged in yet)
expect(loginSpy).not.toHaveBeenCalled();
identityKnown = true; // QQ exposes the restored identity
await vi.advanceTimersByTimeAsync(3000); // next interval probe picks it up
signedIn = true; // the account's database shows up as signed in
await vi.advanceTimersByTimeAsync(3000); // next interval check picks it up
expect(loginSpy).toHaveBeenCalledOnce();
expect(ctx.session.status).toBe('online');
@@ -1208,8 +1231,8 @@ describe('HookSession — login reconcile (Docker auto-login safety net)', () =>
it('does not double-emit when the pushed frame logs in first', async () => {
// Pushed-frame login wins; a subsequent probe with the same uin must not
// re-emit (handleLoginState dedups), and the reconcile timer is stopped.
const probeLogin = vi.fn(async () => ({ port: 4301, uin: '10001', identityKnown: true }));
const ctx = makeSession({ pipeLive: true, probeLogin });
const detectLoginUin = vi.fn(async () => '10001');
const ctx = makeSession({ pipeLive: true, detectLoginUin });
const loginSpy = vi.fn();
ctx.session.on('login', loginSpy);
@@ -1414,27 +1437,27 @@ describe('HookSession — end-to-end receive health (#233)', () => {
});
});
describe('HookSession — login reconcile does not stack concurrent probes', () => {
it('skips overlapping ticks while a slow probe is in flight', async () => {
describe('HookSession — login reconcile does not stack concurrent detections', () => {
it('skips overlapping ticks while a slow detection is in flight', async () => {
vi.useFakeTimers();
try {
// A probe that never resolves — simulates a slow port scan spanning
// A detection that never resolves — simulates a slow read spanning
// multiple intervals. The in-flight guard must call it only once.
const probeLogin = vi.fn(
const detectLoginUin = vi.fn(
() =>
new Promise<never>(() => {
/* pending */
}),
);
const ctx = makeSession({ pipeLive: true, probeLogin });
const ctx = makeSession({ pipeLive: true, detectLoginUin });
await ctx.session.load();
ctx.session.onPipeUp();
await vi.advanceTimersByTimeAsync(0); // connect + immediate probe (starts, stays pending)
await vi.advanceTimersByTimeAsync(9000); // 3 more interval ticks
expect(probeLogin).toHaveBeenCalledTimes(1); // not stacked
expect(detectLoginUin).toHaveBeenCalledTimes(1); // not stacked
} finally {
vi.useRealTimers();
}
@@ -0,0 +1,123 @@
import { afterEach, describe, expect, it, vi } from 'vitest';
import { mkdtemp, rm } from 'node:fs/promises';
import os from 'node:os';
import path from 'node:path';
import { SqliteDatabase } from '@snowluma/sqlite';
import { isQqProcessName, probeDbLock } from '../src/qq-account/db-lock';
const native = vi.hoisted(() => ({ addon: vi.fn<() => unknown>(() => null) }));
vi.mock('../src/injector', () => ({ getNativeHookAddon: native.addon }));
const IS_LINUX = process.platform === 'linux';
const ORIGINAL_PLATFORM = process.platform;
/** Run `probeDbLock` as if the host were Windows, with a stubbed addon. */
function asWindows<T>(addon: unknown, run: () => T): T {
Object.defineProperty(process, 'platform', { value: 'win32', configurable: true });
native.addon.mockReturnValue(addon);
try {
return run();
} finally {
Object.defineProperty(process, 'platform', {
value: ORIGINAL_PLATFORM,
configurable: true,
});
}
}
afterEach(() => {
native.addon.mockReset();
native.addon.mockReturnValue(null);
});
describe('database holder probe', () => {
it.runIf(IS_LINUX)('reports nothing for a file that is not there', () => {
const missing = path.join(os.tmpdir(), `snowluma-absent-${process.pid}.db`);
expect(probeDbLock(missing)).toEqual([]);
});
it.runIf(IS_LINUX)('finds the process holding a database', async () => {
const directory = await mkdtemp(path.join(os.tmpdir(), 'snowluma-lock-'));
const file = path.join(directory, 'nt_msg.db');
const db = new SqliteDatabase(file);
try {
// A rollback-journal write transaction takes a POSIX lock on the
// database file itself, which is exactly what a signed-in client
// holds on the account's nt_msg.db.
await db.exec('PRAGMA journal_mode = DELETE');
await db.exec('CREATE TABLE t(value TEXT)');
await db.exec('BEGIN IMMEDIATE');
const holders = probeDbLock(file);
const self = holders.find((holder) => holder.pid === process.pid);
expect(self).toBeDefined();
// The holder is named from /proc/<pid>/comm, and that name is what
// keeps a holder that is not QQ from being mistaken for one.
expect(self!.name.length).toBeGreaterThan(0);
expect(isQqProcessName(self!.name)).toBe(false);
await db.exec('ROLLBACK');
expect(probeDbLock(file).some((holder) => holder.pid === process.pid)).toBe(false);
} finally {
await db.close();
await rm(directory, { recursive: true, force: true });
}
});
});
describe('Windows holder probe', () => {
it('reports the holders the addon lists', () => {
const holders = asWindows(
{
probeDbLock: () => [
{ pid: 4242, name: 'QQ.exe' },
{ pid: 7, name: 'weq' },
],
},
() => probeDbLock('C:\\Tencent Files\\10001\\nt_qq\\nt_db\\nt_msg.db'),
);
expect(holders).toEqual([
{ pid: 4242, name: 'QQ.exe' },
{ pid: 7, name: 'weq' },
]);
});
it.each([[{ pid: 0, name: 'QQ' }], [{ pid: 9 }], [null], 'not-an-array'])(
'reports malformed native results: %j',
(result) => {
expect(() =>
asWindows({ probeDbLock: () => result }, () => probeDbLock('C:\\nt_msg.db')),
).toThrow('Invalid database holders');
},
);
it('accepts an empty holder list', () => {
expect(asWindows({ probeDbLock: () => [] }, () => probeDbLock('C:\\nt_msg.db'))).toEqual(
[],
);
});
it.each([null, {}])('reports an unavailable native probe: %j', (addon) => {
expect(() => asWindows(addon, () => probeDbLock('C:\\nt_msg.db'))).toThrow(
'requires a hook addon with probeDbLock',
);
});
});
describe('QQ process names', () => {
it('accepts the name each platform reports for the client', () => {
expect(isQqProcessName('QQ')).toBe(true);
expect(isQqProcessName('QQ.exe')).toBe(true);
expect(isQqProcessName(' qq ')).toBe(true);
});
it('rejects other holders', () => {
expect(isQqProcessName('node')).toBe(false);
expect(isQqProcessName('qqmusic')).toBe(false);
expect(isQqProcessName('')).toBe(false);
});
});
@@ -0,0 +1,241 @@
import { afterEach, describe, expect, it, vi } from 'vitest';
import { spawn } from 'node:child_process';
import { mkdtemp, rm } from 'node:fs/promises';
import os from 'node:os';
import path from 'node:path';
import { getLogLevel, setLogLevel, subscribeLogs, type LogEntry } from '@snowluma/common/logger';
const mocks = vi.hoisted(() => ({
readLocalAccounts: vi.fn(),
probeDbLock: vi.fn(),
}));
// The account list and the holder probe are covered on their own; this file is
// about how the two are joined.
vi.mock('../src/qq-account/login-db', () => ({ readLocalAccounts: mocks.readLocalAccounts }));
vi.mock('../src/qq-account/db-lock', async (importOriginal) => ({
...(await importOriginal<typeof import('../src/qq-account/db-lock')>()),
probeDbLock: mocks.probeDbLock,
}));
import { detectAccountLogins, detectAccountLoginsForPids } from '../src/qq-account/detect';
import { loginDbPaths, ntMsgDbPath } from '../src/qq-account/paths';
const ALICE = { uin: '10001', uid: 'u_alice', nickname: 'Alice' };
const BOB = { uin: '10002', uid: 'u_bob', nickname: 'Bob' };
const roots: string[] = [];
const children: Array<ReturnType<typeof spawn>> = [];
afterEach(async () => {
mocks.readLocalAccounts.mockReset();
mocks.probeDbLock.mockReset();
for (const child of children.splice(0)) {
child.kill();
}
for (const root of roots.splice(0)) {
await rm(root, { recursive: true, force: true });
}
});
async function makeRoot(): Promise<string> {
const root = await mkdtemp(path.join(os.tmpdir(), 'snowluma-detect-'));
roots.push(root);
return root;
}
/**
* A live process whose `/proc/<pid>/environ` carries `HOME` (and any extra
* variables given).
*
* `XDG_CONFIG_HOME` is dropped unless the caller sets it: it outranks `HOME`
* when deriving the data root, and a CI runner exports its own, which would
* otherwise decide the result instead of the HOME under test.
*
* Resolves only once the child has run past `execve`, because `/proc/<pid>`
* still shows the parent's environment before that.
*/
function spawnWithHome(home: string, extra: Record<string, string> = {}): Promise<number> {
return new Promise((resolve, reject) => {
const env: NodeJS.ProcessEnv = { ...process.env };
delete env.XDG_CONFIG_HOME;
Object.assign(env, { HOME: home }, extra);
const child = spawn(
process.execPath,
['-e', 'console.log("ready"); setTimeout(() => {}, 30000)'],
{ env, stdio: ['ignore', 'pipe', 'ignore'] },
);
children.push(child);
child.stdout!.once('data', () => resolve(child.pid!));
child.once('error', reject);
});
}
describe('local account detection', () => {
it('labels each account with the process holding its database', async () => {
const root = await makeRoot();
mocks.readLocalAccounts.mockResolvedValue({ accounts: [ALICE, BOB], failures: [] });
mocks.probeDbLock.mockImplementation((dbPath: string) => {
if (dbPath === ntMsgDbPath(root, ALICE)) {
return [{ pid: 4242, name: 'qq' }];
}
// A holder that is not the client must not be mistaken for one.
return [{ pid: 999, name: 'node' }];
});
await expect(detectAccountLogins([root])).resolves.toEqual([
{ ...ALICE, pid: 4242 },
{ ...BOB, pid: null },
]);
});
it('merges the accounts of every root instead of stopping at the first', async () => {
const own = await makeRoot();
const extra = await makeRoot();
mocks.readLocalAccounts.mockImplementation(async (root: string) =>
root === own ? { accounts: [ALICE], failures: [] } : { accounts: [BOB], failures: [] },
);
mocks.probeDbLock.mockImplementation((dbPath: string) =>
dbPath === ntMsgDbPath(extra, BOB) ? [{ pid: 5151, name: 'qq' }] : [],
);
await expect(detectAccountLogins([own, extra])).resolves.toEqual([
{ ...ALICE, pid: null },
{ ...BOB, pid: 5151 },
]);
// An account held under an instance's own HOME is still labelled, which
// is what a single-root lookup cannot do.
expect(mocks.probeDbLock).toHaveBeenCalledWith(ntMsgDbPath(extra, BOB));
});
it('keeps account records with the same uin scoped to their own root', async () => {
const first = await makeRoot();
const second = await makeRoot();
mocks.readLocalAccounts.mockImplementation(async (root: string) =>
root === first
? { accounts: [ALICE], failures: [] }
: { accounts: [{ ...ALICE, nickname: 'Stale' }], failures: [] },
);
mocks.probeDbLock.mockImplementation((file: string) =>
file === ntMsgDbPath(second, ALICE) ? [{ pid: 5151, name: 'qq' }] : [],
);
await expect(detectAccountLogins([first, second])).resolves.toEqual([
{ ...ALICE, pid: null },
{ ...ALICE, nickname: 'Stale', pid: 5151 },
]);
});
it('reports nothing when there are no roots', async () => {
await expect(detectAccountLogins([])).resolves.toEqual([]);
expect(mocks.readLocalAccounts).not.toHaveBeenCalled();
});
it('logs a named reason when a login.db is present but unreadable', async () => {
const root = await makeRoot();
const entries: LogEntry[] = [];
const previousLevel = getLogLevel();
setLogLevel('debug');
const unsubscribe = subscribeLogs((entry) => entries.push(entry));
try {
mocks.readLocalAccounts.mockResolvedValue({
accounts: [],
failures: [
{
path: loginDbPaths(root)[0]!,
reason: 'undecryptable',
},
],
});
mocks.probeDbLock.mockReturnValue([]);
// An unreadable login.db must not look like "no accounts": an
// operator reading the log has to see why nothing was reported.
await detectAccountLogins([root]);
} finally {
unsubscribe();
setLogLevel(previousLevel);
}
const warned = entries.filter(
(entry) => entry.level === 'warn' && entry.scope === 'QqAccount',
);
expect(warned).toHaveLength(1);
expect(warned[0]!.message).toContain('login.db unreadable');
expect(warned[0]!.message).toContain('undecryptable');
});
});
describe.runIf(process.platform === 'linux')('per-process data roots', () => {
it('reads each pid against the HOME that process runs under', async () => {
const home = await makeRoot();
const pid = await spawnWithHome(home);
mocks.readLocalAccounts.mockResolvedValue({ accounts: [], failures: [] });
mocks.probeDbLock.mockReturnValue([]);
await detectAccountLoginsForPids([pid]);
// `<HOME>/.config/QQ`, from the child's environment rather than ours.
expect(mocks.readLocalAccounts).toHaveBeenCalledWith(path.join(home, '.config', 'QQ'));
});
it('asks each root once when several processes share a HOME', async () => {
const home = await makeRoot();
const pids = [await spawnWithHome(home), await spawnWithHome(home)];
mocks.readLocalAccounts.mockResolvedValue({ accounts: [], failures: [] });
mocks.probeDbLock.mockReturnValue([]);
await detectAccountLoginsForPids(pids);
expect(mocks.readLocalAccounts).toHaveBeenCalledTimes(1);
});
it('honours XDG_CONFIG_HOME of the process over its HOME', async () => {
const home = await makeRoot();
const configHome = await makeRoot();
const pid = await spawnWithHome(home, { XDG_CONFIG_HOME: configHome });
mocks.readLocalAccounts.mockResolvedValue({ accounts: [], failures: [] });
mocks.probeDbLock.mockReturnValue([]);
await detectAccountLoginsForPids([pid]);
// The XDG variable outranks HOME, as it does for the client itself.
expect(mocks.readLocalAccounts).toHaveBeenCalledWith(path.join(configHome, 'QQ'));
});
it('keeps each process on its own root when the HOMEs differ', async () => {
const first = await makeRoot();
const second = await makeRoot();
const pids = [await spawnWithHome(first), await spawnWithHome(second)];
mocks.readLocalAccounts.mockResolvedValue({ accounts: [], failures: [] });
mocks.probeDbLock.mockReturnValue([]);
await detectAccountLoginsForPids(pids);
expect(mocks.readLocalAccounts).toHaveBeenCalledWith(path.join(first, '.config', 'QQ'));
expect(mocks.readLocalAccounts).toHaveBeenCalledWith(path.join(second, '.config', 'QQ'));
});
it('does not substitute another HOME when the pid is gone', async () => {
const home = await makeRoot();
const pid = await spawnWithHome(home);
mocks.readLocalAccounts.mockResolvedValue({ accounts: [], failures: [] });
mocks.probeDbLock.mockReturnValue([]);
// The child exits, so its environment is no longer readable.
await new Promise<void>((resolve) => {
const child = children[children.length - 1]!;
child.once('exit', () => resolve());
child.kill();
});
await detectAccountLoginsForPids([pid]);
expect(mocks.readLocalAccounts).not.toHaveBeenCalled();
});
});
@@ -0,0 +1,195 @@
/**
* Encryption helpers for the account-detection tests.
*
* The shipped code only decrypts, so producing an encrypted fixture means
* mirroring SQLCipher's page layout here: `[client header][page 1]…` with each
* page ending in `IV || page HMAC`, and a `-wal` whose frame header stays
* plaintext while the page inside it is encrypted.
*/
import { createCipheriv, createHmac, pbkdf2Sync, randomBytes } from 'node:crypto';
import type { KdfHmacAlgorithm, PageHmacAlgorithm } from '../src/qq-account/sqlcipher';
export interface FixtureAlgorithm {
pageHmac: PageHmacAlgorithm;
kdfHmac: KdfHmacAlgorithm;
}
export const FIXTURE_PASSPHRASE = 'BD156D6710D54D8782F4';
export const FIXTURE_PAGE_SIZE = 4096;
export const FIXTURE_HEADER_SIZE = 1024;
export const FIXTURE_WAL_HEADER_SIZE = 32;
export const FIXTURE_WAL_FRAME_HEADER_SIZE = 24;
const DIGEST_BYTES: Record<PageHmacAlgorithm, number> = {
none: 0,
sha1: 20,
sha256: 32,
sha512: 64,
};
const KDF_ITERATIONS = 4000;
const HMAC_KEY_ITERATIONS = 2;
const HMAC_SALT_MASK = 0x3a;
export function reserveBytes(algorithm: FixtureAlgorithm): number {
return Math.ceil((16 + DIGEST_BYTES[algorithm.pageHmac]) / 16) * 16;
}
/** Encrypt a plaintext SQLite image the way QQ NT stores it. */
export function encryptImage(
plain: Buffer,
algorithm: FixtureAlgorithm,
passphrase = FIXTURE_PASSPHRASE,
salt = randomBytes(16),
): Buffer {
const pageCount = plain.length / FIXTURE_PAGE_SIZE;
const key = pbkdf2Sync(passphrase, salt, KDF_ITERATIONS, 32, algorithm.kdfHmac);
const output = Buffer.alloc(FIXTURE_HEADER_SIZE + plain.length);
for (let index = 0; index < pageCount; index++) {
const pageNumber = index + 1;
const skip = pageNumber === 1 ? 16 : 0;
const body = plain.subarray(
index * FIXTURE_PAGE_SIZE + skip,
(index + 1) * FIXTURE_PAGE_SIZE,
);
if (pageNumber === 1) {
// Page 1 stores the KDF salt where SQLite keeps its magic.
salt.copy(output, FIXTURE_HEADER_SIZE);
}
encryptPageInto(
output,
FIXTURE_HEADER_SIZE + index * FIXTURE_PAGE_SIZE,
body,
pageNumber,
key,
salt,
algorithm,
);
}
return output;
}
/** Encrypt the pages of a real (plaintext) WAL, recomputing the frame checksums. */
export function encryptWal(
plainWal: Buffer,
encryptedImage: Buffer,
algorithm: FixtureAlgorithm,
passphrase = FIXTURE_PASSPHRASE,
): Buffer {
const salt = encryptedImage.subarray(FIXTURE_HEADER_SIZE, FIXTURE_HEADER_SIZE + 16);
const key = pbkdf2Sync(passphrase, salt, KDF_ITERATIONS, 32, algorithm.kdfHmac);
const frameSize = FIXTURE_WAL_FRAME_HEADER_SIZE + FIXTURE_PAGE_SIZE;
const output = Buffer.alloc(plainWal.length);
plainWal.copy(output, 0, 0, FIXTURE_WAL_HEADER_SIZE);
let running = walChecksum([0, 0], [output.subarray(0, FIXTURE_WAL_HEADER_SIZE - 8)], true);
for (
let offset = FIXTURE_WAL_HEADER_SIZE;
offset + frameSize <= plainWal.length;
offset += frameSize
) {
const frameHeader = plainWal.subarray(offset, offset + FIXTURE_WAL_FRAME_HEADER_SIZE);
const pageNumber = frameHeader.readUInt32BE(0);
const skip = pageNumber === 1 ? 16 : 0;
const page = plainWal.subarray(offset + FIXTURE_WAL_FRAME_HEADER_SIZE, offset + frameSize);
encryptPageInto(
output,
offset + FIXTURE_WAL_FRAME_HEADER_SIZE,
page.subarray(skip),
pageNumber,
key,
salt,
algorithm,
);
const stored = output.subarray(offset, offset + FIXTURE_WAL_FRAME_HEADER_SIZE);
frameHeader.copy(stored, 0, 0, 8);
running = walChecksum(
running,
[
stored.subarray(0, 8),
output.subarray(offset + FIXTURE_WAL_FRAME_HEADER_SIZE, offset + frameSize),
],
true,
);
stored.writeUInt32BE(running[0], 16);
stored.writeUInt32BE(running[1], 20);
}
return output;
}
/**
* SQLite's rolling WAL checksum, as the fixture needs it to rebuild frame
* checksums — and to prove the shipped implementation agrees with what SQLite
* itself wrote in a real `-wal`.
*/
export function walChecksum(
seed: [number, number],
chunks: readonly Buffer[],
littleEndian: boolean,
): [number, number] {
let first = seed[0];
let second = seed[1];
for (const chunk of chunks) {
for (let offset = 0; offset + 8 <= chunk.length; offset += 8) {
const high = littleEndian ? chunk.readUInt32LE(offset) : chunk.readUInt32BE(offset);
const low = littleEndian
? chunk.readUInt32LE(offset + 4)
: chunk.readUInt32BE(offset + 4);
first = (first + high + second) >>> 0;
second = (second + low + first) >>> 0;
}
}
return [first, second];
}
function encryptPageInto(
output: Buffer,
pageOffset: number,
body: Buffer,
pageNumber: number,
key: Buffer,
salt: Buffer,
algorithm: FixtureAlgorithm,
): void {
// Page 1 stores the KDF salt where SQLite keeps its magic, so its ciphertext
// starts one salt past the page boundary.
const offset = pageOffset + (pageNumber === 1 ? 16 : 0);
const reserve = reserveBytes(algorithm);
const cipherLength = body.length - reserve;
const iv = randomBytes(16);
const cipher = createCipheriv('aes-256-cbc', key, iv);
cipher.setAutoPadding(false);
const ciphertext = Buffer.concat([
cipher.update(body.subarray(0, cipherLength)),
cipher.final(),
]);
ciphertext.copy(output, offset);
iv.copy(output, offset + cipherLength);
const digestBytes = DIGEST_BYTES[algorithm.pageHmac];
if (digestBytes === 0) {
return;
}
const hmacSalt = Buffer.from(salt.map((byte) => byte ^ HMAC_SALT_MASK));
const hmacKey = pbkdf2Sync(key, hmacSalt, HMAC_KEY_ITERATIONS, 32, algorithm.kdfHmac);
const pageNumberBytes = Buffer.alloc(4);
pageNumberBytes.writeUInt32LE(pageNumber);
const digest = createHmac(algorithm.pageHmac, hmacKey)
.update(ciphertext)
.update(iv)
.update(pageNumberBytes)
.digest();
digest.copy(output, offset + cipherLength + 16);
}
@@ -0,0 +1,246 @@
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
import { mkdir, mkdtemp, rm, utimes, writeFile } from 'node:fs/promises';
import os from 'node:os';
import path from 'node:path';
import { SqliteDatabase } from '@snowluma/sqlite';
const mocks = vi.hoisted(() => ({
detectAlgorithm: vi.fn(),
decryptDatabase: vi.fn(),
}));
// The page crypto is covered on its own; account reading stands on top of it, so
// the fixtures below hand over plaintext images and the decrypt step is stubbed
// to pass them through.
vi.mock('../src/qq-account/sqlcipher', () => ({
detectAlgorithm: mocks.detectAlgorithm,
decryptDatabase: mocks.decryptDatabase,
}));
vi.mock('../src/qq-account/paths', () => ({
loginDbPaths: (root: string) => [path.join(root, PRIMARY), path.join(root, SECONDARY)],
}));
import { readLocalAccounts } from '../src/qq-account/login-db';
const PRIMARY = path.join('global', 'nt_db', 'login.db');
const SECONDARY = path.join('nt_qq', 'global', 'nt_db', 'login.db');
/** Write a plaintext database with QQ's account table at `file`. */
async function writeLoginDb(
file: string,
rows: ReadonlyArray<readonly [string, string, string]>,
): Promise<void> {
await mkdir(path.dirname(file), { recursive: true });
await rm(file, { force: true });
await rm(`${file}-wal`, { force: true });
const db = new SqliteDatabase(file);
try {
await db.exec('CREATE TABLE login_table("1000" TEXT, "1001" TEXT, "1007" TEXT)');
for (const [uin, uid, nickname] of rows) {
await db.prepare('INSERT INTO login_table VALUES (?, ?, ?)').run(uin, uid, nickname);
}
} finally {
await db.close();
}
}
async function makeRoot(
rows: ReadonlyArray<readonly [string, string, string]>,
secondaryRows: ReadonlyArray<readonly [string, string, string]> = [],
): Promise<string> {
const root = await mkdtemp(path.join(os.tmpdir(), 'snowluma-login-'));
await writeLoginDb(path.join(root, PRIMARY), rows);
if (secondaryRows.length > 0) {
await writeLoginDb(path.join(root, SECONDARY), secondaryRows);
}
return root;
}
const roots: string[] = [];
beforeEach(() => {
mocks.detectAlgorithm.mockReturnValue({ pageHmac: 'sha1', kdfHmac: 'sha512' });
mocks.decryptDatabase.mockImplementation((image: Buffer) => ({ image, walFrames: 0 }));
});
afterEach(async () => {
mocks.detectAlgorithm.mockReset();
mocks.decryptDatabase.mockReset();
for (const root of roots.splice(0)) {
await rm(root, { recursive: true, force: true });
}
});
async function trackedRoot(
rows: ReadonlyArray<readonly [string, string, string]>,
secondaryRows: ReadonlyArray<readonly [string, string, string]> = [],
): Promise<string> {
const root = await makeRoot(rows, secondaryRows);
roots.push(root);
return root;
}
describe('local account list', () => {
it('reads the accounts QQ cached locally', async () => {
const root = await trackedRoot([['10001', 'u_a', 'Alice']]);
await expect(readLocalAccounts(root)).resolves.toEqual({
accounts: [{ uin: '10001', uid: 'u_a', nickname: 'Alice' }],
failures: [],
});
});
it('merges both login.db locations, letting the primary win on a clash', async () => {
const root = await trackedRoot(
[
['10001', 'u_a', 'Alice'],
['10002', 'u_b', 'Bob'],
],
[
['10001', 'u_a_stale', 'AliceStale'],
['10003', 'u_c', 'Carol'],
],
);
expect(await readLocalAccounts(root)).toEqual({
accounts: [
{ uin: '10001', uid: 'u_a', nickname: 'Alice' },
{ uin: '10002', uid: 'u_b', nickname: 'Bob' },
{ uin: '10003', uid: 'u_c', nickname: 'Carol' },
],
failures: [],
});
});
it('re-decrypts only when the database or its sidecar changes', async () => {
const root = await trackedRoot([['10001', 'u_a', 'Alice']]);
const file = path.join(root, PRIMARY);
await readLocalAccounts(root);
await readLocalAccounts(root);
expect(mocks.decryptDatabase).toHaveBeenCalledTimes(1);
// A login that just happened rewrites the database; the new rows have to
// show up instead of the cached list.
await writeLoginDb(file, [
['10001', 'u_a', 'Alice'],
['10002', 'u_b', 'Bob'],
]);
await utimes(file, new Date(Date.now() + 60_000), new Date(Date.now() + 60_000));
expect((await readLocalAccounts(root)).accounts).toHaveLength(2);
expect(mocks.decryptDatabase).toHaveBeenCalledTimes(2);
// The sidecar counts as a change too: a batch committed to the WAL only
// leaves login.db untouched.
await writeFile(`${file}-wal`, Buffer.alloc(0));
await readLocalAccounts(root);
expect(mocks.decryptDatabase).toHaveBeenCalledTimes(3);
});
it('shares concurrent reads of the same database image', async () => {
const root = await trackedRoot([['10001', 'u_a', 'Alice']]);
const reports = await Promise.all([readLocalAccounts(root), readLocalAccounts(root)]);
expect(reports[0]).toEqual(reports[1]);
expect(mocks.decryptDatabase).toHaveBeenCalledTimes(1);
});
it('reports an unreadable WAL instead of reading a stale base image', async () => {
const root = await trackedRoot([['10001', 'u_a', 'Alice']]);
const file = path.join(root, PRIMARY);
await mkdir(`${file}-wal`);
const report = await readLocalAccounts(root);
expect(report.accounts).toEqual([]);
expect(report.failures).toMatchObject([{ path: file, reason: 'read-failed' }]);
expect(report.failures[0]!.error).toBeDefined();
});
it('reports missing schema columns instead of accepting quoted column names as identities', async () => {
const root = await trackedRoot([['10001', 'u_a', 'Alice']]);
const file = path.join(root, PRIMARY);
const db = new SqliteDatabase(file);
try {
await db.exec('ALTER TABLE login_table DROP COLUMN "1001"');
} finally {
await db.close();
}
const report = await readLocalAccounts(root);
expect(report.accounts).toEqual([]);
expect(report.failures).toMatchObject([{ path: file, reason: 'query-failed' }]);
expect(report.failures[0]!.error).toBeDefined();
});
it('reports no accounts when the file cannot be decrypted, and retries later', async () => {
const root = await trackedRoot([['10001', 'u_a', 'Alice']]);
mocks.detectAlgorithm.mockReturnValue(null);
await expect(readLocalAccounts(root)).resolves.toEqual({
accounts: [],
failures: [{ path: path.join(root, PRIMARY), reason: 'undecryptable' }],
});
mocks.detectAlgorithm.mockReturnValue({ pageHmac: 'sha1', kdfHmac: 'sha512' });
const file = path.join(root, PRIMARY);
await utimes(file, new Date(Date.now() + 60_000), new Date(Date.now() + 60_000));
await expect(readLocalAccounts(root)).resolves.toEqual({
accounts: [{ uin: '10001', uid: 'u_a', nickname: 'Alice' }],
failures: [],
});
});
it('names an unreadable login.db instead of reporting "no accounts"', async () => {
const root = await trackedRoot([['10001', 'u_a', 'Alice']]);
mocks.detectAlgorithm.mockReturnValue(null);
// A login.db that cannot be decrypted is not the same as a machine with
// no accounts, and the caller has to be able to tell them apart.
await expect(readLocalAccounts(root)).resolves.toEqual({
accounts: [],
failures: [{ path: path.join(root, PRIMARY), reason: 'undecryptable' }],
});
});
it('keeps an unreadable sidecar from hiding the accounts a good database has', async () => {
const root = await trackedRoot([['10001', 'u_a', 'Alice']], [['10002', 'u_b', 'Bob']]);
const secondary = path.join(root, SECONDARY);
const bogus = Buffer.alloc(8192, 7);
mocks.detectAlgorithm.mockImplementation((image: Buffer) =>
image[0] === 7 ? null : { pageHmac: 'sha1', kdfHmac: 'sha512' },
);
await writeFile(secondary, bogus);
const report = await readLocalAccounts(root);
expect(report.accounts.map((account) => account.uin)).toEqual(['10001']);
expect(report.failures).toEqual([{ path: secondary, reason: 'undecryptable' }]);
});
it('skips rows that carry no usable identity', async () => {
const root = await trackedRoot([
['10001', 'u_a', 'Alice'],
['10002', '', 'Broken'],
['', 'u_d', 'Nameless'],
['../10001', 'u_e', 'Invalid UIN'],
]);
await expect(readLocalAccounts(root)).resolves.toEqual({
accounts: [{ uin: '10001', uid: 'u_a', nickname: 'Alice' }],
failures: [],
});
});
it('reports no accounts when login.db is missing', async () => {
const root = await mkdtemp(path.join(os.tmpdir(), 'snowluma-login-'));
roots.push(root);
// Neither candidate file exists: nothing cached, and nothing to report.
await expect(readLocalAccounts(root)).resolves.toEqual({ accounts: [], failures: [] });
});
});
@@ -0,0 +1,51 @@
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
import path from 'node:path';
import { qqDataRoots, qqDataRootsForPid } from '../src/qq-account/paths';
const files = vi.hoisted(() => ({ read: vi.fn() }));
vi.mock('node:fs', () => ({ readFileSync: files.read }));
const platform = process.platform;
beforeEach(() => {
Object.defineProperty(process, 'platform', { value: 'linux', configurable: true });
});
afterEach(() => {
Object.defineProperty(process, 'platform', { value: platform, configurable: true });
files.read.mockReset();
});
describe('account data root isolation', () => {
it('uses the client HOME and honours its XDG configuration', () => {
files.read.mockReturnValue('HOME=/clients/a\0IGNORED=value\0');
expect(qqDataRootsForPid(42)).toEqual([path.join('/clients/a', '.config', 'QQ')]);
files.read.mockReturnValue('HOME=/clients/a\0XDG_CONFIG_HOME=/clients/config\0');
expect(qqDataRootsForPid(42)).toEqual([path.join('/clients/config', 'QQ')]);
});
it('does not guess a HOME when the client environment has none', () => {
files.read.mockReturnValue('OTHER=value\0');
expect(qqDataRootsForPid(42)).toEqual([]);
});
it('reports no root for an exited process', () => {
files.read.mockImplementation(() => {
throw Object.assign(new Error('gone'), { code: 'ENOENT' });
});
expect(qqDataRootsForPid(42)).toEqual([]);
});
it('surfaces permission failures instead of reading another user directory', () => {
const error = Object.assign(new Error('denied'), { code: 'EACCES' });
files.read.mockImplementation(() => {
throw error;
});
expect(() => qqDataRootsForPid(42)).toThrow(error);
});
it('uses only the configured Windows data root', () => {
Object.defineProperty(process, 'platform', { value: 'win32', configurable: true });
files.read.mockReturnValue('[UserDataSet]\nUserDataSavePath=D:\\QQ\\Tencent Files\n');
expect(qqDataRoots()).toEqual(['D:\\QQ\\Tencent Files']);
expect(files.read).toHaveBeenCalledTimes(1);
});
});
@@ -0,0 +1,106 @@
import { describe, expect, it } from 'vitest';
import { mkdir, mkdtemp, rm, writeFile } from 'node:fs/promises';
import os from 'node:os';
import path from 'node:path';
import {
accountDirName,
loginDbPaths,
ntMsgDbPath,
tencentFilesRootFromUserDataInfo,
} from '../src/qq-account/paths';
const IS_WINDOWS = process.platform === 'win32';
describe('QQ data paths', () => {
it('derives the Linux account directory from the account uid', () => {
// md5(md5("u_test_account") + "nt_kernel")
expect(accountDirName('u_test_account')).toBe('nt_qq_7b9b3c3f2cf89e087b2e024777ea5f5f');
});
it('lists the login.db locations of the current platform', () => {
const root = 'root';
const windows = path.join(root, 'nt_qq', 'global', 'nt_db', 'login.db');
expect(loginDbPaths(root)).toEqual(
IS_WINDOWS ? [windows] : [path.join(root, 'global', 'nt_db', 'login.db'), windows],
);
});
it('locates an account database per platform', () => {
const root = 'root';
const account = { uin: '10001', uid: 'u_test_account' };
expect(ntMsgDbPath(root, account)).toBe(
IS_WINDOWS
? path.join(root, '10001', 'nt_qq', 'nt_db', 'nt_msg.db')
: path.join(root, 'nt_qq_7b9b3c3f2cf89e087b2e024777ea5f5f', 'nt_db', 'nt_msg.db'),
);
});
});
describe('Windows data root detection', () => {
/** Recreate `<Public>/Documents/Tencent/QQ/UserDataInfo.ini` for a fake home. */
async function withUserDataInfo(
contents: string,
run: (home: string) => Promise<void> | void,
): Promise<void> {
const base = await mkdtemp(path.join(os.tmpdir(), 'snowluma-ini-'));
try {
const home = path.join(base, 'user');
const ini = path.join(base, 'Public', 'Documents', 'Tencent', 'QQ', 'UserDataInfo.ini');
await mkdir(path.dirname(ini), { recursive: true });
await writeFile(ini, contents, 'utf8');
await run(home);
} finally {
await rm(base, { recursive: true, force: true });
}
}
it('reads UserDataSavePath from the ini QQ itself writes', async () => {
await withUserDataInfo(
'[UserDataSet]\nUserDataSavePath=D:\\Tencent\\Tencent Files\n',
(home) => {
expect(tencentFilesRootFromUserDataInfo(home)).toBe('D:\\Tencent\\Tencent Files');
},
);
});
it('appends the Tencent Files segment when the ini stops one level short', async () => {
await withUserDataInfo('[UserDataSet]\nUserDataSavePath=D:\\Tencent\n', (home) => {
expect(tencentFilesRootFromUserDataInfo(home)).toBe('D:\\Tencent\\Tencent Files');
});
});
it('ignores other sections and the UserDataSavePathType key', async () => {
await withUserDataInfo(
[
'[UserDataImportSet]',
'OldVerDataPath=D:\\Legacy\\Tencent Files',
'[UserDataSet]',
'UserDataSavePathType=2',
'UserDataSavePath=E:\\Current\\Tencent Files',
'',
].join('\n'),
(home) => {
expect(tencentFilesRootFromUserDataInfo(home)).toBe('E:\\Current\\Tencent Files');
},
);
});
it('reports nothing when the ini is missing', async () => {
const base = await mkdtemp(path.join(os.tmpdir(), 'snowluma-ini-'));
try {
expect(tencentFilesRootFromUserDataInfo(path.join(base, 'absent'))).toBeNull();
} finally {
await rm(base, { recursive: true, force: true });
}
});
it('reports nothing when the ini has no usable path', async () => {
await withUserDataInfo('[UserDataSet]\nUserDataSavePath=\n', (home) => {
expect(tencentFilesRootFromUserDataInfo(home)).toBeNull();
});
});
});
@@ -0,0 +1,30 @@
import { describe, expect, it } from 'vitest';
import { detectAccountLogins } from '../src/qq-account/detect';
/**
* Account detection against a real QQ data directory.
*
* Point `SNOWLUMA_QQ_DATA_ROOT` at one (for example `~/.config/QQ`) to run
* these; without it they are skipped, which is what CI and any machine without
* the client do. They are the only check that exercises login.db as QQ actually
* writes it, together with the holder probe on the databases it currently holds.
*/
const REAL_DATA_ROOT = process.env.SNOWLUMA_QQ_DATA_ROOT;
describe('account detection against real client data', () => {
it.runIf(Boolean(REAL_DATA_ROOT))('reads the accounts and their processes', async () => {
const accounts = await detectAccountLogins([REAL_DATA_ROOT!]);
expect(accounts.length).toBeGreaterThan(0);
for (const account of accounts) {
expect(account.uin).toMatch(/^\d{5,10}$/);
expect(account.uid).toMatch(/^u_/);
if (account.pid !== null) {
expect(Number.isInteger(account.pid)).toBe(true);
expect(() => process.kill(account.pid!, 0)).not.toThrow();
}
}
});
});
@@ -0,0 +1,324 @@
import { describe, expect, it } from 'vitest';
import { mkdtemp, readFile, rm } from 'node:fs/promises';
import os from 'node:os';
import path from 'node:path';
import { SqliteDatabase } from '@snowluma/sqlite';
import {
DATABASE_HEADER_SIZE,
decryptDatabase,
detectAlgorithm,
type SqlcipherAlgorithm,
} from '../src/qq-account/sqlcipher';
import {
FIXTURE_HEADER_SIZE,
FIXTURE_PAGE_SIZE,
FIXTURE_PASSPHRASE,
FIXTURE_WAL_FRAME_HEADER_SIZE,
FIXTURE_WAL_HEADER_SIZE,
encryptImage,
encryptWal,
reserveBytes,
walChecksum,
type FixtureAlgorithm,
} from './qq-account-fixtures';
const SHA1_SHA512: FixtureAlgorithm = { pageHmac: 'sha1', kdfHmac: 'sha512' };
/**
* Reserved space SQLite is told about for an encrypted database: room for the
* IV plus the largest page digest. SQLCipher's own reserve always fits inside
* it, which is why the tail of every page is disposable.
*/
const HEADER_RESERVED_BYTES = 80;
/** Offset of one frame in a `-wal` buffer. */
function frameOffset(index: number): number {
return FIXTURE_WAL_HEADER_SIZE + index * (FIXTURE_WAL_FRAME_HEADER_SIZE + FIXTURE_PAGE_SIZE);
}
/** Last frame index a merge may have applied, or -1 when nothing was committed. */
function lastCommitFrame(wal: Buffer, maxFrameIndex = frameCount(wal) - 1): number {
let last = -1;
for (let index = 0; index <= maxFrameIndex; index++) {
if (wal.readUInt32BE(frameOffset(index) + 4) !== 0) {
last = index;
}
}
return last;
}
function frameCount(wal: Buffer): number {
const frameSize = FIXTURE_WAL_FRAME_HEADER_SIZE + FIXTURE_PAGE_SIZE;
return Math.floor((wal.length - FIXTURE_WAL_HEADER_SIZE) / frameSize);
}
/** Frames up to and including the last commit, i.e. what a merge should apply. */
function committedFrames(wal: Buffer, maxFrameIndex?: number): number {
return lastCommitFrame(wal, maxFrameIndex) + 1;
}
/** Database size the last applicable commit declares. */
function lastCommitSize(wal: Buffer, maxFrameIndex?: number): number {
return wal.readUInt32BE(frameOffset(lastCommitFrame(wal, maxFrameIndex)) + 4);
}
/** Page content as the last applicable commit left it, keyed by page number. */
function committedPages(wal: Buffer, maxFrameIndex?: number): Map<number, Buffer> {
const pages = new Map<number, Buffer>();
const last = lastCommitFrame(wal, maxFrameIndex);
const size = lastCommitSize(wal, maxFrameIndex);
for (let index = 0; index <= last; index++) {
const pageNumber = wal.readUInt32BE(frameOffset(index));
if (pageNumber >= 1 && pageNumber <= size) {
pages.set(
pageNumber,
wal.subarray(
frameOffset(index) + FIXTURE_WAL_FRAME_HEADER_SIZE,
frameOffset(index + 1),
),
);
}
}
return pages;
}
/** Compare one merged page against the page a frame carried. */
function expectPageMatches(
merged: Buffer,
expectedPage: Buffer,
pageNumber: number,
algorithm: FixtureAlgorithm,
): void {
const reserve = reserveBytes(algorithm);
const start = (pageNumber - 1) * FIXTURE_PAGE_SIZE;
// Page 1's SQLite header carries the fields the merge keeps consistent with
// the assembled image (change counter, page count, journal mode), so only the
// page body is compared there.
const bodyStart = pageNumber === 1 ? 100 : 0;
expect(merged.subarray(start + bodyStart, start + FIXTURE_PAGE_SIZE - reserve)).toEqual(
expectedPage.subarray(bodyStart, FIXTURE_PAGE_SIZE - reserve),
);
expect(
merged
.subarray(start + FIXTURE_PAGE_SIZE - reserve, start + FIXTURE_PAGE_SIZE)
.equals(Buffer.alloc(reserve)),
).toBe(true);
}
/** A plaintext image with the header fields the merge keeps consistent. */
function plaintextImage(pageCount: number, marker = 0): Buffer {
const image = Buffer.alloc(pageCount * FIXTURE_PAGE_SIZE);
for (let page = 0; page < pageCount; page++) {
for (let offset = 0; offset < FIXTURE_PAGE_SIZE - HEADER_RESERVED_BYTES; offset++) {
image[page * FIXTURE_PAGE_SIZE + offset] = (page * 31 + offset + marker) % 251;
}
}
image.write('SQLite format 3\0', 0, 'latin1');
image.writeUInt16BE(FIXTURE_PAGE_SIZE, 16);
image[18] = 1;
image[19] = 1;
image[20] = HEADER_RESERVED_BYTES;
image[21] = 64;
image[22] = 32;
image[23] = 32;
image.writeUInt32BE(7, 24);
image.writeUInt32BE(pageCount, 28);
image.writeUInt32BE(7, 92);
return image;
}
/** A real SQLite database in WAL mode, plus the sidecar SQLite wrote for it. */
async function realWalDatabase(
directory: string,
inserts: string[][],
): Promise<{ image: Buffer; wal: Buffer; db: SqliteDatabase }> {
const file = path.join(directory, 'source.db');
const db = new SqliteDatabase(file);
await db.exec('PRAGMA wal_autocheckpoint = 0');
await db.exec('CREATE TABLE t(value TEXT)');
for (const [value] of inserts) {
await db.prepare('INSERT INTO t VALUES (?)').run(value);
}
return { image: await readFile(file), wal: await readFile(`${file}-wal`), db };
}
describe('SQLCipher page decryption', () => {
it('round-trips a page image and normalizes the header', () => {
const plain = plaintextImage(3);
plain[18] = 2; // stored as a WAL-mode database, like QQ writes them
plain[19] = 2;
const encrypted = encryptImage(plain, SHA1_SHA512);
expect(detectAlgorithm(encrypted, FIXTURE_PASSPHRASE)).toEqual(SHA1_SHA512);
const decrypted = decryptDatabase(encrypted, null, FIXTURE_PASSPHRASE, SHA1_SHA512);
expect(decrypted).not.toBeNull();
const expected = Buffer.from(plain);
expected[18] = 1;
expected[19] = 1;
expected.writeUInt32BE(3, 28);
expected.writeUInt32BE(7, 92);
expect(decrypted!.image.equals(expected)).toBe(true);
expect(decrypted!.walFrames).toBe(0);
});
it('probes the algorithm pair instead of assuming one', () => {
const plain = plaintextImage(2);
for (const algorithm of [
{ pageHmac: 'sha256', kdfHmac: 'sha256' },
{ pageHmac: 'sha512', kdfHmac: 'sha1' },
{ pageHmac: 'none', kdfHmac: 'sha512' },
] satisfies SqlcipherAlgorithm[]) {
const encrypted = encryptImage(plain, algorithm);
expect(detectAlgorithm(encrypted, FIXTURE_PASSPHRASE)).toEqual(algorithm);
expect(
decryptDatabase(encrypted, null, FIXTURE_PASSPHRASE, algorithm)!.image.equals(
plain,
),
).toBe(true);
}
});
it('rejects a wrong passphrase and a file that is too short', () => {
const encrypted = encryptImage(plaintextImage(2), SHA1_SHA512);
expect(detectAlgorithm(encrypted, 'wrong-passphrase')).toBeNull();
expect(
detectAlgorithm(Buffer.alloc(DATABASE_HEADER_SIZE + 512), FIXTURE_PASSPHRASE),
).toBeNull();
expect(decryptDatabase(Buffer.alloc(64), null, FIXTURE_PASSPHRASE, SHA1_SHA512)).toBeNull();
});
});
describe('SQLCipher WAL folding', () => {
it('reproduces the frame checksums SQLite itself wrote', async () => {
const directory = await mkdtemp(path.join(os.tmpdir(), 'snowluma-wal-'));
try {
const { wal, db } = await realWalDatabase(directory, [['a'], ['b']]);
const littleEndian = wal.readUInt32BE(0) === 0x377f0682;
const frameSize = FIXTURE_WAL_FRAME_HEADER_SIZE + FIXTURE_PAGE_SIZE;
expect((wal.length - FIXTURE_WAL_HEADER_SIZE) % frameSize).toBe(0);
const header = walChecksum(
[0, 0],
[wal.subarray(0, FIXTURE_WAL_HEADER_SIZE - 8)],
littleEndian,
);
expect(header).toEqual([wal.readUInt32BE(24), wal.readUInt32BE(28)]);
let running = header;
for (
let offset = FIXTURE_WAL_HEADER_SIZE;
offset + frameSize <= wal.length;
offset += frameSize
) {
const frame = wal.subarray(offset, offset + FIXTURE_WAL_FRAME_HEADER_SIZE);
running = walChecksum(
running,
[
frame.subarray(0, 8),
wal.subarray(offset + FIXTURE_WAL_FRAME_HEADER_SIZE, offset + frameSize),
],
littleEndian,
);
expect(running).toEqual([frame.readUInt32BE(16), frame.readUInt32BE(20)]);
}
await db.close();
} finally {
await rm(directory, { recursive: true, force: true });
}
});
it('folds every committed frame into the decrypted image', async () => {
const directory = await mkdtemp(path.join(os.tmpdir(), 'snowluma-wal-'));
try {
const { image, wal, db } = await realWalDatabase(directory, [['a'], ['b']]);
const encryptedImage = encryptImage(image, SHA1_SHA512);
const encryptedWal = encryptWal(wal, encryptedImage, SHA1_SHA512);
const decrypted = decryptDatabase(
encryptedImage,
encryptedWal,
FIXTURE_PASSPHRASE,
SHA1_SHA512,
);
expect(decrypted!.walFrames).toBe(committedFrames(wal));
expect(decrypted!.image.length).toBe(lastCommitSize(wal) * FIXTURE_PAGE_SIZE);
// Every page a committed frame carried has to arrive as it was written,
// apart from the on-disk IV/HMAC region the encryptor owns.
for (const [pageNumber, page] of committedPages(wal)) {
expectPageMatches(decrypted!.image, page, pageNumber, SHA1_SHA512);
}
await db.close();
} finally {
await rm(directory, { recursive: true, force: true });
}
});
it('keeps the intact prefix of a WAL torn by a running client', async () => {
const directory = await mkdtemp(path.join(os.tmpdir(), 'snowluma-wal-'));
try {
const { image, wal, db } = await realWalDatabase(directory, [['a'], ['b']]);
const encryptedImage = encryptImage(image, SHA1_SHA512);
const encryptedWal = encryptWal(wal, encryptedImage, SHA1_SHA512);
const frameSize = FIXTURE_WAL_FRAME_HEADER_SIZE + FIXTURE_PAGE_SIZE;
const frameCount = (wal.length - FIXTURE_WAL_HEADER_SIZE) / frameSize;
// Shred the last frame's page: everything after the previous commit
// must be dropped rather than half-applied.
encryptedWal[encryptedWal.length - 8] ^= 0xff;
const decrypted = decryptDatabase(
encryptedImage,
encryptedWal,
FIXTURE_PASSPHRASE,
SHA1_SHA512,
);
expect(decrypted).not.toBeNull();
expect(decrypted!.walFrames).toBeLessThan(frameCount);
// Frames up to the tear survive; the merge still stops at the last
// commit they contain rather than applying a partial transaction.
expect(decrypted!.walFrames).toBe(committedFrames(wal, frameCount - 2));
// Everything the surviving commits wrote has to be in the image.
for (const [pageNumber, page] of committedPages(wal, frameCount - 2)) {
expectPageMatches(decrypted!.image, page, pageNumber, SHA1_SHA512);
}
await db.close();
} finally {
await rm(directory, { recursive: true, force: true });
}
});
});
describe('SQLCipher header handling', () => {
it('keeps the client header opaque and stores the salt at the start of page 1', () => {
const plain = plaintextImage(2);
const encrypted = encryptImage(plain, SHA1_SHA512);
const header = encrypted.subarray(0, FIXTURE_HEADER_SIZE);
expect(header.equals(Buffer.alloc(FIXTURE_HEADER_SIZE))).toBe(true);
expect(
encrypted
.subarray(FIXTURE_HEADER_SIZE + 16, FIXTURE_HEADER_SIZE + 48)
.equals(plain.subarray(16, 48)),
).toBe(false);
});
});
@@ -1,724 +0,0 @@
import { EventEmitter } from 'events';
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
import { getLogLevel, setLogLevel, subscribeLogs } from '@snowluma/common/logger';
const execMock = vi.hoisted(() => vi.fn());
const httpGetMock = vi.hoisted(() => vi.fn());
const httpsGetMock = vi.hoisted(() => vi.fn());
vi.mock('child_process', () => ({ exec: execMock }));
vi.mock('http', () => ({
default: { get: httpGetMock },
get: httpGetMock,
}));
vi.mock('https', () => ({
default: { get: httpsGetMock },
get: httpsGetMock,
}));
import { probeQqLoginInfo } from '../src/qq-port-probe';
const originalPlatform = process.platform;
const EXEC_OPTIONS = { timeout: 1500, killSignal: 'SIGKILL' };
const PTLOGIN_HEADERS = {
Host: 'localhost.ptlogin2.qq.com',
Referer: 'https://xui.ptlogin2.qq.com/',
Cookie: 'pt_local_token=0',
};
type ExecCallback = (error: Error | null, result?: { stdout: string; stderr: string }) => void;
type RequestLike = EventEmitter & { destroy: ReturnType<typeof vi.fn> };
function setPlatform(platform: string): void {
Object.defineProperty(process, 'platform', { value: platform, configurable: true });
}
function mockExec(replies: Record<string, string | Error>): void {
execMock.mockImplementation((command: string, _options: unknown, callback: ExecCallback) => {
const reply = replies[command];
if (reply === undefined) {
callback(new Error(`unexpected command ${command}`));
return;
}
if (reply instanceof Error) {
callback(reply);
return;
}
callback(null, { stdout: reply, stderr: '' });
});
}
function execCommands(): string[] {
return execMock.mock.calls.map((call) => String(call[0]));
}
function ssLine(port: number, pid: number, owner: 'comma' | 'paren' = 'comma'): string {
const tag = owner === 'comma' ? `pid=${pid},fd=9` : `pid=${pid}`;
return `LISTEN 0 128 127.0.0.1:${port} 0.0.0.0:* users:(("qq",${tag}))`;
}
function netstatLine(localAddr: string, pid: number): string {
return ` TCP ${localAddr} 0.0.0.0:0 LISTENING ${pid}`;
}
function jsonp(accounts: unknown[]): string {
return `ptui_getuins_CB(${JSON.stringify(accounts)});`;
}
function requestStub(): RequestLike {
const req = new EventEmitter() as RequestLike;
req.destroy = vi.fn();
return req;
}
function replyBody(body: string | ReadonlyArray<string | Buffer>) {
return (
_url: string,
_options: unknown,
onResponse: (res: EventEmitter) => void,
): RequestLike => {
const req = requestStub();
const res = new EventEmitter();
onResponse(res);
const chunks = typeof body === 'string' ? [body] : body;
for (const chunk of chunks) {
res.emit('data', chunk);
}
res.emit('end');
return req;
};
}
function replyError(error: Error) {
return (): RequestLike => {
const req = requestStub();
queueMicrotask(() => req.emit('error', error));
return req;
};
}
beforeEach(() => {
execMock.mockReset();
httpGetMock.mockReset();
httpsGetMock.mockReset();
setPlatform('linux');
});
afterEach(() => {
setPlatform(originalPlatform);
vi.useRealTimers();
});
describe('probeQqLoginInfo — unix listing', () => {
it('returns null when ss cannot list sockets', async () => {
mockExec({ 'ss -tlnp': new Error('ss: not found') });
await expect(probeQqLoginInfo(3310)).resolves.toBeNull();
expect(execCommands()).toEqual(['ss -tlnp']);
expect(execMock.mock.calls[0]?.[1]).toEqual(EXEC_OPTIONS);
expect(httpGetMock).not.toHaveBeenCalled();
expect(httpsGetMock).not.toHaveBeenCalled();
});
it('reports a logged-out identity when the PID has no sockets and pgrep is below 6', async () => {
mockExec({
'ss -tlnp': 'State Recv-Q Send-Q Local Address:Port Peer Address:Port\n',
'pgrep -c qq': '5\n',
});
await expect(probeQqLoginInfo(3311)).resolves.toEqual({
port: 0,
uin: '',
identityKnown: false,
});
expect(execCommands()).toEqual(['ss -tlnp', 'pgrep -c qq']);
expect(execMock.mock.calls[1]?.[1]).toEqual(EXEC_OPTIONS);
});
it('treats a pgrep count of 0 as logged out', async () => {
mockExec({
'ss -tlnp': '',
'pgrep -c qq': '0\n',
});
await expect(probeQqLoginInfo(3312)).resolves.toEqual({
port: 0,
uin: '',
identityKnown: false,
});
});
it('treats a non-numeric pgrep count as 0 and therefore logged out', async () => {
mockExec({
'ss -tlnp': '',
'pgrep -c qq': 'qq: no process found\n',
});
await expect(probeQqLoginInfo(3313)).resolves.toEqual({
port: 0,
uin: '',
identityKnown: false,
});
});
it('returns null when there are no sockets and pgrep is 6 or higher', async () => {
mockExec({
'ss -tlnp': '',
'pgrep -c qq': '6\n',
});
await expect(probeQqLoginInfo(3314)).resolves.toBeNull();
mockExec({
'ss -tlnp': '',
'pgrep -c qq': '9\n',
});
await expect(probeQqLoginInfo(3315)).resolves.toBeNull();
});
it('does not treat a failed pgrep as logged out', async () => {
mockExec({
'ss -tlnp': '',
'pgrep -c qq': new Error('pgrep: exit 1'),
});
await expect(probeQqLoginInfo(3316)).resolves.toBeNull();
});
it('uses the first listening port as a logged-out hint when no Ptlogin port is present', async () => {
mockExec({
'ss -tlnp': [ssLine(9218, 4410), ssLine(18000, 4410)].join('\n'),
'pgrep -c qq': ' 4 \n',
});
await expect(probeQqLoginInfo(4410)).resolves.toEqual({
port: 9218,
uin: '',
identityKnown: false,
});
expect(httpGetMock).not.toHaveBeenCalled();
expect(httpsGetMock).not.toHaveBeenCalled();
});
it('returns null for non-Ptlogin ports when the QQ process count is ambiguous', async () => {
mockExec({
'ss -tlnp': ssLine(9218, 4411),
'pgrep -c qq': '7\n',
});
await expect(probeQqLoginInfo(4411)).resolves.toBeNull();
expect(httpGetMock).not.toHaveBeenCalled();
expect(httpsGetMock).not.toHaveBeenCalled();
});
it('collects unique ports from ss lines that name the PID with either pid=N, or pid=N)', async () => {
mockExec({
'ss -tlnp': [
'LISTEN 0 128 127.0.0.1:4301users:(("qq",pid=4412,fd=1))',
ssLine(4301, 4412, 'comma'),
ssLine(4301, 4412, 'comma'),
ssLine(4305, 4412, 'paren'),
ssLine(4305, 9999, 'comma'),
'ESTAB 0 0 127.0.0.1:4307 127.0.0.1:443 users:(("qq",pid=4412,fd=4))',
].join('\n'),
});
httpsGetMock.mockImplementation(replyBody(jsonp([{ uin: '10001', nickname: 'Ada' }])));
await expect(probeQqLoginInfo(4412)).resolves.toEqual({
port: 4301,
uin: '10001',
nickName: 'Ada',
identityKnown: true,
});
expect(httpsGetMock).toHaveBeenCalledTimes(2);
expect(httpsGetMock.mock.calls[0]?.[0]).toBe(
'https://127.0.0.1:4301/pt_get_uins?callback=ptui_getuins_CB&pt_local_tk=0',
);
});
});
describe('probeQqLoginInfo — Ptlogin identity', () => {
it('reads a single account from an odd Ptlogin port over https', async () => {
mockExec({ 'ss -tlnp': ssLine(4301, 5501) });
httpsGetMock.mockImplementation(
replyBody(
jsonp([
{
uin: 319427101,
account: 1,
nickname: 'Snow',
extra: 'ignored',
},
]),
),
);
await expect(probeQqLoginInfo(5501)).resolves.toEqual({
port: 4301,
uin: '319427101',
nickName: 'Snow',
identityKnown: true,
});
expect(httpGetMock).not.toHaveBeenCalled();
expect(httpsGetMock).toHaveBeenCalledTimes(2);
expect(httpsGetMock.mock.calls[0]?.[1]).toEqual({
headers: PTLOGIN_HEADERS,
timeout: 500,
rejectUnauthorized: false,
});
});
it('reads a single account from an even Ptlogin port over http', async () => {
mockExec({ 'ss -tlnp': ssLine(4302, 5502) });
httpGetMock.mockImplementation(
replyBody(
jsonp([
{
account: '2880036470',
},
]),
),
);
await expect(probeQqLoginInfo(5502)).resolves.toEqual({
port: 4302,
uin: '2880036470',
nickName: '',
identityKnown: true,
});
expect(httpsGetMock).not.toHaveBeenCalled();
expect(httpGetMock).toHaveBeenCalledTimes(2);
expect(httpGetMock.mock.calls[0]?.[0]).toBe(
'http://127.0.0.1:4302/pt_get_uins?callback=ptui_getuins_CB&pt_local_tk=0',
);
expect(httpGetMock.mock.calls[0]?.[1]).toEqual({
headers: PTLOGIN_HEADERS,
timeout: 500,
});
});
it('probes every documented odd Ptlogin port over https', async () => {
for (const port of [4301, 4303, 4305, 4307, 4309]) {
execMock.mockReset();
httpsGetMock.mockReset();
httpGetMock.mockReset();
mockExec({ 'ss -tlnp': ssLine(port, 5510) });
httpsGetMock.mockImplementation(replyBody(jsonp([{ uin: '70001', nickname: 'Odd' }])));
await expect(probeQqLoginInfo(5510)).resolves.toEqual({
port,
uin: '70001',
nickName: 'Odd',
identityKnown: true,
});
expect(httpGetMock).not.toHaveBeenCalled();
expect(String(httpsGetMock.mock.calls[0]?.[0])).toBe(
`https://127.0.0.1:${port}/pt_get_uins?callback=ptui_getuins_CB&pt_local_tk=0`,
);
}
});
it('probes every documented even Ptlogin port over http when no odd port is listening', async () => {
for (const port of [4302, 4304, 4306, 4308, 4310]) {
execMock.mockReset();
httpsGetMock.mockReset();
httpGetMock.mockReset();
mockExec({ 'ss -tlnp': ssLine(port, 5511) });
httpGetMock.mockImplementation(replyBody(jsonp([{ uin: '70002', nickname: 'Even' }])));
await expect(probeQqLoginInfo(5511)).resolves.toEqual({
port,
uin: '70002',
nickName: 'Even',
identityKnown: true,
});
expect(httpsGetMock).not.toHaveBeenCalled();
expect(String(httpGetMock.mock.calls[0]?.[0])).toBe(
`http://127.0.0.1:${port}/pt_get_uins?callback=ptui_getuins_CB&pt_local_tk=0`,
);
}
});
it('prefers odd Ptlogin ports and never falls through to even ones', async () => {
mockExec({
'ss -tlnp': [ssLine(4302, 5520), ssLine(4301, 5520)].join('\n'),
});
httpsGetMock.mockImplementation(replyError(new Error('ECONNREFUSED')));
await expect(probeQqLoginInfo(5520)).resolves.toBeNull();
expect(httpsGetMock).toHaveBeenCalled();
expect(httpGetMock).not.toHaveBeenCalled();
expect(execCommands()).toEqual(['ss -tlnp']);
});
it('tries the next odd Ptlogin port after the first one fails', async () => {
mockExec({
'ss -tlnp': [ssLine(4301, 5521), ssLine(4305, 5521)].join('\n'),
});
httpsGetMock
.mockImplementationOnce(replyBody('<html>nope</html>'))
.mockImplementationOnce(replyBody('<html>nope</html>'))
.mockImplementationOnce(replyBody(jsonp([{ uin: '188888', nickname: 'Next' }])))
.mockImplementationOnce(replyBody(jsonp([{ uin: '188888', nickname: 'Next' }])));
await expect(probeQqLoginInfo(5521)).resolves.toEqual({
port: 4305,
uin: '188888',
nickName: 'Next',
identityKnown: true,
});
expect(httpsGetMock.mock.calls.map((call) => call[0])).toEqual([
'https://127.0.0.1:4301/pt_get_uins?callback=ptui_getuins_CB&pt_local_tk=0',
'https://127.0.0.1:4301/pt_get_uins?callback=ptui_getuins_CB&pt_local_tk=0',
'https://127.0.0.1:4305/pt_get_uins?callback=ptui_getuins_CB&pt_local_tk=0',
'https://127.0.0.1:4305/pt_get_uins?callback=ptui_getuins_CB&pt_local_tk=0',
]);
});
it('stops after the first Ptlogin port that yields a single account', async () => {
mockExec({
'ss -tlnp': [ssLine(4303, 5522), ssLine(4309, 5522)].join('\n'),
});
httpsGetMock.mockImplementation(replyBody(jsonp([{ uin: '42', nickname: 'First' }])));
await expect(probeQqLoginInfo(5522)).resolves.toEqual({
port: 4303,
uin: '42',
nickName: 'First',
identityKnown: true,
});
expect(httpsGetMock).toHaveBeenCalledTimes(2);
});
it('uses account when uin is missing or empty, including a numeric 0 uin', async () => {
mockExec({ 'ss -tlnp': ssLine(4301, 5530) });
httpsGetMock
.mockImplementationOnce(
replyBody(jsonp([{ uin: 0, account: 314159, nickname: 'Zero' }])),
)
.mockImplementationOnce(
replyBody(jsonp([{ uin: '', account: '314159', nickname: 'Zero' }])),
);
await expect(probeQqLoginInfo(5530)).resolves.toEqual({
port: 4301,
uin: '314159',
nickName: 'Zero',
identityKnown: true,
});
});
it('returns an empty uin when the single account has neither uin nor account', async () => {
mockExec({ 'ss -tlnp': ssLine(4301, 5531) });
httpsGetMock.mockImplementation(replyBody('[{"nickname":"Anon"}]'));
await expect(probeQqLoginInfo(5531)).resolves.toEqual({
port: 4301,
uin: '',
nickName: 'Anon',
identityKnown: true,
});
});
it('keeps the shorter of the two pt_get_uins snapshots', async () => {
mockExec({ 'ss -tlnp': ssLine(4301, 5540) });
httpsGetMock
.mockImplementationOnce(
replyBody(
jsonp([
{ uin: '11', nickname: 'A' },
{ uin: '22', nickname: 'B' },
]),
),
)
.mockImplementationOnce(replyBody(jsonp([{ uin: '33', nickname: 'Cora' }])));
await expect(probeQqLoginInfo(5540)).resolves.toEqual({
port: 4301,
uin: '33',
nickName: 'Cora',
identityKnown: true,
});
});
it('keeps the first snapshot when both pt_get_uins calls have one account', async () => {
mockExec({ 'ss -tlnp': ssLine(4301, 5541) });
httpsGetMock
.mockImplementationOnce(replyBody(jsonp([{ uin: '100', nickname: 'Left' }])))
.mockImplementationOnce(replyBody(jsonp([{ uin: '200', nickname: 'Right' }])));
await expect(probeQqLoginInfo(5541)).resolves.toEqual({
port: 4301,
uin: '100',
nickName: 'Left',
identityKnown: true,
});
});
it('accepts a single account from the second fetch when the first fetch is unusable', async () => {
mockExec({ 'ss -tlnp': ssLine(4301, 5542) });
httpsGetMock
.mockImplementationOnce(replyError(new Error('ECONNRESET')))
.mockImplementationOnce(replyBody(jsonp([{ uin: '9090', nickname: 'Retry' }])));
await expect(probeQqLoginInfo(5542)).resolves.toEqual({
port: 4301,
uin: '9090',
nickName: 'Retry',
identityKnown: true,
});
});
it('returns null for an empty pt_get_uins array and does not consult pgrep', async () => {
mockExec({ 'ss -tlnp': ssLine(4301, 5550) });
httpsGetMock.mockImplementation(replyBody('ptui_getuins_CB([]);'));
await expect(probeQqLoginInfo(5550)).resolves.toBeNull();
expect(execCommands()).toEqual(['ss -tlnp']);
});
it('returns null when both snapshots have more than one account', async () => {
mockExec({ 'ss -tlnp': ssLine(4304, 5551) });
httpGetMock.mockImplementation(replyBody(jsonp([{ uin: '1' }, { uin: '2' }])));
await expect(probeQqLoginInfo(5551)).resolves.toBeNull();
});
it('returns null when both fetches fail to parse a pt_get_uins body', async () => {
mockExec({ 'ss -tlnp': ssLine(4301, 5552) });
httpsGetMock.mockImplementation(replyBody('not-jsonp'));
await expect(probeQqLoginInfo(5552)).resolves.toBeNull();
});
it('returns null when both fetches error', async () => {
mockExec({ 'ss -tlnp': ssLine(4301, 5553) });
httpsGetMock.mockImplementation(replyError(new Error('ECONNREFUSED')));
await expect(probeQqLoginInfo(5553)).resolves.toBeNull();
});
it('destroys the request and returns null when both fetches time out', async () => {
mockExec({ 'ss -tlnp': ssLine(4301, 5554) });
const seen: RequestLike[] = [];
httpsGetMock.mockImplementation(() => {
const req = requestStub();
seen.push(req);
queueMicrotask(() => req.emit('timeout'));
return req;
});
await expect(probeQqLoginInfo(5554)).resolves.toBeNull();
expect(seen).toHaveLength(2);
expect(seen[0]?.destroy).toHaveBeenCalledTimes(1);
expect(seen[1]?.destroy).toHaveBeenCalledTimes(1);
});
it('joins chunked pt_get_uins bodies including Buffer pieces', async () => {
mockExec({ 'ss -tlnp': ssLine(4301, 5560) });
httpsGetMock.mockImplementation(
replyBody([
'ptui_getuins_CB([',
Buffer.from('{"uin":"10001","nickname":"Ada"}'),
']);',
]),
);
await expect(probeQqLoginInfo(5560)).resolves.toEqual({
port: 4301,
uin: '10001',
nickName: 'Ada',
identityKnown: true,
});
});
it('treats a nickname that closes the JSONP array early as unusable', async () => {
mockExec({ 'ss -tlnp': ssLine(4301, 5561) });
httpsGetMock.mockImplementation(
replyBody('ptui_getuins_CB([{"nickname":"a]b","uin":"1"}]);'),
);
await expect(probeQqLoginInfo(5561)).resolves.toBeNull();
});
});
describe('probeQqLoginInfo — win32 listing', () => {
beforeEach(() => {
setPlatform('win32');
});
it('returns null when netstat cannot list sockets', async () => {
mockExec({ 'netstat -ano': new Error('netstat: access denied') });
await expect(probeQqLoginInfo(6610)).resolves.toBeNull();
expect(execCommands()).toEqual(['netstat -ano']);
expect(execMock.mock.calls[0]?.[1]).toEqual(EXEC_OPTIONS);
});
it('counts QQ.exe rows from tasklist when netstat lists no sockets for the PID', async () => {
mockExec({
'netstat -ano': [
'Active Connections',
'',
' Proto Local Address Foreign Address State PID',
netstatLine('127.0.0.1:4301', 1),
].join('\n'),
'tasklist /fi "imagename eq QQ.exe" /nh': [
'QQ.exe 100 Console 1 10,000 K',
'QQ.exe 101 Console 1 11,000 K',
'explorer.exe 200 Console 1 9,000 K',
].join('\n'),
});
await expect(probeQqLoginInfo(6611)).resolves.toEqual({
port: 0,
uin: '',
identityKnown: false,
});
expect(execCommands()).toEqual(['netstat -ano', 'tasklist /fi "imagename eq QQ.exe" /nh']);
});
it('returns null when tasklist reports 6 or more QQ.exe rows and the PID has no sockets', async () => {
mockExec({
'netstat -ano': '',
'tasklist /fi "imagename eq QQ.exe" /nh': [
'QQ.exe 1',
'QQ.exe 2',
'QQ.exe 3',
'qq.exe 4',
'QQ.EXE 5',
'QQ.exe 6',
].join('\n'),
});
await expect(probeQqLoginInfo(6612)).resolves.toBeNull();
});
it('does not treat a failed tasklist as logged out', async () => {
mockExec({
'netstat -ano': '',
'tasklist /fi "imagename eq QQ.exe" /nh': new Error('tasklist: exit 1'),
});
await expect(probeQqLoginInfo(6613)).resolves.toBeNull();
});
it('parses netstat rows for the owning PID and skips short or portless lines', async () => {
mockExec({
'netstat -ano': [
'Active Connections',
' TCP 127.0.0.1:4301 LISTENING',
' TCP 127.0.0.1 0.0.0.0:0 LISTENING 6620',
netstatLine('10.0.0.8:18000', 1),
netstatLine('127.0.0.1:4303', 6620),
netstatLine('[::1]:4303', 6620),
netstatLine('127.0.0.1:9218', 6620),
].join('\n'),
});
httpsGetMock.mockImplementation(replyBody(jsonp([{ uin: '20002', nickname: 'Win' }])));
await expect(probeQqLoginInfo(6620)).resolves.toEqual({
port: 4303,
uin: '20002',
nickName: 'Win',
identityKnown: true,
});
expect(httpsGetMock).toHaveBeenCalledTimes(2);
expect(httpsGetMock.mock.calls[0]?.[0]).toBe(
'https://127.0.0.1:4303/pt_get_uins?callback=ptui_getuins_CB&pt_local_tk=0',
);
});
it('uses the first netstat port as a logged-out hint when no Ptlogin port is present', async () => {
mockExec({
'netstat -ano': [
netstatLine('127.0.0.1:18000', 6630),
netstatLine('127.0.0.1:18001', 6630),
].join('\n'),
'tasklist /fi "imagename eq QQ.exe" /nh': 'QQ.exe 100\n',
});
await expect(probeQqLoginInfo(6630)).resolves.toEqual({
port: 18000,
uin: '',
identityKnown: false,
});
expect(httpGetMock).not.toHaveBeenCalled();
expect(httpsGetMock).not.toHaveBeenCalled();
});
});
describe('probeQqLoginInfo — overall deadline', () => {
it('returns null and warns after 5000ms if listing never finishes', async () => {
vi.useFakeTimers();
execMock.mockImplementation(() => undefined);
const previousLevel = getLogLevel();
setLogLevel('info');
const warnings: string[] = [];
const unsubscribe = subscribeLogs((entry) => {
if (entry.scope === 'LoginProbe' && entry.level === 'warn') {
warnings.push(entry.message);
}
});
try {
const pending = probeQqLoginInfo(9001);
let settled: unknown = 'pending';
void pending.then((value) => {
settled = value;
});
await vi.advanceTimersByTimeAsync(4999);
expect(settled).toBe('pending');
await vi.advanceTimersByTimeAsync(1);
await expect(pending).resolves.toBeNull();
expect(warnings).toEqual(['login check timed out: PID=9001']);
} finally {
unsubscribe();
setLogLevel(previousLevel);
}
});
it('does not warn when the probe finishes before the deadline', async () => {
mockExec({
'ss -tlnp': '',
'pgrep -c qq': '2\n',
});
const previousLevel = getLogLevel();
setLogLevel('info');
const warnings: string[] = [];
const unsubscribe = subscribeLogs((entry) => {
if (entry.scope === 'LoginProbe') {
warnings.push(entry.message);
}
});
try {
await expect(probeQqLoginInfo(9002)).resolves.toEqual({
port: 0,
uin: '',
identityKnown: false,
});
await probeQqLoginInfo(9002);
expect(warnings).toEqual(['login probe: PID=9002 result=no-ports ports=0 processes=2']);
} finally {
unsubscribe();
setLogLevel(previousLevel);
}
});
it('abandons a hung Ptlogin fetch at the overall deadline', async () => {
vi.useFakeTimers();
mockExec({ 'ss -tlnp': ssLine(4301, 9003) });
httpsGetMock.mockImplementation(() => requestStub());
const pending = probeQqLoginInfo(9003);
await vi.advanceTimersByTimeAsync(5000);
await expect(pending).resolves.toBeNull();
});
});
@@ -1,77 +0,0 @@
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
const execMock = vi.hoisted(() => vi.fn());
const socketCtorMock = vi.hoisted(() =>
vi.fn(function MockSocket() {
throw new Error('interactive QQ probe must not run');
}),
);
vi.mock('child_process', () => ({ exec: execMock }));
vi.mock('net', () => ({
default: { Socket: socketCtorMock },
Socket: socketCtorMock,
}));
import { probeQqLoginInfo } from '../src/qq-port-probe';
describe('probeQqLoginInfo — bounded execution', () => {
beforeEach(() => {
vi.useFakeTimers();
execMock.mockReset();
socketCtorMock.mockClear();
});
afterEach(() => {
vi.useRealTimers();
});
it('allows a later probe after a timed-out attempt', async () => {
execMock.mockImplementation(() => undefined);
const first = probeQqLoginInfo(4242);
await vi.advanceTimersByTimeAsync(10_000);
await expect(first).resolves.toBeNull();
execMock
.mockImplementationOnce((_command, _options, callback) => {
callback(null, { stdout: '', stderr: '' });
})
.mockImplementationOnce((_command, _options, callback) => {
callback(null, {
stdout: process.platform === 'win32' ? 'QQ.exe 4242 Console 1 1234 K\n' : '1\n',
stderr: '',
});
});
await expect(probeQqLoginInfo(4242)).resolves.toEqual({
port: 0,
uin: '',
identityKnown: false,
});
});
it('keeps background identity discovery passive', async () => {
execMock
.mockImplementationOnce((_command, _options, callback) => {
callback(null, {
stdout:
process.platform === 'win32'
? 'TCP 127.0.0.1:9218 0.0.0.0:0 LISTENING 4242\n'
: 'LISTEN 0 128 127.0.0.1:9218 0.0.0.0:* users:(("qq",pid=4242,fd=12))\n',
stderr: '',
});
})
.mockImplementationOnce((_command, _options, callback) => {
callback(null, {
stdout:
process.platform === 'win32'
? 'QQ.exe 4242 Console 1 1234 K\n'.repeat(8)
: '8\n',
stderr: '',
});
});
await expect(probeQqLoginInfo(4242)).resolves.toBeNull();
expect(socketCtorMock).not.toHaveBeenCalled();
});
});