aboutsummaryrefslogtreecommitdiffstats
path: root/gateway/src/voice-session.js
blob: 039df7b09d9618e47f4f43fa76007057f3ecb72b (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
// One browser <-> TeamSpeak voice session.
//
// Wire protocol on /ws/voice (no WebRTC; everything rides on this WebSocket):
//   browser -> gateway  JSON  {type:"join", nickname, password, channelId?, channelPassword?, identity?, serverDecode?}
//                       JSON  {type:"move", channelId, password?} | {type:"mute", muted} | {type:"deafen", deafened}
//                             {type:"chat", scope?:"channel"|"server"|"private", message, targetId?}
//                             {type:"whisper", targetIds:number[], active:boolean}
//                             {type:"leave"}
//                       binary  1920 bytes = 20 ms of 48 kHz mono Int16LE PCM from the microphone
//   gateway -> browser  JSON  {type:"joined"|"state"|"chatMessage"|"whisperTargets"|"error"|"disconnected", ...}
//                       binary  [kind u8][clientId u16BE][payload]
//                               kind 4/5 = TeamSpeak Opus (voice/music) frame, decoded by WebCodecs in the browser
//                               kind 0xF0 = 48 kHz mono Int16LE PCM (gateway-side decode fallback)
//                               an empty payload marks the end of that speaker's transmission
import { WebSocket } from "ws";
import {
  asChannelID,
  asClientID,
  moveClient,
  sendChannelMessage,
  sendPrivateMessage,
  sendServerMessage,
  updateClient,
} from "@honeybbq/teamspeak";
import { Client, generateIdentity, parseIdentity, subscribeAllChannels } from "@honeybbq/teamspeak/client";
import { createOpusCodec, FRAME_BYTES } from "./opus.js";
import { passwordMatches, sanitizeNickname } from "./auth.js";

const CONNECT_TIMEOUT_MS = 15_000;
const STATE_THROTTLE_MS = 150;
const END_OF_SPEECH_MS = 100;
const OPUS_BITRATE = 40_000;
const MAX_BUFFERED_OPUS_BYTES = 8 * 1024;
const MAX_BUFFERED_PCM_BYTES = 32 * 1024;
const MAX_SPEAKER_DECODERS = 16;
const MAX_CHAT_LENGTH = 1024;
const MAX_WHISPER_TARGETS = 32;
const KIND_PCM = 0xf0;
// Token bucket for microphone frames: 50 frames/s nominal, small burst allowance.
const FRAME_RATE = 55;
const FRAME_BURST = 25;

const ERROR_TEXT = {
  1028: ["BAD_PASSWORD", "The TeamSpeak server rejected the password."],
  781: ["CHANNEL_PASSWORD", "Wrong channel password."],
  513: ["NICKNAME_IN_USE", "That nickname is already in use."],
  514: ["NICKNAME_INVALID", "That nickname is not allowed."],
  521: ["TOO_MANY_CLONES", "Too many connections from this gateway."],
  524: ["FLOODING", "Slow down, the server thinks you are flooding."],
  777: ["CHANNEL_FULL", "That channel is full."],
  770: ["ALREADY_IN_CHANNEL", "You are already in that channel."],
  2568: ["NO_PERMISSION", "You do not have permission to do that."],
  3329: ["BANNED", "You are banned from this server."],
};

function describeError(error) {
  for (let e = error, depth = 0; e && depth < 5; e = e.cause, depth++) {
    if (typeof e.code === "number" && ERROR_TEXT[e.code]) {
      const [code, message] = ERROR_TEXT[e.code];
      return { code, message };
    }
  }
  const message = error instanceof Error ? error.message : String(error);
  if (/abort|timeout|timed out/i.test(message)) return { code: "TIMEOUT", message: "Timed out reaching the TeamSpeak server." };
  return { code: "TEAMSPEAK_ERROR", message: message.slice(0, 200) || "TeamSpeak error" };
}

function snapshot(client) {
  const view = client.view;
  return {
    serverName: view.serverName ?? "",
    self: { id: Number(client.clientID), channelId: String(client.channelID) },
    channels: [...view.channels.values()].map((c) => ({
      id: String(c.id),
      parentId: String(c.parentID),
      order: String(c.order),
      name: c.name,
      hasPassword: Boolean(c.hasPassword),
    })),
    clients: [...view.clients.values()].map((e) => ({
      id: Number(e.id),
      nickname: e.nickname,
      channelId: String(e.channelID),
      type: e.type,
      away: Boolean(e.isAway),
      awayMessage: e.awayMessage ?? "",
      inputMuted: Boolean(e.isInputMuted),
      outputMuted: Boolean(e.isOutputMuted),
      serverGroups: (e.serverGroups ?? []).map(String),
    })),
  };
}

const CHANNEL_ID = /^\d{1,20}$/;

export class VoiceSession {
  /**
   * @param {WebSocket} ws
   * @param {{ip: string, config: ReturnType<import("./config.js").loadConfig>, limiter: import("./auth.js").LoginLimiter, log: Console, onClose: () => void}} ctx
   */
  constructor(ws, ctx) {
    this.ws = ws;
    this.ctx = ctx;
    this.client = null;
    this.state = "awaiting-join"; // -> connecting -> ready -> closed
    this.muted = false;
    this.deafened = false;
    this.serverDecode = false;
    this.encoder = null;
    this.decoders = new Map();
    this.whisperTargetIds = new Set();
    this.whisperActive = false;
    this.stateTimer = null;
    this.eosTimer = null;
    this.tokens = FRAME_BURST;
    this.tokensAt = Date.now();
    this.badFrames = 0;
    this.kickReason = "";
    this.unsubscribers = [];
    this.closing = false;

    this.joinTimer = setTimeout(() => this.fail("JOIN_TIMEOUT", "No join request received.", 4408), 20_000);
    ws.on("message", (data, isBinary) => {
      if (isBinary) this.onPcm(data);
      else this.onJson(data);
    });
    ws.on("close", () => this.close());
    ws.on("error", () => this.close());
  }

  send(message) {
    if (this.ws.readyState === WebSocket.OPEN) this.ws.send(JSON.stringify(message));
  }

  fail(code, message, closeCode = 4400) {
    this.send({ type: "error", code, message, fatal: true });
    try { this.ws.close(closeCode, code.slice(0, 60)); } catch { /* already closed */ }
    this.close();
  }

  error(code, message) {
    this.send({ type: "error", code, message, fatal: false });
  }

  onJson(data) {
    let msg;
    try {
      msg = JSON.parse(String(data));
    } catch {
      return this.fail("BAD_MESSAGE", "Malformed message.");
    }
    if (!msg || typeof msg !== "object") return this.fail("BAD_MESSAGE", "Malformed message.");

    if (msg.type === "join") return void this.join(msg);
    if (this.state !== "ready") return this.error("NOT_READY", "Not connected yet.");
    switch (msg.type) {
      case "move": return void this.move(msg);
      case "mute": return void this.setMuted(Boolean(msg.muted));
      case "deafen": return void this.setDeafened(Boolean(msg.deafened));
      case "chat": return void this.sendChat(msg);
      case "whisper": return void this.setWhisper(msg);
      case "leave": return void this.close();
      default: return this.error("UNKNOWN_MESSAGE", "Unknown message type.");
    }
  }

  async join(msg) {
    if (this.state !== "awaiting-join") return this.error("ALREADY_JOINED", "Already joined.");
    clearTimeout(this.joinTimer);
    const { config, limiter, ip, log } = this.ctx;

    if (!config.server.password) return this.fail("VOICE_DISABLED", "Web voice is disabled: no server password is configured.", 4403);
    if (!config.server.host) return this.fail("NOT_CONFIGURED", "The TeamSpeak host is not configured.", 4503);

    const lockedMs = limiter.lockedFor(ip);
    if (lockedMs > 0) {
      return this.fail("LOCKED_OUT", `Too many wrong passwords. Try again in ${Math.ceil(lockedMs / 60_000)} min.`, 4429);
    }
    // The gateway itself verifies the server password before spending any
    // resources on a TeamSpeak connection; the TeamSpeak server checks it again.
    if (!passwordMatches(msg.password, config.server.password)) {
      limiter.recordFailure(ip);
      log.warn(`[voice] wrong password from ${ip}`);
      return this.fail("BAD_PASSWORD", "Wrong server password.", 4401);
    }
    limiter.recordSuccess(ip);

    const nickname = sanitizeNickname(msg.nickname, config.voice.nicknamePrefix);
    if (!nickname) return this.fail("NICKNAME_INVALID", "Nickname must be 3-30 characters.");

    let targetChannel = null;
    if (msg.channelId !== undefined && msg.channelId !== null && msg.channelId !== "") {
      if (!CHANNEL_ID.test(String(msg.channelId))) return this.fail("BAD_CHANNEL", "Invalid channel.");
      targetChannel = String(msg.channelId);
    }
    this.serverDecode = msg.serverDecode === true;
    this.state = "connecting";

    let identity = null;
    if (typeof msg.identity === "string" && msg.identity.length > 0 && msg.identity.length < 512) {
      try { identity = parseIdentity(msg.identity); } catch { identity = null; }
    }
    try {
      identity ??= await generateIdentity(config.voice.identitySecurityLevel, { signal: AbortSignal.timeout(CONNECT_TIMEOUT_MS) });
    } catch {
      return this.fail("IDENTITY_FAILED", "Could not create a TeamSpeak identity.", 4500);
    }
    if (this.closing) return;

    const client = new Client(identity, `${config.server.host}:${config.server.voicePort}`, nickname, {
      serverPassword: config.server.password,
      defaultChannel: config.voice.defaultChannel || undefined,
      logger: {
        debug() {},
        info() {},
        warn: (m) => log.warn(`[ts ${nickname}] ${m}`),
        error: (m) => log.error(`[ts ${nickname}] ${m}`),
      },
    });
    this.client = client;
    this.attachClientEvents(client);

    try {
      await client.connect({ signal: AbortSignal.timeout(CONNECT_TIMEOUT_MS) });
      await client.view.whenReady({ signal: AbortSignal.timeout(CONNECT_TIMEOUT_MS) });
    } catch (error) {
      if (this.closing) return;
      const { code, message } = describeError(error);
      log.warn(`[voice] ${ip} could not connect as "${nickname}": ${code} ${error?.message ?? ""}`);
      return this.fail(code, message, 4502);
    }
    if (this.closing) return;

    try {
      // Without this the server only reports clients of our own channel.
      await subscribeAllChannels(client, { timeoutMs: 5000 });
    } catch (error) {
      log.warn(`[voice] could not subscribe to all channels: ${error?.message ?? error}`);
    }

    this.encoder = createOpusCodec({ bitrate: OPUS_BITRATE });
    this.state = "ready";
    log.info(`[voice] ${ip} joined as "${nickname}" (clid ${client.clientID})`);
    this.send({ type: "joined", identity: identity.export(), nickname, ...snapshot(client) });

    if (targetChannel && targetChannel !== String(client.channelID)) {
      await this.move({ channelId: targetChannel, password: msg.channelPassword });
    }
  }

  attachClientEvents(client) {
    const on = (event, fn) => this.unsubscribers.push(client.on(event, fn));
    on("viewChanged", () => this.scheduleState());
    on("clientMoved", () => this.scheduleState());
    on("clientLeave", (event) => {
      const id = Number(event?.clientID);
      const decoder = this.decoders.get(id);
      if (decoder) { decoder.dispose(); this.decoders.delete(id); }
      if (this.whisperTargetIds.delete(id)) {
        if (!this.whisperTargetIds.size) this.whisperActive = false;
        this.send({ type: "whisperTargets", targetIds: [...this.whisperTargetIds], active: this.whisperActive });
      }
    });
    on("textMessage", (event) => {
      const scope = event.targetMode === 1 ? "private" : event.targetMode === 2 ? "channel" : "server";
      if (scope === "private" && Number(event.invokerID) === Number(client.clientID)) return;
      const targetId = scope === "channel"
        ? String(client.channelID)
        : event.targetID ? String(event.targetID) : undefined;
      this.send({
        type: "chatMessage",
        scope,
        ...(targetId ? { targetId } : {}),
        invokerId: Number(event.invokerID),
        invokerName: event.invokerName,
        senderUid: String(event.invokerUID ?? ""),
        message: event.message,
        timestamp: Date.now(),
      });
    });
    on("kicked", (event) => { this.kickReason = event?.reasonMessage ?? ""; });
    on("voiceData", (event) => this.onTeamSpeakVoice(event));
    on("disconnected", (event) => {
      if (this.closing || this.state !== "ready") return;
      const reason = this.kickReason
        ? `Kicked: ${this.kickReason}`
        : event?.error ? describeError(event.error).message : "Disconnected from TeamSpeak.";
      this.send({ type: "disconnected", reason });
      try { this.ws.close(1000, "disconnected"); } catch { /* ignore */ }
      this.close();
    });
  }

  scheduleState() {
    if (this.stateTimer || this.state !== "ready") return;
    this.stateTimer = setTimeout(() => {
      this.stateTimer = null;
      if (this.state === "ready" && this.client) this.send({ type: "state", ...snapshot(this.client) });
    }, STATE_THROTTLE_MS);
  }

  async move(msg) {
    const id = String(msg.channelId ?? "");
    if (!CHANNEL_ID.test(id)) return this.error("BAD_CHANNEL", "Invalid channel.");
    const password = typeof msg.password === "string" && msg.password ? msg.password.slice(0, 512) : undefined;
    try {
      await moveClient(this.client, this.client.clientID, asChannelID(BigInt(id)), { password, timeoutMs: 5000 });
      this.scheduleState();
    } catch (error) {
      const { code, message } = describeError(error);
      this.send({ type: "error", code, message, fatal: false, channelId: id });
    }
  }

  async sendChat(msg) {
    const text = typeof msg.message === "string" ? msg.message.trim().slice(0, MAX_CHAT_LENGTH) : "";
    if (!text) return;
    const scope = msg.scope === "private" ? "private" : msg.scope === "server" ? "server" : "channel";
    try {
      if (scope === "private") {
        const targetId = Number(msg.targetId);
        if (!Number.isInteger(targetId) || targetId <= 0 || targetId > 65535) {
          return this.error("BAD_TARGET", "Invalid private message recipient.");
        }
        await sendPrivateMessage(this.client, asClientID(targetId), text, { timeoutMs: 5000 });
        const selfId = Number(this.client.clientID);
        const selfEntry = this.client.view?.clients?.get?.(this.client.clientID);
        this.send({
          type: "chatMessage",
          scope: "private",
          targetId: String(targetId),
          invokerId: selfId,
          invokerName: selfEntry?.nickname || "you",
          senderUid: "",
          message: text,
          timestamp: Date.now(),
        });
      } else if (scope === "server") {
        await sendServerMessage(this.client, text, { timeoutMs: 5000 });
      } else {
        await sendChannelMessage(this.client, text, { timeoutMs: 5000 });
      }
    } catch (error) {
      const { code, message } = describeError(error);
      this.error(code, message);
    }
  }

  setWhisper(msg) {
    const selfId = Number(this.client?.clientID ?? 0);
    if (Array.isArray(msg.targetIds)) {
      const clean = [];
      for (const raw of msg.targetIds) {
        const id = Number(raw);
        if (Number.isInteger(id) && id > 0 && id <= 65535 && id !== selfId && !clean.includes(id)) {
          clean.push(id);
          if (clean.length >= MAX_WHISPER_TARGETS) break;
        }
      }
      this.whisperTargetIds = new Set(clean);
    }
    if (typeof msg.active === "boolean") {
      this.whisperActive = msg.active && this.whisperTargetIds.size > 0;
    } else if (!this.whisperTargetIds.size) {
      this.whisperActive = false;
    }
    this.send({ type: "whisperTargets", targetIds: [...this.whisperTargetIds], active: this.whisperActive });
  }

  async setMuted(muted) {
    this.muted = muted;
    if (muted) this.endOfSpeech();
    try { await updateClient(this.client, { isInputMuted: muted }, { timeoutMs: 5000 }); }
    catch (error) { this.error(describeError(error).code, "Could not update mute state."); }
  }

  async setDeafened(deafened) {
    this.deafened = deafened;
    try { await updateClient(this.client, { isOutputMuted: deafened }, { timeoutMs: 5000 }); }
    catch (error) { this.error(describeError(error).code, "Could not update deafen state."); }
  }

  // ---- audio ----------------------------------------------------------------

  takeToken() {
    const now = Date.now();
    this.tokens = Math.min(FRAME_BURST, this.tokens + ((now - this.tokensAt) / 1000) * FRAME_RATE);
    this.tokensAt = now;
    if (this.tokens < 1) return false;
    this.tokens -= 1;
    return true;
  }

  sendVoiceOrWhisper(payload) {
    if (this.whisperActive && this.whisperTargetIds.size > 0) {
      this.client.sendWhisper(payload, { clients: [...this.whisperTargetIds].map(asClientID) }, 4 /* Codec.OpusVoice */);
    } else {
      this.client.sendVoice(payload, 4 /* Codec.OpusVoice */);
    }
  }

  onPcm(frame) {
    if (this.state !== "ready" || this.muted || !this.encoder) return;
    if (!Buffer.isBuffer(frame) || frame.length !== FRAME_BYTES) {
      if (++this.badFrames > 100) this.fail("BAD_AUDIO", "Malformed audio frames.");
      return;
    }
    if (!this.takeToken()) return;
    try {
      const encoded = this.encoder.encode(frame);
      this.sendVoiceOrWhisper(encoded);
    } catch {
      return;
    }
    clearTimeout(this.eosTimer);
    this.eosTimer = setTimeout(() => this.endOfSpeech(), END_OF_SPEECH_MS);
  }

  /** An empty voice packet tells TeamSpeak clients the transmission ended. */
  endOfSpeech() {
    clearTimeout(this.eosTimer);
    this.eosTimer = null;
    if (this.state !== "ready") return;
    try { this.sendVoiceOrWhisper(new Uint8Array(0)); } catch { /* not connected */ }
  }

  speakerDecoder(clientId) {
    let decoder = this.decoders.get(clientId);
    if (decoder) {
      this.decoders.delete(clientId); // refresh LRU position
    } else {
      decoder = createOpusCodec();
      while (this.decoders.size >= MAX_SPEAKER_DECODERS) {
        const [oldestId, oldest] = this.decoders.entries().next().value;
        oldest.dispose();
        this.decoders.delete(oldestId);
      }
    }
    this.decoders.set(clientId, decoder);
    return decoder;
  }

  onTeamSpeakVoice(event) {
    if (this.state !== "ready" || this.deafened || this.ws.readyState !== WebSocket.OPEN) return;
    const clientId = Number(event.clientID);
    if (clientId === Number(this.client.clientID) || clientId < 1 || clientId > 65535) return;
    if (event.codec !== 4 && event.codec !== 5) return; // legacy Speex/CELT are not supported
    const data = event.data instanceof Uint8Array ? event.data : new Uint8Array(0);

    let kind = event.codec;
    let payload = data;
    if (this.serverDecode) {
      if (this.ws.bufferedAmount > MAX_BUFFERED_PCM_BYTES) return;
      kind = KIND_PCM;
      if (data.length > 0) {
        try { payload = this.speakerDecoder(clientId).decode(Buffer.from(data.buffer, data.byteOffset, data.byteLength)); }
        catch { return; }
      }
    } else if (this.ws.bufferedAmount > MAX_BUFFERED_OPUS_BYTES) {
      return;
    }

    const packet = Buffer.allocUnsafe(3 + payload.length);
    packet[0] = kind;
    packet.writeUInt16BE(clientId, 1);
    packet.set(payload, 3);
    this.ws.send(packet);
  }

  // ---- teardown -------------------------------------------------------------

  close() {
    if (this.closing) return;
    this.closing = true;
    const wasReady = this.state === "ready";
    this.state = "closed";
    clearTimeout(this.joinTimer);
    clearTimeout(this.stateTimer);
    clearTimeout(this.eosTimer);
    for (const off of this.unsubscribers) { try { off(); } catch { /* ignore */ } }
    this.unsubscribers = [];
    try { this.encoder?.dispose(); } catch { /* ignore */ }
    this.encoder = null;
    for (const decoder of this.decoders.values()) { try { decoder.dispose(); } catch { /* ignore */ } }
    this.decoders.clear();
    this.whisperTargetIds.clear();
    this.whisperActive = false;
    const client = this.client;
    this.client = null;
    if (client) {
      client.disconnect({ reasonMessage: "Left from the web", signal: AbortSignal.timeout(2000) })
        .catch(() => undefined);
    }
    if (wasReady) this.ctx.log.info(`[voice] ${this.ctx.ip} left`);
    if (this.ws.readyState === WebSocket.OPEN || this.ws.readyState === WebSocket.CONNECTING) {
      try { this.ws.close(1000, "bye"); } catch { /* ignore */ }
    }
    this.ctx.onClose();
  }
}
send patches to the email below
yukais@pinapelz.com
include the subject [PATCH repo_name]
pinapelz.com
homepage