feat(voice): support Cloudflare Tunnel deployments and WebRTC fallback

Route page and signaling traffic through Cloudflare Tunnel while sending
WebRTC media over direct UDP, with optional TURN REST as a fallback.
When WebRTC was already offered and then fails, stay in the current
session, automatically resume compatibility audio, and keep a Reconnect
WebRTC control. A reconnect retries WebRTC only, leaves compatibility
running until it succeeds, and stays on compatibility if it fails again.

Database schema 14 adds nullable voice override columns and is a one-way
boundary: older binaries reject this database. This change is for review,
not a production rollout.
This commit is contained in:
OddTurtleHead committed 2026-11-26 23:47:50 +08:00
1 parent 9a12e2ee7b
commit b6e7b1e4da
68 files changed
+3525 -189

No files matched your search

+7
View File
@@ -615,6 +615,13 @@ function readSettingsInput(body: Record<string, unknown>): AdminSettingsInput {
webRtcStunServer: body.webRtcStunServer as string | undefined,
webRtcUdpStart: readOptionalInteger(body, "webRtcUdpStart"),
webRtcUdpEnd: readOptionalInteger(body, "webRtcUdpEnd"),
voiceProfile: body.voiceProfile as AdminSettingsInput["voiceProfile"],
voiceTurnUrls: typeof body.voiceTurnUrls === "string" ? body.voiceTurnUrls.slice(0, 4096) : undefined,
voiceTurnSecret: typeof body.voiceTurnSecret === "string" ? body.voiceTurnSecret.slice(0, 512) : undefined,
voiceTurnSecretAction: readPasswordAction(body.voiceTurnSecretAction),
voiceTurnTtlSeconds: readOptionalInteger(body, "voiceTurnTtlSeconds"),
voiceOpusWs: typeof body.voiceOpusWs === "boolean" ? body.voiceOpusWs : undefined,
voiceJitterMaxMs: readOptionalInteger(body, "voiceJitterMaxMs"),
relaySettingsAction: readRelaySettingsAction(body.relaySettingsAction),
relayEnabled: body.relayEnabled === true,
relayName: typeof body.relayName === "string" ? body.relayName.slice(0, 80) : undefined,
+122 -1
View File
@@ -15,8 +15,10 @@ 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 { normalizeVoiceMediaHost, normalizeVoiceStunServer, normalizeVoiceTurnRestUrls, VOICE_JITTER_MAX_MS, VOICE_JITTER_MIN_MS, VOICE_TURN_MIN_SECRET_LENGTH, VOICE_TURN_TTL_DEFAULT_SECONDS, VOICE_TURN_TTL_MAX_SECONDS, VOICE_TURN_TTL_MIN_SECONDS } from "../shared/voice-ice.js";
import type { WebRtcAudioOptions } from "../server/webrtc-audio.js";
import { DEFAULT_VOICE_ICE_CONFIG, type VoiceIceConfig } from "../server/voice-ice-config.js";
import { isVoiceProfileSetting } from "../shared/voice-profile.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";
import { DEFAULT_WELCOME_TEXTS, resolveWelcomeTexts } from "../site-copy.js";
@@ -43,6 +45,7 @@ export interface ManagedInviteView {
}
type ProbeFunction = typeof probeTeamSpeak;
const VOICE_TURN_SECRET_PURPOSE = "webspeak:voice-turn-rest-secret:v1";
export class AdminService {
private readonly tsAdmin: TsAdminService;
@@ -56,6 +59,8 @@ export class AdminService {
private readonly probe: ProbeFunction = probeTeamSpeak,
private readonly version = "0.1.0",
tsAdminClientFactory?: TsAdminQueryClientFactory,
/** Environment baseline; console values override it without requiring a restart. */
private readonly voiceIceDefaults: VoiceIceConfig = DEFAULT_VOICE_ICE_CONFIG,
) {
this.tsAdmin = new TsAdminService(database, masterSecret, logger, () => {
const settings = database.getSettings();
@@ -124,6 +129,7 @@ export class AdminService {
getAdminSettings(): AdminSettings {
const settings = this.database.getSettings();
const turn = this.resolveVoiceTurnSettings(settings);
return {
target: settingsTarget(settings),
hasPassword: Boolean(settings.tsPasswordEncrypted),
@@ -144,6 +150,12 @@ export class AdminService {
webRtcStunServer: settings.webRtcStunServer,
webRtcUdpStart: settings.webRtcUdpStart,
webRtcUdpEnd: settings.webRtcUdpEnd,
voiceProfile: settings.voiceProfile ?? this.voiceIceDefaults.profile,
voiceTurnUrls: turn.urls.join("\n"),
hasVoiceTurnSecret: turn.secret.length > 0,
voiceTurnTtlSeconds: turn.ttlSeconds,
voiceOpusWs: settings.voiceOpusWs ?? this.voiceIceDefaults.opusWebSocket,
voiceJitterMaxMs: settings.voiceJitterMaxMs ?? this.voiceIceDefaults.jitterMaxMs,
relayConfigured: settings.relayConfigured,
relayEnabled: settings.relayEnabled,
relayName: settings.relayName,
@@ -166,6 +178,43 @@ export class AdminService {
};
}
/** Resolve environment defaults plus console overrides for every new voice connection. */
getVoiceIceConfig(): VoiceIceConfig {
const settings = this.database.getSettings();
const turn = this.resolveVoiceTurnSettings(settings);
const turnRest = turn.urls.length > 0 && turn.secret.length >= VOICE_TURN_MIN_SECRET_LENGTH
? { urls: turn.urls, secret: turn.secret, ttlSeconds: turn.ttlSeconds }
: undefined;
return {
servers: [...this.voiceIceDefaults.servers],
...(turnRest ? { turnRest } : {}),
transportPolicy: this.voiceIceDefaults.transportPolicy,
gatewayTransportPolicy: this.voiceIceDefaults.gatewayTransportPolicy,
profile: settings.voiceProfile ?? this.voiceIceDefaults.profile,
opusWebSocket: settings.voiceOpusWs ?? this.voiceIceDefaults.opusWebSocket,
jitterMaxMs: settings.voiceJitterMaxMs ?? this.voiceIceDefaults.jitterMaxMs,
};
}
private resolveVoiceTurnSettings(settings: ReturnType<WebSpeakDatabase["getSettings"]>): { urls: string[]; secret: string; ttlSeconds: number } {
const baseline = this.voiceIceDefaults.turnRest;
const urls = settings.voiceTurnUrls === null
? baseline?.urls ?? []
: normalizeVoiceTurnRestUrls(settings.voiceTurnUrls) ?? [];
const ttlSeconds = settings.voiceTurnTtlSeconds ?? baseline?.ttlSeconds ?? VOICE_TURN_TTL_DEFAULT_SECONDS;
let secret = "";
if (settings.voiceTurnSecretEncrypted === null) {
secret = baseline?.secret ?? "";
} else if (settings.voiceTurnSecretEncrypted !== "") {
try {
secret = decryptSecret(settings.voiceTurnSecretEncrypted, this.masterSecret, VOICE_TURN_SECRET_PURPOSE);
} catch (error: unknown) {
this.logger.error({ err: error instanceof Error ? error.message : String(error) }, "Stored TURN shared secret could not be decrypted");
}
}
return { urls, secret, ttlSeconds };
}
getAccelerationRelayOptions(): ConfiguredAccelerationRelay[] {
const relays: ConfiguredAccelerationRelay[] = [];
for (const node of this.database.listRelayNodes()) {
@@ -420,6 +469,60 @@ export class AdminService {
throw new AdminInputError("WEBRTC_PORT_LOCKED", "Disable WebRTC and save before changing its UDP port range");
}
const voiceProfile = input.voiceProfile === undefined ? current.voiceProfile : input.voiceProfile;
if (voiceProfile !== null && !isVoiceProfileSetting(voiceProfile)) {
throw new AdminInputError("INVALID_VOICE_PROFILE", "Voice profile must be auto, legacy or adaptive");
}
let voiceTurnUrls = current.voiceTurnUrls;
let requestedTurnUrls = current.voiceTurnUrls === null
? this.voiceIceDefaults.turnRest?.urls ?? []
: normalizeVoiceTurnRestUrls(current.voiceTurnUrls) ?? [];
if (input.voiceTurnUrls !== undefined) {
const normalized = normalizeVoiceTurnRestUrls(input.voiceTurnUrls);
if (normalized === null) throw new AdminInputError("INVALID_VOICE_TURN_URLS", "Use one turn:/turns: URL per entry, at most eight");
voiceTurnUrls = normalized.join("\n");
requestedTurnUrls = normalized;
}
let voiceTurnSecretEncrypted = current.voiceTurnSecretEncrypted;
const voiceTurnSecretAction = input.voiceTurnSecretAction ?? (input.voiceTurnSecret === undefined ? "keep" : "replace");
if (voiceTurnSecretAction === "remove") {
voiceTurnSecretEncrypted = "";
voiceTurnUrls = "";
requestedTurnUrls = [];
}
if (voiceTurnSecretAction === "replace") {
const secret = input.voiceTurnSecret?.trim() ?? "";
if (secret && secret.length < VOICE_TURN_MIN_SECRET_LENGTH) {
throw new AdminInputError("INVALID_VOICE_TURN_SECRET", `The TURN shared secret must contain at least ${VOICE_TURN_MIN_SECRET_LENGTH} characters`);
}
voiceTurnSecretEncrypted = secret ? encryptSecret(secret, this.masterSecret, VOICE_TURN_SECRET_PURPOSE) : "";
}
const voiceTurnTtlSeconds = input.voiceTurnTtlSeconds === undefined ? current.voiceTurnTtlSeconds : input.voiceTurnTtlSeconds;
if (voiceTurnTtlSeconds !== null && (!Number.isInteger(voiceTurnTtlSeconds) || voiceTurnTtlSeconds < VOICE_TURN_TTL_MIN_SECONDS || voiceTurnTtlSeconds > VOICE_TURN_TTL_MAX_SECONDS)) {
throw new AdminInputError("INVALID_VOICE_TURN_TTL", `TURN credential lifetime must be between ${VOICE_TURN_TTL_MIN_SECONDS} and ${VOICE_TURN_TTL_MAX_SECONDS} seconds`);
}
const voiceOpusWs = input.voiceOpusWs === undefined ? current.voiceOpusWs : input.voiceOpusWs;
if (voiceOpusWs !== null && typeof voiceOpusWs !== "boolean") {
throw new AdminInputError("INVALID_VOICE_OPUS", "Opus over WebSocket must be a boolean");
}
const voiceJitterMaxMs = input.voiceJitterMaxMs === undefined ? current.voiceJitterMaxMs : input.voiceJitterMaxMs;
if (voiceJitterMaxMs !== null && (!Number.isInteger(voiceJitterMaxMs) || voiceJitterMaxMs < VOICE_JITTER_MIN_MS || voiceJitterMaxMs > VOICE_JITTER_MAX_MS)) {
throw new AdminInputError("INVALID_VOICE_JITTER_MAX", `Adaptive jitter limit must be between ${VOICE_JITTER_MIN_MS} and ${VOICE_JITTER_MAX_MS} ms`);
}
let turnSecret = "";
if (voiceTurnSecretEncrypted === null) {
turnSecret = this.voiceIceDefaults.turnRest?.secret ?? "";
} else if (voiceTurnSecretEncrypted !== "") {
try {
turnSecret = decryptSecret(voiceTurnSecretEncrypted, this.masterSecret, VOICE_TURN_SECRET_PURPOSE);
} catch {
throw new AdminInputError("INVALID_VOICE_TURN_SECRET", "The stored TURN shared secret cannot be decrypted; enter it again");
}
}
if (requestedTurnUrls.length > 0 && turnSecret.length < VOICE_TURN_MIN_SECRET_LENGTH) {
throw new AdminInputError("INVALID_VOICE_TURN_SECRET", `Configure a TURN shared secret of at least ${VOICE_TURN_MIN_SECRET_LENGTH} characters for the TURN URLs`);
}
let encryptedPassword = current.tsPasswordEncrypted;
const action = input.passwordAction ?? (input.serverPassword === undefined ? "keep" : "replace");
if (action === "remove") encryptedPassword = null;
@@ -489,6 +592,12 @@ export class AdminService {
webRtcPublicHost, webRtcIpv6Enabled, webRtcStunServer,
webRtcUdpStart,
webRtcUdpEnd,
voiceProfile,
voiceTurnUrls,
voiceTurnSecretEncrypted,
voiceTurnTtlSeconds,
voiceOpusWs,
voiceJitterMaxMs,
relayConfigured,
relayEnabled,
relayName,
@@ -615,6 +724,12 @@ export class AdminService {
webRtcStunServer: settings.webRtcStunServer,
webRtcUdpStart: settings.webRtcUdpStart,
webRtcUdpEnd: settings.webRtcUdpEnd,
voiceProfile: settings.voiceProfile,
voiceTurnUrls: settings.voiceTurnUrls,
voiceTurnSecretEncrypted: settings.voiceTurnSecretEncrypted,
voiceTurnTtlSeconds: settings.voiceTurnTtlSeconds,
voiceOpusWs: settings.voiceOpusWs,
voiceJitterMaxMs: settings.voiceJitterMaxMs,
relayConfigured: settings.relayConfigured,
relayEnabled: settings.relayEnabled,
relayName: settings.relayName,
@@ -647,6 +762,12 @@ export class AdminService {
webRtcStunServer: current.webRtcStunServer,
webRtcUdpStart: current.webRtcUdpStart,
webRtcUdpEnd: current.webRtcUdpEnd,
voiceProfile: current.voiceProfile,
voiceTurnUrls: current.voiceTurnUrls,
voiceTurnSecretEncrypted: current.voiceTurnSecretEncrypted,
voiceTurnTtlSeconds: current.voiceTurnTtlSeconds,
voiceOpusWs: current.voiceOpusWs,
voiceJitterMaxMs: current.voiceJitterMaxMs,
relayConfigured: current.relayConfigured,
relayEnabled: current.relayEnabled,
relayName: current.relayName,
+7
View File
@@ -3,6 +3,7 @@ import { existsSync, readFileSync, unlinkSync } from "node:fs";
import { fileURLToPath } from "node:url";
import { createAccelerationRelayServer } from "./server/acceleration-relay.js";
import { normalizeScreenShareIceServers, type ScreenShareIceServer } from "./server/screen-share.js";
import { readVoiceIceConfig } from "./server/voice-ice-config.js";
import { SkinRegistry } from "./admin/skin-registry.js";
import { PluginRegistry } from "./plugins/registry.js";
import { UpdateService } from "./updater/update-service.js";
@@ -18,6 +19,7 @@ const LOG_DIR = path.join(DATA_DIR, "logs");
const STATIC_DIR = path.join(ROOT_DIR, "web", "dist");
const APP_VERSION = readPackageVersion();
const SCREEN_SHARE_ICE_SERVERS = readScreenShareIceServers(process.env.WEBSPEAK_SCREEN_SHARE_ICE_SERVERS);
const VOICE_ICE_CONFIG = readVoiceIceConfig(process.env);
async function main() {
if (process.env.WEBSPEAK_MODE?.trim().toLowerCase() === "relay") {
@@ -43,6 +45,8 @@ async function main() {
CONFIG_PATH,
undefined,
APP_VERSION,
undefined,
VOICE_ICE_CONFIG,
);
await adminService.initialize();
removeObsoleteBootstrapFile();
@@ -93,6 +97,8 @@ async function main() {
joinTickets,
trustedProxies: readTrustedProxies(process.env.WEBSPEAK_TRUSTED_PROXIES),
webRtc: () => adminService.getWebRtcAudioOptions(),
// Read per new connection so console changes apply without a process restart.
voiceIce: () => adminService.getVoiceIceConfig(),
screenShareIceServers: () => SCREEN_SHARE_ICE_SERVERS,
// The public gateway only uses the relay configuration explicitly
// saved in the admin console. Environment variables belong to the
@@ -163,6 +169,7 @@ async function runRelayMode(): Promise<void> {
: {}),
udpPortRange: [webRtcUdpStart, webRtcUdpEnd] as [number, number],
},
voiceIce: VOICE_ICE_CONFIG,
screenShareIceServers: SCREEN_SHARE_ICE_SERVERS,
trustedProxies: readTrustedProxies(process.env.WEBSPEAK_TRUSTED_PROXIES),
});
+3 -3
View File
@@ -15,7 +15,7 @@ test("relay voice endpoint is stored by the current database migration", (contex
rmSync(directory, { recursive: true, force: true });
});
assert.equal(DATABASE_SCHEMA_VERSION, 13);
assert.equal(DATABASE_SCHEMA_VERSION, 14);
assert.equal(database.schemaVersion, DATABASE_SCHEMA_VERSION);
assert.equal(database.getTsAdminSettings().transport, "web");
assert.equal(database.getTsAdminSettings().enabled, false);
@@ -38,13 +38,13 @@ test("schema 11 migration preserves encrypted SSH credentials and does not silen
const original = new WebSpeakDatabase(filename);
original.close();
const old = new DatabaseSync(filename);
old.exec("ALTER TABLE ts_admin_settings DROP COLUMN transport; ALTER TABLE ts_admin_settings DROP COLUMN query_host; ALTER TABLE ts_admin_settings DROP COLUMN web_query_url; ALTER TABLE ts_admin_settings DROP COLUMN api_key_encrypted; ALTER TABLE ts_admin_settings DROP COLUMN server_id; DROP TABLE workspace_invites; PRAGMA user_version = 11;");
old.exec("ALTER TABLE ts_admin_settings DROP COLUMN transport; ALTER TABLE ts_admin_settings DROP COLUMN query_host; ALTER TABLE ts_admin_settings DROP COLUMN web_query_url; ALTER TABLE ts_admin_settings DROP COLUMN api_key_encrypted; ALTER TABLE ts_admin_settings DROP COLUMN server_id; DROP TABLE workspace_invites; ALTER TABLE settings DROP COLUMN voice_profile; ALTER TABLE settings DROP COLUMN voice_turn_urls; ALTER TABLE settings DROP COLUMN voice_turn_secret_encrypted; ALTER TABLE settings DROP COLUMN voice_turn_ttl_seconds; ALTER TABLE settings DROP COLUMN voice_opus_ws; ALTER TABLE settings DROP COLUMN voice_jitter_max_ms; PRAGMA user_version = 11;");
old.prepare("UPDATE ts_admin_settings SET enabled=1, query_port=10222, username='query-owner', password_encrypted=?, host_key_fingerprint=?").run(encrypted, `SHA256:${"A".repeat(43)}`);
old.close();
const migrated = new WebSpeakDatabase(filename);
t.after(() => { migrated.close(); rmSync(directory, { recursive: true, force: true }); });
const settings = migrated.getTsAdminSettings();
assert.equal(migrated.schemaVersion, 13);
assert.equal(migrated.schemaVersion, 14);
assert.equal(settings.transport, "ssh"); assert.equal(settings.enabled, true);
assert.equal(settings.queryPort, 10222); assert.equal(settings.username, "query-owner");
assert.equal(settings.passwordEncrypted, encrypted);
+52 -2
View File
@@ -5,8 +5,9 @@ import { DatabaseSync } from "node:sqlite";
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";
import type { VoiceProfileSetting } from "../shared/voice-profile.js";
export const DATABASE_SCHEMA_VERSION = 13;
export const DATABASE_SCHEMA_VERSION = 14;
export type AccessMode = "fixed" | "open";
export interface PersistedSettings {
@@ -31,6 +32,13 @@ export interface PersistedSettings {
webRtcStunServer: string;
webRtcUdpStart: number;
webRtcUdpEnd: number;
/** Console-owned overrides; null inherits the environment baseline. */
voiceProfile: VoiceProfileSetting | null;
voiceTurnUrls: string | null;
voiceTurnSecretEncrypted: string | null;
voiceTurnTtlSeconds: number | null;
voiceOpusWs: boolean | null;
voiceJitterMaxMs: number | null;
relayConfigured: boolean;
relayEnabled: boolean;
relayName: string;
@@ -58,6 +66,12 @@ export interface SettingsUpdate {
webRtcStunServer?: string;
webRtcUdpStart?: number;
webRtcUdpEnd?: number;
voiceProfile?: VoiceProfileSetting | null;
voiceTurnUrls?: string | null;
voiceTurnSecretEncrypted?: string | null;
voiceTurnTtlSeconds?: number | null;
voiceOpusWs?: boolean | null;
voiceJitterMaxMs?: number | null;
relayConfigured: boolean;
relayEnabled: boolean;
relayName: string;
@@ -144,6 +158,12 @@ interface SettingsRow extends Record<string, unknown> {
webrtc_stun_server: string;
webrtc_udp_start: number;
webrtc_udp_end: number;
voice_profile: string | null;
voice_turn_urls: string | null;
voice_turn_secret_encrypted: string | null;
voice_turn_ttl_seconds: number | null;
voice_opus_ws: number | null;
voice_jitter_max_ms: number | null;
relay_configured: number;
relay_enabled: number;
relay_name: string;
@@ -269,6 +289,12 @@ export class WebSpeakDatabase {
webRtcStunServer: row.webrtc_stun_server,
webRtcUdpStart: row.webrtc_udp_start,
webRtcUdpEnd: row.webrtc_udp_end,
voiceProfile: row.voice_profile === "legacy" || row.voice_profile === "adaptive" || row.voice_profile === "auto" ? row.voice_profile : null,
voiceTurnUrls: row.voice_turn_urls,
voiceTurnSecretEncrypted: row.voice_turn_secret_encrypted,
voiceTurnTtlSeconds: row.voice_turn_ttl_seconds,
voiceOpusWs: row.voice_opus_ws === null ? null : row.voice_opus_ws === 1,
voiceJitterMaxMs: row.voice_jitter_max_ms,
relayConfigured: row.relay_configured === 1,
relayEnabled: row.relay_enabled === 1,
relayName: row.relay_name,
@@ -754,6 +780,23 @@ export class WebSpeakDatabase {
); CREATE INDEX workspace_invites_expiry ON workspace_invites(expires_at);
PRAGMA user_version = 13;`);
});
version = 13;
}
if (version === 13) {
this.transaction(() => {
this.database.exec(`
-- Console-managed voice deployment overrides. NULL keeps the
-- environment baseline; an empty TURN URL or secret explicitly
-- disables the corresponding environment value.
ALTER TABLE settings ADD COLUMN voice_profile TEXT CHECK (voice_profile IS NULL OR voice_profile IN ('auto', 'legacy', 'adaptive'));
ALTER TABLE settings ADD COLUMN voice_turn_urls TEXT;
ALTER TABLE settings ADD COLUMN voice_turn_secret_encrypted TEXT;
ALTER TABLE settings ADD COLUMN voice_turn_ttl_seconds INTEGER CHECK (voice_turn_ttl_seconds IS NULL OR voice_turn_ttl_seconds BETWEEN 300 AND 86400);
ALTER TABLE settings ADD COLUMN voice_opus_ws INTEGER CHECK (voice_opus_ws IS NULL OR voice_opus_ws IN (0, 1));
ALTER TABLE settings ADD COLUMN voice_jitter_max_ms INTEGER CHECK (voice_jitter_max_ms IS NULL OR voice_jitter_max_ms BETWEEN 80 AND 500);
PRAGMA user_version = 14;
`);
});
}
}
@@ -762,7 +805,8 @@ export class WebSpeakDatabase {
`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_target = ?,
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 = ?,
webrtc_udp_end = ?, voice_profile = ?, voice_turn_urls = ?, voice_turn_secret_encrypted = ?, voice_turn_ttl_seconds = ?, voice_opus_ws = ?, voice_jitter_max_ms = ?,
relay_configured = ?, relay_enabled = ?, relay_name = ?,
relay_host = ?, relay_port = ?, relay_token_encrypted = ?, updated_at = ?
WHERE id = 1`,
).run(
@@ -783,6 +827,12 @@ export class WebSpeakDatabase {
settings.webRtcStunServer ?? "",
settings.webRtcUdpStart ?? DEFAULT_WEBRTC_UDP_PORT_RANGE[0],
settings.webRtcUdpEnd ?? DEFAULT_WEBRTC_UDP_PORT_RANGE[1],
settings.voiceProfile ?? null,
settings.voiceTurnUrls ?? null,
settings.voiceTurnSecretEncrypted ?? null,
settings.voiceTurnTtlSeconds ?? null,
settings.voiceOpusWs == null ? null : settings.voiceOpusWs ? 1 : 0,
settings.voiceJitterMaxMs ?? null,
settings.relayConfigured ? 1 : 0,
settings.relayEnabled ? 1 : 0,
settings.relayName,
+73
View File
@@ -0,0 +1,73 @@
import assert from "node:assert/strict";
import { test } from "node:test";
import { AudioPacer } from "./audio-pacer.js";
function fakeClock() {
let now = 0;
let nextId = 1;
let task: { id: number; at: number; callback: () => void } | null = null;
const schedule = (callback: () => void, delayMs: number) => {
task = { id: nextId++, at: now + delayMs, callback };
return task as unknown as ReturnType<typeof setTimeout>;
};
const cancel = (handle: ReturnType<typeof setTimeout>) => {
if (task && task.id === (handle as unknown as { id: number }).id) task = null;
};
const runNext = () => {
assert.ok(task, "expected a scheduled tick");
now = Math.max(now, task.at);
const callback = task.callback;
task = null;
callback();
};
return { now: () => now, setNow: (value: number) => { now = value; }, schedule, cancel, runNext, hasTask: () => task !== null };
}
test("pacer emits one frame every 20 ms and preserves order", () => {
const clock = fakeClock();
const sent: number[] = [];
const pacer = new AudioPacer((_data, codec) => sent.push(codec), {
now: clock.now, schedule: clock.schedule, cancel: clock.cancel, maxFrames: 4,
});
pacer.push(Buffer.from([1]), 1);
pacer.push(Buffer.from([2]), 2);
pacer.push(Buffer.from([3]), 3);
assert.equal(sent.length, 0, "frames wait for the first timer turn");
clock.runNext();
assert.deepEqual(sent, [1]);
assert.equal(pacer.getStats().currentFrames, 2);
clock.runNext();
assert.deepEqual(sent, [1, 2]);
clock.runNext();
assert.deepEqual(sent, [1, 2, 3]);
assert.equal(pacer.getStats().currentFrames, 0);
assert.equal(clock.hasTask(), false);
});
test("pacer drops the oldest frame when the queue is full and records peak", () => {
const clock = fakeClock();
const pacer = new AudioPacer(() => {}, { now: clock.now, schedule: clock.schedule, cancel: clock.cancel, maxFrames: 2 });
pacer.push(Buffer.from([1]), 1);
pacer.push(Buffer.from([2]), 2);
pacer.push(Buffer.from([3]), 3);
const stats = pacer.getStats();
assert.equal(stats.currentFrames, 2);
assert.equal(stats.peakFrames, 2);
assert.equal(stats.droppedFrames, 1);
pacer.close();
});
test("a late event-loop turn resets the deadline instead of bursting", () => {
const clock = fakeClock();
const sent: number[] = [];
const pacer = new AudioPacer(() => sent.push(1), {
now: clock.now, schedule: clock.schedule, cancel: clock.cancel, maxFrames: 4,
});
pacer.push(Buffer.from([1]), 1);
pacer.push(Buffer.from([2]), 2);
clock.setNow(100);
clock.runNext();
assert.equal(sent.length, 1);
assert.equal(pacer.getStats().lateTicks, 1);
pacer.close();
});
+138
View File
@@ -0,0 +1,138 @@
import { performance } from "node:perf_hooks";
/**
* A tiny 20 ms sender for browser PCM/Opus uplink. Cloudflare Tunnel can
* deliver a burst of WebSocket frames at once; forwarding those frames to
* TeamSpeak immediately preserves the burst and makes the receiving client's
* jitter buffer work harder. This pacer absorbs the burst and emits at a fixed
* cadence, dropping the oldest frame only when the queue is genuinely behind.
*/
export interface PacerFrame {
data: Buffer;
codec: number;
enqueuedAt: number;
}
export interface AudioPacerOptions {
frameMs?: number;
maxFrames?: number;
maxLagMs?: number;
now?: () => number;
schedule?: (callback: () => void, delayMs: number) => ReturnType<typeof setTimeout>;
cancel?: (timer: ReturnType<typeof setTimeout>) => void;
onStats?: (stats: AudioPacerStats) => void;
}
export interface AudioPacerStats {
currentFrames: number;
peakFrames: number;
droppedFrames: number;
lateTicks: number;
sentFrames: number;
}
export class AudioPacer {
private readonly frameMs: number;
private readonly maxFrames: number;
private readonly maxLagMs: number;
private readonly now: () => number;
private readonly schedule: NonNullable<AudioPacerOptions["schedule"]>;
private readonly cancel: NonNullable<AudioPacerOptions["cancel"]>;
private readonly onStats: AudioPacerOptions["onStats"];
private readonly queue: PacerFrame[] = [];
private timer: ReturnType<typeof setTimeout> | null = null;
private nextAt: number | null = null;
private closed = false;
private droppedFrames = 0;
private lateTicks = 0;
private sentFrames = 0;
private peakFrames = 0;
constructor(
private readonly send: (data: Buffer, codec: number) => void,
options: AudioPacerOptions = {},
) {
this.frameMs = Math.max(1, options.frameMs ?? 20);
this.maxFrames = Math.max(1, options.maxFrames ?? 6);
this.maxLagMs = Math.max(0, options.maxLagMs ?? 40);
this.now = options.now ?? (() => performance.now());
this.schedule = options.schedule ?? ((callback, delayMs) => setTimeout(callback, delayMs));
this.cancel = options.cancel ?? ((handle) => clearTimeout(handle));
this.onStats = options.onStats;
}
push(data: Buffer, codec: number): boolean {
if (this.closed || !data.length) return false;
while (this.queue.length >= this.maxFrames) {
this.queue.shift();
this.droppedFrames++;
}
this.queue.push({ data, codec, enqueuedAt: this.now() });
this.peakFrames = Math.max(this.peakFrames, this.queue.length);
if (!this.timer) {
this.nextAt = this.now();
this.arm(0);
}
this.emitStats();
return true;
}
private arm(delayMs: number): void {
this.timer = this.schedule(() => this.tick(), Math.max(0, delayMs));
// Do not keep the Node process alive solely for an idle voice pacer.
(this.timer as unknown as { unref?: () => void }).unref?.();
}
private tick(): void {
this.timer = null;
if (this.closed) return;
if (!this.queue.length) {
this.nextAt = null;
return;
}
const now = this.now();
if (this.nextAt !== null && now - this.nextAt > this.maxLagMs) {
// A late event loop turn must not create a catch-up burst. Drop the
// accumulated backlog of time and emit one frame from the current time.
this.lateTicks++;
this.nextAt = now;
}
const frame = this.queue.shift()!;
try { this.send(frame.data, frame.codec); } catch { /* sendVoice reports its own failure */ }
this.sentFrames++;
if (this.queue.length) {
this.nextAt = this.nextAt === null ? now + this.frameMs : this.nextAt + this.frameMs;
if (this.nextAt < now + 1) this.nextAt = now + this.frameMs;
this.arm(this.nextAt - now);
} else {
this.nextAt = null;
}
this.emitStats();
}
private emitStats(): void {
this.onStats?.(this.getStats());
}
getStats(): AudioPacerStats {
return {
currentFrames: this.queue.length,
peakFrames: this.peakFrames,
droppedFrames: this.droppedFrames,
lateTicks: this.lateTicks,
sentFrames: this.sentFrames,
};
}
close(): void {
this.closed = true;
if (this.timer) {
this.cancel(this.timer);
this.timer = null;
}
this.queue.length = 0;
this.nextAt = null;
this.emitStats();
}
}
+17
View File
@@ -3,6 +3,8 @@ import type { WebRtcAudioSession, WebRtcAudioStats } from "./webrtc-audio.js";
export interface AudioFlowStats extends WebRtcAudioStats {
ingressFrames: number;
ingressPcmFrames: number;
ingressOpusFrames: number;
ingressDroppedFrames: number;
ingressFirstAt: number | null;
ingressLastAt: number | null;
@@ -13,6 +15,10 @@ export interface AudioFlowStats extends WebRtcAudioStats {
tsSendLastAt: number | null;
tsSendMaxGapMs: number;
tsEncodeMaxMs: number;
uplinkQueueCurrentFrames: number;
uplinkQueuePeakFrames: number;
uplinkQueueDroppedFrames: number;
uplinkPacerLateTicks: number;
tsReceiveFrames: number;
tsReceiveFirstAt: number | null;
tsReceiveLastAt: number | null;
@@ -38,6 +44,8 @@ export interface AudioStatsSource {
export function createAudioFlowStats(): AudioFlowStats {
return {
ingressFrames: 0,
ingressPcmFrames: 0,
ingressOpusFrames: 0,
ingressDroppedFrames: 0,
ingressFirstAt: null,
ingressLastAt: null,
@@ -48,6 +56,10 @@ export function createAudioFlowStats(): AudioFlowStats {
tsSendLastAt: null,
tsSendMaxGapMs: 0,
tsEncodeMaxMs: 0,
uplinkQueueCurrentFrames: 0,
uplinkQueuePeakFrames: 0,
uplinkQueueDroppedFrames: 0,
uplinkPacerLateTicks: 0,
tsReceiveFrames: 0,
tsReceiveFirstAt: null,
tsReceiveLastAt: null,
@@ -95,11 +107,16 @@ export function snapshotAudioStatus(entry: AudioStatsSource): VoiceAudioBridgeSt
return {
transport: entry.webrtc ? "webrtc" : "websocket",
ingressFrames: stats.ingressFrames,
ingressPcmFrames: stats.ingressPcmFrames,
ingressOpusFrames: stats.ingressOpusFrames,
ingressDroppedFrames: stats.ingressDroppedFrames,
ingressMaxGapMs: stats.ingressMaxGapMs,
tsSendFrames: stats.tsSendFrames,
tsSendErrors: stats.tsSendErrors,
tsSendMaxGapMs: stats.tsSendMaxGapMs,
uplinkQueuePeakFrames: stats.uplinkQueuePeakFrames,
uplinkQueueDroppedFrames: stats.uplinkQueueDroppedFrames,
uplinkPacerLateTicks: stats.uplinkPacerLateTicks,
tsReceiveFrames: stats.tsReceiveFrames,
tsReceiveMaxGapMs: stats.tsReceiveMaxGapMs,
egressFrames: stats.egressFrames,
+16 -3
View File
@@ -34,7 +34,7 @@ function fixture() {
const transport = new SessionAudioTransport({
audio, socket, client, logger, isCurrent: () => state.current, isReady: () => state.ready,
selfId: () => 1, peer: () => state.peer, whisperTargets: () => state.targets,
sendJson: message => { notices.push(message); },
sendJson: message => { notices.push(message); }, pacing: false,
}, encoder, () => state.now, () => state.now);
const remote = (clientId = 513) => ({ clientId, codec: 4, data: Buffer.from([11, 12, 13]) });
return { transport, audio, state, socket, client, encoder, packets, encoded, forwarded, notices, warnings, remote };
@@ -117,8 +117,8 @@ test("repeated malformed frames are counted in full but reported once per window
assert.equal(f.audio.ingressDroppedFrames, 4, "every discarded frame still reaches the flow counters");
assert.equal(f.notices.length, 2, "the browser sees one error per window, not one per frame");
assert.deepEqual(f.warnings, [
{ code: "INVALID_AUDIO_FRAME", frameBytes: 1_919, expectedBytes: 1_920, droppedFrames: 1 },
{ code: "INVALID_AUDIO_FRAME", frameBytes: 1_919, expectedBytes: 1_920, droppedFrames: 4 },
{ code: "INVALID_AUDIO_FRAME", frameBytes: 1_919, expectedBytes: "1920 or tagged", droppedFrames: 1 },
{ code: "INVALID_AUDIO_FRAME", frameBytes: 1_919, expectedBytes: "1920 or tagged", droppedFrames: 4 },
], "operators get the same rate-limited view through the logger");
});
@@ -131,6 +131,19 @@ test("an encoder failure and a malformed frame do not suppress each other", t =>
t.mock.restoreAll();
});
test("tagged PCM and pre-encoded Opus frames share the uplink without double encoding", () => {
const f = fixture();
f.transport.receivePcm(Buffer.concat([Buffer.from([1]), Buffer.alloc(1_920)]));
f.transport.receivePcm(Buffer.concat([Buffer.from([2]), Buffer.from([1, 2, 3])]));
assert.equal(f.encoded.length, 1);
assert.equal(f.audio.ingressPcmFrames, 1);
assert.equal(f.audio.ingressOpusFrames, 1);
assert.deepEqual(f.forwarded.map(({ data, codec }) => ({ data: [...data], codec })), [
{ data: [9, 8, 7], codec: 4 },
{ data: [1, 2, 3], codec: 4 },
]);
});
test("WebRTC ingress excludes queued PCM and fallback re-enables PCM", () => {
const f = fixture();
f.state.peer = { pushTeamSpeakVoice() {} };
+47 -6
View File
@@ -5,8 +5,19 @@ import type { ServerMessage } from "../shared/server-messages.js";
import type { AudioFlowStats } from "./audio-stats.js";
import type { TSClient, TSVoiceData } from "./ts-client.js";
import type { WebRtcAudioSession } from "./webrtc-audio.js";
import { AudioPacer } from "./audio-pacer.js";
import {
VOICE_MAX_OPUS_FRAME_BYTES,
VOICE_OPUS_TAG,
VOICE_PCM_FRAME_BYTES,
VOICE_PCM_TAG,
} from "../shared/voice-audio.js";
const AUDIO_FRAME_BYTES = 1_920; // 20 ms of 48 kHz mono Int16 PCM.
const AUDIO_FRAME_BYTES = VOICE_PCM_FRAME_BYTES;
const TAGGED_PCM_FRAME_BYTES = AUDIO_FRAME_BYTES + 1;
const PCM_FRAME_TAG = VOICE_PCM_TAG;
const OPUS_FRAME_TAG = VOICE_OPUS_TAG;
const MAX_OPUS_FRAME_BYTES = VOICE_MAX_OPUS_FRAME_BYTES;
// Keep the established byte guard; the browser also bounds playback by time.
const MAX_BUFFERED_BYTES = 4_096;
// A client that keeps sending bad audio must not turn into one JSON error per
@@ -33,6 +44,8 @@ export interface SessionAudioOptions {
peer(): Pick<WebRtcAudioSession, "pushTeamSpeakVoice"> | null;
whisperTargets(): readonly number[] | null;
sendJson(message: ServerMessage): void;
/** Tests that assert synchronous SDK calls can opt out; production keeps pacing. */
pacing?: boolean;
}
/** A session owns one encoder and one active audio route in each direction. */
@@ -42,6 +55,7 @@ export class SessionAudioTransport {
/** Last report time per audio fault code; see `shouldReportAudioIssue`. */
private readonly reportedAt = new Map<string, number>();
private readonly logger: LoggerType | null;
private readonly pacer: AudioPacer | null;
private pcmTokens = PCM_BURST_FRAMES;
private pcmRefilledAt: number | null = null;
@@ -49,6 +63,18 @@ export class SessionAudioTransport {
private readonly rateClock: () => number = performance.now.bind(performance)) {
this.encoder = encoder;
this.logger = options.logger ?? null;
this.pacer = options.pacing === false ? null : new AudioPacer(
(data, codec) => this.sendVoice(data, codec),
{
now: this.rateClock,
onStats: stats => {
options.audio.uplinkQueueCurrentFrames = stats.currentFrames;
options.audio.uplinkQueuePeakFrames = Math.max(options.audio.uplinkQueuePeakFrames, stats.peakFrames);
options.audio.uplinkQueueDroppedFrames = stats.droppedFrames;
options.audio.uplinkPacerLateTicks = stats.lateTicks;
},
},
);
}
private isCurrent(): boolean {
@@ -112,7 +138,7 @@ export class SessionAudioTransport {
// logged anywhere, so without this an operator has no way to notice a client
// that keeps sending malformed audio until the session is torn down.
this.logger?.warn(
{ code: "INVALID_AUDIO_FRAME", frameBytes: length, expectedBytes: AUDIO_FRAME_BYTES, droppedFrames: this.options.audio.ingressDroppedFrames },
{ code: "INVALID_AUDIO_FRAME", frameBytes: length, expectedBytes: `${AUDIO_FRAME_BYTES} or tagged`, droppedFrames: this.options.audio.ingressDroppedFrames },
"Discarded malformed browser audio frame",
);
try {
@@ -128,7 +154,11 @@ export class SessionAudioTransport {
// misattribute the drop and raise a spurious client error in the browser.
// Late TCP frames from before a WebRTC switch must not duplicate RTP audio.
if (!this.options.isReady() || this.options.peer()) { stats.ingressDroppedFrames++; return; }
if (frame.length !== AUDIO_FRAME_BYTES) {
const legacyPcm = frame.length === AUDIO_FRAME_BYTES ? frame : null;
const taggedPcm = frame.length === TAGGED_PCM_FRAME_BYTES && frame[0] === PCM_FRAME_TAG ? frame.subarray(1) : null;
const opus = frame.length > 1 && frame.length <= MAX_OPUS_FRAME_BYTES + 1 && frame[0] === OPUS_FRAME_TAG
? frame.subarray(1) : null;
if (!legacyPcm && !taggedPcm && !opus) {
stats.ingressDroppedFrames++;
this.reportInvalidFrame(frame.length);
return;
@@ -141,17 +171,26 @@ export class SessionAudioTransport {
if (this.pcmTokens < 1) {
stats.ingressDroppedFrames++;
if (this.shouldReportAudioIssue("AUDIO_RATE_EXCEEDED")) {
this.logger?.warn({ code: "AUDIO_RATE_EXCEEDED", droppedFrames: stats.ingressDroppedFrames }, "Discarded browser PCM above the real-time budget");
this.logger?.warn({ code: "AUDIO_RATE_EXCEEDED", droppedFrames: stats.ingressDroppedFrames }, "Discarded browser audio above the real-time budget");
}
return;
}
this.pcmTokens--;
this.recordIngress();
if (opus) {
stats.ingressOpusFrames++;
// The pacer absorbs Cloudflare's bursty WebSocket delivery. Opus is
// already encoded, so this costs one buffer copy and no CPU-heavy encode.
if (this.pacer) this.pacer.push(opus, 4);
else this.sendVoice(opus, 4);
return;
}
stats.ingressPcmFrames++;
const startedAt = this.clock();
let encoded: Buffer;
try {
if (!this.encoder) throw new Error("Encoder unavailable");
encoded = this.encoder.encode(frame);
encoded = this.encoder.encode(taggedPcm ?? legacyPcm!);
stats.tsEncodeMaxMs = Math.max(stats.tsEncodeMaxMs, this.clock() - startedAt);
} catch {
stats.tsSendErrors++;
@@ -159,7 +198,8 @@ export class SessionAudioTransport {
this.reportEncoderFailure();
return;
}
this.sendVoice(encoded, 4);
this.pacer?.push(encoded, 4);
if (!this.pacer) this.sendVoice(encoded, 4);
}
receiveWebRtc(data: Buffer, codec: number): void {
@@ -214,6 +254,7 @@ export class SessionAudioTransport {
if (this.closed) return;
this.closed = true;
this.reportedAt.clear();
this.pacer?.close();
const encoder = this.encoder;
this.encoder = null;
try { encoder?.dispose(); } catch { /* other session resources must still be released */ }
@@ -131,11 +131,11 @@ test("schema 8 settings and invites survive the nickname migration", async (cont
});
database.close();
const legacy = new DatabaseSync(file);
legacy.exec("DROP TABLE ts_admin_settings; ALTER TABLE relay_nodes DROP COLUMN voice_endpoint; ALTER TABLE settings DROP COLUMN ts_target; ALTER TABLE managed_invites DROP COLUMN target_text; DROP TABLE workspace_invites; PRAGMA user_version = 8;");
legacy.exec("DROP TABLE ts_admin_settings; ALTER TABLE relay_nodes DROP COLUMN voice_endpoint; ALTER TABLE settings DROP COLUMN ts_target; ALTER TABLE managed_invites DROP COLUMN target_text; DROP TABLE workspace_invites; ALTER TABLE settings DROP COLUMN voice_profile; ALTER TABLE settings DROP COLUMN voice_turn_urls; ALTER TABLE settings DROP COLUMN voice_turn_secret_encrypted; ALTER TABLE settings DROP COLUMN voice_turn_ttl_seconds; ALTER TABLE settings DROP COLUMN voice_opus_ws; ALTER TABLE settings DROP COLUMN voice_jitter_max_ms; PRAGMA user_version = 8;");
legacy.close();
const migrated = new WebSpeakDatabase(file);
try {
assert.equal(migrated.schemaVersion, 13);
assert.equal(migrated.schemaVersion, 14);
assert.equal(migrated.getSettings().tsHost, "127.0.0.1");
assert.equal(migrated.getSettings().tsTarget, null);
const invite = migrated.consumeManagedInvite("legacy-token");
+25
View File
@@ -0,0 +1,25 @@
import assert from "node:assert/strict";
import { test } from "node:test";
import { createHmac } from "node:crypto";
import { createTurnRestCredential, createTurnRestUsername } from "./turn-credentials.js";
test("TURN REST username and credential match coturn's HMAC contract", () => {
const secret = "a-test-secret-with-enough-length";
const config = { urls: ["turns:turn.example.com:443?transport=tcp"], secret, ttlSeconds: 3_600 };
const now = 1_700_000_000_000;
const credential = createTurnRestCredential(config, "session-1", now);
const expiry = Math.floor(now / 1_000) + 3_600;
const username = createTurnRestUsername(expiry, "session-1");
assert.equal(credential.username, username);
assert.equal(credential.credential, createHmac("sha1", secret).update(username).digest("base64"));
});
test("TURN REST session ids are sanitized and expiry stays in the future", () => {
const credential = createTurnRestCredential(
{ urls: ["turn:turn.example.com:3478?transport=udp"], secret: "another-long-test-secret", ttlSeconds: 300 },
"bad session:id!",
1_000,
);
assert.match(credential.username!, /^[0-9]+:badsessionid/);
assert.equal(credential.credential?.length, 28);
});
+36
View File
@@ -0,0 +1,36 @@
import { createHmac, randomBytes } from "node:crypto";
import type { VoiceIceServer } from "../shared/voice-ice.js";
export interface TurnRestConfig {
urls: string[];
secret: string;
ttlSeconds: number;
}
/**
* coturn's `use-auth-secret` REST API:
* username = "<expiry unix seconds>:<session id>"
* credential = base64(HMAC-SHA1(secret, username))
*
* Credentials are minted per browser connection; they are not shared between
* sessions and never need to be persisted.
*/
export function createTurnRestCredential(
config: TurnRestConfig,
sessionId: string,
nowMs = Date.now(),
): VoiceIceServer {
const suffix = sessionId.replace(/[^A-Za-z0-9_-]/g, "").slice(0, 64) || randomBytes(8).toString("hex");
const expiry = Math.floor(nowMs / 1_000) + Math.max(1, Math.trunc(config.ttlSeconds));
const username = `${expiry}:${suffix}`;
const credential = createHmac("sha1", config.secret).update(username).digest("base64");
return {
urls: config.urls.length === 1 ? config.urls[0]! : [...config.urls],
username,
credential,
};
}
export function createTurnRestUsername(expirySeconds: number, sessionId: string): string {
return `${Math.trunc(expirySeconds)}:${sessionId}`;
}
+114 -3
View File
@@ -11,7 +11,8 @@ import { OpusEncoder } from "./opus-codec.js";
import { normalizeTeamSpeakKickedReason } from "../errors.js";
import type { TSClient, TSClientAvatar, TSDirectorySnapshot } from "./ts-client.js";
import type { AudioFlowStats } from "./audio-stats.js";
import type { WebRtcAudioSession } from "./webrtc-audio.js";
import type { WebRtcAudioSession, WebRtcAudioOptions } from "./webrtc-audio.js";
import type { VoiceBridgeOptions } from "./voice-bridge.js";
// Real loopback HTTP/WebSocket and native codec, with only the external SDK
// replaced. This validates gateway wiring, not a connection to TeamSpeak.
@@ -52,11 +53,19 @@ async function fixture(t: TestContext, overrides: {
waitForFirstMessage?: boolean;
createWorkspaceInvite?: import("./voice-bridge.js").VoiceBridgeOptions["createWorkspaceInvite"];
connection?: Partial<import("./join-ticket.js").JoinTicketPayload>;
webRtc?: WebRtcAudioOptions;
voiceIce?: VoiceBridgeOptions["voiceIce"];
headers?: Record<string, string>;
} = {}) {
const sdk = new TeamSpeakStub();
overrides.configureSdk?.(sdk);
const tickets = new JoinTicketStore();
const bridge = new VoiceBridge({ joinTickets: tickets, createWorkspaceInvite: overrides.createWorkspaceInvite }, pino({ enabled: false }), undefined, {
const bridge = new VoiceBridge({
joinTickets: tickets,
createWorkspaceInvite: overrides.createWorkspaceInvite,
...(overrides.webRtc ? { webRtc: overrides.webRtc } : {}),
...(overrides.voiceIce ? { voiceIce: overrides.voiceIce } : {}),
}, pino({ enabled: false }), undefined, {
createTeamSpeakClient: overrides.createTeamSpeakClient ?? (() => sdk as unknown as TSClient),
...(overrides.createEncoder ? { createEncoder: overrides.createEncoder } : {}),
});
@@ -68,7 +77,7 @@ async function fixture(t: TestContext, overrides: {
const address = server.address();
assert.ok(address && typeof address !== "string");
const ticket = tickets.create({ target: { host: "voice.example.invalid", port: 9987 }, nickname: "Test", serverPassword: "", ...overrides.connection });
const socket = new WebSocket(`ws://127.0.0.1:${address.port}/ws/voice?ticket=${ticket}`);
const socket = new WebSocket(`ws://127.0.0.1:${address.port}/ws/voice?ticket=${ticket}`, overrides.headers ? { headers: overrides.headers } : undefined);
const messages: Array<{ data: Buffer; binary: boolean }> = [];
socket.on("message", (data, binary) => messages.push({ data: data as Buffer, binary }));
const first = once(socket, "message");
@@ -107,6 +116,18 @@ function waitForMessage<T extends Record<string, unknown>>(socket: WebSocket, ty
});
}
async function waitForBufferedMessage<T extends Record<string, unknown>>(
messages: Array<{ data: Buffer; binary: boolean }>,
type: string,
): Promise<T> {
for (let attempt = 0; attempt < 100; attempt++) {
const found = messages.find(message => !message.binary && (JSON.parse(message.data.toString()) as { type?: string }).type === type);
if (found) return JSON.parse(found.data.toString()) as T;
await nextTurn();
}
throw new Error(`message ${type} was not published`);
}
// The native Opus codec is unavailable in some environments. These tests only
// exercise gateway wiring, so the encoder is stubbed out.
const stubEncoder = () => ({ encode: () => Buffer.alloc(0), dispose: () => {} });
@@ -153,6 +174,96 @@ test("server identity lookup waits until the directory sync publishes the connec
assert.ok(f.bridge.getActiveCount() > 0);
});
test("a direct connection keeps the legacy audio profile and the original media path", { timeout: 5_000 }, async t => {
const f = await fixture(t, {
webRtc: { enabled: true, stunServer: "stun:stun.example.invalid:3478" },
voiceIce: {
servers: [],
transportPolicy: "all",
gatewayTransportPolicy: "all",
profile: "auto",
opusWebSocket: false,
jitterMaxMs: 300,
},
});
const connected = await waitForBufferedMessage<Record<string, unknown>>(f.messages, "connected");
assert.equal(connected.voiceProfile, "legacy");
assert.equal(connected.webrtcAvailable, true);
assert.equal(connected.webrtcUnavailableReason, undefined);
assert.equal(connected.audioFrameVersion, undefined);
assert.equal(connected.audioUplinkCodecs, undefined);
assert.equal(connected.audioJitterMaxMs, undefined);
assert.equal(connected.voiceIceTransportPolicy, "all");
assert.deepEqual(connected.voiceIceServers, [{ urls: "stun:stun.example.invalid:3478" }]);
});
test("an explicit adaptive profile enables the new audio path on a direct connection", { timeout: 5_000 }, async t => {
const f = await fixture(t, {
webRtc: { enabled: true },
voiceIce: {
servers: [],
transportPolicy: "all",
gatewayTransportPolicy: "all",
profile: "adaptive",
opusWebSocket: true,
jitterMaxMs: 300,
},
});
const connected = await waitForBufferedMessage<Record<string, unknown>>(f.messages, "connected");
assert.equal(connected.voiceProfile, "adaptive");
assert.equal(connected.webrtcAvailable, true);
assert.equal(connected.audioFrameVersion, 2);
assert.deepEqual(connected.audioUplinkCodecs, ["pcm", "opus"]);
assert.equal(connected.audioJitterMaxMs, 300);
});
test("a Cloudflare request opts into adaptive audio without inventing an ICE host", { timeout: 5_000 }, async t => {
const f = await fixture(t, {
webRtc: { enabled: true },
voiceIce: {
servers: [],
transportPolicy: "all",
gatewayTransportPolicy: "all",
profile: "auto",
opusWebSocket: false,
jitterMaxMs: 300,
},
headers: { "cf-ray": "test-ray" },
});
const connected = await waitForBufferedMessage<Record<string, unknown>>(f.messages, "connected");
assert.equal(connected.voiceProfile, "adaptive");
assert.equal(connected.webrtcAvailable, false);
assert.equal(connected.webrtcUnavailableReason, "NO_MEDIA_PATH");
assert.equal(connected.audioFrameVersion, 2);
assert.deepEqual(connected.audioUplinkCodecs, ["pcm"]);
assert.equal(connected.audioJitterMaxMs, 300);
assert.deepEqual(connected.voiceIceServers, []);
});
test("a voice ICE getter is resolved when a new connection is accepted", { timeout: 5_000 }, async t => {
let calls = 0;
const f = await fixture(t, {
webRtc: { enabled: true },
voiceIce: () => {
calls++;
return {
servers: [],
transportPolicy: "all",
gatewayTransportPolicy: "all",
profile: "auto",
opusWebSocket: false,
jitterMaxMs: 300,
};
},
headers: { "cf-ray": "console-refresh-ray" },
});
const connected = await waitForBufferedMessage<Record<string, unknown>>(f.messages, "connected");
assert.equal(calls, 1);
assert.equal(connected.voiceProfile, "adaptive");
});
test("a TeamSpeak drop before the directory sync fails the connection instead of stalling", { timeout: 5_000 }, async t => {
const f = await fixture(t, {
waitForFirstMessage: false,
+37 -1
View File
@@ -3,7 +3,7 @@ import test from "node:test";
import { setImmediate as nextTurn } from "node:timers/promises";
import type { IncomingMessage } from "node:http";
import pino from "pino";
import { VoiceBridge, createTrustedProxies, resolveClientIp, resolveWebRtcPublicHost } from "./voice-bridge.js";
import { VoiceBridge, createTrustedProxies, isCloudflareRequest, resolveClientIp, resolveWebRtcPublicHost } from "./voice-bridge.js";
import { JoinTicketStore } from "./join-ticket.js";
import { createAudioFlowStats } from "./audio-stats.js";
import { SessionAudioTransport } from "./session-audio.js";
@@ -40,6 +40,8 @@ function fixture(webRtc = { enabled: true } as import("./webrtc-audio.js").WebRt
tsClient: { isConnected: () => true, setInputMuted: async (_muted: boolean) => {}, setAccompanimentActive: async (_active: boolean) => {}, sendVoice: () => { forwarded++; }, sendWhisper: () => { forwarded++; } },
whisperActive: false, whisperTargetIds: new Set<number>(), audio: createAudioFlowStats(),
audioTransport: null as SessionAudioTransport | null,
voiceIceServers: [], voiceIceTransportPolicy: "all" as const, voiceIceGatewayTransportPolicy: "all" as const,
voiceProfile: "legacy" as const,
};
let forwarded = 0;
let configurePeer = (_peer: PeerStub): void => {};
@@ -62,6 +64,7 @@ function fixture(webRtc = { enabled: true } as import("./webrtc-audio.js").WebRt
isCurrent: () => bridge.entries.get(entry.id) === entry,
isReady: () => entry.session.state === "connected", selfId: () => 1,
peer: () => entry.webrtc, whisperTargets: () => null, sendJson: message => messages.push(message),
pacing: false,
}, { encode: frame => frame, dispose() {} });
const offer = (sdp: string) => bridge.handleWebRtcOffer(entry, { type: "offer", sdp }, message => messages.push(message));
return { bridge, entry, peers, messages, offer, forwarded: () => forwarded, configure: (callback: typeof configurePeer) => { configurePeer = callback; } };
@@ -174,6 +177,27 @@ test("WebRTC candidates use the voice gateway host when the page Origin belongs
assert.equal(resolveWebRtcPublicHost(request), "voice-relay.example.com");
});
test("Cloudflare headers only classify a request from a trusted proxy", () => {
const trusted = createTrustedProxies(["127.0.0.1", "198.51.100.0/24"]);
const headers = { "cf-ray": "abc123-SJC", "cf-connecting-ip": "203.0.113.10" };
assert.equal(isCloudflareRequest(ipRequest("192.0.2.7", headers), trusted), false);
assert.equal(isCloudflareRequest(ipRequest("127.0.0.1", headers), trusted), true);
assert.equal(isCloudflareRequest(ipRequest("198.51.100.8", { "cdn-loop": "one, cloudflare two" }), trusted), true);
assert.equal(isCloudflareRequest(ipRequest("198.51.100.8", { "cdn-loop": "one, other two" }), trusted), false);
});
test("a Cloudflare-proxied request never falls back to the edge hostname for ICE", () => {
const request = {
headers: {
host: "voice.example.com",
"cf-ray": "abc123-SJC",
"cf-connecting-ip": "203.0.113.10",
},
} as unknown as IncomingMessage;
assert.equal(resolveWebRtcPublicHost(request, { allowHostFallback: false }), undefined);
assert.equal(resolveWebRtcPublicHost(request), "voice.example.com");
});
test("initial accompaniment updates TeamSpeak before creating a muted mixer and resets on stop", async () => {
const f = fixture();
const inputs: Array<[string, boolean]> = [];
@@ -234,6 +258,18 @@ test("an unset media override still uses a literal request host", async () => {
assert.deepEqual(f.peers[0].options.publicAddresses, ["192.0.2.10"]);
});
test("TURN servers are passed to werift while direct-first remains the default policy", async () => {
const f = fixture({ enabled: true, publicHost: "192.0.2.20" });
Object.assign(f.entry, {
webrtcPublicHost: "192.0.2.20",
voiceIceServers: [{ urls: "turns:turn.example.com:443?transport=tcp", username: "u", credential: "c" }],
voiceIceGatewayTransportPolicy: "all" as const,
});
await f.offer("turn");
assert.deepEqual(f.peers[0].options.iceServers, f.entry.voiceIceServers);
assert.equal(f.peers[0].options.iceTransportPolicy, "all");
});
function ipRequest(remoteAddress: string | undefined, headers: Record<string, string> = {}): IncomingMessage {
return { headers, socket: { remoteAddress } } as unknown as IncomingMessage;
}
+97 -4
View File
@@ -28,6 +28,15 @@ import { normalizeScreenShareIceServers, parseScreenShareMessage, type ScreenSha
import { OpusEncoder } from "./opus-codec.js";
import { avatarDataUrl } from "./directory-view.js";
import type { PluginParticipant } from "../shared/plugins.js";
import {
hasVoiceTurnServer,
normalizeVoiceIceServers,
normalizeVoiceIceTransportPolicy,
type VoiceIceServer,
type VoiceIceTransportPolicy,
} from "../shared/voice-ice.js";
import { resolveVoiceIceServers, type VoiceIceConfig } from "./voice-ice-config.js";
import { resolveVoiceProfile, type VoiceProfile } from "../shared/voice-profile.js";
const HEARTBEAT_INTERVAL_MS = 30_000;
const MAX_MISSED_HEARTBEATS = 2;
@@ -54,6 +63,8 @@ export interface VoiceBridgeOptions {
pluginRuntimeEnabled?: boolean;
joinTickets: JoinTicketStore;
webRtc?: WebRtcAudioOptions | (() => WebRtcAudioOptions);
/** TURN / ICE deployment configuration; resolved for each new connection. */
voiceIce?: VoiceIceConfig | (() => VoiceIceConfig);
screenShareIceServers?: ScreenShareIceServer[] | (() => ScreenShareIceServer[]);
acceleration?: ConfiguredAccelerationRelay[] | (() => ConfiguredAccelerationRelay[]);
accelerationName?: string | (() => string | undefined);
@@ -97,6 +108,10 @@ interface WebClientEntry extends SessionDirectoryState {
acceleration?: AccelerationRelayOptions;
identityLeaseKey?: string;
webrtcPublicHost?: string;
voiceProfile: VoiceProfile;
voiceIceServers: VoiceIceServer[];
voiceIceTransportPolicy: VoiceIceTransportPolicy;
voiceIceGatewayTransportPolicy: VoiceIceTransportPolicy;
events: SessionEventCoordinator | null;
eventLog: ServerEvent[];
audioTransport: SessionAudioTransport | null;
@@ -178,7 +193,13 @@ export class VoiceBridge {
return;
}
const clientIp = resolveClientIp(req, this.trustedProxies);
const webrtcPublicHost = resolveWebRtcPublicHost(req);
// Cloudflare Tunnel forwards the public hostname in `Host`, but that
// hostname points at Cloudflare's edge, not at this origin's UDP ports.
// Never advertise it as an ICE media address.
const cloudflareRequest = isCloudflareRequest(req, this.trustedProxies);
const webrtcPublicHost = resolveWebRtcPublicHost(req, { allowHostFallback: !cloudflareRequest });
const voiceIce = this.getVoiceIceConfig();
const voiceProfile = resolveVoiceProfile(voiceIce?.profile ?? "auto", cloudflareRequest);
let identity;
try {
identity = connection.identity ? parseIdentity(connection.identity) : undefined;
@@ -190,6 +211,9 @@ export class VoiceBridge {
return;
}
const entryId = `w-${Date.now().toString(36)}-${Math.random().toString(36).slice(2, 6)}`;
const voiceIceServers = this.buildVoiceIceServers(entryId, voiceIce);
const voiceIceTransportPolicy = normalizeVoiceIceTransportPolicy(voiceIce?.transportPolicy);
const voiceIceGatewayTransportPolicy = normalizeVoiceIceTransportPolicy(voiceIce?.gatewayTransportPolicy);
let entry: WebClientEntry | null = null;
const session = this.sessionManager.admit(entryId, async (reason) => {
if (entry) await this.cleanupEntry(entry, reason);
@@ -247,6 +271,10 @@ export class VoiceBridge {
...(acceleration ? { acceleration } : {}),
...(identityLeaseKey ? { identityLeaseKey } : {}),
...(webrtcPublicHost ? { webrtcPublicHost } : {}),
voiceProfile,
voiceIceServers,
voiceIceTransportPolicy,
voiceIceGatewayTransportPolicy,
channelTree: [],
members: new Map(),
avatarCache: new Map(),
@@ -281,6 +309,7 @@ export class VoiceBridge {
peer: () => entry!.webrtc,
whisperTargets: () => entry!.whisperActive ? [...entry!.whisperTargetIds] : null,
sendJson: message => sendJson(message),
pacing: entry!.voiceProfile === "adaptive",
}, this.dependencies.createEncoder?.() ?? new OpusEncoder(48000, 1));
} catch (error: unknown) {
this.logger.error({ err: error, entryId }, "Could not create Opus encoder");
@@ -328,6 +357,13 @@ export class VoiceBridge {
}
session.transition("connected");
if (this.options.pluginRuntimeEnabled) entry!.pluginSession = randomBytes(32).toString("base64url");
const webRtc = this.getWebRtcOptions();
const hasDirectMediaPath = Boolean(webRtc?.publicHost || entry!.webrtcPublicHost);
const hasRelayMediaPath = hasVoiceTurnServer(entry!.voiceIceServers);
const webRtcAvailable = webRtc?.enabled === true && (hasDirectMediaPath || hasRelayMediaPath);
const webRtcUnavailableReason = webRtc?.enabled !== true
? "DISABLED" as const
: webRtcAvailable ? undefined : "NO_MEDIA_PATH" as const;
sendJson({
type: "connected",
tsClientId: events.selfId,
@@ -335,8 +371,19 @@ export class VoiceBridge {
serverEventLog: entry!.eventLog,
whisperTargetIds: [...entry!.whisperTargetIds],
whisperActive: entry!.whisperActive,
webrtcAvailable: this.getWebRtcOptions()?.enabled === true,
webRtcStunServer: this.getWebRtcOptions()?.stunServer ?? "",
webrtcAvailable: webRtcAvailable,
...(webRtcUnavailableReason ? { webrtcUnavailableReason: webRtcUnavailableReason } : {}),
webRtcStunServer: webRtc?.stunServer ?? "",
voiceProfile: entry!.voiceProfile,
voiceIceServers: entry!.voiceIceServers,
voiceIceTransportPolicy: entry!.voiceIceTransportPolicy,
...(entry!.voiceProfile === "adaptive" ? {
audioFrameVersion: 2 as const,
audioUplinkCodecs: voiceIce?.opusWebSocket === true
? ["pcm", "opus"] as ("pcm" | "opus")[]
: ["pcm"] as ("pcm" | "opus")[],
audioJitterMaxMs: voiceIce?.jitterMaxMs ?? 300,
} : {}),
screenShareIceServers: this.getScreenShareIceServers(),
accelerated: Boolean(entry!.acceleration),
...(entry!.pluginSession ? { pluginSession: entry!.pluginSession } : {}),
@@ -838,6 +885,18 @@ export class VoiceBridge {
return typeof configured === "function" ? configured() : configured;
}
private getVoiceIceConfig(): VoiceIceConfig | undefined {
const configured = this.options.voiceIce;
return typeof configured === "function" ? configured() : configured;
}
private buildVoiceIceServers(entryId: string, config = this.getVoiceIceConfig()): VoiceIceServer[] {
const servers = resolveVoiceIceServers(config, entryId);
const stunServer = this.getWebRtcOptions()?.stunServer;
if (stunServer) servers.push({ urls: stunServer });
return normalizeVoiceIceServers(servers);
}
private getScreenShareIceServers(): ScreenShareIceServer[] {
const configured = this.options.screenShareIceServers;
const servers = typeof configured === "function" ? configured() : configured;
@@ -900,12 +959,25 @@ export class VoiceBridge {
try {
const publicAddresses = await resolveVoiceMediaAddresses(config.publicHost || entry.webrtcPublicHost, config.ipv6Enabled === true);
if (!isCurrent()) return;
const iceServers = config.iceServers?.length ? config.iceServers : entry.voiceIceServers;
const configuredGatewayPolicy = config.iceTransportPolicy ?? entry.voiceIceGatewayTransportPolicy;
// Relay-only gathering without a TURN server would leave the gateway
// with no candidates at all. Fall back to direct gathering instead.
const gatewayPolicy = configuredGatewayPolicy === "relay" && !hasVoiceTurnServer(iceServers)
? "all"
: configuredGatewayPolicy;
if (configuredGatewayPolicy === "relay" && gatewayPolicy === "all") {
this.logger.warn({ entryId: entry.id }, "Relay-only WebRTC gateway policy has no TURN server; using direct candidates");
}
peer = this.createWebRtcSession({
connectionId: entry.id,
publicAddresses,
...(config.publicHost || entry.webrtcPublicHost ? { publicHost: config.publicHost || entry.webrtcPublicHost } : {}),
ipv6Enabled: config.ipv6Enabled,
stunServer: config.stunServer,
iceServers,
iceTransportPolicy: gatewayPolicy,
profile: entry.voiceProfile,
udpPortRange: config.udpPortRange,
logger: this.logger,
microphoneMuted: muted,
@@ -938,7 +1010,28 @@ export class VoiceBridge {
}
}
export function resolveWebRtcPublicHost(request: IncomingMessage): string | undefined {
/**
* Headers Cloudflare adds to proxied requests (including Tunnel origins).
* Only a configured trusted proxy may assert that a request came through
* Cloudflare; otherwise a direct client could spoof the adaptive audio path
* and suppress the legacy Host-based ICE fallback.
*/
export function isCloudflareRequest(request: IncomingMessage, trustedProxies: BlockList): boolean {
const direct = normalizeClientIp(request.socket.remoteAddress);
if (!direct || !isTrustedProxy(direct, trustedProxies)) return false;
const cdnLoop = firstHeader(request.headers["cdn-loop"]);
return Boolean(
firstHeader(request.headers["cf-ray"])
|| firstHeader(request.headers["cf-connecting-ip"])
|| (cdnLoop && /\bcloudflare\b/i.test(cdnLoop))
);
}
export function resolveWebRtcPublicHost(
request: IncomingMessage,
options: { allowHostFallback?: boolean } = {},
): string | undefined {
if (options.allowHostFallback === false) return undefined;
const origin = firstHeader(request.headers.origin);
const forwardedHost = firstHeader(request.headers["x-forwarded-host"]);
const directHost = firstHeader(request.headers.host);
+3
View File
@@ -6,6 +6,7 @@ import { parseDelegatedVoiceSession, VoiceGatewayRequestVerifier } from "./voice
import type { Logger } from "../logger.js";
import type { WebRtcAudioOptions } from "./webrtc-audio.js";
import type { ScreenShareIceServer } from "./screen-share.js";
import type { VoiceIceConfig } from "./voice-ice-config.js";
export interface VoiceGatewayServerOptions {
workspaceInvites?: import("./workspace-invites.js").WorkspaceInvites;
@@ -14,6 +15,7 @@ export interface VoiceGatewayServerOptions {
sharedToken: string;
logger: Logger;
webRtc: WebRtcAudioOptions;
voiceIce?: VoiceIceConfig;
screenShareIceServers?: ScreenShareIceServer[];
trustedProxies?: readonly string[];
}
@@ -33,6 +35,7 @@ export function createVoiceGatewayServer(options: VoiceGatewayServerOptions): Vo
joinTickets: tickets,
...(options.workspaceInvites ? { createWorkspaceInvite: (credentials, minutes) => options.workspaceInvites!.create(credentials, minutes) } : {}),
webRtc: options.webRtc,
voiceIce: options.voiceIce,
screenShareIceServers: options.screenShareIceServers,
trustedProxies: options.trustedProxies,
};
+48
View File
@@ -0,0 +1,48 @@
import assert from "node:assert/strict";
import { test } from "node:test";
import { readVoiceIceConfig, resolveVoiceIceServers } from "./voice-ice-config.js";
test("voice ICE env parses static servers and direct-first defaults", () => {
const config = readVoiceIceConfig({
WEBSPEAK_VOICE_ICE_SERVERS: '[{"urls":"stun:stun.example.com:3478"}]',
});
assert.deepEqual(config.servers, [{ urls: "stun:stun.example.com:3478" }]);
assert.equal(config.transportPolicy, "all");
assert.equal(config.gatewayTransportPolicy, "all");
assert.equal(config.profile, "auto");
assert.equal(config.opusWebSocket, false);
assert.equal(config.jitterMaxMs, 300);
assert.equal(config.turnRest, undefined);
});
test("voice profile is explicit-only for Opus and can force legacy or adaptive", () => {
assert.equal(readVoiceIceConfig({}).profile, "auto");
assert.equal(readVoiceIceConfig({ WEBSPEAK_VOICE_PROFILE: "legacy" }).profile, "legacy");
assert.equal(readVoiceIceConfig({ WEBSPEAK_VOICE_PROFILE: "adaptive" }).profile, "adaptive");
assert.equal(readVoiceIceConfig({ WEBSPEAK_VOICE_PROFILE: "invalid" }).profile, "auto");
assert.equal(readVoiceIceConfig({ WEBSPEAK_VOICE_PROFILE: "adaptive", WEBSPEAK_VOICE_OPUS_WS: "1" }).opusWebSocket, true);
});
test("TURN REST env mints a per-session credential and keeps direct-first policy", () => {
const config = readVoiceIceConfig({
WEBSPEAK_TURN_REST_URLS: "turns:turn.example.com:443?transport=tcp,turn:turn.example.com:3478?transport=udp",
WEBSPEAK_TURN_REST_SECRET: "a-test-secret-with-enough-length",
WEBSPEAK_TURN_REST_TTL_SECONDS: "3600",
WEBSPEAK_VOICE_ICE_TRANSPORT_POLICY: "relay",
});
assert.equal(config.transportPolicy, "relay");
assert.ok(config.turnRest);
const servers = resolveVoiceIceServers(config, "session-a", 1_000_000);
assert.equal(servers.length, 1);
assert.match(servers[0]!.username!, /^[0-9]+:session-a$/);
assert.ok(servers[0]!.credential);
});
test("short TURN secret is ignored instead of starting a broken relay", () => {
const config = readVoiceIceConfig({
WEBSPEAK_TURN_REST_URLS: "turns:turn.example.com:443",
WEBSPEAK_TURN_REST_SECRET: "short",
});
assert.equal(config.turnRest, undefined);
assert.deepEqual(resolveVoiceIceServers(config, "x"), []);
});
+139
View File
@@ -0,0 +1,139 @@
import {
hasVoiceTurnServer,
normalizeVoiceIceServers,
normalizeVoiceIceTransportPolicy,
VOICE_JITTER_DEFAULT_MS,
VOICE_JITTER_MAX_MS,
VOICE_JITTER_MIN_MS,
VOICE_TURN_MIN_SECRET_LENGTH,
VOICE_TURN_TTL_DEFAULT_SECONDS,
VOICE_TURN_TTL_MAX_SECONDS,
VOICE_TURN_TTL_MIN_SECONDS,
type VoiceIceServer,
type VoiceIceTransportPolicy,
} from "../shared/voice-ice.js";
import { createTurnRestCredential, type TurnRestConfig } from "./turn-credentials.js";
import { normalizeVoiceProfileSetting, type VoiceProfileSetting } from "../shared/voice-profile.js";
export interface VoiceIceConfig {
servers: VoiceIceServer[];
turnRest?: TurnRestConfig;
/** Browser policy; keep `all` for direct UDP-first deployments. */
transportPolicy: VoiceIceTransportPolicy;
/** werift policy; use `relay` only when the gateway itself is behind NAT. */
gatewayTransportPolicy: VoiceIceTransportPolicy;
/** Per-connection audio profile: direct traffic defaults to legacy. */
profile: VoiceProfileSetting;
opusWebSocket: boolean;
jitterMaxMs: number;
}
export interface VoiceIceSettings {
servers: VoiceIceServer[];
transportPolicy: VoiceIceTransportPolicy;
gatewayTransportPolicy: VoiceIceTransportPolicy;
profile: VoiceProfileSetting;
opusWebSocket: boolean;
jitterMaxMs: number;
}
/** Baseline used when neither the console nor the environment configures a value. */
export const DEFAULT_VOICE_ICE_CONFIG: VoiceIceConfig = {
servers: [],
transportPolicy: "all",
gatewayTransportPolicy: "all",
profile: "auto",
opusWebSocket: false,
jitterMaxMs: VOICE_JITTER_DEFAULT_MS,
};
function parseBoolean(value: string | undefined, fallback: boolean): boolean {
if (value === undefined) return fallback;
const normalized = value.trim().toLowerCase();
if (!normalized) return fallback;
return normalized === "1" || normalized === "true" || normalized === "yes" || normalized === "on";
}
function parseInteger(value: string | undefined, fallback: number, min: number, max: number): number {
if (!value?.trim()) return fallback;
const parsed = Number(value);
if (!Number.isInteger(parsed)) return fallback;
return Math.max(min, Math.min(max, parsed));
}
function parseStaticServers(raw: string | undefined): VoiceIceServer[] {
const value = raw?.trim();
if (!value) return [];
if (value.startsWith("[") || value.startsWith("{")) {
try {
const parsed: unknown = JSON.parse(value);
if (Array.isArray(parsed)) return normalizeVoiceIceServers(parsed);
if (parsed && typeof parsed === "object") return normalizeVoiceIceServers([parsed]);
return [];
} catch {
// Fall through to the convenient comma/space-separated STUN form.
}
}
return normalizeVoiceIceServers(value.split(/[\s,]+/).filter(Boolean).map((urls) => ({ urls })));
}
function parseTurnRestUrls(raw: string | undefined): string[] {
if (!raw?.trim()) return [];
// Environment parsing stays lenient: one bad entry must not disable a
// previously working TURN deployment during an upgrade.
const urls = raw.split(/[\s,]+/).filter(Boolean).flatMap((token) => {
const [server] = normalizeVoiceIceServers([{ urls: token }]);
if (!server) return [];
const candidates = Array.isArray(server.urls) ? server.urls : [server.urls];
return candidates.filter((url) => /^turns?:/i.test(url));
});
return [...new Set(urls)].slice(0, 8);
}
export function readVoiceIceConfig(env: NodeJS.ProcessEnv = process.env): VoiceIceConfig {
const servers = parseStaticServers(env.WEBSPEAK_VOICE_ICE_SERVERS);
const turnUrls = parseTurnRestUrls(env.WEBSPEAK_TURN_REST_URLS);
const secret = env.WEBSPEAK_TURN_REST_SECRET?.trim() ?? "";
const ttlSeconds = parseInteger(env.WEBSPEAK_TURN_REST_TTL_SECONDS, VOICE_TURN_TTL_DEFAULT_SECONDS, VOICE_TURN_TTL_MIN_SECONDS, VOICE_TURN_TTL_MAX_SECONDS);
const turnRest = turnUrls.length && secret.length >= VOICE_TURN_MIN_SECRET_LENGTH
? { urls: turnUrls, secret, ttlSeconds }
: undefined;
return {
...DEFAULT_VOICE_ICE_CONFIG,
servers,
...(turnRest ? { turnRest } : {}),
transportPolicy: normalizeVoiceIceTransportPolicy(env.WEBSPEAK_VOICE_ICE_TRANSPORT_POLICY),
gatewayTransportPolicy: normalizeVoiceIceTransportPolicy(env.WEBSPEAK_VOICE_GATEWAY_ICE_TRANSPORT_POLICY),
profile: normalizeVoiceProfileSetting(env.WEBSPEAK_VOICE_PROFILE),
// Opus over WebSocket is additive and remains opt-in even in adaptive mode.
opusWebSocket: parseBoolean(env.WEBSPEAK_VOICE_OPUS_WS, false),
jitterMaxMs: parseInteger(env.WEBSPEAK_VOICE_JITTER_MAX_MS, VOICE_JITTER_DEFAULT_MS, VOICE_JITTER_MIN_MS, VOICE_JITTER_MAX_MS),
};
}
/** Build the per-connection list, minting one short-lived TURN credential. */
export function resolveVoiceIceServers(
config: VoiceIceConfig | undefined,
sessionId: string,
nowMs = Date.now(),
): VoiceIceServer[] {
if (!config) return [];
const servers = [...config.servers];
if (config.turnRest) {
servers.push(createTurnRestCredential(config.turnRest, sessionId, nowMs));
}
return normalizeVoiceIceServers(servers);
}
export function voiceConfigSettings(config: VoiceIceConfig): VoiceIceSettings {
return {
servers: normalizeVoiceIceServers(config.servers),
transportPolicy: config.transportPolicy,
gatewayTransportPolicy: config.gatewayTransportPolicy,
profile: config.profile,
opusWebSocket: config.opusWebSocket,
jitterMaxMs: config.jitterMaxMs,
};
}
export { hasVoiceTurnServer };
+83
View File
@@ -109,6 +109,89 @@ for (const scenario of ["silence gaps", "alternating speakers", "volume changes"
});
}
test("WebRTC marks only the first audible RTP packet after a gap", () => {
const packets: RtpPacket[] = [];
const session = Object.assign(Object.create(WebRtcAudioSession.prototype), {
closed: false,
outgoingPayloadType: 111,
sequenceNumber: 0,
timestamp: 0,
ssrc: 7,
lastAudioRtpAt: null as number | null,
lastEgressRtpAt: null as number | null,
outgoingTrack: { writeRtp(packet: RtpPacket) { packets.push(packet); } },
stats: { webrtcEgressRtpFrames: 0, webrtcEgressRtpMaxGapMs: 0, webrtcEgressRtpFirstAt: null, webrtcEgressRtpLastAt: null },
}) as unknown as WebRtcAudioSession;
const send = (session as unknown as { sendRtpAudio(payload: Buffer, hasAudio: boolean): void }).sendRtpAudio.bind(session);
send(Buffer.from([1]), true);
send(Buffer.from([2]), true);
send(Buffer.from([3]), false);
assert.deepEqual(packets.map(packet => packet.header.marker), [true, false, false]);
(session as unknown as { lastAudioRtpAt: number | null }).lastAudioRtpAt = performance.now() - 50;
send(Buffer.from([4]), true);
send(Buffer.from([5]), true);
assert.deepEqual(packets.map(packet => packet.header.marker), [true, false, false, true, false]);
});
test("legacy RTP pacing keeps the original marker on every packet", () => {
const packets: RtpPacket[] = [];
const session = Object.assign(Object.create(WebRtcAudioSession.prototype), {
closed: false,
outgoingPayloadType: 111,
sequenceNumber: 0,
timestamp: 0,
ssrc: 7,
lastAudioRtpAt: null as number | null,
lastEgressRtpAt: null as number | null,
rtpMarkerAlways: true,
outgoingTrack: { writeRtp(packet: RtpPacket) { packets.push(packet); } },
stats: { webrtcEgressRtpFrames: 0, webrtcEgressRtpMaxGapMs: 0, webrtcEgressRtpFirstAt: null, webrtcEgressRtpLastAt: null },
}) as unknown as WebRtcAudioSession;
const send = (session as unknown as { sendRtpAudio(payload: Buffer, hasAudio: boolean): void }).sendRtpAudio.bind(session);
send(Buffer.from([1]), true);
send(Buffer.from([2]), false);
assert.deepEqual(packets.map(packet => packet.header.marker), [true, true]);
});
test("legacy WebRTC profile selects the original bounded mixer constants", async t => {
const session = new WebRtcAudioSession({ connectionId: "legacy-mixer", logger: pino({ enabled: false }), onVoiceFrame() {}, onVoiceActivity() {} });
t.after(() => session.close());
const internals = session as unknown as { mixerQueueFrames: number; maxMixerFrameAgeMs: number; mixerQueueAfterLateTick: number; rtpMarkerAlways: boolean };
assert.equal(internals.mixerQueueFrames, 4);
assert.equal(internals.maxMixerFrameAgeMs, 80);
assert.equal(internals.mixerQueueAfterLateTick, 1);
assert.equal(internals.rtpMarkerAlways, true);
});
test("adaptive WebRTC profile keeps the longer queue and corrected marker", async t => {
const session = new WebRtcAudioSession({ connectionId: "adaptive-mixer", profile: "adaptive", logger: pino({ enabled: false }), onVoiceFrame() {}, onVoiceActivity() {} });
t.after(() => session.close());
const internals = session as unknown as { mixerQueueFrames: number; maxMixerFrameAgeMs: number; mixerQueueAfterLateTick: number; rtpMarkerAlways: boolean };
assert.equal(internals.mixerQueueFrames, 6);
assert.equal(internals.maxMixerFrameAgeMs, 200);
assert.equal(internals.mixerQueueAfterLateTick, 2);
assert.equal(internals.rtpMarkerAlways, false);
});
test("late-tick trimming keeps legacy queue bounds and clears adaptive stale frames", () => {
for (const [profile, queueAfterLateTick, frameAgeMs, frameCount, expectedRemaining, expectedDropped] of [
["legacy", 1, 0, 3, 1, 2],
["legacy", 1, 100, 1, 0, 1],
["adaptive", 2, 100, 3, 0, 3],
] as const) {
const queue = Array.from({ length: frameCount }, () => ({ pcm: Buffer.alloc(4), receivedAt: performance.now() - frameAgeMs - 1 }));
const session = Object.assign(Object.create(WebRtcAudioSession.prototype), {
pendingFrames: new Map([["speaker", queue]]),
mixerQueueAfterLateTick: queueAfterLateTick,
maxMixerFrameAgeMs: 100,
stats: { webrtcQueueDroppedFrames: 0 },
}) as WebRtcAudioSession;
(session as unknown as { trimQueuesAfterLateTick(): void }).trimQueuesAfterLateTick();
assert.equal(queue.length, expectedRemaining, profile);
assert.equal((session as unknown as { stats: { webrtcQueueDroppedFrames: number } }).stats.webrtcQueueDroppedFrames, expectedDropped, profile);
}
});
function fixture() {
const released: string[] = [];
// Exercise the real close path with failures at codec/track/peer boundaries.
+47 -9
View File
@@ -12,6 +12,8 @@ import { WEBRTC_UDP_PORT_RANGE } from "./webrtc-config.js";
import { OpusEncoder } from "./opus-codec.js";
import type { WebRtcSessionDescription } from "../shared/webrtc.js";
import { addOpusFmtpParameters } from "../shared/opus-sdp.js";
import type { VoiceIceServer, VoiceIceTransportPolicy } from "../shared/voice-ice.js";
import type { VoiceProfile } from "../shared/voice-profile.js";
export type { WebRtcSessionDescription } from "../shared/webrtc.js";
export { DEFAULT_WEBRTC_UDP_PORT_RANGE, WEBRTC_UDP_PORT_RANGE } from "./webrtc-config.js";
@@ -23,9 +25,15 @@ const AUDIO_FRAME_BYTES = AUDIO_FRAME_SAMPLES * AUDIO_CHANNELS * 2;
const DEFAULT_WEBRTC_OPUS_PAYLOAD_TYPE = 111;
const AUDIO_CLOCK_INTERVAL_MS = 20;
const SPEAKER_ACTIVITY_INTERVAL_MS = 100;
const MAX_MIXER_QUEUE_FRAMES = 4;
const MAX_MIXER_QUEUE_FRAMES = 6;
const MAX_MIXER_PACER_LAG_MS = AUDIO_CLOCK_INTERVAL_MS * 2;
const MAX_MIXER_FRAME_AGE_MS = MAX_MIXER_QUEUE_FRAMES * AUDIO_CLOCK_INTERVAL_MS;
const MAX_MIXER_FRAME_AGE_MS = 200;
const MAX_MIXER_QUEUE_AFTER_LATE_TICK = 2;
// The pre-CFT implementation used a 4-frame queue, an 80 ms age bound and one
// retained frame after a late tick. Keep those values for direct deployments.
const LEGACY_MAX_MIXER_QUEUE_FRAMES = 4;
const LEGACY_MAX_MIXER_FRAME_AGE_MS = LEGACY_MAX_MIXER_QUEUE_FRAMES * AUDIO_CLOCK_INTERVAL_MS;
const LEGACY_MAX_MIXER_QUEUE_AFTER_LATE_TICK = 1;
const MIXER_UNDERRUN_WINDOW_MS = 200;
// This threshold is used only for the speaking indicator. It must never decide
// whether a media packet is forwarded or queued: quiet/comfort-noise Opus
@@ -40,6 +48,9 @@ export interface WebRtcAudioOptions {
publicHost?: string;
ipv6Enabled?: boolean;
stunServer?: string;
/** Full ICE list, including TURN; takes precedence over `stunServer`. */
iceServers?: VoiceIceServer[];
iceTransportPolicy?: VoiceIceTransportPolicy;
udpPortRange?: [number, number];
}
@@ -51,6 +62,10 @@ export interface WebRtcAudioSessionOptions {
publicAddresses?: string[];
ipv6Enabled?: boolean;
stunServer?: string;
iceServers?: VoiceIceServer[];
iceTransportPolicy?: VoiceIceTransportPolicy;
/** `legacy` preserves the direct-deployment mixer; `adaptive` is the CFT path. */
profile?: VoiceProfile;
publicHost?: string;
udpPortRange?: [number, number];
logger: LoggerType;
@@ -122,7 +137,12 @@ export class WebRtcAudioSession {
private nextAudioDeadline = 0;
private lastIngressRtpAt: number | null = null;
private lastEgressRtpAt: number | null = null;
private lastAudioRtpAt: number | null = null;
private lastQueueEnqueuedAt: number | null = null;
private readonly mixerQueueFrames: number;
private readonly maxMixerFrameAgeMs: number;
private readonly mixerQueueAfterLateTick: number;
private readonly rtpMarkerAlways: boolean;
private microphoneMuted: boolean;
private accompanimentActive: boolean;
private readonly stats: WebRtcAudioStats = {
@@ -150,19 +170,31 @@ export class WebRtcAudioSession {
this.logger = options.logger.child({ component: "webrtc-audio", connectionId: options.connectionId });
this.onVoiceFrame = options.onVoiceFrame;
this.onVoiceActivity = options.onVoiceActivity;
const profile = options.profile ?? "legacy";
this.mixerQueueFrames = profile === "legacy" ? LEGACY_MAX_MIXER_QUEUE_FRAMES : MAX_MIXER_QUEUE_FRAMES;
this.maxMixerFrameAgeMs = profile === "legacy" ? LEGACY_MAX_MIXER_FRAME_AGE_MS : MAX_MIXER_FRAME_AGE_MS;
this.mixerQueueAfterLateTick = profile === "legacy" ? LEGACY_MAX_MIXER_QUEUE_AFTER_LATE_TICK : MAX_MIXER_QUEUE_AFTER_LATE_TICK;
this.rtpMarkerAlways = profile === "legacy";
this.microphoneMuted = options.microphoneMuted === true;
this.accompanimentActive = options.accompanimentActive === true;
this.outgoingTrack = new MediaStreamTrack({ kind: "audio" });
const iceAdditionalHostAddresses = options.publicAddresses ?? (options.publicHost ? [options.publicHost] : undefined);
const udpPortRange = options.udpPortRange ?? WEBRTC_UDP_PORT_RANGE;
const iceServers = options.iceServers?.length
? options.iceServers
: options.stunServer ? [{ urls: options.stunServer }] : [];
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: options.stunServer ? [{ urls: options.stunServer }] : [],
iceServers,
iceTransportPolicy: options.iceTransportPolicy ?? "all",
iceUseIpv4: true,
iceUseIpv6: options.ipv6Enabled === true,
// This controls ICE-TCP host candidates, not TURN control transport.
// werift parses `turns:` as a TLS TURN client independently; verified in
// peerConnection.ts createTransport() -> parseIceServers().
iceUseTcp: false,
icePortRange: [...udpPortRange] as [number, number],
...(iceAdditionalHostAddresses ? { iceAdditionalHostAddresses } : {}),
@@ -315,7 +347,7 @@ export class WebRtcAudioSession {
queue = [];
this.pendingFrames.set(data.clientId, queue);
}
if (queue.length >= MAX_MIXER_QUEUE_FRAMES) {
if (queue.length >= this.mixerQueueFrames) {
queue.shift();
this.stats.webrtcQueueDroppedFrames++;
}
@@ -398,6 +430,7 @@ export class WebRtcAudioSession {
}
}
const mixed = new Int32Array(AUDIO_FRAME_SAMPLES * AUDIO_CHANNELS);
const hasAudio = this.pendingFrames.size > 0;
for (const [clientId, queue] of this.pendingFrames) {
const frame = queue.shift();
if (queue.length === 0) this.pendingFrames.delete(clientId);
@@ -422,25 +455,30 @@ export class WebRtcAudioSession {
}
try {
const encoded = this.encoder.encode(pcm);
this.sendRtpAudio(encoded);
this.sendRtpAudio(encoded, hasAudio);
} catch {
// A peer closing concurrently may reject a packet; teardown owns the
// session lifecycle and no per-frame error needs to reach the logs.
}
}
private sendRtpAudio(encoded: Buffer): void {
private sendRtpAudio(encoded: Buffer, hasAudio: boolean): void {
const now = performance.now();
const marker = this.rtpMarkerAlways
? true
: hasAudio && (this.lastAudioRtpAt === null || now - this.lastAudioRtpAt > 40);
const packet = new RtpPacket(new RtpHeader({
payloadType: this.outgoingPayloadType,
sequenceNumber: this.sequenceNumber,
timestamp: this.timestamp,
ssrc: this.ssrc,
marker: true,
marker,
}), encoded);
this.sequenceNumber = (this.sequenceNumber + 1) & 0xffff;
this.timestamp = (this.timestamp + AUDIO_FRAME_SAMPLES) >>> 0;
this.outgoingTrack.writeRtp(packet);
const sentAt = performance.now();
if (hasAudio) this.lastAudioRtpAt = sentAt;
if (this.lastEgressRtpAt !== null) this.stats.webrtcEgressRtpMaxGapMs = Math.max(this.stats.webrtcEgressRtpMaxGapMs, Math.round(sentAt - this.lastEgressRtpAt));
this.lastEgressRtpAt = sentAt;
this.stats.webrtcEgressRtpFirstAt ??= Date.now();
@@ -497,11 +535,11 @@ export class WebRtcAudioSession {
private trimQueuesAfterLateTick(): void {
const now = performance.now();
for (const [clientId, queue] of this.pendingFrames) {
while (queue.length > 1) {
while (queue.length > this.mixerQueueAfterLateTick) {
queue.shift();
this.stats.webrtcQueueDroppedFrames++;
}
if (queue[0] && now - queue[0].receivedAt > MAX_MIXER_FRAME_AGE_MS) {
while (queue[0] && now - queue[0].receivedAt > this.maxMixerFrameAgeMs) {
queue.shift();
this.stats.webrtcQueueDroppedFrames++;
}
+7
View File
@@ -15,6 +15,13 @@ export interface AdminSettingsInput {
webRtcStunServer?: string;
webRtcUdpStart?: number;
webRtcUdpEnd?: number;
voiceProfile?: "auto" | "legacy" | "adaptive";
voiceTurnUrls?: string;
voiceTurnSecret?: string;
voiceTurnSecretAction?: "keep" | "replace" | "remove";
voiceTurnTtlSeconds?: number;
voiceOpusWs?: boolean;
voiceJitterMaxMs?: number;
relaySettingsAction?: "keep" | "replace" | "remove";
relayEnabled?: boolean;
relayName?: string;
+6
View File
@@ -33,6 +33,12 @@ const settings = object({
webRtcPublicHost: value => value === undefined ? "" : text(value),
webRtcIpv6Enabled: value => value === undefined ? false : boolean(value),
webRtcStunServer: value => value === undefined ? "" : text(value),
voiceProfile: value => value === undefined ? "auto" as const : choice("auto", "legacy", "adaptive")(value),
voiceTurnUrls: value => value === undefined ? "" : text(value),
hasVoiceTurnSecret: value => value === undefined ? false : boolean(value),
voiceTurnTtlSeconds: value => value === undefined ? 21600 : number(value),
voiceOpusWs: value => value === undefined ? false : boolean(value),
voiceJitterMaxMs: value => value === undefined ? 300 : number(value),
relayConfigured: boolean, relayEnabled: boolean, relayName: text, relayTarget: text, hasRelayToken: boolean,
relayNodes: array(relayNode), internalPort: number, updatedAt: text,
});
+9
View File
@@ -60,12 +60,21 @@ test("every current gateway message survives JSON transport and shared validatio
}
});
test("voice profile is optional and invalid values are rejected", () => {
const adaptive = parseServerMessage({ type: "connected", tsClientId: 1, voiceProfile: "adaptive" });
assert.equal(adaptive?.type === "connected" ? adaptive.voiceProfile : undefined, "adaptive");
const legacy = parseServerMessage({ type: "connected", tsClientId: 1, voiceProfile: "legacy" });
assert.equal(legacy?.type === "connected" ? legacy.voiceProfile : undefined, "legacy");
assert.equal(parseServerMessage({ type: "connected", tsClientId: 1, voiceProfile: "future" }), null);
});
test("malformed nested directory and event data is rejected before client state changes", () => {
for (const message of [
null, [], {}, { type: "toString" }, { type: "futureMessage" },
{ type: "connected", tsClientId: 1, members: [null] },
{ type: "connected", tsClientId: 1, members: [{ id: "1", nickname: "bad id" }] },
{ type: "connected", tsClientId: 1, serverEventLog: [{ id: "incomplete" }] },
{ type: "connected", tsClientId: 1, voiceProfile: "future" },
{ type: "serverInfo", name: "TeamSpeak", icon: "https://example.com/icon.png" },
{ type: "serverInfo", name: "TeamSpeak", bannerUrl: "javascript:alert(1)" },
{ type: "serverInfo", name: "TeamSpeak", welcomeMessage: "x".repeat(4_097) },
+16 -3
View File
@@ -1,8 +1,9 @@
import type { ChannelMember, ChannelInfo, ServerEvent, VoiceAudioBridgeStats } from "./voice-models.js";
import { normalizeScreenShareIceServers, parseScreenShareSignal, SCREEN_SHARE_LEGACY_AVATAR_BUDGET, type ScreenShareIceServer, type ScreenSharePeerSignal, type ScreenShareStreamDescription, type ScreenShareViewerDescription } from "./screen-share.js";
import { normalizeVoiceStunServer } from "./voice-ice.js";
import { normalizeVoiceIceServers, normalizeVoiceIceTransportPolicy, normalizeVoiceStunServer, type VoiceIceServer } from "./voice-ice.js";
import { isSessionDescription, type SessionDescription } from "./webrtc.js";
import { isVoiceProfile, type VoiceProfile } from "./voice-profile.js";
export type { SessionDescription } from "./webrtc.js";
type Message<T extends string, Fields = object> = { type: T } & Fields;
@@ -13,7 +14,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<"inviteCreated", Request & { token: string; expiresAt: number }>
| Message<"connected", { tsClientId: number; pluginSession?: string; members?: ChannelMember[]; serverEventLog?: ServerEvent[]; identity?: string; webrtcAvailable?: boolean; webRtcStunServer?: string; whisperTargetIds?: number[]; whisperActive?: boolean; screenShareIceServers?: ScreenShareIceServer[]; accelerated?: boolean }>
| Message<"connected", { tsClientId: number; pluginSession?: string; members?: ChannelMember[]; serverEventLog?: ServerEvent[]; identity?: string; webrtcAvailable?: boolean; webrtcUnavailableReason?: "DISABLED" | "NO_MEDIA_PATH"; webRtcStunServer?: string; voiceProfile?: VoiceProfile; voiceIceServers?: VoiceIceServer[]; voiceIceTransportPolicy?: "all" | "relay"; audioFrameVersion?: 2; audioUplinkCodecs?: ("pcm" | "opus")[]; audioJitterMaxMs?: number; whisperTargetIds?: number[]; whisperActive?: boolean; screenShareIceServers?: ScreenShareIceServer[]; accelerated?: boolean }>
| Message<"serverInfo", { name: string; icon?: string | null; bannerUrl?: string | null; welcomeMessage?: string }>
| Message<"memberEnter", ChannelMember>
| Message<"memberLeave", { id: number }>
@@ -88,8 +89,11 @@ export function parseVoiceAudioBridgeStats(value: unknown): VoiceAudioBridgeStat
const count = (key: string): number => finite(value[key]) && value[key] >= 0 ? value[key] : 0;
return {
transport: value.transport === "webrtc" ? "webrtc" : "websocket",
ingressFrames: count("ingressFrames"), ingressDroppedFrames: count("ingressDroppedFrames"), ingressMaxGapMs: count("ingressMaxGapMs"),
ingressFrames: count("ingressFrames"), ingressPcmFrames: count("ingressPcmFrames"), ingressOpusFrames: count("ingressOpusFrames"),
ingressDroppedFrames: count("ingressDroppedFrames"), ingressMaxGapMs: count("ingressMaxGapMs"),
tsSendFrames: count("tsSendFrames"), tsSendErrors: count("tsSendErrors"), tsSendMaxGapMs: count("tsSendMaxGapMs"),
uplinkQueuePeakFrames: count("uplinkQueuePeakFrames"), uplinkQueueDroppedFrames: count("uplinkQueueDroppedFrames"),
uplinkPacerLateTicks: count("uplinkPacerLateTicks"),
tsReceiveFrames: count("tsReceiveFrames"), tsReceiveMaxGapMs: count("tsReceiveMaxGapMs"),
egressFrames: count("egressFrames"), egressDroppedFrames: count("egressDroppedFrames"), egressMaxGapMs: count("egressMaxGapMs"),
webrtcIngressRtpFrames: count("webrtcIngressRtpFrames"), webrtcIngressRtpMaxGapMs: count("webrtcIngressRtpMaxGapMs"),
@@ -138,6 +142,13 @@ export function parseScreenShareStream(value: unknown): ScreenShareStreamDescrip
const valid: Record<ServerMessage["type"], (message: RecordValue) => boolean> = {
connected: m => optional(m.pluginSession, v => text(v) && /^[A-Za-z0-9_-]{43}$/.test(v)) && 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.webRtcStunServer, v => normalizeVoiceStunServer(v) !== null)
&& optional(m.webrtcUnavailableReason, v => v === "DISABLED" || v === "NO_MEDIA_PATH")
&& optional(m.voiceProfile, isVoiceProfile)
&& optional(m.voiceIceServers, v => Array.isArray(v) && normalizeVoiceIceServers(v).length === v.length)
&& optional(m.voiceIceTransportPolicy, v => v === "all" || v === "relay")
&& optional(m.audioFrameVersion, v => v === 2)
&& optional(m.audioUplinkCodecs, v => Array.isArray(v) && v.length > 0 && v.every(codec => codec === "pcm" || codec === "opus"))
&& optional(m.audioJitterMaxMs, v => finite(v) && Number.isInteger(v) && v >= 80 && v <= 500)
&& optional(m.whisperTargetIds, v => arrayOf(v, clientId)) && optional(m.whisperActive, boolean) && optional(m.accelerated, boolean),
serverInfo: m => text(m.name) && m.name.length <= 256
&& optional(m.icon, v => v === null || (text(v) && v.length <= 180_000
@@ -191,6 +202,8 @@ export function parseServerMessage(value: unknown): ServerMessage | null {
let result = value;
if (value.type === "connected") {
result = { ...value, ...(value.webRtcStunServer === undefined ? {} : { webRtcStunServer: normalizeVoiceStunServer(value.webRtcStunServer)! }), screenShareIceServers: normalizeScreenShareIceServers(Array.isArray(value.screenShareIceServers) ? value.screenShareIceServers : undefined) };
if (Array.isArray(value.voiceIceServers)) result = { ...result, voiceIceServers: normalizeVoiceIceServers(value.voiceIceServers) };
if (value.voiceIceTransportPolicy !== undefined) result = { ...result, voiceIceTransportPolicy: normalizeVoiceIceTransportPolicy(value.voiceIceTransportPolicy) };
} else if (value.type === "audioStats") {
result = { ...value, stats: parseVoiceAudioBridgeStats(value.stats) };
} else if (value.type === "screenShareList") {
+8
View File
@@ -0,0 +1,8 @@
/** Shared binary framing for the compatibility (PCM/Opus over WebSocket) path. */
export const VOICE_FRAME_SAMPLES = 960;
export const VOICE_PCM_FRAME_BYTES = VOICE_FRAME_SAMPLES * 2;
export const VOICE_PCM_TAG = 0x01;
export const VOICE_OPUS_TAG = 0x02;
/** RFC 6716 maximum Opus packet length; the server validates the same bound. */
export const VOICE_MAX_OPUS_FRAME_BYTES = 1_275;
+49
View File
@@ -0,0 +1,49 @@
import assert from "node:assert/strict";
import { test } from "node:test";
import {
hasVoiceTurnServer,
normalizeVoiceIceServers,
normalizeVoiceIceTransportPolicy,
normalizeVoiceTurnRestUrls,
} from "./voice-ice.js";
test("voice ICE normalization accepts STUN and TURN URLs", () => {
const servers = normalizeVoiceIceServers([
{ urls: "stun:stun.example.com:3478" },
{ urls: "stuns:stun.example.com:5349" },
{ urls: ["turns:turn.example.com:443?transport=tcp", "turn:turn.example.com:3478?transport=udp"], username: "u", credential: "c" },
]);
assert.deepEqual(servers, [
{ urls: "stun:stun.example.com:3478" },
{ urls: "stuns:stun.example.com:5349" },
{ urls: ["turns:turn.example.com:443?transport=tcp", "turn:turn.example.com:3478?transport=udp"], username: "u", credential: "c" },
]);
assert.equal(hasVoiceTurnServer(servers), true);
});
test("voice ICE normalization drops malformed, half-credentialed, and duplicate entries", () => {
assert.deepEqual(normalizeVoiceIceServers([
{ urls: "http://turn.example.com" },
{ urls: "turns:turn.example.com:443?transport=udp" },
{ urls: "turn:turn.example.com:3478", username: "u" },
{ urls: "stun:stun.example.com:3478" },
{ urls: "stun:stun.example.com:3478" },
]), [{ urls: "stun:stun.example.com:3478" }]);
});
test("transport policy defaults to direct-first", () => {
assert.equal(normalizeVoiceIceTransportPolicy(undefined), "all");
assert.equal(normalizeVoiceIceTransportPolicy("relay"), "relay");
assert.equal(normalizeVoiceIceTransportPolicy("invalid"), "all");
});
test("TURN REST URL input is strict and keeps direct-first configuration bounded", () => {
assert.deepEqual(normalizeVoiceTurnRestUrls(" turn:turn.example.com:3478\nturns:turn.example.com:5349?transport=tcp "), [
"turn:turn.example.com:3478",
"turns:turn.example.com:5349?transport=tcp",
]);
assert.deepEqual(normalizeVoiceTurnRestUrls(""), []);
assert.equal(normalizeVoiceTurnRestUrls("stun:stun.example.com:3478"), null);
assert.equal(normalizeVoiceTurnRestUrls("https://turn.example.com"), null);
assert.equal(normalizeVoiceTurnRestUrls("turn:turn.example.com:3478\nbad"), null);
});
+109 -1
View File
@@ -15,7 +15,7 @@ export function normalizeVoiceMediaHost(value: unknown): string | null {
return host.toLowerCase();
}
/** Voice currently exposes UDP STUN discovery only, without relay credentials. */
/** UDP STUN discovery only; TURN credentials are supplied separately. */
export function normalizeVoiceStunServer(value: unknown): string | null {
if (typeof value !== "string" || value.length > 300) return null;
if (!value.trim()) return "";
@@ -28,3 +28,111 @@ export function normalizeVoiceStunServer(value: unknown): string | null {
if (!host || port < 1 || port > 65535) return null;
return `stun:${host}:${port}`;
}
export interface VoiceIceServer {
urls: string | string[];
username?: string;
credential?: string;
}
export type VoiceIceTransportPolicy = "all" | "relay";
export const VOICE_TURN_TTL_DEFAULT_SECONDS = 21_600;
export const VOICE_TURN_TTL_MIN_SECONDS = 300;
export const VOICE_TURN_TTL_MAX_SECONDS = 86_400;
export const VOICE_TURN_MIN_SECRET_LENGTH = 16;
export const VOICE_JITTER_DEFAULT_MS = 300;
export const VOICE_JITTER_MIN_MS = 80;
export const VOICE_JITTER_MAX_MS = 500;
const MAX_ICE_SERVER_COUNT = 8;
const MAX_ICE_URL_LENGTH = 512;
const MAX_ICE_CREDENTIAL_LENGTH = 512;
const ICE_URL_PATTERN = /^(stun|stuns|turn|turns):([a-z0-9.-]+|\[[0-9a-f:.]+\])(?::(\d{1,5}))?(?:\?transport=(udp|tcp))?$/i;
function normalizeIceUrl(value: unknown): string | null {
if (typeof value !== "string") return null;
const url = value.trim();
if (!url || url.length > MAX_ICE_URL_LENGTH) return null;
const match = ICE_URL_PATTERN.exec(url);
if (!match) return null;
const scheme = match[1]!.toLowerCase();
const port = match[3] === undefined ? undefined : Number(match[3]);
if (port !== undefined && (port < 1 || port > 65_535)) return null;
const transport = match[4]?.toLowerCase();
if (scheme === "stun" || scheme === "stuns") {
return transport ? null : `${scheme}:${match[2]}${port === undefined ? "" : `:${port}`}`;
}
if (scheme === "turns" && transport === "udp") return null;
return `${scheme}:${match[2]}${port === undefined ? "" : `:${port}`}${transport ? `?transport=${transport}` : ""}`;
}
/**
* Bound server-owned ICE configuration before it reaches a browser or werift.
* TURN is accepted only as an explicitly configured external service; no
* gateway-owned relay is inserted here.
*/
export function normalizeVoiceIceServers(value?: readonly unknown[]): VoiceIceServer[] {
if (!value?.length) return [];
const normalized: VoiceIceServer[] = [];
const seen = new Set<string>();
for (const raw of value) {
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])
.map(normalizeIceUrl)
.filter((url): url is string => url !== null);
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;
// Do not forward a half-configured TURN credential pair.
if ((username === undefined) !== (credential === undefined)) continue;
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;
}
return normalized;
}
export function normalizeVoiceIceTransportPolicy(value: unknown): VoiceIceTransportPolicy {
return value === "relay" ? "relay" : "all";
}
/**
* Normalize the TURN REST service URL list used by the admin console.
* Unlike the environment parser, an invalid token is a configuration error
* rather than a silently ignored value.
*/
export function normalizeVoiceTurnRestUrls(value: unknown): string[] | null {
if (typeof value !== "string" || value.length > 4096) return null;
const tokens = value.trim() ? value.trim().split(/[\s,]+/).filter(Boolean) : [];
if (tokens.length > MAX_ICE_SERVER_COUNT) return null;
const urls: string[] = [];
for (const token of tokens) {
const [server] = normalizeVoiceIceServers([{ urls: token }]);
if (!server) return null;
const candidates = Array.isArray(server.urls) ? server.urls : [server.urls];
if (!candidates.every((url) => /^turns?:/i.test(url))) return null;
urls.push(...candidates);
}
return [...new Set(urls)];
}
export function hasVoiceTurnServer(servers: readonly VoiceIceServer[]): boolean {
return servers.some((server) => {
const urls = Array.isArray(server.urls) ? server.urls : [server.urls];
return urls.some((url) => /^turns?:/i.test(url));
});
}
+5
View File
@@ -58,11 +58,16 @@ export interface ServerEvent {
export interface VoiceAudioBridgeStats {
transport: "webrtc" | "websocket";
ingressFrames: number;
ingressPcmFrames?: number;
ingressOpusFrames?: number;
ingressDroppedFrames: number;
ingressMaxGapMs: number;
tsSendFrames: number;
tsSendErrors: number;
tsSendMaxGapMs: number;
uplinkQueuePeakFrames?: number;
uplinkQueueDroppedFrames?: number;
uplinkPacerLateTicks?: number;
tsReceiveFrames: number;
tsReceiveMaxGapMs: number;
egressFrames: number;
+18
View File
@@ -0,0 +1,18 @@
import assert from "node:assert/strict";
import test from "node:test";
import { normalizeVoiceProfileSetting, resolveVoiceProfile } from "./voice-profile.js";
test("auto keeps direct requests on legacy and opts Cloudflare requests into adaptive", () => {
assert.equal(normalizeVoiceProfileSetting(undefined), "auto");
assert.equal(normalizeVoiceProfileSetting(""), "auto");
assert.equal(normalizeVoiceProfileSetting("unknown"), "auto");
assert.equal(resolveVoiceProfile("auto", false), "legacy");
assert.equal(resolveVoiceProfile("auto", true), "adaptive");
});
test("explicit profile settings override request detection in both directions", () => {
assert.equal(resolveVoiceProfile("legacy", true), "legacy");
assert.equal(resolveVoiceProfile("adaptive", false), "adaptive");
assert.equal(normalizeVoiceProfileSetting(" LEGACY "), "legacy");
assert.equal(normalizeVoiceProfileSetting("Adaptive"), "adaptive");
});
+26
View File
@@ -0,0 +1,26 @@
export type VoiceProfile = "legacy" | "adaptive";
export type VoiceProfileSetting = VoiceProfile | "auto";
/**
* `auto` is the deployment default: direct HTTP/WebSocket traffic keeps the
* historical audio path, while Cloudflare-proxied connections opt into the
* adaptive path automatically. Explicit `legacy`/`adaptive` wins everywhere.
*/
export function normalizeVoiceProfileSetting(value: unknown): VoiceProfileSetting {
if (typeof value !== "string") return "auto";
const normalized = value.trim().toLowerCase();
return normalized === "legacy" || normalized === "adaptive" ? normalized : "auto";
}
export function resolveVoiceProfile(setting: VoiceProfileSetting, cloudflareRequest: boolean): VoiceProfile {
if (setting === "legacy" || setting === "adaptive") return setting;
return cloudflareRequest ? "adaptive" : "legacy";
}
export function isVoiceProfile(value: unknown): value is VoiceProfile {
return value === "legacy" || value === "adaptive";
}
export function isVoiceProfileSetting(value: unknown): value is VoiceProfileSetting {
return value === "auto" || isVoiceProfile(value);
}
+1 -1
View File
@@ -67,7 +67,7 @@ test("official relative .bin symlinks are accepted and resolve inside the packag
await extractReleaseArchive(archive, destination, "release.tar.gz");
const link = path.join(destination, "webspeak/node_modules/.bin/nanoid");
assert.equal(lstatSync(link).isSymbolicLink(), true);
assert.equal(readlinkSync(link), "../nanoid/bin/nanoid.cjs");
assert.equal(readlinkSync(link), path.normalize("../nanoid/bin/nanoid.cjs"));
assert.equal(readFileSync(link, "utf8"), "#!/usr/bin/env node\nconsole.log('nanoid');\n");
});