fix: consolidate audited dev updates

This commit is contained in:
illusia committed 2026-10-08 10:32:59 +08:00
1 parent 568b8fd8be
commit 0a552f7ee8
58 files changed
+1930 -132

No files matched your search

+26
View File
@@ -42,6 +42,32 @@ test("a stale partial snapshot cannot bring back a departed client before an exp
assert.deepEqual(directory.getSnapshot()?.clients.find((client) => client.id === 2), member(2, 2n, { uid: "new-uid" }));
});
test("a status refresh enriches current clients without adding clients or restoring departures", () => {
const directory = new DirectorySynchronizer();
directory.applySnapshot(snapshot(member(1), member(2)));
directory.applyClientLeave(2);
directory.applyClientListSnapshot([
member(1, 1n, { away: true, inputMuted: true, outputMuted: false }),
member(2, 1n, { away: false, inputMuted: false }),
member(3, 1n, { inputMuted: true }),
]);
assert.deepEqual(directory.getSnapshot()?.clients, [
member(1, 1n, { away: true, inputMuted: true, outputMuted: false }),
]);
});
test("a status snapshot received before the welcome directory is merged after queued enter and leave events", () => {
const directory = new DirectorySynchronizer();
directory.applyClientEnter(member(3));
directory.applyClientLeave(2);
directory.applyClientListSnapshot([member(2, 1n, { inputMuted: true }), member(3, 1n, { inputMuted: true })]);
directory.applySnapshot(snapshot(member(1), member(2)));
assert.deepEqual(directory.getSnapshot()?.clients, [
member(1),
member(3, 1n, { inputMuted: true }),
]);
});
test("clearing the directory drops pending events and departure history for a new connection", () => {
const directory = new DirectorySynchronizer();
directory.applyClientLeave(1);
+15 -1
View File
@@ -5,7 +5,8 @@ type DirectoryDelta =
| { type: "clientEnter"; info: ClientInfo }
| { type: "clientLeave"; id: number }
| { type: "clientMoved"; id: number; channelID: bigint }
| { type: "clientUpdated"; info: DirectoryClientInfo };
| { type: "clientUpdated"; info: DirectoryClientInfo }
| { type: "clientListSnapshot"; clients: DirectoryClientInfo[] };
/**
* Merges staged welcome snapshots with events received while the snapshot is
@@ -52,6 +53,10 @@ export class DirectorySynchronizer {
this.applyOrQueue({ type: "clientUpdated", info });
}
applyClientListSnapshot(clients: DirectoryClientInfo[]): void {
this.applyOrQueue({ type: "clientListSnapshot", clients });
}
getSnapshot(): TSDirectorySnapshot | null {
if (!this.snapshot) return null;
return {
@@ -92,6 +97,15 @@ export class DirectorySynchronizer {
this.clients.set(delta.info.id, current ? { ...current, ...delta.info } : delta.info);
return;
}
if (delta.type === "clientListSnapshot") {
for (const info of delta.clients) {
const current = this.clients.get(info.id);
// A refresh enriches known members; it must not resurrect someone who
// left while the asynchronous list request was in flight.
if (current && !this.departedClientIds.has(info.id)) this.clients.set(info.id, { ...current, ...info });
}
return;
}
const current = this.clients.get(delta.id);
if (current) this.clients.set(delta.id, { ...current, channelID: delta.channelID });
}
+143
View File
@@ -130,6 +130,149 @@ test("native discovery runs again when the last session on a target has left", a
assert.ok(f.commands.some(({ from, command }) => from === second.id && command === "requeststreaminfo clid=2"));
});
test("a later session rediscovers a previously queried source and announces it only once", async () => {
const f = fixture();
const first = f.participant("first", 1);
first.members = new Map([[17, {}]]);
first.channelTree[0]!.members!.push({ id: 17, nickname: "Native" });
await f.coordinator.discoverExistingStreams(first);
const later = f.participant("later", 2);
later.members = first.members;
later.channelTree = first.channelTree;
let queries = 0;
later.tsClient.sendProtocolCommand = async command => {
assert.equal(command, "requeststreaminfo clid=17");
queries++;
f.coordinator.handleNotification(later, { name: "notifystreaminfo", params: { id: "native", clid: "17" } });
};
await f.coordinator.discoverExistingStreams(later);
await f.coordinator.discoverExistingStreams(later);
assert.equal(queries, 2);
assert.equal(f.list(later)[0]?.streamId, "native");
assert.equal(f.messages.filter(({ to, message }) => to === later.id && message.type === "screenShareStarted").length, 1);
});
test("overlapping discovery uses one trailing pass with the latest directory and does not block another server", async () => {
const f = fixture();
const first = f.participant("first", 1);
first.members = new Map([[17, {}]]);
let release!: () => void;
const blocked = new Promise<void>(resolve => { release = resolve; });
let firstQueries = 0;
first.tsClient.sendProtocolCommand = async () => { firstQueries++; await blocked; };
const running = f.coordinator.discoverExistingStreams(first);
await nextTurn();
const second = f.participant("second", 2);
const latest = f.participant("latest", 3);
latest.members = new Map([[17, {}], [18, {}]]);
const pending = f.coordinator.discoverExistingStreams(second);
const coalesced = f.coordinator.discoverExistingStreams(latest);
const other = f.participant("other", 4, 1n, "second.example");
await f.coordinator.discoverExistingStreams(other);
assert.deepEqual(f.commands, [{ from: "other", command: "requeststreaminfo clid=4" }]);
release();
await Promise.all([running, pending, coalesced]);
assert.equal(firstQueries, 1);
assert.deepEqual(f.commands.slice(1), [
{ from: "latest", command: "requeststreaminfo clid=17" },
{ from: "latest", command: "requeststreaminfo clid=18" },
]);
});
test("discovery abandons a removed connection and falls back when its queued session also leaves", async () => {
const f = fixture();
const first = f.participant("first", 1);
first.members = new Map([[17, {}], [18, {}]]);
let release!: () => void;
let firstQueries = 0;
first.tsClient.sendProtocolCommand = async () => {
firstQueries++;
await new Promise<void>(resolve => { release = resolve; });
};
const running = f.coordinator.discoverExistingStreams(first);
await nextTurn();
const leaving = f.participant("leaving", 2);
const pending = f.coordinator.discoverExistingStreams(leaving);
f.participant("other-server", 3, 1n, "second.example");
const survivor = f.participant("survivor", 4);
survivor.members = first.members;
f.entries.delete(first.id);
f.entries.delete(leaving.id);
release();
await Promise.all([running, pending]);
assert.equal(firstQueries, 1);
assert.deepEqual(f.commands, [
{ from: "survivor", command: "requeststreaminfo clid=17" },
{ from: "survivor", command: "requeststreaminfo clid=18" },
]);
});
test("a failed native query does not suppress later clients or future discovery passes", async () => {
const f = fixture();
const entry = f.participant("viewer", 1);
entry.members = new Map([[17, {}], [18, {}]]);
const queries: string[] = [];
entry.tsClient.sendProtocolCommand = async command => {
queries.push(command);
if (queries.length === 1) throw new Error("query failed");
};
await f.coordinator.discoverExistingStreams(entry);
await f.coordinator.discoverExistingStreams(entry);
assert.deepEqual(queries, [17, 18, 17, 18].map(id => `requeststreaminfo clid=${id}`));
});
test("native lookup can use a connected directory on the same server when the observer lacks the source", () => {
const f = fixture();
const collision = f.participant("collision", 3, 99n, "second.example");
collision.channelTree[0]!.members!.push({ id: 17, nickname: "Collision" });
const offline = f.participant("offline", 4, 88n);
offline.channelTree[0]!.members!.push({ id: 17, nickname: "Stale" });
offline.tsClient.isConnected = () => false;
const observer = f.participant("observer", 1);
const viewer = f.participant("viewer", 2, 2n);
viewer.channelTree[0]!.members!.push({ id: 17, nickname: "Native" });
f.coordinator.handleNotification(observer, { name: "notifystreaminfo", params: { id: "native", clid: "17" } });
assert.deepEqual(f.messages.filter(({ message }) => message.type === "screenShareStarted").map(({ to }) => to), [viewer.id]);
assert.equal(f.list(observer).length, 0);
assert.equal(f.list(viewer)[0]?.streamId, "native");
});
test("an unknown native source never inherits the observer's channel", () => {
const f = fixture();
const viewer = f.participant("viewer", 1);
const collision = f.participant("collision", 2, 1n, "second.example");
collision.channelTree[0]!.members!.push({ id: 17, nickname: "Other source" });
f.coordinator.handleNotification(viewer, { name: "notifystreaminfo", params: { id: "native", clid: "17" } });
assert.equal(f.list(viewer).length, 0);
});
test("channel correction retires old viewers before announcing the native stream in its current channel", async () => {
const f = fixture();
const oldViewer = f.participant("old-viewer", 1);
oldViewer.channelTree[0]!.members!.push({ id: 17, nickname: "Native" });
const newViewer = f.participant("new-viewer", 2, 2n);
f.coordinator.handleNotification(oldViewer, { name: "notifystreaminfo", params: { id: "native", clid: "17" } });
f.handle(oldViewer, { type: "screenShareJoin", streamId: "native" });
assert.equal(f.list(oldViewer)[0]?.viewerCount, 1);
await nextTurn();
f.messages.length = 0;
// A fresh directory corrects the source channel without a clientMoved event.
// The observer must take precedence over the first session's stale snapshot.
newViewer.channelTree[0]!.members!.push({ id: 17, nickname: "Native" });
f.coordinator.handleNotification(newViewer, { name: "notifystreaminfo", params: { id: "native", clid: "17" } });
const stopped = f.messages.findIndex(({ to, message }) => to === oldViewer.id && message.type === "screenShareStopped");
const started = f.messages.findIndex(({ to, message }) => to === newViewer.id && message.type === "screenShareStarted");
assert.ok(stopped >= 0 && started > stopped);
assert.ok(f.commands.some(({ from, command }) => from === oldViewer.id && command === "removeclientfromstream id=native clid=1 reason=1"));
assert.equal(f.list(oldViewer).length, 0);
assert.equal(f.list(newViewer)[0]?.viewerCount, 0);
f.messages.length = 0;
f.coordinator.handleNotification(oldViewer, { name: "notifyrespondjoinstreamrequest", params: { id: "native", offer: "late-offer" } });
assert.equal(f.messages.some(({ message }) => message.type === "screenShareSignal"), false);
f.handle(newViewer, { type: "screenShareJoin", streamId: "native" });
assert.equal(f.list(newViewer)[0]?.viewerCount, 1);
});
test("owner removal is idempotent and clears the stream from remaining viewers", async () => {
const f = fixture();
const owner = f.participant("owner", 1);
+61 -25
View File
@@ -39,7 +39,10 @@ function screenStreamKey(targetKey: string, streamId: string): string {
/** Coordinates channel-scoped browser/native sharing; media stays peer-to-peer. */
export class ScreenShareCoordinator {
private readonly screenStreams = new Map<string, ScreenStreamRecord>();
private readonly discoveredClients = new Map<string, Set<number>>();
private readonly discoveries = new Map<string, {
pendingEntry: ScreenShareParticipant | undefined;
completion: Promise<void>;
}>();
constructor(
private readonly entries: ReadonlyMap<string, ScreenShareParticipant>,
@@ -164,29 +167,49 @@ export class ScreenShareCoordinator {
* A gateway session can connect after a native TeamSpeak stream has already
* started. TS6 does not replay that stream in the normal welcome snapshot;
* requeststreaminfo is the official client-protocol query for this case.
* Query each visible client once per TeamSpeak target, then let the normal
* raw notification path announce the discovered stream to web viewers.
* Rescan on each connection. Concurrent requests for the same server share
* one running pass and one pending pass using the latest session directory.
*/
async discoverExistingStreams(entry: ScreenShareParticipant): Promise<void> {
discoverExistingStreams(entry: ScreenShareParticipant): Promise<void> {
const targetKey = teamSpeakTargetKey(entry.target);
let discovered = this.discoveredClients.get(targetKey);
if (!discovered) this.discoveredClients.set(targetKey, discovered = new Set());
const clientIds = [...entry.members.keys()].filter((clientId) => Number.isInteger(clientId) && clientId > 0);
for (const clientId of clientIds) {
if (this.entries.get(entry.id) !== entry || !entry.tsClient.isConnected()) return;
if (discovered.has(clientId)) continue;
discovered.add(clientId);
try {
await entry.tsClient.sendProtocolCommand(`requeststreaminfo clid=${clientId}`);
} catch (error: unknown) {
discovered.delete(clientId);
this.logger.debug({
target: formatTeamSpeakTarget(entry.target),
clientId,
err: error instanceof Error ? error.message : String(error),
}, "Could not query existing TeamSpeak screen stream");
}
const active = this.discoveries.get(targetKey);
if (active) {
active.pendingEntry = entry;
return active.completion;
}
const discovery = {
pendingEntry: entry as ScreenShareParticipant | undefined,
completion: Promise.resolve(),
};
discovery.completion = Promise.resolve().then(async () => {
try {
while (discovery.pendingEntry) {
const requestedEntry = discovery.pendingEntry;
discovery.pendingEntry = undefined;
const queryEntry = this.entries.get(requestedEntry.id) === requestedEntry && requestedEntry.tsClient.isConnected()
? requestedEntry
: [...this.entries.values()].find(candidate => teamSpeakTargetKey(candidate.target) === targetKey && candidate.tsClient.isConnected());
if (!queryEntry) continue;
const clientIds = [...queryEntry.members.keys()].filter(clientId => Number.isInteger(clientId) && clientId > 0);
for (const clientId of clientIds) {
if (this.entries.get(queryEntry.id) !== queryEntry || !queryEntry.tsClient.isConnected()) break;
try {
await queryEntry.tsClient.sendProtocolCommand(`requeststreaminfo clid=${clientId}`);
} catch (error: unknown) {
this.logger.debug({
target: formatTeamSpeakTarget(queryEntry.target),
clientId,
err: error instanceof Error ? error.message : String(error),
}, "Could not query existing TeamSpeak screen stream");
}
}
}
} finally {
this.discoveries.delete(targetKey);
}
});
this.discoveries.set(targetKey, discovery);
return discovery.completion;
}
private describeScreenStream(stream: ScreenStreamRecord): ScreenShareStreamDescription {
@@ -466,7 +489,6 @@ export class ScreenShareCoordinator {
if (!departing) return;
const targetKey = teamSpeakTargetKey(departing.target);
if (![...this.entries.values()].some(entry => entry.id !== entryId && teamSpeakTargetKey(entry.target) === targetKey)) {
this.discoveredClients.delete(targetKey);
// Native notifications are not observed while no session is attached.
// Rediscover on the next connection instead of retaining stale cards.
for (const stream of [...this.screenStreams.values()]) {
@@ -502,7 +524,6 @@ export class ScreenShareCoordinator {
onClientLeave(entry: ScreenShareParticipant, clientId: number): void {
const targetKey = teamSpeakTargetKey(entry.target);
this.discoveredClients.get(targetKey)?.delete(clientId);
for (const stream of [...this.screenStreams.values()]) {
if (stream.targetKey === targetKey && stream.source === "teamspeak" && stream.sourceClientId === clientId) {
this.stopScreenStream(stream, "source-left");
@@ -558,12 +579,27 @@ export class ScreenShareCoordinator {
void publisherEntry.tsClient.sendProtocolCommand(buildTeamSpeakCommand("stopstream", { id: streamId, reason: "1" })).catch(() => undefined);
return;
}
const sourceChannel = entry.channelTree.find(channel => channel.members?.some(member => member.id === sourceClientId));
// Prefer the observer's directory; another connection can still be
// processing an older snapshot of the same source.
const sourceChannel = [entry, ...this.entries.values()]
.filter(candidate => teamSpeakTargetKey(candidate.target) === targetKey && candidate.tsClient.isConnected())
.map(candidate => candidate.channelTree.find(channel => channel.id !== "0" && channel.members?.some(member => member.id === sourceClientId)))
.find(channel => channel !== undefined);
// Do not guess a channel from the observer, or from a colliding client id
// on another server. Discovery will retry after the directory is ready.
if (!sourceChannel) return;
const key = screenStreamKey(targetKey, streamId);
const current = this.screenStreams.get(key);
let current = this.screenStreams.get(key);
if (current && current.channelId !== BigInt(sourceChannel.id)) {
// Retire the old channel's card and memberships before announcing the
// corrected source. Never carry viewers across a channel boundary.
for (const viewerId of current.viewerEntryIds.keys()) {
const viewer = this.entries.get(viewerId);
if (viewer) this.leaveScreenStream(viewer, current);
}
this.stopScreenStream(current, "source-moved-channel");
current = undefined;
}
const stream: ScreenStreamRecord = current ?? {
streamId,
source: "teamspeak",
+17 -1
View File
@@ -22,6 +22,7 @@ interface SdkEvents {
clientLeave: { id: number };
clientMoved: { id: number; targetChannelID?: bigint };
clientUpdated: TSDirectoryClient;
directoryClientsSnapshot: TSDirectoryClient[];
rawNotification: TSRawNotification;
voiceData: TSVoiceData;
textMessage: TSChatMessage;
@@ -32,7 +33,7 @@ interface SdkEvents {
export interface SessionEventOptions {
state: SessionDirectoryState;
client: Pick<TSClient, "getClientId" | "getChannelId" | "getClientAvatar"> & Pick<EventEmitter, "on" | "off">;
client: Pick<TSClient, "getClientId" | "getChannelId" | "getClientAvatar"> & Partial<Pick<TSClient, "refreshDirectoryClients">> & Pick<EventEmitter, "on" | "off">;
nickname: string;
requestedChannel?: string;
isCurrent(): boolean;
@@ -59,6 +60,7 @@ export class SessionEventCoordinator {
private closed = false;
private clientId = 0;
private channelId = 0n;
private directoryStatusRefreshTimer: ReturnType<typeof setTimeout> | null = null;
constructor(private readonly options: SessionEventOptions) {
const { state, client } = options;
@@ -88,6 +90,11 @@ export class SessionEventCoordinator {
const wasKnown = state.members.has(info.id);
this.directory.applyClientEnter(info);
this.refresh();
if (this.directoryStatusRefreshTimer) clearTimeout(this.directoryStatusRefreshTimer);
this.directoryStatusRefreshTimer = setTimeout(() => {
this.directoryStatusRefreshTimer = null;
void options.client.refreshDirectoryClients?.();
}, 300);
if (options.isPublished()) {
this.publishDirectory();
if (!wasKnown) options.sendJson({ type: "memberEnter", id: info.id, nickname: info.nickname, uid: info.uid, isSelf: info.id === this.clientId });
@@ -123,6 +130,11 @@ export class SessionEventCoordinator {
this.refresh();
this.publishDirectory();
});
this.listenDirectory("directoryClientsSnapshot", clients => {
this.directory.applyClientListSnapshot(clients);
this.refresh();
this.publishDirectory();
});
this.listen("rawNotification", options.onNotification);
this.listen("voiceData", options.onVoice);
this.listen("textMessage", message => {
@@ -217,6 +229,8 @@ export class SessionEventCoordinator {
}
reset(): void {
if (this.directoryStatusRefreshTimer) clearTimeout(this.directoryStatusRefreshTimer);
this.directoryStatusRefreshTimer = null;
this.avatars.reset();
this.clientId = 0;
this.channelId = 0n;
@@ -230,6 +244,8 @@ export class SessionEventCoordinator {
close(): void {
if (this.closed) return;
this.closed = true;
if (this.directoryStatusRefreshTimer) clearTimeout(this.directoryStatusRefreshTimer);
this.directoryStatusRefreshTimer = null;
for (const unsubscribe of this.subscriptions.splice(0)) unsubscribe();
this.avatars.close();
this.reset();
+17
View File
@@ -194,6 +194,23 @@ export class TSClient extends EventEmitter {
this.emit("connected", this.clientId);
}
/** Refresh optional member status fields omitted by some client-enter events. */
async refreshDirectoryClients(): Promise<void> {
const client = this.client;
const generation = this.connectionGeneration;
if (!client || !this.connected) return;
try {
const clients = await tsListClients(client);
if (this.client === client && this.connected && this.connectionGeneration === generation) {
this.emit("directoryClientsSnapshot", clients);
}
} catch (error: unknown) {
if (this.client === client && this.connected && this.connectionGeneration === generation) {
this.logger.warn({ err: error instanceof Error ? error.message : String(error) }, "Could not refresh TeamSpeak member statuses");
}
}
}
/**
* Load a visible client's TeamSpeak avatar through the client protocol.
*
+19 -2
View File
@@ -30,7 +30,7 @@ class PeerStub {
}
}
function fixture() {
function fixture(webRtc = { enabled: true } as import("./webrtc-audio.js").WebRtcAudioOptions) {
const peers: PeerStub[] = [];
const messages: ServerMessage[] = [];
const entry = {
@@ -42,7 +42,7 @@ function fixture() {
};
let forwarded = 0;
let configurePeer = (_peer: PeerStub): void => {};
const instance = new VoiceBridge({ joinTickets: new JoinTicketStore(), webRtc: { enabled: true } }, pino({ enabled: false }), options => {
const instance = new VoiceBridge({ joinTickets: new JoinTicketStore(), webRtc }, pino({ enabled: false }), options => {
const peer = new PeerStub(options);
peers.push(peer);
configurePeer(peer);
@@ -205,3 +205,20 @@ test("old close statistics cannot overwrite a new peer's live snapshot", async (
assert.equal(f.entry.audio.webrtcIngressRtpFrames, 27);
assert.equal(f.entry.webrtc, f.peers[1]);
});
test("configured media address overrides the proxy host and passes IPv6/STUN to the session", async () => {
const f = fixture({ enabled: true, publicHost: "2001:db8::42", ipv6Enabled: true, stunServer: "stun:stun.example.com:3478" });
Object.assign(f.entry, { webrtcPublicHost: "proxy.example.invalid" });
await f.offer("configured");
assert.deepEqual(f.peers[0].options.publicAddresses, ["2001:db8::42"]);
assert.equal(f.peers[0].options.ipv6Enabled, true);
assert.equal(f.peers[0].options.stunServer, "stun:stun.example.com:3478");
});
test("an unset media override still uses a literal request host", async () => {
const f = fixture();
Object.assign(f.entry, { webrtcPublicHost: "192.0.2.10" });
await f.offer("legacy");
assert.deepEqual(f.peers[0].options.publicAddresses, ["192.0.2.10"]);
});
+11 -2
View File
@@ -6,6 +6,7 @@ import { createAudioFlowStats, snapshotAudioStats, type AudioFlowStats } from ".
export type { AudioFlowStats } from "./audio-stats.js";
import type { ServerMessage } from "../shared/server-messages.js";
import { parseWebRtcClientMessage } from "../shared/webrtc.js";
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";
@@ -281,6 +282,7 @@ export class VoiceBridge {
whisperTargetIds: [...entry!.whisperTargetIds],
whisperActive: entry!.whisperActive,
webrtcAvailable: this.getWebRtcOptions()?.enabled === true,
webRtcStunServer: this.getWebRtcOptions()?.stunServer ?? "",
screenShareIceServers: this.getScreenShareIceServers(),
accelerated: Boolean(entry!.acceleration),
...(entry!.rememberIdentity ? { identity: tsClient.getIdentityString() } : {}),
@@ -353,7 +355,9 @@ export class VoiceBridge {
tsReady = true;
events.syncSelf();
sendInitialState();
void this.screenShares.discoverExistingStreams(entry!);
void this.screenShares.discoverExistingStreams(entry!).catch((error: unknown) => {
this.logger.debug({ entryId, err: error instanceof Error ? error.message : String(error) }, "Could not discover existing TeamSpeak screen streams");
});
} catch (error: unknown) {
const normalized = normalizeTeamSpeakError(error);
const failureCode = clientConnectionFailureCode(normalized, serverPassword);
@@ -700,9 +704,14 @@ export class VoiceBridge {
let peer: WebRtcAudioSession | null = null;
const isCurrentPeer = (): boolean => isCurrent() && peer !== null && entry.webrtc === peer;
try {
const publicAddresses = await resolveVoiceMediaAddresses(config.publicHost || entry.webrtcPublicHost, config.ipv6Enabled === true);
if (!isCurrent()) return;
peer = this.createWebRtcSession({
connectionId: entry.id,
...(entry.webrtcPublicHost ? { publicHost: entry.webrtcPublicHost } : {}),
publicAddresses,
...(config.publicHost || entry.webrtcPublicHost ? { publicHost: config.publicHost || entry.webrtcPublicHost } : {}),
ipv6Enabled: config.ipv6Enabled,
stunServer: config.stunServer,
udpPortRange: config.udpPortRange,
logger: this.logger,
microphoneMuted: muted,
+33
View File
@@ -1,10 +1,43 @@
import assert from "node:assert/strict";
import test from "node:test";
import { createSocket } from "node:dgram";
import pino from "pino";
import { RTCPeerConnection, useOPUS, usePCMU, type RtpPacket } from "werift";
import { OpusEncoder } from "./opus-codec.js";
import { WebRtcAudioSession } from "./webrtc-audio.js";
test("configured STUN is actually queried and contributes srflx candidates", async t => {
const stun = createSocket("udp4");
await new Promise<void>(resolve => stun.bind(0, "127.0.0.1", resolve));
t.after(() => stun.close());
let requests = 0;
stun.on("message", (request, remote) => {
if (request.length < 20 || request.readUInt16BE(0) !== 1) return;
requests++;
const response = Buffer.alloc(32);
response.writeUInt16BE(0x0101, 0);
response.writeUInt16BE(12, 2);
request.copy(response, 4, 4, 20);
response.writeUInt16BE(0x0020, 20); // XOR-MAPPED-ADDRESS
response.writeUInt16BE(8, 22);
response[25] = 1;
response.writeUInt16BE(remote.port ^ 0x2112, 26);
remote.address.split(".").map(Number).forEach((octet, index) => { response[28 + index] = octet ^ request[4 + index]!; });
stun.send(response, remote.port, remote.address);
});
const session = new WebRtcAudioSession({ connectionId: "configured-ice", logger: pino({ enabled: false }),
stunServer: `stun:127.0.0.1:${stun.address().port}`, ipv6Enabled: true, publicAddresses: ["127.0.0.1"],
onVoiceFrame() {}, onVoiceActivity() {} });
const source = new RTCPeerConnection({ iceServers: [], codecs: { audio: [useOPUS()] } });
t.after(async () => { await session.close(); await source.close(); });
source.addTransceiver("audio", { direction: "sendrecv" });
const offer = await source.createOffer();
const answer = await session.createAnswer({ type: "offer", sdp: offer.sdp });
assert.ok(requests > 0);
assert.match(answer.sdp, / typ srflx /);
assert.equal(session.peer.iceTransports[0]!.connection.options.useIpv6, true);
});
test("WebRTC rejects an offer without negotiated audio instead of returning an empty answer", async t => {
const session = new WebRtcAudioSession({ connectionId: "invalid-offer", logger: pino({ enabled: false }), onVoiceFrame() {}, onVoiceActivity() {} });
t.after(() => session.close());
+9 -3
View File
@@ -35,11 +35,17 @@ const SPEAKER_ACTIVITY_RMS = 160;
// change it in the admin console before enabling WebRTC.
export interface WebRtcAudioOptions {
enabled: boolean;
publicHost?: string;
ipv6Enabled?: boolean;
stunServer?: string;
udpPortRange?: [number, number];
}
export interface WebRtcAudioSessionOptions {
connectionId: string;
publicAddresses?: string[];
ipv6Enabled?: boolean;
stunServer?: string;
publicHost?: string;
udpPortRange?: [number, number];
logger: LoggerType;
@@ -140,15 +146,15 @@ export class WebRtcAudioSession {
this.accompanimentActive = options.accompanimentActive === true;
this.outgoingTrack = new MediaStreamTrack({ kind: "audio" });
const iceAdditionalHostAddresses = options.publicHost ? [options.publicHost] : undefined;
const iceAdditionalHostAddresses = options.publicAddresses ?? (options.publicHost ? [options.publicHost] : undefined);
const udpPortRange = options.udpPortRange ?? WEBRTC_UDP_PORT_RANGE;
this.peer = new RTCPeerConnection({
// Both audio routes carry Opus; accepting PCMU would label Opus output
// as another codec and silently discard the peer's incoming audio.
codecs: { audio: [useOPUS()] },
iceServers: [],
iceServers: options.stunServer ? [{ urls: options.stunServer }] : [],
iceUseIpv4: true,
iceUseIpv6: false,
iceUseIpv6: options.ipv6Enabled === true,
iceUseTcp: false,
icePortRange: [...udpPortRange] as [number, number],
...(iceAdditionalHostAddresses ? { iceAdditionalHostAddresses } : {}),
+35
View File
@@ -0,0 +1,35 @@
import assert from "node:assert/strict";
import test from "node:test";
import { normalizeVoiceMediaHost, normalizeVoiceStunServer } from "../shared/voice-ice.js";
import { resolveVoiceMediaAddresses } from "./webrtc-config.js";
test("media hosts accept DNS and IPv4/IPv6, reject web URLs, ports and injected components", () => {
for (const [input, expected] of [["", ""], [" MEDIA.example.com ", "media.example.com"], ["192.0.2.1", "192.0.2.1"], ["[2001:db8::1]", "2001:db8::1"], ["::1", "::1"]]) {
assert.equal(normalizeVoiceMediaHost(input), expected);
}
for (const input of [null, 5, "https://media.example.com", "media.example.com:443", "user@media.example.com", "[::1]?x", "[::1]/x", "[::1]:443", "a\r\nb", "-invalid", "x".repeat(254)]) {
assert.equal(normalizeVoiceMediaHost(input), null, String(input));
}
});
test("voice STUN accepts supported UDP URLs and rejects TURN credentials and other protocols", () => {
assert.equal(normalizeVoiceStunServer(" STUN:stun.example.com "), "stun:stun.example.com:3478");
assert.equal(normalizeVoiceStunServer("stun:[2001:db8::1]:3478"), null);
assert.equal(normalizeVoiceStunServer(""), "");
for (const value of [null, [], "turn:example.com", "stuns:example.com", "https://example.com", "stun:user:pass@example.com", "stun:example.com:0", "stun:example.com:65536", "stun:example.com?transport=tcp", "stun:example.com/path"]) {
assert.equal(normalizeVoiceStunServer(value), null, String(value));
}
});
test("media DNS produces literal candidates and honors IPv6 without disabling IPv4", async () => {
const resolve = async (host: string) => {
assert.equal(host, "media.example.com");
return [{ address: "2001:db8::1", family: 6 }, { address: "192.0.2.1", family: 4 }, { address: "192.0.2.1", family: 4 }];
};
assert.deepEqual(await resolveVoiceMediaAddresses("media.example.com", false, resolve), ["192.0.2.1"]);
assert.deepEqual(await resolveVoiceMediaAddresses("media.example.com", true, resolve), ["2001:db8::1", "192.0.2.1"]);
assert.deepEqual(await resolveVoiceMediaAddresses("[2001:db8::1]", false, resolve), []);
assert.deepEqual(await resolveVoiceMediaAddresses("[2001:db8::1]", true, resolve), ["2001:db8::1"]);
assert.deepEqual(await resolveVoiceMediaAddresses("192.0.2.1", false, resolve), ["192.0.2.1"]);
assert.deepEqual(await resolveVoiceMediaAddresses("media.example.com", true, async () => { throw new Error("DNS unavailable"); }), []);
});
+27
View File
@@ -1,3 +1,7 @@
import { lookup } from "node:dns/promises";
import { isIP } from "node:net";
import { normalizeVoiceMediaHost } from "../shared/voice-ice.js";
/** Default WebRTC media port range used by WebSpeak and its Docker image. */
export const DEFAULT_WEBRTC_UDP_PORT_RANGE: [number, number] = [40000, 40099];
@@ -5,3 +9,26 @@ export const DEFAULT_WEBRTC_UDP_PORT_RANGE: [number, number] = [40000, 40099];
export const WEBRTC_UDP_PORT_RANGE = DEFAULT_WEBRTC_UDP_PORT_RANGE;
export const WEBRTC_UDP_PORT_MIN = 1024;
export const WEBRTC_UDP_PORT_MAX = 65535;
/** SDP candidates must contain usable addresses, not the HTTP proxy's hostname. */
export async function resolveVoiceMediaAddresses(
host: string | undefined,
ipv6: boolean,
resolve = (name: string) => lookup(name, { all: true }),
): Promise<string[]> {
const normalized = normalizeVoiceMediaHost(host ?? "");
if (!normalized) return [];
const family = isIP(normalized);
if (family) return family === 4 || ipv6 ? [normalized] : [];
let timer: ReturnType<typeof setTimeout> | undefined;
try {
const addresses = await Promise.race([
resolve(normalized),
new Promise<never>((_, reject) => { timer = setTimeout(() => reject(new Error("Media DNS timeout")), 1500); }),
]);
return [...new Set(addresses.filter(value => value.family === 4 || ipv6 && value.family === 6).map(value => value.address))];
} catch {
// Host discovery and STUN may still work when the optional additional address does not.
return [];
} finally { clearTimeout(timer); }
}