refactor: share wire contracts and isolate screen-sharing lifecycle

This commit is contained in:
illusia committed 2026-10-01 09:06:15 +08:00
1 parent 541a216c4d
commit f4cbd61cff
19 files changed
+2179 -1479

No files matched your search

+1 -234
View File
@@ -1,234 +1 @@
/**
* Screen-share signaling for browser peers and native TeamSpeak peers.
*
* Media never passes through this module. The gateway only authenticates the
* connected TeamSpeak session and relays SDP/ICE messages. Browser peers use
* the configured ICE servers only for candidate discovery/negotiation; this
* module never handles the resulting media packets.
*/
export interface ScreenShareIceServer {
urls: string | string[];
username?: string;
credential?: string;
}
/** TeamSpeak's public ICE services are STUN-only, so media remains peer-to-peer. */
export const DEFAULT_SCREEN_SHARE_ICE_SERVERS: readonly ScreenShareIceServer[] = [
{ urls: "stun:turn.teamspeak.com:3478" },
{ urls: "stun:turn2.teamspeak.com:3478" },
];
const SCREEN_SHARE_ICE_URL_PATTERN = /^(?:stun|stuns|turn|turns):/i;
const MAX_ICE_SERVER_COUNT = 8;
const MAX_ICE_URL_LENGTH = 512;
const MAX_ICE_CREDENTIAL_LENGTH = 512;
/**
* Keep ICE configuration server-owned and bounded before exposing it to a
* browser. TURN is accepted only as an explicitly configured external server;
* the WebSpeak gateway is never inserted into this list.
*/
export function normalizeScreenShareIceServers(value?: readonly unknown[]): ScreenShareIceServer[] {
const source: readonly unknown[] = value ?? DEFAULT_SCREEN_SHARE_ICE_SERVERS;
const normalized: ScreenShareIceServer[] = [];
const seen = new Set<string>();
for (const raw of source) {
if (!raw || typeof raw !== "object" || Array.isArray(raw)) continue;
const candidate = raw as Record<string, unknown>;
const rawUrls = candidate.urls;
const urls = (Array.isArray(rawUrls) ? rawUrls : [rawUrls])
.filter((url): url is string => typeof url === "string" && url.trim().length > 0 && url.trim().length <= MAX_ICE_URL_LENGTH)
.map((url) => url.trim())
.filter((url) => SCREEN_SHARE_ICE_URL_PATTERN.test(url));
const uniqueUrls = [...new Set(urls)];
if (!uniqueUrls.length) continue;
const username = typeof candidate.username === "string" && candidate.username.length <= MAX_ICE_CREDENTIAL_LENGTH
? candidate.username
: undefined;
const credential = typeof candidate.credential === "string" && candidate.credential.length <= MAX_ICE_CREDENTIAL_LENGTH
? candidate.credential
: undefined;
const key = JSON.stringify([uniqueUrls, username ?? ""]);
if (seen.has(key)) continue;
seen.add(key);
normalized.push({
urls: uniqueUrls.length === 1 ? uniqueUrls[0] : uniqueUrls,
...(username !== undefined ? { username } : {}),
...(credential !== undefined ? { credential } : {}),
});
if (normalized.length >= MAX_ICE_SERVER_COUNT) break;
}
if (normalized.length) return normalized;
return DEFAULT_SCREEN_SHARE_ICE_SERVERS.map((server) => ({ ...server }));
}
export type ScreenSharePeerSignal =
| {
kind: "offer" | "answer";
sdp: string;
}
| {
kind: "iceCandidate";
candidate: string;
sdpMid?: string | null;
sdpMLineIndex?: number | null;
}
| {
kind: "close";
};
export interface ScreenShareViewerDescription {
peerId: string;
nickname: string;
avatar?: string;
}
export interface ScreenShareStreamDescription {
streamId: string;
source: "browser" | "teamspeak";
ownerPeerId: string;
/** TeamSpeak client id used to match a stream to the member card. */
ownerClientId?: number;
ownerNickname: string;
name: string;
audio: boolean;
createdAt: number;
viewerCount: number;
viewers: ScreenShareViewerDescription[];
}
export type ScreenShareClientMessage =
| {
type: "screenShareList";
}
| {
type: "screenShareStart";
requestId?: string;
name?: string;
audio?: boolean;
}
| {
type: "screenShareStop";
requestId?: string;
streamId: string;
}
| {
type: "screenShareJoin";
requestId?: string;
streamId: string;
}
| {
type: "screenShareLeave";
requestId?: string;
streamId: string;
}
| {
type: "screenShareSignal";
streamId: string;
targetPeerId: string;
signal: ScreenSharePeerSignal;
};
export type ScreenShareMessageParseResult =
| ScreenShareClientMessage
| { error: { code: string; message: string } };
const MAX_STREAM_ID_LENGTH = 128;
const MAX_PEER_ID_LENGTH = 128;
const MAX_NAME_LENGTH = 120;
const MAX_SDP_LENGTH = 256 * 1024;
const MAX_CANDIDATE_LENGTH = 8 * 1024;
export function parseScreenShareMessage(raw: string): ScreenShareMessageParseResult | null {
let value: unknown;
try {
value = JSON.parse(raw);
} catch {
return null;
}
if (!isRecord(value) || typeof value.type !== "string" || !value.type.startsWith("screenShare")) return null;
const requestId = parseRequestId(value.requestId);
if (requestId === false) return invalid("INVALID_SCREEN_SHARE_REQUEST", "屏幕共享请求标识无效");
switch (value.type) {
case "screenShareList":
return { type: "screenShareList" };
case "screenShareStart": {
const name = value.name === undefined ? undefined : parseName(value.name);
if (name === false) return invalid("INVALID_SCREEN_SHARE_NAME", "屏幕共享名称无效");
if (value.audio !== undefined && typeof value.audio !== "boolean") return invalid("INVALID_SCREEN_SHARE_AUDIO", "共享音频选项无效");
return {
type: "screenShareStart",
...(requestId ? { requestId } : {}),
...(name ? { name } : {}),
...(value.audio === true ? { audio: true } : {}),
};
}
case "screenShareStop":
case "screenShareJoin":
case "screenShareLeave": {
const streamId = parseIdentifier(value.streamId, MAX_STREAM_ID_LENGTH);
if (!streamId) return invalid("INVALID_SCREEN_SHARE_STREAM", "屏幕共享标识无效");
return {
type: value.type,
...(requestId ? { requestId } : {}),
streamId,
};
}
case "screenShareSignal": {
const streamId = parseIdentifier(value.streamId, MAX_STREAM_ID_LENGTH);
const targetPeerId = parseIdentifier(value.targetPeerId, MAX_PEER_ID_LENGTH);
const signal = parseSignal(value.signal);
if (!streamId) return invalid("INVALID_SCREEN_SHARE_STREAM", "屏幕共享标识无效");
if (!targetPeerId) return invalid("INVALID_SCREEN_SHARE_PEER", "屏幕共享对端无效");
if (!signal) return invalid("INVALID_SCREEN_SHARE_SIGNAL", "屏幕共享信令无效");
return { type: "screenShareSignal", streamId, targetPeerId, signal };
}
default:
return invalid("UNKNOWN_SCREEN_SHARE_MESSAGE", "不支持的屏幕共享消息");
}
}
function parseSignal(value: unknown): ScreenSharePeerSignal | null {
if (!isRecord(value) || typeof value.kind !== "string") return null;
if (value.kind === "close") return { kind: "close" };
if (value.kind === "offer" || value.kind === "answer") {
if (typeof value.sdp !== "string" || value.sdp.length === 0 || value.sdp.length > MAX_SDP_LENGTH) return null;
return { kind: value.kind, sdp: value.sdp };
}
if (value.kind !== "iceCandidate" || typeof value.candidate !== "string" || value.candidate.length > MAX_CANDIDATE_LENGTH) return null;
if (value.sdpMid !== undefined && value.sdpMid !== null && typeof value.sdpMid !== "string") return null;
const sdpMLineIndex = value.sdpMLineIndex;
if (sdpMLineIndex !== undefined && sdpMLineIndex !== null && (typeof sdpMLineIndex !== "number" || !Number.isInteger(sdpMLineIndex) || sdpMLineIndex < 0 || sdpMLineIndex > 255)) return null;
return {
kind: "iceCandidate",
candidate: value.candidate,
...(value.sdpMid === null || typeof value.sdpMid === "string" ? { sdpMid: value.sdpMid } : {}),
...(sdpMLineIndex === null || typeof sdpMLineIndex === "number" ? { sdpMLineIndex } : {}),
};
}
function parseRequestId(value: unknown): string | undefined | false {
if (value === undefined) return undefined;
return typeof value === "string" && value.length > 0 && value.length <= 64 ? value : false;
}
function parseName(value: unknown): string | false {
if (typeof value !== "string") return false;
const name = value.trim();
return name.length > 0 && name.length <= MAX_NAME_LENGTH ? name : false;
}
function parseIdentifier(value: unknown, maxLength: number): string | null {
if (typeof value !== "string" || value.length === 0 || value.length > maxLength) return null;
return value;
}
function invalid(code: string, message: string): { error: { code: string; message: string } } {
return { error: { code, message } };
}
function isRecord(value: unknown): value is Record<string, unknown> {
return Boolean(value) && typeof value === "object" && !Array.isArray(value);
}
export * from "../shared/screen-share.js";
+19 -32
View File
@@ -1,3 +1,6 @@
import type { ServerMessage } from "../shared/server-messages.js";
import type { ChannelInfo, VoiceAudioBridgeStats } from "../shared/voice-models.js";
import type { ChannelMember as SharedChannelMember, 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";
@@ -104,24 +107,8 @@ export interface AudioFlowStats {
webrtcDownlinkShortFrames: number;
}
interface ChannelMember {
id: number;
nickname: string;
uid: string;
avatar?: string;
away?: boolean;
awayMessage?: string;
inputMuted?: boolean;
outputMuted?: boolean;
channelCommander?: boolean;
}
interface ServerEvent {
id: string;
kind: "joined" | "left" | "moved" | "poke" | "connection";
message: string;
timestamp: number;
}
type ChannelMember = SharedChannelMember & { uid: string };
type ServerEvent = SharedServerEvent & { kind: "joined" | "left" | "moved" | "poke" | "connection" };
interface WebClientEntry {
id: string;
@@ -136,7 +123,7 @@ interface WebClientEntry {
acceleration?: AccelerationRelayOptions;
identityLeaseKey?: string;
webrtcPublicHost?: string;
channelTree: unknown[];
channelTree: ChannelInfo[];
members: Map<number, ChannelMember>;
avatarCache: Map<string, string | null>;
eventLog: ServerEvent[];
@@ -322,7 +309,7 @@ export class VoiceBridge {
let avatarRefreshTimer: ReturnType<typeof setTimeout> | null = null;
let avatarRefreshRunning = false;
const sendJson = (message: Record<string, unknown>) => {
const sendJson = (message: ServerMessage) => {
if (ws.readyState === WebSocket.OPEN) ws.send(JSON.stringify(message));
};
const addServerEvent = (kind: ServerEvent["kind"], message: string) => {
@@ -1013,7 +1000,7 @@ export class VoiceBridge {
private handleScreenShareMessage(
entry: WebClientEntry,
message: ScreenShareClientMessage,
sendJson: (message: Record<string, unknown>) => void,
sendJson: (message: ServerMessage) => void,
): void {
if (message.type === "screenShareList") {
sendJson({ type: "screenShareList", streams: this.listScreenStreamsFor(entry) });
@@ -1179,7 +1166,7 @@ export class VoiceBridge {
});
}
private screenShareViewerCountMessage(stream: ScreenStreamRecord): Record<string, unknown> {
private screenShareViewerCountMessage(stream: ScreenStreamRecord): ServerMessage {
return {
type: "screenShareViewerCount",
streamId: stream.streamId,
@@ -1192,7 +1179,7 @@ export class VoiceBridge {
return stream.viewerEntryIds.size + stream.nativeViewerClids.size;
}
private broadcastScreenMessage(stream: ScreenStreamRecord, message: Record<string, unknown>, excludeEntryId?: string): void {
private broadcastScreenMessage(stream: ScreenStreamRecord, message: ServerMessage, excludeEntryId?: string): void {
for (const candidate of this.entries.values()) {
if (candidate.id === excludeEntryId || candidate.target && teamSpeakTargetKey(candidate.target) !== stream.targetKey) continue;
// A stream is scoped to the source channel. Do not leak its card or
@@ -1209,7 +1196,7 @@ export class VoiceBridge {
}
}
private sendToEntry(entryId: string, message: Record<string, unknown>): void {
private sendToEntry(entryId: string, message: ServerMessage): void {
const candidate = this.entries.get(entryId);
if (candidate?.ws.readyState === WebSocket.OPEN) candidate.ws.send(JSON.stringify(message));
}
@@ -1225,7 +1212,7 @@ export class VoiceBridge {
}
}
if (!this.screenStreams.delete(screenStreamKey(stream.targetKey, stream.streamId))) return;
const message = { type: "screenShareStopped", streamId: stream.streamId, reason };
const message: ServerMessage = { type: "screenShareStopped", streamId: stream.streamId, reason };
this.broadcastScreenMessage(stream, message);
stream.viewerEntryIds.clear();
stream.nativeViewerClids.clear();
@@ -1251,7 +1238,7 @@ export class VoiceBridge {
stream: ScreenStreamRecord,
targetPeerId: string,
signal: ScreenSharePeerSignal,
sendJson: (message: Record<string, unknown>) => void,
sendJson: (message: ServerMessage) => void,
): void {
if (stream.source === "teamspeak") {
if (!stream.viewerEntryIds.has(entry.id) || targetPeerId !== stream.ownerPeerId) {
@@ -1375,7 +1362,7 @@ export class VoiceBridge {
private async joinNativeScreenStream(
entry: WebClientEntry,
stream: ScreenStreamRecord,
sendJson: (message: Record<string, unknown>) => void,
sendJson: (message: ServerMessage) => void,
requestId?: string,
): Promise<void> {
const sourceClientId = stream.sourceClientId;
@@ -1606,7 +1593,7 @@ export class VoiceBridge {
private async handleWebRtcOffer(
entry: WebClientEntry,
offer: WebRtcSessionDescription,
sendJson: (message: Record<string, unknown>) => void,
sendJson: (message: ServerMessage) => void,
): Promise<void> {
if (entry.webrtc) {
const previousWebRtc = entry.webrtc;
@@ -1725,7 +1712,7 @@ function normalizeWebRtcHost(value: string | undefined): string | undefined {
async function handleCommand(
entry: WebClientEntry,
command: ClientCommand,
sendJson: (message: Record<string, unknown>) => void,
sendJson: (message: ServerMessage) => void,
): Promise<void> {
if (command.type === "latencyProbe") {
// Keep the control-path probe for already-open older browser clients. The
@@ -1889,7 +1876,7 @@ function classifyOperationError(error: unknown, fallbackCode: string, fallbackMe
return { code: fallbackCode, message: fallbackMessage };
}
function sendProtocolError(sendJson: (message: Record<string, unknown>) => void, code: string, message: string): void {
function sendProtocolError(sendJson: (message: ServerMessage) => void, code: string, message: string): void {
sendJson({ type: "error", error: { code, message, recoverable: false } });
}
@@ -2055,7 +2042,7 @@ function snapshotAudioStats(entry: WebClientEntry): AudioFlowStats {
return stats;
}
function snapshotAudioStatus(entry: WebClientEntry): Record<string, number | string | null> {
function snapshotAudioStatus(entry: WebClientEntry): VoiceAudioBridgeStats {
const stats = snapshotAudioStats(entry);
return {
transport: entry.webrtc ? "webrtc" : "websocket",
@@ -2082,7 +2069,7 @@ function snapshotAudioStatus(entry: WebClientEntry): Record<string, number | str
};
}
function mapChannelTree(snapshot: TSDirectorySnapshot, avatarCache = new Map<string, string | null>()): unknown[] {
function mapChannelTree(snapshot: TSDirectorySnapshot, avatarCache = new Map<string, string | null>()): ChannelInfo[] {
return snapshot.channels.map((channel) => ({
id: String(channel.id),
parentID: String(channel.parentID),
+1 -92
View File
@@ -1,92 +1 @@
export interface ClientCommand {
type: "switchChannel" | "moveClient" | "sendTextMessage" | "sendServerMessage" | "sendPrivateMessage" | "poke" | "setAway" | "setWhisperTargets" | "setWhisperActive" | "setMicrophoneMuted" | "setAccompanimentActive" | "setMemberVolume" | "latencyProbe" | "audioStatsProbe";
requestId?: string;
payload: Record<string, unknown>;
}
export type ClientCommandResult = ClientCommand | { error: { code: string; message: string } };
export function parseClientCommand(raw: string): ClientCommandResult {
let value: unknown;
try {
value = JSON.parse(raw);
} catch {
return { error: { code: "INVALID_JSON", message: "消息不是有效的 JSON" } };
}
if (!isRecord(value) || typeof value.type !== "string") {
return { error: { code: "INVALID_MESSAGE", message: "消息类型不能为空" } };
}
if (value.requestId !== undefined && (typeof value.requestId !== "string" || value.requestId.length > 64)) {
return { error: { code: "INVALID_REQUEST_ID", message: "请求标识无效" } };
}
const supportedTypes = new Set(["switchChannel", "moveClient", "sendTextMessage", "sendServerMessage", "sendPrivateMessage", "poke", "setAway", "setWhisperTargets", "setWhisperActive", "setMicrophoneMuted", "setAccompanimentActive", "setMemberVolume", "latencyProbe", "audioStatsProbe"]);
if (!supportedTypes.has(value.type)) {
return { error: { code: "UNKNOWN_MESSAGE_TYPE", message: "不支持的消息类型" } };
}
if (!isRecord(value.payload)) {
return { error: { code: "INVALID_PAYLOAD", message: "消息参数无效" } };
}
if (value.type === "switchChannel" && (typeof value.payload.channelId !== "string" || !/^\d{1,20}$/.test(value.payload.channelId))) {
return { error: { code: "INVALID_CHANNEL_ID", message: "频道标识无效" } };
}
if (value.type === "switchChannel" && value.payload.password !== undefined && (typeof value.payload.password !== "string" || value.payload.password.length > 512)) {
return { error: { code: "INVALID_CHANNEL_PASSWORD", message: "频道密码无效" } };
}
if (value.type === "moveClient" && (typeof value.payload.clientId !== "number" || !Number.isInteger(value.payload.clientId) || value.payload.clientId <= 0 || value.payload.clientId > 65535)) {
return { error: { code: "INVALID_CLIENT_ID", message: "成员标识无效" } };
}
if (value.type === "moveClient" && (typeof value.payload.channelId !== "string" || !/^\d{1,20}$/.test(value.payload.channelId))) {
return { error: { code: "INVALID_CHANNEL_ID", message: "频道标识无效" } };
}
if (value.type === "moveClient" && value.payload.password !== undefined && (typeof value.payload.password !== "string" || value.payload.password.length > 512)) {
return { error: { code: "INVALID_CHANNEL_PASSWORD", message: "频道密码无效" } };
}
if (value.type === "sendTextMessage" && (typeof value.payload.message !== "string" || value.payload.message.length > 500)) {
return { error: { code: "INVALID_TEXT_MESSAGE", message: "文字消息无效" } };
}
if ((value.type === "sendServerMessage" || value.type === "sendPrivateMessage") && (typeof value.payload.message !== "string" || value.payload.message.length > 500)) {
return { error: { code: "INVALID_TEXT_MESSAGE", message: "文字消息无效" } };
}
if ((value.type === "sendPrivateMessage" || value.type === "poke") && (typeof value.payload.clientId !== "number" || !Number.isInteger(value.payload.clientId) || value.payload.clientId <= 0 || value.payload.clientId > 65535)) {
return { error: { code: "INVALID_CLIENT_ID", message: "成员标识无效" } };
}
if (value.type === "poke" && (typeof value.payload.message !== "string" || value.payload.message.length > 200)) {
return { error: { code: "INVALID_POKE_MESSAGE", message: "戳一戳消息无效" } };
}
if (value.type === "setAway" && (typeof value.payload.away !== "boolean" || (value.payload.message !== undefined && (typeof value.payload.message !== "string" || value.payload.message.length > 200)))) {
return { error: { code: "INVALID_AWAY_STATUS", message: "离开状态无效" } };
}
if (value.type === "setWhisperTargets") {
const targetIds = value.payload.targetIds;
if (!Array.isArray(targetIds) || targetIds.length > 8 || targetIds.some((clientId) => typeof clientId !== "number" || !Number.isInteger(clientId) || clientId <= 0 || clientId > 65535) || new Set(targetIds).size !== targetIds.length) {
return { error: { code: "INVALID_WHISPER_TARGETS", message: "私语目标无效" } };
}
}
if (value.type === "setWhisperActive" && typeof value.payload.active !== "boolean") {
return { error: { code: "INVALID_WHISPER_STATE", message: "私语状态无效" } };
}
if (value.type === "setMicrophoneMuted" && typeof value.payload.muted !== "boolean") {
return { error: { code: "INVALID_MICROPHONE_STATE", message: "麦克风状态无效" } };
}
if (value.type === "setAccompanimentActive" && typeof value.payload.active !== "boolean") {
return { error: { code: "INVALID_ACCOMPANIMENT_STATE", message: "伴奏状态无效" } };
}
if (value.type === "setMemberVolume" && (typeof value.payload.clientId !== "number" || !Number.isInteger(value.payload.clientId) || value.payload.clientId <= 0 || value.payload.clientId > 65535 || typeof value.payload.volume !== "number" || !Number.isFinite(value.payload.volume) || value.payload.volume < 0 || value.payload.volume > 4)) {
return { error: { code: "INVALID_MEMBER_VOLUME", message: "成员音量无效" } };
}
if (value.type === "audioStatsProbe" && (typeof value.payload.sequence !== "string" || value.payload.sequence.length > 64)) {
return { error: { code: "INVALID_AUDIO_STATS_PROBE", message: "音频状态采样标识无效" } };
}
if (value.type === "latencyProbe" && (typeof value.payload.sequence !== "string" || value.payload.sequence.length > 64)) {
return { error: { code: "INVALID_LATENCY_PROBE", message: "延迟探测标识无效" } };
}
return {
type: value.type as ClientCommand["type"],
...(typeof value.requestId === "string" ? { requestId: value.requestId } : {}),
payload: value.payload,
};
}
function isRecord(value: unknown): value is Record<string, unknown> {
return Boolean(value) && typeof value === "object" && !Array.isArray(value);
}
export * from "../shared/client-commands.js";