Merge pull request #5 from venti1112/main
fix: fix reverse-ws reload/reconnect idempotency, preserve explicit no-token config values, and make WebUI config rendering consistent after refresh
This commit is contained in:
4 files changed
+47
-37
No files matched your search
@@ -1,6 +1,5 @@
|
|||||||
import fs from 'fs';
|
import fs from 'fs';
|
||||||
import path from 'path';
|
import path from 'path';
|
||||||
import { randomBytes } from 'crypto';
|
|
||||||
import type {
|
import type {
|
||||||
HttpPostEndpoint,
|
HttpPostEndpoint,
|
||||||
HttpServerEndpoint,
|
HttpServerEndpoint,
|
||||||
@@ -42,26 +41,6 @@ export function loadOneBotConfig(uin: string): OneBotConfig {
|
|||||||
const config = fromJson(merged);
|
const config = fromJson(merged);
|
||||||
let shouldSave = !perUinConfig;
|
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.
|
// Persist normalized endpoints and generated keys.
|
||||||
merged.httpServers = config.httpServers.map((s) => {
|
merged.httpServers = config.httpServers.map((s) => {
|
||||||
const out: JsonObject = {
|
const out: JsonObject = {
|
||||||
@@ -276,10 +255,6 @@ function asNumber(value: unknown, fallback = 0): number {
|
|||||||
return fallback;
|
return fallback;
|
||||||
}
|
}
|
||||||
|
|
||||||
function generateRandomKey(byteLength = 18): string {
|
|
||||||
return randomBytes(byteLength).toString('hex');
|
|
||||||
}
|
|
||||||
|
|
||||||
function tryLoadJson(filePath: string): JsonObject | null {
|
function tryLoadJson(filePath: string): JsonObject | null {
|
||||||
if (!fs.existsSync(filePath)) return null;
|
if (!fs.existsSync(filePath)) return null;
|
||||||
try {
|
try {
|
||||||
|
|||||||
@@ -33,18 +33,23 @@ export class WsTransport {
|
|||||||
private readonly forwardConnections = new Map<WebSocket, ForwardConnection>();
|
private readonly forwardConnections = new Map<WebSocket, ForwardConnection>();
|
||||||
private readonly reverseConnections = new Set<ReverseConnection>();
|
private readonly reverseConnections = new Set<ReverseConnection>();
|
||||||
private readonly reconnectTimers = new Set<NodeJS.Timeout>();
|
private readonly reconnectTimers = new Set<NodeJS.Timeout>();
|
||||||
|
private readonly reconnectTimersByKey = new Map<string, NodeJS.Timeout>();
|
||||||
|
private readonly activeReverseClientKeys = new Set<string>();
|
||||||
private serverEndpoints: WsServerEndpoint[] = [];
|
private serverEndpoints: WsServerEndpoint[] = [];
|
||||||
private clientEndpoints: WsClientEndpoint[] = [];
|
private clientEndpoints: WsClientEndpoint[] = [];
|
||||||
|
private desiredClientKeys = new Set<string>();
|
||||||
private stopped = false;
|
private stopped = false;
|
||||||
|
|
||||||
constructor(config: OneBotConfig, context: WsTransportContext) {
|
constructor(config: OneBotConfig, context: WsTransportContext) {
|
||||||
this.serverEndpoints = [...config.wsServers];
|
this.serverEndpoints = [...config.wsServers];
|
||||||
this.clientEndpoints = [...config.wsClients];
|
this.clientEndpoints = [...config.wsClients];
|
||||||
|
this.desiredClientKeys = new Set(this.clientEndpoints.map(wsClientKey));
|
||||||
this.context = context;
|
this.context = context;
|
||||||
}
|
}
|
||||||
|
|
||||||
start(): void {
|
start(): void {
|
||||||
this.stopped = false;
|
this.stopped = false;
|
||||||
|
this.desiredClientKeys = new Set(this.clientEndpoints.map(wsClientKey));
|
||||||
this.startServers();
|
this.startServers();
|
||||||
this.startReverseClients();
|
this.startReverseClients();
|
||||||
}
|
}
|
||||||
@@ -54,6 +59,7 @@ export class WsTransport {
|
|||||||
const nextClients = [...config.wsClients];
|
const nextClients = [...config.wsClients];
|
||||||
const nextServerKeys = new Set(nextServers.map(wsServerKey));
|
const nextServerKeys = new Set(nextServers.map(wsServerKey));
|
||||||
const nextClientKeys = new Set(nextClients.map(wsClientKey));
|
const nextClientKeys = new Set(nextClients.map(wsClientKey));
|
||||||
|
this.desiredClientKeys = nextClientKeys;
|
||||||
|
|
||||||
for (const [key, server] of this.servers) {
|
for (const [key, server] of this.servers) {
|
||||||
if (!nextServerKeys.has(key)) {
|
if (!nextServerKeys.has(key)) {
|
||||||
@@ -71,6 +77,8 @@ export class WsTransport {
|
|||||||
|
|
||||||
for (const conn of [...this.reverseConnections]) {
|
for (const conn of [...this.reverseConnections]) {
|
||||||
if (!nextClientKeys.has(conn.key)) {
|
if (!nextClientKeys.has(conn.key)) {
|
||||||
|
this.clearReconnectTimer(conn.key);
|
||||||
|
this.activeReverseClientKeys.delete(conn.key);
|
||||||
safeClose(conn.socket);
|
safeClose(conn.socket);
|
||||||
this.reverseConnections.delete(conn);
|
this.reverseConnections.delete(conn);
|
||||||
log.info('stopped reverse client %s', conn.endpointUrl);
|
log.info('stopped reverse client %s', conn.endpointUrl);
|
||||||
@@ -79,7 +87,7 @@ export class WsTransport {
|
|||||||
|
|
||||||
for (const endpoint of nextClients) {
|
for (const endpoint of nextClients) {
|
||||||
const key = wsClientKey(endpoint);
|
const key = wsClientKey(endpoint);
|
||||||
if (![...this.reverseConnections].some(conn => conn.key === key)) {
|
if (!this.activeReverseClientKeys.has(key) && !this.reconnectTimersByKey.has(key)) {
|
||||||
this.startClientEndpoint(endpoint);
|
this.startClientEndpoint(endpoint);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -90,12 +98,15 @@ export class WsTransport {
|
|||||||
|
|
||||||
stop(): void {
|
stop(): void {
|
||||||
this.stopped = true;
|
this.stopped = true;
|
||||||
|
this.desiredClientKeys.clear();
|
||||||
this.publishEvent(this.context.buildLifecycleEvent('disable'));
|
this.publishEvent(this.context.buildLifecycleEvent('disable'));
|
||||||
|
|
||||||
for (const timer of this.reconnectTimers) {
|
for (const timer of this.reconnectTimers) {
|
||||||
clearTimeout(timer);
|
clearTimeout(timer);
|
||||||
}
|
}
|
||||||
this.reconnectTimers.clear();
|
this.reconnectTimers.clear();
|
||||||
|
this.reconnectTimersByKey.clear();
|
||||||
|
this.activeReverseClientKeys.clear();
|
||||||
|
|
||||||
for (const [socket] of this.forwardConnections) {
|
for (const [socket] of this.forwardConnections) {
|
||||||
safeClose(socket);
|
safeClose(socket);
|
||||||
@@ -186,11 +197,17 @@ export class WsTransport {
|
|||||||
private startClientEndpoint(endpoint: WsClientEndpoint): void {
|
private startClientEndpoint(endpoint: WsClientEndpoint): void {
|
||||||
const role = endpoint.role ?? 'universal';
|
const role = endpoint.role ?? 'universal';
|
||||||
const reconnectIntervalMs = Math.max(1000, endpoint.reconnectIntervalMs ?? 5000);
|
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 {
|
private connectReverseClient(endpointUrl: string, role: WsRole, reconnectIntervalMs: number, accessToken: string, name?: string, key?: string): void {
|
||||||
if (this.stopped) return;
|
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<string, string> = {
|
const headers: Record<string, string> = {
|
||||||
'User-Agent': 'OneBot',
|
'User-Agent': 'OneBot',
|
||||||
@@ -203,7 +220,7 @@ export class WsTransport {
|
|||||||
}
|
}
|
||||||
|
|
||||||
const socket = new WebSocket(endpointUrl, { headers });
|
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);
|
this.reverseConnections.add(conn);
|
||||||
|
|
||||||
socket.on('open', () => {
|
socket.on('open', () => {
|
||||||
@@ -218,14 +235,20 @@ export class WsTransport {
|
|||||||
|
|
||||||
socket.on('close', () => {
|
socket.on('close', () => {
|
||||||
this.reverseConnections.delete(conn);
|
this.reverseConnections.delete(conn);
|
||||||
|
this.activeReverseClientKeys.delete(connKey);
|
||||||
if (this.stopped) return;
|
if (this.stopped) return;
|
||||||
|
if (!this.desiredClientKeys.has(connKey)) return;
|
||||||
|
if (this.reconnectTimersByKey.has(connKey)) return;
|
||||||
|
|
||||||
const timer = setTimeout(() => {
|
const timer = setTimeout(() => {
|
||||||
this.reconnectTimers.delete(timer);
|
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);
|
}, reconnectIntervalMs);
|
||||||
timer.unref?.();
|
timer.unref?.();
|
||||||
this.reconnectTimers.add(timer);
|
this.reconnectTimers.add(timer);
|
||||||
|
this.reconnectTimersByKey.set(connKey, timer);
|
||||||
});
|
});
|
||||||
|
|
||||||
socket.on('error', (error: Error) => {
|
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<void> {
|
private async handleApiMessage(socket: WebSocket, role: WsRole, raw: Buffer | string): Promise<void> {
|
||||||
if (role !== 'api' && role !== 'universal') return;
|
if (role !== 'api' && role !== 'universal') return;
|
||||||
|
|
||||||
|
|||||||
@@ -440,7 +440,10 @@ export async function initWebUI(
|
|||||||
const uin = c.req.param('uin');
|
const uin = c.req.param('uin');
|
||||||
if (!UIN_REGEX.test(uin)) return c.json({ message: 'invalid uin' }, 400);
|
if (!UIN_REGEX.test(uin)) return c.json({ message: 'invalid uin' }, 400);
|
||||||
const config = loadOneBotConfig(uin);
|
const config = loadOneBotConfig(uin);
|
||||||
return c.json({ config });
|
return c.json({
|
||||||
|
...config,
|
||||||
|
config,
|
||||||
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
app.post('/api/config/:uin', async (c) => {
|
app.post('/api/config/:uin', async (c) => {
|
||||||
|
|||||||
@@ -167,13 +167,14 @@ function AppInner() {
|
|||||||
const res = await fetchApi(`/api/config/${encodeURIComponent(selectedUin)}`);
|
const res = await fetchApi(`/api/config/${encodeURIComponent(selectedUin)}`);
|
||||||
if (!res.ok) return;
|
if (!res.ok) return;
|
||||||
const data = await res.json();
|
const data = await res.json();
|
||||||
|
const loaded = data?.config ?? data;
|
||||||
if (cancelled) return;
|
if (cancelled) return;
|
||||||
setConfig({
|
setConfig({
|
||||||
httpServers: data.httpServers || [],
|
httpServers: loaded?.httpServers || [],
|
||||||
httpPostEndpoints: data.httpPostEndpoints || [],
|
httpPostEndpoints: loaded?.httpPostEndpoints || [],
|
||||||
wsServers: data.wsServers || [],
|
wsServers: loaded?.wsServers || [],
|
||||||
wsClients: data.wsClients || [],
|
wsClients: loaded?.wsClients || [],
|
||||||
musicSignUrl: data.musicSignUrl,
|
musicSignUrl: loaded?.musicSignUrl,
|
||||||
});
|
});
|
||||||
} catch (e) {
|
} catch (e) {
|
||||||
console.error('load-config', e);
|
console.error('load-config', e);
|
||||||
|
|||||||
Reference in new issue
Block a user