diff --git a/.gitignore b/.gitignore index d72959a4..0e235bec 100644 --- a/.gitignore +++ b/.gitignore @@ -11,6 +11,7 @@ dist/ /config/ /data/ +logs/ # macOS metadata .DS_Store diff --git a/packages/core/src/hook/hook-manager.ts b/packages/core/src/hook/hook-manager.ts index b03a07b3..18728c54 100644 --- a/packages/core/src/hook/hook-manager.ts +++ b/packages/core/src/hook/hook-manager.ts @@ -12,9 +12,11 @@ import { HookSession, type HookSessionDeps } from './hook-session'; import { PipeWatcher } from './pipe-watcher'; import { QqHookClient } from './qq-hook-client'; import type { HookProcessInfo } from './types'; +import { probeQqLoginInfo, type QqPortLoginInfo } from './qq-port-probe'; export type { HookProcessInfo, HookProcessStatus } from './types'; export type { HookProcessBaseInfo } from './injector'; +export type { QqPortLoginInfo } from './qq-port-probe'; export type HookManagerDeps = { bridgeManager: BridgeManager; @@ -147,6 +149,11 @@ export class HookManager { return session.refresh(); } + async probeProcessLoginInfo(pid: number): Promise { + this.assertValidPid(pid); + return probeQqLoginInfo(pid); + } + dispose(): void { if (this.disposed) return; this.disposed = true; diff --git a/packages/core/src/hook/qq-port-probe.ts b/packages/core/src/hook/qq-port-probe.ts new file mode 100644 index 00000000..b9bde522 --- /dev/null +++ b/packages/core/src/hook/qq-port-probe.ts @@ -0,0 +1,168 @@ +import net from 'net'; +import { exec } from 'child_process'; +import { promisify } from 'util'; + +const execAsync = promisify(exec); + +const PORT_RANGE_START = 9210; +const PORT_RANGE_END = 9219; +const PROBE_TIMEOUT_MS = 1000; +const CONNECTION_TIMEOUT_MS = 500; + +export interface QqPortLoginInfo { + port: number; + uin: string; + uid?: string; + nickName?: string; + loggedIn: boolean; +} + +interface JwtPayload { + errCode: number; + errMsg: string; + port: number; + uin?: string; + uid?: string; + nickName?: string; + data?: { + uin?: string; + url?: string; + }; + iat: number; +} + +function decodeJwt(token: string): JwtPayload | null { + try { + const parts = token.split('.'); + if (parts.length !== 3) return null; + const payload = Buffer.from(parts[1], 'base64').toString('utf8'); + return JSON.parse(payload); + } catch { + return null; + } +} + +async function probePort(port: number): Promise { + return new Promise((resolve) => { + const client = new net.Socket(); + const link = 'tencent://'; + const payload = `POST /tencent HTTP/1.1\r\nHost: 127.0.0.1:${port}\r\nConnection: close\r\nContent-Length: ${link.length}\r\n\r\n${link}`; + + let responseData = ''; + let timer: NodeJS.Timeout; + + const cleanup = () => { + clearTimeout(timer); + client.removeAllListeners(); + client.destroy(); + }; + + timer = setTimeout(() => { + cleanup(); + resolve(null); + }, PROBE_TIMEOUT_MS); + + client.setTimeout(CONNECTION_TIMEOUT_MS); + + client.connect(port, '127.0.0.1', () => { + client.write(payload); + }); + + client.on('data', (data) => { + responseData += data.toString(); + }); + + client.on('close', () => { + cleanup(); + const jwtMatch = responseData.match(/eyJ[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+/); + if (!jwtMatch) { + resolve(null); + return; + } + + const decoded = decodeJwt(jwtMatch[0]); + if (!decoded || decoded.errCode !== 0) { + resolve(null); + return; + } + + const uin = decoded.uin || decoded.data?.uin || ''; + resolve({ + port, + uin, + uid: decoded.uid, + nickName: decoded.nickName, + loggedIn: uin.length > 0, + }); + }); + + client.on('error', () => { + cleanup(); + resolve(null); + }); + + client.on('timeout', () => { + cleanup(); + resolve(null); + }); + }); +} + +async function getProcessPorts(pid: number): Promise { + try { + if (process.platform === 'win32') { + const { stdout } = await execAsync(`netstat -ano | findstr ${pid}`); + const ports = new Set(); + const lines = stdout.split('\n'); + for (const line of lines) { + const parts = line.trim().split(/\s+/); + if (parts.length < 5) continue; + const owningPid = parts[parts.length - 1]; + if (owningPid !== String(pid)) continue; + const localAddr = parts[1]; + const portMatch = localAddr.match(/:(\d+)$/); + if (!portMatch) continue; + const port = Number(portMatch[1]); + if (port >= PORT_RANGE_START && port <= PORT_RANGE_END) { + ports.add(port); + } + } + return Array.from(ports); + } else { + const { stdout } = await execAsync(`ss -tlnp | grep pid=${pid}`); + const ports = new Set(); + const lines = stdout.split('\n'); + for (const line of lines) { + const match = line.match(/:(\d+)\s/); + if (match) { + const port = Number(match[1]); + if (port >= PORT_RANGE_START && port <= PORT_RANGE_END) { + ports.add(port); + } + } + } + return Array.from(ports); + } + } catch { + return []; + } +} + +export async function probeQqLoginInfo(pid: number): Promise { + const ports = await getProcessPorts(pid); + + if (ports.length === 0) { + for (let port = PORT_RANGE_START; port <= PORT_RANGE_END; port++) { + const info = await probePort(port); + if (info) return info; + } + return null; + } + + for (const port of ports) { + const info = await probePort(port); + if (info) return info; + } + + return null; +} diff --git a/packages/core/src/webui/server.ts b/packages/core/src/webui/server.ts index 1848eb0a..87cfa31d 100644 --- a/packages/core/src/webui/server.ts +++ b/packages/core/src/webui/server.ts @@ -450,6 +450,21 @@ export async function initWebUI( app.post('/api/processes/:pid/unload', processAction('unload', (pid) => hookManager!.unloadProcess(pid))); app.post('/api/processes/:pid/refresh', processAction('refresh', (pid) => hookManager!.refreshProcess(pid))); + app.get('/api/processes/:pid/probe-login', async (c) => { + if (!hookManager) return c.json({ info: null, message: 'hook manager is not available' }, 503); + const pid = Number(c.req.param('pid')); + if (!Number.isInteger(pid) || pid <= 0 || pid > MAX_PID) { + return c.json({ info: null, message: 'invalid pid' }, 400); + } + try { + const info = await hookManager.probeProcessLoginInfo(pid); + return c.json({ info }); + } catch (err) { + log.warn('probe-login pid=%d failed: %s', pid, err instanceof Error ? err.message : String(err)); + return c.json({ info: null, message: '探测失败' }, 500); + } + }); + app.get('/api/config/:uin', (c) => { const uin = c.req.param('uin'); if (!UIN_REGEX.test(uin)) return c.json({ message: 'invalid uin' }, 400); diff --git a/packages/webui/src/components/pages/overview-page.tsx b/packages/webui/src/components/pages/overview-page.tsx index 54b8e2cc..096d1db2 100644 --- a/packages/webui/src/components/pages/overview-page.tsx +++ b/packages/webui/src/components/pages/overview-page.tsx @@ -5,6 +5,7 @@ import { AlertCircle, CheckCircle2, Cpu, + Eye, Loader2, MemoryStick, MonitorCog, @@ -21,6 +22,7 @@ import { ScrollArea } from '@/components/ui/scroll-area'; import { Avatar, AvatarFallback, AvatarImage } from '@/components/ui/avatar'; import { Skeleton } from '@/components/ui/skeleton'; import { ConfirmDialog } from '@/components/confirm-dialog'; +import { ProcessProbeDialog } from '@/components/process-probe-dialog'; import { cn, formatBytes, formatUptime } from '@/lib/utils'; import type { HookProcessInfo } from '@/types'; import { useAppState } from '@/contexts/AppStateContext'; @@ -91,6 +93,7 @@ export function OverviewPage() { | { kind: 'load' | 'unload'; pid: number; name: string } | null >(null); + const [probeDialog, setProbeDialog] = useState<{ pid: number; name: string } | null>(null); // Lightweight tick to refresh "uptime" pretty-print every 30s const [, force] = useState(0); @@ -325,6 +328,14 @@ export function OverviewPage() { )}
+ {showRefresh && (
); } diff --git a/packages/webui/src/components/process-probe-dialog.tsx b/packages/webui/src/components/process-probe-dialog.tsx new file mode 100644 index 00000000..bbd221ba --- /dev/null +++ b/packages/webui/src/components/process-probe-dialog.tsx @@ -0,0 +1,140 @@ +import { useEffect, useState } from 'react'; +import { Eye, Loader2, User, UserX } from 'lucide-react'; +import { Button } from '@/components/ui/button'; +import { + Dialog, + DialogContent, + DialogDescription, + DialogHeader, + DialogTitle, +} from '@/components/ui/dialog'; +import { Avatar, AvatarFallback, AvatarImage } from '@/components/ui/avatar'; +import { Badge } from '@/components/ui/badge'; +import { useApi } from '@/lib/api'; + +interface QqPortLoginInfo { + port: number; + uin: string; + uid?: string; + nickName?: string; + loggedIn: boolean; +} + +interface ProcessProbeDialogProps { + pid: number; + processName: string; + open: boolean; + onOpenChange: (open: boolean) => void; +} + +function qqAvatarUrl(uin: string) { + return `/avatar/${encodeURIComponent(uin)}`; +} + +export function ProcessProbeDialog({ pid, processName, open, onOpenChange }: ProcessProbeDialogProps) { + const api = useApi(); + const [loading, setLoading] = useState(false); + const [info, setInfo] = useState(null); + const [error, setError] = useState(null); + + const probe = async () => { + setLoading(true); + setError(null); + setInfo(null); + try { + const result = await api.processes.probeLoginInfo(pid); + setInfo(result as QqPortLoginInfo | null); + if (!result) { + setError('未检测到登录信息(端口 9210-9219 无响应)'); + } + } catch (err) { + setError(err instanceof Error ? err.message : '探测失败'); + } finally { + setLoading(false); + } + }; + + useEffect(() => { + if (open) { + probe(); + } else { + setInfo(null); + setError(null); + } + }, [open]); + + return ( + + + + 查看登录状态 + + {processName} (PID {pid}) + + + +
+ {loading && ( +
+ +
+ )} + + {!loading && error && ( +
+ +

{error}

+
+ )} + + {!loading && info && ( +
+ {info.loggedIn ? ( +
+ + + + + + +
+
+ {info.nickName || info.uin} + 已登录 +
+
UIN: {info.uin}
+ {info.uid && ( +
+ UID: {info.uid} +
+ )} +
端口: {info.port}
+
+
+ ) : ( +
+ +
+

等待登录

+

端口 {info.port} 已响应,但未检测到登录账号

+
+
+ )} +
+ )} + +
+ + {!loading && ( + + )} +
+
+
+
+ ); +} diff --git a/packages/webui/src/lib/api/client.ts b/packages/webui/src/lib/api/client.ts index b732727c..617de321 100644 --- a/packages/webui/src/lib/api/client.ts +++ b/packages/webui/src/lib/api/client.ts @@ -53,6 +53,7 @@ class HttpApiClient implements ApiClient { load: (pid) => this.postJson(`/api/processes/${pid}/load`), unload: (pid) => this.postJson(`/api/processes/${pid}/unload`), refresh: (pid) => this.postJson(`/api/processes/${pid}/refresh`), + probeLoginInfo: (pid) => this.getJson<{ info: unknown }>(`/api/processes/${pid}/probe-login`).then((d) => d.info ?? null), }; this.config = { diff --git a/packages/webui/src/lib/api/types.ts b/packages/webui/src/lib/api/types.ts index 01153200..83beb3a0 100644 --- a/packages/webui/src/lib/api/types.ts +++ b/packages/webui/src/lib/api/types.ts @@ -57,6 +57,7 @@ export interface ApiClient { load(pid: number): Promise; unload(pid: number): Promise; refresh(pid: number): Promise; + probeLoginInfo(pid: number): Promise; }; // ---- OneBotInstance per-UIN config ----