From 34a572f1531f5ff448b670d0599a4bcb251bb27e Mon Sep 17 00:00:00 2001 From: venti1112 <3788365896@qq.com> Date: Tue, 5 May 2026 17:15:13 +0800 Subject: [PATCH] fix: fix reverse-ws reload/reconnect idempotency, preserve explicit no-token config values, and make WebUI config rendering consistent after refresh Previous behavior: after editing an unreachable reverse-ws OneBot config entry, the new config took effect, but reconnect attempts could still target the old URL. Fixed behavior: reconnect now only applies to currently active OneBot config entries; removed or changed old entries are no longer retried. Previous behavior: after refreshing the WebUI, OneBot config entries for the same account were already loaded and active in backend, but appeared empty in the WebUI config page. Fixed behavior: OneBot config API response shape is now unified and backward-compatible, so persisted OneBot config entries render correctly after WebUI refresh. Previous behavior: no-token OneBot config entries could be automatically assigned a token during load/refresh. Fixed behavior: fixed the issue where no-token config entries were auto-populated with tokens; OneBot config entry token values now strictly follow explicit user configuration (empty stays empty). Previous behavior: after multiple reconnect failures for a reverse-ws OneBot config entry, multiple connections could be created concurrently when the target server came back. Fixed behavior: added per-entry connection/reconnect deduplication so each OneBot config entry maintains only one active connection and one reconnect timer. --- packages/core/src/onebot/config.ts | 25 -------------- packages/core/src/onebot/ws-transport.ts | 43 ++++++++++++++++++++---- packages/core/src/webui/server.ts | 5 ++- packages/webui/src/App.tsx | 11 +++--- 4 files changed, 47 insertions(+), 37 deletions(-) diff --git a/packages/core/src/onebot/config.ts b/packages/core/src/onebot/config.ts index 99f06fc9..c3eec783 100644 --- a/packages/core/src/onebot/config.ts +++ b/packages/core/src/onebot/config.ts @@ -1,6 +1,5 @@ import fs from 'fs'; import path from 'path'; -import { randomBytes } from 'crypto'; import type { HttpPostEndpoint, HttpServerEndpoint, @@ -42,26 +41,6 @@ export function loadOneBotConfig(uin: string): OneBotConfig { const config = fromJson(merged); let shouldSave = !perUinConfig; - // Auto-generate per-endpoint accessToken if not set. - for (const s of config.httpServers) { - if (!s.accessToken) { - s.accessToken = generateRandomKey(); - shouldSave = true; - } - } - for (const s of config.wsServers) { - if (!s.accessToken) { - s.accessToken = generateRandomKey(); - shouldSave = true; - } - } - for (const c of config.wsClients) { - if (!c.accessToken) { - c.accessToken = generateRandomKey(); - shouldSave = true; - } - } - // Persist normalized endpoints and generated keys. merged.httpServers = config.httpServers.map((s) => { const out: JsonObject = { @@ -276,10 +255,6 @@ function asNumber(value: unknown, fallback = 0): number { return fallback; } -function generateRandomKey(byteLength = 18): string { - return randomBytes(byteLength).toString('hex'); -} - function tryLoadJson(filePath: string): JsonObject | null { if (!fs.existsSync(filePath)) return null; try { diff --git a/packages/core/src/onebot/ws-transport.ts b/packages/core/src/onebot/ws-transport.ts index 5a14f251..a25fadfc 100644 --- a/packages/core/src/onebot/ws-transport.ts +++ b/packages/core/src/onebot/ws-transport.ts @@ -33,18 +33,23 @@ export class WsTransport { private readonly forwardConnections = new Map(); private readonly reverseConnections = new Set(); private readonly reconnectTimers = new Set(); + private readonly reconnectTimersByKey = new Map(); + private readonly activeReverseClientKeys = new Set(); private serverEndpoints: WsServerEndpoint[] = []; private clientEndpoints: WsClientEndpoint[] = []; + private desiredClientKeys = new Set(); private stopped = false; constructor(config: OneBotConfig, context: WsTransportContext) { this.serverEndpoints = [...config.wsServers]; this.clientEndpoints = [...config.wsClients]; + this.desiredClientKeys = new Set(this.clientEndpoints.map(wsClientKey)); this.context = context; } start(): void { this.stopped = false; + this.desiredClientKeys = new Set(this.clientEndpoints.map(wsClientKey)); this.startServers(); this.startReverseClients(); } @@ -54,6 +59,7 @@ export class WsTransport { const nextClients = [...config.wsClients]; const nextServerKeys = new Set(nextServers.map(wsServerKey)); const nextClientKeys = new Set(nextClients.map(wsClientKey)); + this.desiredClientKeys = nextClientKeys; for (const [key, server] of this.servers) { if (!nextServerKeys.has(key)) { @@ -71,6 +77,8 @@ export class WsTransport { for (const conn of [...this.reverseConnections]) { if (!nextClientKeys.has(conn.key)) { + this.clearReconnectTimer(conn.key); + this.activeReverseClientKeys.delete(conn.key); safeClose(conn.socket); this.reverseConnections.delete(conn); log.info('stopped reverse client %s', conn.endpointUrl); @@ -79,7 +87,7 @@ export class WsTransport { for (const endpoint of nextClients) { const key = wsClientKey(endpoint); - if (![...this.reverseConnections].some(conn => conn.key === key)) { + if (!this.activeReverseClientKeys.has(key) && !this.reconnectTimersByKey.has(key)) { this.startClientEndpoint(endpoint); } } @@ -90,12 +98,15 @@ export class WsTransport { stop(): void { this.stopped = true; + this.desiredClientKeys.clear(); this.publishEvent(this.context.buildLifecycleEvent('disable')); for (const timer of this.reconnectTimers) { clearTimeout(timer); } this.reconnectTimers.clear(); + this.reconnectTimersByKey.clear(); + this.activeReverseClientKeys.clear(); for (const [socket] of this.forwardConnections) { safeClose(socket); @@ -186,11 +197,17 @@ export class WsTransport { private startClientEndpoint(endpoint: WsClientEndpoint): void { const role = endpoint.role ?? 'universal'; const reconnectIntervalMs = Math.max(1000, endpoint.reconnectIntervalMs ?? 5000); - this.connectReverseClient(endpoint.url, role, reconnectIntervalMs, endpoint.accessToken ?? '', endpoint.name); + const key = wsClientKey(endpoint); + if (this.activeReverseClientKeys.has(key) || this.reconnectTimersByKey.has(key)) return; + this.connectReverseClient(endpoint.url, role, reconnectIntervalMs, endpoint.accessToken ?? '', endpoint.name, key); } - private connectReverseClient(endpointUrl: string, role: WsRole, reconnectIntervalMs: number, accessToken: string, name?: string): void { - if (this.stopped) return; + private connectReverseClient(endpointUrl: string, role: WsRole, reconnectIntervalMs: number, accessToken: string, name?: string, key?: string): void { + const connKey = key ?? wsClientPartsKey(endpointUrl, role, reconnectIntervalMs, accessToken); + if (this.stopped || !this.desiredClientKeys.has(connKey)) return; + if (this.activeReverseClientKeys.has(connKey)) return; + this.clearReconnectTimer(connKey); + this.activeReverseClientKeys.add(connKey); const headers: Record = { 'User-Agent': 'OneBot', @@ -203,7 +220,7 @@ export class WsTransport { } const socket = new WebSocket(endpointUrl, { headers }); - const conn: ReverseConnection = { socket, role, endpointUrl, reconnectIntervalMs, key: wsClientPartsKey(endpointUrl, role, reconnectIntervalMs, accessToken) }; + const conn: ReverseConnection = { socket, role, endpointUrl, reconnectIntervalMs, key: connKey }; this.reverseConnections.add(conn); socket.on('open', () => { @@ -218,14 +235,20 @@ export class WsTransport { socket.on('close', () => { this.reverseConnections.delete(conn); + this.activeReverseClientKeys.delete(connKey); if (this.stopped) return; + if (!this.desiredClientKeys.has(connKey)) return; + if (this.reconnectTimersByKey.has(connKey)) return; const timer = setTimeout(() => { this.reconnectTimers.delete(timer); - this.connectReverseClient(endpointUrl, role, reconnectIntervalMs, accessToken, name); + this.reconnectTimersByKey.delete(connKey); + if (this.stopped || !this.desiredClientKeys.has(connKey)) return; + this.connectReverseClient(endpointUrl, role, reconnectIntervalMs, accessToken, name, connKey); }, reconnectIntervalMs); timer.unref?.(); this.reconnectTimers.add(timer); + this.reconnectTimersByKey.set(connKey, timer); }); socket.on('error', (error: Error) => { @@ -233,6 +256,14 @@ export class WsTransport { }); } + private clearReconnectTimer(key: string): void { + const timer = this.reconnectTimersByKey.get(key); + if (!timer) return; + clearTimeout(timer); + this.reconnectTimersByKey.delete(key); + this.reconnectTimers.delete(timer); + } + private async handleApiMessage(socket: WebSocket, role: WsRole, raw: Buffer | string): Promise { if (role !== 'api' && role !== 'universal') return; diff --git a/packages/core/src/webui/server.ts b/packages/core/src/webui/server.ts index 891e8137..794b2762 100644 --- a/packages/core/src/webui/server.ts +++ b/packages/core/src/webui/server.ts @@ -440,7 +440,10 @@ export async function initWebUI( const uin = c.req.param('uin'); if (!UIN_REGEX.test(uin)) return c.json({ message: 'invalid uin' }, 400); const config = loadOneBotConfig(uin); - return c.json({ config }); + return c.json({ + ...config, + config, + }); }); app.post('/api/config/:uin', async (c) => { diff --git a/packages/webui/src/App.tsx b/packages/webui/src/App.tsx index 302ddb0f..d28b3770 100644 --- a/packages/webui/src/App.tsx +++ b/packages/webui/src/App.tsx @@ -167,13 +167,14 @@ function AppInner() { const res = await fetchApi(`/api/config/${encodeURIComponent(selectedUin)}`); if (!res.ok) return; const data = await res.json(); + const loaded = data?.config ?? data; if (cancelled) return; setConfig({ - httpServers: data.httpServers || [], - httpPostEndpoints: data.httpPostEndpoints || [], - wsServers: data.wsServers || [], - wsClients: data.wsClients || [], - musicSignUrl: data.musicSignUrl, + httpServers: loaded?.httpServers || [], + httpPostEndpoints: loaded?.httpPostEndpoints || [], + wsServers: loaded?.wsServers || [], + wsClients: loaded?.wsClients || [], + musicSignUrl: loaded?.musicSignUrl, }); } catch (e) { console.error('load-config', e);