feat: add plugin application runtime and unified instance authorization

This commit is contained in:
illusia committed 2026-11-03 20:13:01 +08:00
1 parent 8bca848c21
commit 3430a8a753
80 files changed
+2133 -1004

No files matched your search

+19 -9
View File
@@ -19,6 +19,8 @@ import { createVoiceGatewayAuthHeaders, type DelegatedVoiceSession } from "./voi
import type { SkinRegistry } from "../admin/skin-registry.js";
import { resolveVisitorTotal } from "./visitor-count.js";
import type { PluginRegistry } from "../plugins/registry.js";
import { PluginRuntime } from "../plugins/runtime.js";
import { createPluginRuntimeRouter } from "../plugins/runtime-router.js";
export interface WebServerOptions {
port: number;
@@ -30,6 +32,7 @@ export interface WebServerOptions {
adminService: AdminService;
skinRegistry?: SkinRegistry;
pluginRegistry?: PluginRegistry;
pluginRuntime?: { port?: number; host?: string; publicOrigin?: string; maxWorkers?: number };
logger: Logger;
nextVisitorNumber?: () => number;
visitorCount?: () => number;
@@ -57,10 +60,13 @@ export function createWebServer(options: WebServerOptions): WebServer {
server = createHttpServer(app);
}
app.use("/api/admin/plugins/upload", express.json({ limit: "600kb" }));
app.use(express.json({ limit: "100kb" }));
const json = express.json({ limit: "100kb" });
app.use((request, response, next) => request.path.startsWith("/api/admin/plugins") ? next() : json(request, response, next));
const voiceBridge = new VoiceBridge({ ...options.voiceBridgeOptions, pluginRegistry: options.pluginRegistry }, logger);
const voiceBridge = new VoiceBridge({ ...options.voiceBridgeOptions, pluginRuntimeEnabled: !!options.pluginRegistry }, logger);
const pluginRuntime = options.pluginRegistry ? new PluginRuntime({ registry: options.pluginRegistry, participant: token => voiceBridge.resolvePluginParticipant(token), logger,
...options.pluginRuntime, ...(options.certDir ? { tls: { cert: readFileSync(path.join(options.certDir,"cert.pem")), key: readFileSync(path.join(options.certDir,"key.pem")) } } : {}) }) : undefined;
app.use("/api/plugins", createPluginRuntimeRouter(pluginRuntime));
const adminSessions = new AdminSessionStore();
const joinRateLimiter = new JoinRateLimiter();
const startedAt = Date.now();
@@ -277,6 +283,7 @@ export function createWebServer(options: WebServerOptions): WebServer {
terminateSession: (id) => voiceBridge.terminateSession(id),
skinRegistry: options.skinRegistry,
pluginRegistry: options.pluginRegistry,
pluginRuntime,
version: options.version,
logFile: options.logFile,
startedAt,
@@ -293,15 +300,18 @@ export function createWebServer(options: WebServerOptions): WebServer {
voiceBridge.attach(server);
return {
start(): Promise<void> {
return new Promise((resolve) => {
server.listen(options.port, () => {
logger.info({ port: options.port }, "Web server started");
resolve();
});
async start(): Promise<void> {
await new Promise<void>((resolve, reject) => {
server.once("error", reject);
server.listen(options.port, () => { server.off("error", reject); logger.info({ port: options.port }, "Web server started"); resolve(); });
});
if (pluginRuntime) {
try { await pluginRuntime.start(); }
catch { logger.warn({code:"PLUGIN_RUNTIME_UNAVAILABLE"},"Plugin application origin could not start; voice and administration remain available"); }
}
},
async stop(): Promise<void> {
await pluginRuntime?.close();
await voiceBridge.shutdown();
adminSessions.clear();
return new Promise((resolve) => {
+24 -2
View File
@@ -2,7 +2,7 @@ import assert from "node:assert/strict";
import { EventEmitter } from "node:events";
import { setImmediate as nextTurn } from "node:timers/promises";
import test from "node:test";
import { asChannelGroupID, asChannelID, asClientID, asUID, avatarFileName, type Channel, type ClientEntry } from "@honeybbq/teamspeak";
import { asChannelGroupID, asChannelID, asClientID, asClientDBID, asUID, avatarFileName, type Channel, type ClientEntry } from "@honeybbq/teamspeak";
import { Client, generateIdentitySync, type ServerView } from "@honeybbq/teamspeak/client";
import { TeamSpeakSdkClient, type DirectorySnapshot } from "./teamspeak-sdk.js";
@@ -13,7 +13,7 @@ function channel(id = 1): Channel {
description: "", hasPassword: true, isPermanent: true, maxClients: 12, isMaxClientsUnlimited: false } as Channel;
}
function member(id = 1): ClientEntry {
return { id: asClientID(id), nickname: `Member ${id}`, uid: asUID(uid), channelID: asChannelID(1n), type: 0,
return { id: asClientID(id), databaseID: asClientDBID(BigInt(id)), nickname: `Member ${id}`, uid: asUID(uid), channelID: asChannelID(1n), type: 0,
serverGroups: [], isAway: true, awayMessage: "Away", isInputMuted: true, isOutputMuted: false,
isChannelCommander: true, avatar: "avatar-hash", isRecording: false, isTalker: false,
channelGroupID: asChannelGroupID(0n), createdAt: undefined, lastConnectedAt: undefined, idleTimeMs: undefined };
@@ -53,6 +53,28 @@ test("ordinary-client directories and avatar metadata use the live view without
assert.deepEqual(native.queries, []);
});
test('partial SDK records preserve unknown status and channel descriptions without querying', async () => {
const { sdk, native } = fixture();
const { uid: _uid, serverGroups: _groups, isAway: _away, awayMessage: _message,
isInputMuted: _input, isOutputMuted: _output, isChannelCommander: _commander, ...partial } = member();
native.view.clients.set(partial.id, partial);
const { description: _description, ...room } = channel(); native.view.channels.set(room.id, room);
assert.deepEqual(await sdk.listDirectoryClients(), [{ id: 1, nickname: 'Member 1', uid: '', serverGroups: [], channelID: 1n, type: 0 }]);
assert.equal((await sdk.listDirectoryChannels())[0].description, undefined);
assert.equal(await sdk.getClientAvatarMetadata(1), null);
assert.deepEqual(native.queries, []);
});
test('SDK end-of-speech markers are not sent into the audio decoder or browser transport', () => {
const { sdk, native } = fixture(), received: unknown[] = [];
sdk.on('voiceData', frame => received.push(frame));
native.emit('voiceData', { clientID: asClientID(1), codec: 4, data: new Uint8Array() });
assert.deepEqual(received, []);
const data = Uint8Array.of(1, 2);
native.emit('voiceData', { clientID: asClientID(1), codec: 4, data });
assert.deepEqual(received, [{ clientId: 1, codec: 4, data }]);
});
test("live-view snapshots include channel edits and remove clients that went out of view", () => {
const { sdk, native } = fixture();
const snapshots: DirectorySnapshot[] = [];
+5 -4
View File
@@ -46,7 +46,7 @@ export interface DirectoryChannelInfo {
parentID: bigint;
order: bigint;
name: string;
description: string;
description?: string;
passwordProtected?: boolean;
isPermanent?: boolean;
maxClients?: number;
@@ -230,7 +230,8 @@ export class TeamSpeakSdkClient extends EventEmitter implements CommandExecutor
client.on("viewReady", () => this.publishDirectory(client));
client.on("viewChanged", () => this.publishDirectory(client));
client.on("voiceData", (event) => {
if (!isCurrent()) return;
// beta.20+ reports an empty payload for end-of-speech, not an Opus frame.
if (!isCurrent() || event.data.byteLength === 0) return;
this.emit("voiceData", { clientId: Number(event.clientID), codec: event.codec, data: event.data } satisfies VoiceData);
});
client.on("textMessage", (event) => {
@@ -328,8 +329,8 @@ function toDirectoryClient(entry: ClientEntry): DirectoryClientInfo {
return {
id: Number(entry.id),
nickname: entry.nickname,
uid: entry.uid,
serverGroups: entry.serverGroups.map(String),
uid: entry.uid ?? "",
serverGroups: (entry.serverGroups ?? []).map(String),
channelID: BigInt(entry.channelID),
type: entry.type,
...(entry.isAway !== undefined ? { away: entry.isAway } : {}),
+21 -23
View File
@@ -10,7 +10,7 @@ import { resolveVoiceMediaAddresses } from "./webrtc-config.js";
import type { ServerEvent as SharedServerEvent } from "../shared/voice-models.js";
import { WebSocketServer, WebSocket } from "ws";
import type { IncomingMessage, Server } from "node:http";
import { randomUUID } from "node:crypto";
import { randomUUID, randomBytes } from "node:crypto";
import { BlockList, isIP } from "node:net";
import { parseIdentity } from "@honeybbq/teamspeak/client";
import { TSClient, type TSClientOptions } from "./ts-client.js";
@@ -27,8 +27,7 @@ import type { AccelerationRelayOptions, ConfiguredAccelerationRelay } from "./ac
import { normalizeScreenShareIceServers, parseScreenShareMessage, type ScreenShareIceServer } from "./screen-share.js";
import { OpusEncoder } from "./opus-codec.js";
import { avatarDataUrl } from "./directory-view.js";
import { PluginCoordinator } from "../plugins/coordinator.js";
import type { PluginRegistry } from "../plugins/registry.js";
import type { PluginParticipant } from "../shared/plugins.js";
const HEARTBEAT_INTERVAL_MS = 30_000;
const MAX_MISSED_HEARTBEATS = 2;
@@ -51,7 +50,7 @@ function publicFailureDetail(error: ReturnType<typeof normalizeTeamSpeakError>):
}
export interface VoiceBridgeOptions {
pluginRegistry?: PluginRegistry;
pluginRuntimeEnabled?: boolean;
joinTickets: JoinTicketStore;
webRtc?: WebRtcAudioOptions | (() => WebRtcAudioOptions);
screenShareIceServers?: ScreenShareIceServer[] | (() => ScreenShareIceServer[]);
@@ -110,13 +109,13 @@ interface WebClientEntry extends SessionDirectoryState {
lastAudioStatsProbeAt: number;
connectionFailureCode?: string;
screenPeerId: string;
pluginSession?: string;
}
export class VoiceBridge {
private readonly sessionManager = new SessionManager();
private readonly entries = new Map<string, WebClientEntry>();
private readonly screenShares: ScreenShareCoordinator;
private readonly plugins: PluginCoordinator;
private readonly identityLeases = new IdentityLeaseStore();
private wss: WebSocketServer | null = null;
private heartbeatTimer: ReturnType<typeof setInterval> | null = null;
@@ -131,14 +130,6 @@ export class VoiceBridge {
) {
this.logger = logger.child({ component: "voice-bridge" });
this.trustedProxies = createTrustedProxies(options.trustedProxies);
this.plugins = new PluginCoordinator(options.pluginRegistry, this.entries, (id, message) => {
const ws = this.entries.get(id)?.ws;
// Optional plugin traffic must not build an unbounded queue on the voice socket.
// A slow participant can request a fresh snapshot or reopen after draining.
if (ws?.readyState === WebSocket.OPEN && ws.bufferedAmount <= 512 * 1024) {
try { ws.send(JSON.stringify(message)); } catch { /* retired socket */ }
}
});
this.screenShares = new ScreenShareCoordinator(this.entries, (entryId, message) => {
const entry = this.entries.get(entryId);
if (entry?.ws.readyState === WebSocket.OPEN) {
@@ -331,6 +322,7 @@ export class VoiceBridge {
}, "Web client connected to TeamSpeak");
}
session.transition("connected");
if (this.options.pluginRuntimeEnabled) entry!.pluginSession = randomBytes(32).toString("base64url");
sendJson({
type: "connected",
tsClientId: events.selfId,
@@ -342,6 +334,7 @@ export class VoiceBridge {
webRtcStunServer: this.getWebRtcOptions()?.stunServer ?? "",
screenShareIceServers: this.getScreenShareIceServers(),
accelerated: Boolean(entry!.acceleration),
...(entry!.pluginSession ? { pluginSession: entry!.pluginSession } : {}),
...(entry!.rememberIdentity ? { identity: tsClient.getIdentityString() } : {}),
});
sendJson({ type: "channelList", channels: entry!.channelTree });
@@ -506,7 +499,6 @@ export class VoiceBridge {
},
onClientMove: (id, channelId) => {
this.screenShares.onClientMove(entry!, id, channelId);
if (id === entry!.tsClient.getClientId()) queueMicrotask(() => this.plugins.reconcile(entry!));
},
onNotification: notification => this.screenShares.handleNotification(entry!, notification),
onVoice: data => entry!.audioTransport?.receiveTeamSpeak(data),
@@ -559,7 +551,6 @@ export class VoiceBridge {
}
if (session.state !== "connected") return;
this.screenShares.removePeer(entryId);
this.plugins.remove(entryId);
resetDirectoryForReconnect();
sendJson({ type: "disconnected", recoverable: isRecoverable(normalized) });
scheduleReconnect(normalized);
@@ -581,12 +572,6 @@ export class VoiceBridge {
}
const rawMessage = typeof data === "string" ? data : data.toString("utf-8");
try {
const value: unknown = JSON.parse(rawMessage);
if (value && typeof value === "object" && "type" in value && value.type === "pluginRequest") {
this.plugins.reconcile(entry!); this.plugins.handle(entry!, value); return;
}
} catch { /* Existing command parser owns malformed messages. */ }
const webRtcMessage = parseWebRtcClientMessage(rawMessage);
if (webRtcMessage?.type === "webrtcOffer") {
if (this.getWebRtcOptions()?.enabled !== true) {
@@ -670,7 +655,6 @@ export class VoiceBridge {
}
async shutdown(): Promise<void> {
this.plugins.dispose();
if (this.heartbeatTimer) {
clearInterval(this.heartbeatTimer);
this.heartbeatTimer = null;
@@ -723,6 +707,21 @@ export class VoiceBridge {
});
}
resolvePluginParticipant(token: string): PluginParticipant | null {
if (!/^[A-Za-z0-9_-]{43}$/.test(token)) return null;
for (const entry of this.entries.values()) {
if (entry.pluginSession !== token || entry.session.state !== "connected" || entry.ws.readyState !== WebSocket.OPEN) continue;
try {
const selfId = entry.tsClient.getClientId(), channelId = entry.tsClient.getChannelId().toString();
const uid = entry.members.get(selfId)?.uid;
const members = entry.channelTree.find(channel => channel.id === channelId)?.members ?? [];
return { id: entry.id, nickname: entry.nickname, ...(uid ? { uid } : {}), target: teamSpeakTargetKey(entry.target), channelId,
members: members.map(member => ({ id: member.id, nickname: member.nickname, ...(member.uid ? { uid: member.uid } : {}) })) };
} catch { return null; }
}
return null;
}
async terminateSession(entryId: string): Promise<boolean> {
if (!this.entries.has(entryId)) return false;
await this.sessionManager.teardown(entryId, "admin-terminated");
@@ -735,7 +734,6 @@ export class VoiceBridge {
private async cleanupEntry(entry: WebClientEntry, reason: SessionTeardownReason): Promise<void> {
this.screenShares.removePeer(entry.id);
this.plugins.remove(entry.id);
if (this.entries.get(entry.id) === entry) this.entries.delete(entry.id);
entry.events?.close();
entry.events = null;