mirror of
https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak.git
synced 2026-12-03 12:02:50 +08:00
fix: consolidate audited dev updates
This commit is contained in:
1 parent
568b8fd8be
commit
0a552f7ee8
58 files changed
+1930
-132
No files matched your search
@@ -464,6 +464,9 @@ function readSettingsInput(body: Record<string, unknown>): AdminSettingsInput {
|
||||
welcomeTextRu: typeof body.welcomeTextRu === "string" ? body.welcomeTextRu.slice(0, 500) : undefined,
|
||||
welcomeTextJa: typeof body.welcomeTextJa === "string" ? body.welcomeTextJa.slice(0, 500) : undefined,
|
||||
webRtcEnabled: body.webRtcEnabled === true,
|
||||
webRtcPublicHost: body.webRtcPublicHost as string | undefined,
|
||||
webRtcIpv6Enabled: body.webRtcIpv6Enabled as boolean | undefined,
|
||||
webRtcStunServer: body.webRtcStunServer as string | undefined,
|
||||
webRtcUdpStart: readOptionalInteger(body, "webRtcUdpStart"),
|
||||
webRtcUdpEnd: readOptionalInteger(body, "webRtcUdpEnd"),
|
||||
relaySettingsAction: readRelaySettingsAction(body.relaySettingsAction),
|
||||
|
||||
@@ -11,6 +11,7 @@ import { hashAdminPassword, validateAdminPassword, verifyAdminPassword } from ".
|
||||
import { decryptSecret, encryptSecret } from "../security/secret-crypto.js";
|
||||
import { probeTeamSpeak, TeamSpeakProbeError } from "../server/teamspeak-probe.js";
|
||||
import { pingTeamSpeakHost } from "../server/network-probe.js";
|
||||
import { normalizeVoiceMediaHost, normalizeVoiceStunServer } from "../shared/voice-ice.js";
|
||||
import type { WebRtcAudioOptions } from "../server/webrtc-audio.js";
|
||||
import { DEFAULT_ACCELERATION_RELAY_PORT, type ConfiguredAccelerationRelay } from "../server/acceleration-relay.js";
|
||||
import { DEFAULT_WEBRTC_UDP_PORT_RANGE, WEBRTC_UDP_PORT_MAX, WEBRTC_UDP_PORT_MIN } from "../server/webrtc-config.js";
|
||||
@@ -118,6 +119,9 @@ export class AdminService {
|
||||
lastTestLatencyMs: settings.lastTestLatencyMs,
|
||||
lastTestError: settings.lastTestError,
|
||||
webRtcEnabled: settings.webRtcEnabled,
|
||||
webRtcPublicHost: settings.webRtcPublicHost,
|
||||
webRtcIpv6Enabled: settings.webRtcIpv6Enabled,
|
||||
webRtcStunServer: settings.webRtcStunServer,
|
||||
webRtcUdpStart: settings.webRtcUdpStart,
|
||||
webRtcUdpEnd: settings.webRtcUdpEnd,
|
||||
relayConfigured: settings.relayConfigured,
|
||||
@@ -135,6 +139,9 @@ export class AdminService {
|
||||
const settings = this.database.getSettings();
|
||||
return {
|
||||
enabled: settings.webRtcEnabled,
|
||||
publicHost: settings.webRtcPublicHost,
|
||||
ipv6Enabled: settings.webRtcIpv6Enabled,
|
||||
stunServer: settings.webRtcStunServer,
|
||||
udpPortRange: [settings.webRtcUdpStart, settings.webRtcUdpEnd],
|
||||
};
|
||||
}
|
||||
@@ -341,6 +348,12 @@ export class AdminService {
|
||||
if (typeof input.webRtcEnabled !== "boolean") {
|
||||
throw new AdminInputError("INVALID_WEBRTC_ENABLED", "WebRTC enabled value is invalid");
|
||||
}
|
||||
const webRtcPublicHost = normalizeVoiceMediaHost(input.webRtcPublicHost === undefined ? current.webRtcPublicHost : input.webRtcPublicHost);
|
||||
const webRtcStunServer = normalizeVoiceStunServer(input.webRtcStunServer === undefined ? current.webRtcStunServer : input.webRtcStunServer);
|
||||
const webRtcIpv6Enabled = input.webRtcIpv6Enabled === undefined ? current.webRtcIpv6Enabled : input.webRtcIpv6Enabled;
|
||||
if (webRtcPublicHost === null) throw new AdminInputError("INVALID_WEBRTC_PUBLIC_HOST", "Use an IP address or hostname without a scheme, path or port");
|
||||
if (webRtcStunServer === null) throw new AdminInputError("INVALID_WEBRTC_STUN_SERVER", "Use a UDP STUN URL: stun:host:port");
|
||||
if (typeof webRtcIpv6Enabled !== "boolean") throw new AdminInputError("INVALID_WEBRTC_IPV6", "WebRTC IPv6 value must be boolean");
|
||||
const webRtcUdpStart = input.webRtcUdpStart ?? current.webRtcUdpStart ?? DEFAULT_WEBRTC_UDP_PORT_RANGE[0];
|
||||
const webRtcUdpEnd = input.webRtcUdpEnd ?? current.webRtcUdpEnd ?? DEFAULT_WEBRTC_UDP_PORT_RANGE[1];
|
||||
if (!Number.isInteger(webRtcUdpStart) || webRtcUdpStart < WEBRTC_UDP_PORT_MIN || webRtcUdpStart > WEBRTC_UDP_PORT_MAX) {
|
||||
@@ -421,6 +434,7 @@ export class AdminService {
|
||||
tsPort: target.port,
|
||||
tsPasswordEncrypted: encryptedPassword,
|
||||
webRtcEnabled: input.webRtcEnabled,
|
||||
webRtcPublicHost, webRtcIpv6Enabled, webRtcStunServer,
|
||||
webRtcUdpStart,
|
||||
webRtcUdpEnd,
|
||||
relayConfigured,
|
||||
@@ -538,6 +552,9 @@ export class AdminService {
|
||||
tsPort: settings.tsPort,
|
||||
tsPasswordEncrypted: settings.tsPasswordEncrypted,
|
||||
webRtcEnabled: settings.webRtcEnabled,
|
||||
webRtcPublicHost: settings.webRtcPublicHost,
|
||||
webRtcIpv6Enabled: settings.webRtcIpv6Enabled,
|
||||
webRtcStunServer: settings.webRtcStunServer,
|
||||
webRtcUdpStart: settings.webRtcUdpStart,
|
||||
webRtcUdpEnd: settings.webRtcUdpEnd,
|
||||
relayConfigured: settings.relayConfigured,
|
||||
@@ -566,6 +583,9 @@ export class AdminService {
|
||||
tsPort: legacy.tsPort,
|
||||
tsPasswordEncrypted: legacy.tsServerPassword ? encryptSecret(legacy.tsServerPassword, this.masterSecret) : null,
|
||||
webRtcEnabled: current.webRtcEnabled,
|
||||
webRtcPublicHost: current.webRtcPublicHost,
|
||||
webRtcIpv6Enabled: current.webRtcIpv6Enabled,
|
||||
webRtcStunServer: current.webRtcStunServer,
|
||||
webRtcUdpStart: current.webRtcUdpStart,
|
||||
webRtcUdpEnd: current.webRtcUdpEnd,
|
||||
relayConfigured: current.relayConfigured,
|
||||
|
||||
@@ -6,7 +6,7 @@ import type { AdminCredential } from "../security/admin-password.js";
|
||||
import type { TeamSpeakProtocol } from "../server/teamspeak-adapter.js";
|
||||
import { DEFAULT_WEBRTC_UDP_PORT_RANGE } from "../server/webrtc-config.js";
|
||||
|
||||
export const DATABASE_SCHEMA_VERSION = 7;
|
||||
export const DATABASE_SCHEMA_VERSION = 8;
|
||||
export type AccessMode = "fixed" | "open";
|
||||
|
||||
export interface PersistedSettings {
|
||||
@@ -25,6 +25,9 @@ export interface PersistedSettings {
|
||||
lastTestLatencyMs: number | null;
|
||||
lastTestError: string | null;
|
||||
webRtcEnabled: boolean;
|
||||
webRtcPublicHost: string;
|
||||
webRtcIpv6Enabled: boolean;
|
||||
webRtcStunServer: string;
|
||||
webRtcUdpStart: number;
|
||||
webRtcUdpEnd: number;
|
||||
relayConfigured: boolean;
|
||||
@@ -48,6 +51,9 @@ export interface SettingsUpdate {
|
||||
tsPort: number;
|
||||
tsPasswordEncrypted: string | null;
|
||||
webRtcEnabled: boolean;
|
||||
webRtcPublicHost?: string;
|
||||
webRtcIpv6Enabled?: boolean;
|
||||
webRtcStunServer?: string;
|
||||
webRtcUdpStart?: number;
|
||||
webRtcUdpEnd?: number;
|
||||
relayConfigured: boolean;
|
||||
@@ -114,6 +120,8 @@ interface SettingsRow extends Record<string, unknown> {
|
||||
last_test_error: string | null;
|
||||
webrtc_enabled: number;
|
||||
webrtc_public_host: string;
|
||||
webrtc_ipv6_enabled: number;
|
||||
webrtc_stun_server: string;
|
||||
webrtc_udp_start: number;
|
||||
webrtc_udp_end: number;
|
||||
relay_configured: number;
|
||||
@@ -208,6 +216,9 @@ export class WebSpeakDatabase {
|
||||
lastTestLatencyMs: row.last_test_latency_ms,
|
||||
lastTestError: row.last_test_error,
|
||||
webRtcEnabled: row.webrtc_enabled === 1,
|
||||
webRtcPublicHost: row.webrtc_public_host,
|
||||
webRtcIpv6Enabled: row.webrtc_ipv6_enabled === 1,
|
||||
webRtcStunServer: row.webrtc_stun_server,
|
||||
webRtcUdpStart: row.webrtc_udp_start,
|
||||
webRtcUdpEnd: row.webrtc_udp_end,
|
||||
relayConfigured: row.relay_configured === 1,
|
||||
@@ -576,6 +587,16 @@ export class WebSpeakDatabase {
|
||||
`);
|
||||
this.database.exec("PRAGMA user_version = 7");
|
||||
});
|
||||
version = 7;
|
||||
}
|
||||
if (version === 7) {
|
||||
this.transaction(() => {
|
||||
this.database.exec(`
|
||||
ALTER TABLE settings ADD COLUMN webrtc_ipv6_enabled INTEGER NOT NULL DEFAULT 0 CHECK (webrtc_ipv6_enabled IN (0, 1));
|
||||
ALTER TABLE settings ADD COLUMN webrtc_stun_server TEXT NOT NULL DEFAULT '';
|
||||
`);
|
||||
this.database.exec("PRAGMA user_version = 8");
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
@@ -583,7 +604,7 @@ export class WebSpeakDatabase {
|
||||
this.database.prepare(
|
||||
`UPDATE settings SET
|
||||
site_name = ?, welcome_text = ?, welcome_text_en = ?, welcome_text_de = ?, welcome_text_ru = ?, welcome_text_ja = ?, access_mode = ?, ts_host = ?, ts_port = ?,
|
||||
ts_password_encrypted = ?, webrtc_enabled = ?, webrtc_udp_start = ?,
|
||||
ts_password_encrypted = ?, webrtc_enabled = ?, webrtc_public_host = ?, webrtc_ipv6_enabled = ?, webrtc_stun_server = ?, webrtc_udp_start = ?,
|
||||
webrtc_udp_end = ?, relay_configured = ?, relay_enabled = ?, relay_name = ?,
|
||||
relay_host = ?, relay_port = ?, relay_token_encrypted = ?, updated_at = ?
|
||||
WHERE id = 1`,
|
||||
@@ -599,6 +620,9 @@ export class WebSpeakDatabase {
|
||||
settings.tsPort,
|
||||
settings.tsPasswordEncrypted,
|
||||
settings.webRtcEnabled ? 1 : 0,
|
||||
settings.webRtcPublicHost ?? "",
|
||||
settings.webRtcIpv6Enabled ? 1 : 0,
|
||||
settings.webRtcStunServer ?? "",
|
||||
settings.webRtcUdpStart ?? DEFAULT_WEBRTC_UDP_PORT_RANGE[0],
|
||||
settings.webRtcUdpEnd ?? DEFAULT_WEBRTC_UDP_PORT_RANGE[1],
|
||||
settings.relayConfigured ? 1 : 0,
|
||||
|
||||
@@ -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);
|
||||
|
||||
@@ -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 });
|
||||
}
|
||||
|
||||
@@ -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);
|
||||
|
||||
@@ -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",
|
||||
|
||||
@@ -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();
|
||||
|
||||
@@ -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.
|
||||
*
|
||||
|
||||
@@ -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"]);
|
||||
});
|
||||
@@ -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,
|
||||
|
||||
@@ -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());
|
||||
|
||||
@@ -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 } : {}),
|
||||
|
||||
@@ -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"); }), []);
|
||||
});
|
||||
@@ -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); }
|
||||
}
|
||||
@@ -10,6 +10,9 @@ export interface AdminSettingsInput {
|
||||
welcomeTextRu?: string;
|
||||
welcomeTextJa?: string;
|
||||
webRtcEnabled: boolean;
|
||||
webRtcPublicHost?: string;
|
||||
webRtcIpv6Enabled?: boolean;
|
||||
webRtcStunServer?: string;
|
||||
webRtcUdpStart?: number;
|
||||
webRtcUdpEnd?: number;
|
||||
relaySettingsAction?: "keep" | "replace" | "remove";
|
||||
|
||||
@@ -30,6 +30,9 @@ const settings = object({
|
||||
welcomeText: text, welcomeTextEn: text, welcomeTextDe: text, welcomeTextRu: text, welcomeTextJa: text,
|
||||
welcomeDefaults: welcomeTexts, lastTestAt: nullable(text), lastTestLatencyMs: nullable(number), lastTestError: nullable(text),
|
||||
webRtcEnabled: boolean, webRtcUdpStart: number, webRtcUdpEnd: number,
|
||||
webRtcPublicHost: value => value === undefined ? "" : text(value),
|
||||
webRtcIpv6Enabled: value => value === undefined ? false : boolean(value),
|
||||
webRtcStunServer: value => value === undefined ? "" : text(value),
|
||||
relayConfigured: boolean, relayEnabled: boolean, relayName: text, relayTarget: text, hasRelayToken: boolean,
|
||||
relayNodes: array(relayNode), internalPort: number, updatedAt: text,
|
||||
});
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
import type { ChannelMember, ChannelInfo, ServerEvent, VoiceAudioBridgeStats } from "./voice-models.js";
|
||||
import { normalizeScreenShareIceServers, parseScreenShareSignal, type ScreenShareIceServer, type ScreenSharePeerSignal, type ScreenShareStreamDescription, type ScreenShareViewerDescription } from "./screen-share.js";
|
||||
|
||||
import { normalizeVoiceStunServer } from "./voice-ice.js";
|
||||
import { isSessionDescription, type SessionDescription } from "./webrtc.js";
|
||||
export type { SessionDescription } from "./webrtc.js";
|
||||
|
||||
@@ -11,7 +12,7 @@ type ChatFields = { invokerId?: number; invokerName?: string; message: string; t
|
||||
|
||||
/** Public JSON messages. Internal sockets, SDK clients and media objects stay out. */
|
||||
export type ServerMessage =
|
||||
| Message<"connected", { tsClientId: number; members?: ChannelMember[]; serverEventLog?: ServerEvent[]; identity?: string; webrtcAvailable?: boolean; whisperTargetIds?: number[]; whisperActive?: boolean; screenShareIceServers?: ScreenShareIceServer[]; accelerated?: boolean }>
|
||||
| Message<"connected", { tsClientId: number; members?: ChannelMember[]; serverEventLog?: ServerEvent[]; identity?: string; webrtcAvailable?: boolean; webRtcStunServer?: string; whisperTargetIds?: number[]; whisperActive?: boolean; screenShareIceServers?: ScreenShareIceServer[]; accelerated?: boolean }>
|
||||
| Message<"memberEnter", ChannelMember>
|
||||
| Message<"memberLeave", { id: number }>
|
||||
| Message<"memberAvatar", { id: number; uid?: string; avatar?: string }>
|
||||
@@ -109,7 +110,7 @@ export function parseScreenShareStream(value: unknown): ScreenShareStreamDescrip
|
||||
|
||||
const valid: Record<ServerMessage["type"], (message: RecordValue) => boolean> = {
|
||||
connected: m => clientId(m.tsClientId) && optional(m.members, v => arrayOf(v, member)) && optional(m.serverEventLog, v => arrayOf(v, event))
|
||||
&& optional(m.identity, v => text(v) && v.length <= 8192) && optional(m.webrtcAvailable, boolean)
|
||||
&& optional(m.identity, v => text(v) && v.length <= 8192) && optional(m.webrtcAvailable, boolean) && optional(m.webRtcStunServer, v => normalizeVoiceStunServer(v) !== null)
|
||||
&& optional(m.whisperTargetIds, v => arrayOf(v, clientId)) && optional(m.whisperActive, boolean) && optional(m.accelerated, boolean),
|
||||
memberEnter: member,
|
||||
memberLeave: m => clientId(m.id),
|
||||
@@ -156,7 +157,7 @@ export function parseServerMessage(value: unknown): ServerMessage | null {
|
||||
if (!valid[value.type as ServerMessage["type"]](value)) return null;
|
||||
let result = value;
|
||||
if (value.type === "connected") {
|
||||
result = { ...value, screenShareIceServers: normalizeScreenShareIceServers(Array.isArray(value.screenShareIceServers) ? value.screenShareIceServers : undefined) };
|
||||
result = { ...value, ...(value.webRtcStunServer === undefined ? {} : { webRtcStunServer: normalizeVoiceStunServer(value.webRtcStunServer)! }), screenShareIceServers: normalizeScreenShareIceServers(Array.isArray(value.screenShareIceServers) ? value.screenShareIceServers : undefined) };
|
||||
} else if (value.type === "audioStats") {
|
||||
result = { ...value, stats: parseVoiceAudioBridgeStats(value.stats) };
|
||||
} else if (value.type === "screenShareList") {
|
||||
|
||||
@@ -0,0 +1,30 @@
|
||||
/** A media host is an address, never an HTTP URL or an address with a port. */
|
||||
export function normalizeVoiceMediaHost(value: unknown): string | null {
|
||||
if (typeof value !== "string" || value.length > 253) return null;
|
||||
const host = value.trim();
|
||||
if (!host) return "";
|
||||
if (/[:\[\]]/.test(host)) {
|
||||
if (!/^(?:\[[\da-f:.]+\]|[\da-f:.]+)$/i.test(host)) return null;
|
||||
try {
|
||||
const parsed = new URL(`http://${host.startsWith("[") ? host : `[${host}]`}`);
|
||||
return parsed.hostname.startsWith("[") && !parsed.port && parsed.pathname === "/"
|
||||
? parsed.hostname.slice(1, -1) : null;
|
||||
} catch { return null; }
|
||||
}
|
||||
if (!host.split(".").every(label => /^[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?$/i.test(label))) return null;
|
||||
return host.toLowerCase();
|
||||
}
|
||||
|
||||
/** Voice currently exposes UDP STUN discovery only, without relay credentials. */
|
||||
export function normalizeVoiceStunServer(value: unknown): string | null {
|
||||
if (typeof value !== "string" || value.length > 300) return null;
|
||||
if (!value.trim()) return "";
|
||||
// werift currently performs srflx discovery on IPv4 sockets. IPv6 media
|
||||
// candidates still work independently, but an IPv6-only STUN URL would not.
|
||||
const match = /^stun:([a-z\d.-]+)(?::(\d{1,5}))?$/i.exec(value.trim());
|
||||
if (!match) return null;
|
||||
const host = normalizeVoiceMediaHost(match[1]);
|
||||
const port = Number(match[2] ?? 3478);
|
||||
if (!host || port < 1 || port > 65535) return null;
|
||||
return `stun:${host}:${port}`;
|
||||
}
|
||||
@@ -36,6 +36,8 @@ export interface ChatMessage {
|
||||
message: string;
|
||||
timestamp: number;
|
||||
isSelf?: boolean;
|
||||
/** Message came from browser-local history rather than the active session. */
|
||||
isHistory?: boolean;
|
||||
}
|
||||
|
||||
export interface ServerEvent {
|
||||
|
||||
Reference in new issue
Block a user