@honeybbq/teamspeak 1.0.0-beta.11 → 1.0.0-beta.13

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (187) hide show
  1. package/README.md +52 -7
  2. package/dist/client/api/voice.d.ts +13 -0
  3. package/dist/client/api/voice.d.ts.map +1 -1
  4. package/dist/client/api/voice.js +20 -1
  5. package/dist/client/api/voice.js.map +1 -1
  6. package/dist/client/capabilities.d.ts +4 -4
  7. package/dist/client/capabilities.d.ts.map +1 -1
  8. package/dist/client/capabilities.js +3 -8
  9. package/dist/client/capabilities.js.map +1 -1
  10. package/dist/client/client.d.ts.map +1 -1
  11. package/dist/client/client.js +120 -18
  12. package/dist/client/client.js.map +1 -1
  13. package/dist/client/crypto/crypt.d.ts +25 -4
  14. package/dist/client/crypto/crypt.d.ts.map +1 -1
  15. package/dist/client/crypto/crypt.js +41 -9
  16. package/dist/client/crypto/crypt.js.map +1 -1
  17. package/dist/client/crypto/identity.d.ts +2 -0
  18. package/dist/client/crypto/identity.d.ts.map +1 -1
  19. package/dist/client/crypto/identity.js +2 -2
  20. package/dist/client/crypto/identity.js.map +1 -1
  21. package/dist/client/crypto/index.d.ts +1 -1
  22. package/dist/client/crypto/index.d.ts.map +1 -1
  23. package/dist/client/crypto/index.js +1 -1
  24. package/dist/client/crypto/index.js.map +1 -1
  25. package/dist/client/errors.d.ts +14 -0
  26. package/dist/client/errors.d.ts.map +1 -1
  27. package/dist/client/errors.js +28 -0
  28. package/dist/client/errors.js.map +1 -1
  29. package/dist/client/handshake/crypt-handshake.d.ts +8 -2
  30. package/dist/client/handshake/crypt-handshake.d.ts.map +1 -1
  31. package/dist/client/handshake/crypt-handshake.js +26 -20
  32. package/dist/client/handshake/crypt-handshake.js.map +1 -1
  33. package/dist/client/index.d.ts +3 -3
  34. package/dist/client/index.d.ts.map +1 -1
  35. package/dist/client/index.js +2 -2
  36. package/dist/client/index.js.map +1 -1
  37. package/dist/client/trace.d.ts +7 -0
  38. package/dist/client/trace.d.ts.map +1 -1
  39. package/dist/client/transport/handler.d.ts +2 -0
  40. package/dist/client/transport/handler.d.ts.map +1 -1
  41. package/dist/client/transport/handler.js +4 -0
  42. package/dist/client/transport/handler.js.map +1 -1
  43. package/dist/client/types.d.ts +25 -3
  44. package/dist/client/types.d.ts.map +1 -1
  45. package/dist/client/types.js +4 -0
  46. package/dist/client/types.js.map +1 -1
  47. package/dist/client/view.d.ts +71 -4
  48. package/dist/client/view.d.ts.map +1 -1
  49. package/dist/client/view.js +165 -5
  50. package/dist/client/view.js.map +1 -1
  51. package/dist/core/api/channels.d.ts +7 -3
  52. package/dist/core/api/channels.d.ts.map +1 -1
  53. package/dist/core/api/channels.js +5 -3
  54. package/dist/core/api/channels.js.map +1 -1
  55. package/dist/core/api/clients.d.ts +38 -1
  56. package/dist/core/api/clients.d.ts.map +1 -1
  57. package/dist/core/api/clients.js +33 -2
  58. package/dist/core/api/clients.js.map +1 -1
  59. package/dist/core/api/command.d.ts +18 -1
  60. package/dist/core/api/command.d.ts.map +1 -1
  61. package/dist/core/api/command.js +7 -1
  62. package/dist/core/api/command.js.map +1 -1
  63. package/dist/core/api/group-rows.d.ts +12 -0
  64. package/dist/core/api/group-rows.d.ts.map +1 -0
  65. package/dist/core/api/group-rows.js +34 -0
  66. package/dist/core/api/group-rows.js.map +1 -0
  67. package/dist/core/api/groups.d.ts.map +1 -1
  68. package/dist/core/api/groups.js +2 -13
  69. package/dist/core/api/groups.js.map +1 -1
  70. package/dist/core/api/instance.d.ts +10 -2
  71. package/dist/core/api/instance.d.ts.map +1 -1
  72. package/dist/core/api/instance.js +6 -2
  73. package/dist/core/api/instance.js.map +1 -1
  74. package/dist/core/api/moderation.d.ts +7 -0
  75. package/dist/core/api/moderation.d.ts.map +1 -1
  76. package/dist/core/api/moderation.js +7 -0
  77. package/dist/core/api/moderation.js.map +1 -1
  78. package/dist/core/api/parse.d.ts.map +1 -1
  79. package/dist/core/api/parse.js +1 -0
  80. package/dist/core/api/parse.js.map +1 -1
  81. package/dist/core/api/server.d.ts +9 -0
  82. package/dist/core/api/server.d.ts.map +1 -1
  83. package/dist/core/api/server.js +5 -13
  84. package/dist/core/api/server.js.map +1 -1
  85. package/dist/core/command/responses.d.ts.map +1 -1
  86. package/dist/core/command/responses.js +1 -0
  87. package/dist/core/command/responses.js.map +1 -1
  88. package/dist/core/errorcode.d.ts +16 -0
  89. package/dist/core/errorcode.d.ts.map +1 -1
  90. package/dist/core/errorcode.js +16 -0
  91. package/dist/core/errorcode.js.map +1 -1
  92. package/dist/core/events.d.ts +67 -6
  93. package/dist/core/events.d.ts.map +1 -1
  94. package/dist/core/index.d.ts +2 -2
  95. package/dist/core/index.d.ts.map +1 -1
  96. package/dist/core/index.js +1 -1
  97. package/dist/core/index.js.map +1 -1
  98. package/dist/core/internal.d.ts +1 -0
  99. package/dist/core/internal.d.ts.map +1 -1
  100. package/dist/core/internal.js +1 -0
  101. package/dist/core/internal.js.map +1 -1
  102. package/dist/core/notification-name.d.ts +4 -0
  103. package/dist/core/notification-name.d.ts.map +1 -1
  104. package/dist/core/notification-name.js +4 -0
  105. package/dist/core/notification-name.js.map +1 -1
  106. package/dist/core/notifications.d.ts +6 -2
  107. package/dist/core/notifications.d.ts.map +1 -1
  108. package/dist/core/notifications.js +32 -1
  109. package/dist/core/notifications.js.map +1 -1
  110. package/dist/core/types.d.ts +7 -0
  111. package/dist/core/types.d.ts.map +1 -1
  112. package/dist/core/types.js +16 -0
  113. package/dist/core/types.js.map +1 -1
  114. package/dist/query/client.d.ts +16 -7
  115. package/dist/query/client.d.ts.map +1 -1
  116. package/dist/query/client.js +55 -20
  117. package/dist/query/client.js.map +1 -1
  118. package/dist/query/errors.d.ts +21 -0
  119. package/dist/query/errors.d.ts.map +1 -1
  120. package/dist/query/errors.js +34 -0
  121. package/dist/query/errors.js.map +1 -1
  122. package/dist/query/index.d.ts +4 -3
  123. package/dist/query/index.d.ts.map +1 -1
  124. package/dist/query/index.js +3 -2
  125. package/dist/query/index.js.map +1 -1
  126. package/dist/query/options.d.ts +32 -19
  127. package/dist/query/options.d.ts.map +1 -1
  128. package/dist/query/options.js +21 -16
  129. package/dist/query/options.js.map +1 -1
  130. package/dist/query/ssh.d.ts +3 -1
  131. package/dist/query/ssh.d.ts.map +1 -1
  132. package/dist/query/ssh.js +4 -1
  133. package/dist/query/ssh.js.map +1 -1
  134. package/dist/query/stream.d.ts +16 -3
  135. package/dist/query/stream.d.ts.map +1 -1
  136. package/dist/query/stream.js +57 -6
  137. package/dist/query/stream.js.map +1 -1
  138. package/dist/query/tcp.js +1 -1
  139. package/dist/query/tcp.js.map +1 -1
  140. package/dist/query/transport.d.ts +39 -3
  141. package/dist/query/transport.d.ts.map +1 -1
  142. package/dist/query/web.d.ts +25 -7
  143. package/dist/query/web.d.ts.map +1 -1
  144. package/dist/query/web.js +40 -10
  145. package/dist/query/web.js.map +1 -1
  146. package/package.json +6 -5
  147. package/src/client/api/voice.ts +25 -1
  148. package/src/client/capabilities.ts +14 -11
  149. package/src/client/client.ts +128 -14
  150. package/src/client/crypto/crypt.ts +46 -9
  151. package/src/client/crypto/identity.ts +2 -2
  152. package/src/client/crypto/index.ts +1 -0
  153. package/src/client/errors.ts +31 -0
  154. package/src/client/handshake/crypt-handshake.ts +51 -16
  155. package/src/client/index.ts +4 -1
  156. package/src/client/trace.ts +7 -0
  157. package/src/client/transport/handler.ts +5 -0
  158. package/src/client/types.ts +25 -1
  159. package/src/client/view.ts +227 -8
  160. package/src/core/api/channels.ts +9 -3
  161. package/src/core/api/clients.ts +73 -2
  162. package/src/core/api/command.ts +22 -1
  163. package/src/core/api/group-rows.ts +38 -0
  164. package/src/core/api/groups.ts +1 -14
  165. package/src/core/api/instance.ts +20 -2
  166. package/src/core/api/moderation.ts +7 -0
  167. package/src/core/api/parse.ts +1 -0
  168. package/src/core/api/server.ts +13 -15
  169. package/src/core/command/responses.ts +1 -0
  170. package/src/core/errorcode.ts +16 -0
  171. package/src/core/events.ts +68 -6
  172. package/src/core/index.ts +2 -1
  173. package/src/core/internal.ts +1 -0
  174. package/src/core/notification-name.ts +4 -0
  175. package/src/core/notifications.ts +48 -17
  176. package/src/core/types.ts +14 -0
  177. package/src/query/client.ts +63 -20
  178. package/src/query/errors.ts +37 -0
  179. package/src/query/index.ts +9 -3
  180. package/src/query/options.ts +53 -33
  181. package/src/query/ssh.ts +9 -2
  182. package/src/query/stream.ts +65 -7
  183. package/src/query/tcp.ts +1 -1
  184. package/src/query/testing/live.ts +311 -0
  185. package/src/query/testing/ssh-keys.ts +67 -0
  186. package/src/query/transport.ts +40 -3
  187. package/src/query/web.ts +65 -16
@@ -8,7 +8,7 @@
8
8
  */
9
9
 
10
10
  import type { Client } from "../client.js";
11
- import { ErrorCode, ServerError } from "@honeybbq/teamspeak";
11
+ import { ErrorCode, NoDataError, ServerError } from "@honeybbq/teamspeak";
12
12
  import type { ChannelID, ClientID, CommandOptions } from "@honeybbq/teamspeak";
13
13
 
14
14
  /**
@@ -32,6 +32,30 @@ export async function getChannelDescription(
32
32
  return answer?.["channel_description"] ?? "";
33
33
  }
34
34
 
35
+ /**
36
+ * The virtual server's properties as the server sends them on request, which
37
+ * is a different set from `getServerInfo`'s: it has the settings, limits and
38
+ * counters (clients online, uptime, traffic) and lacks the identity ones such as
39
+ * the unique identifier. It is the whole row, counters included.
40
+ *
41
+ * The client's `view.server` takes every answer in, whoever asked, less the
42
+ * counters, so this is also how to bring it up to date after an edit the
43
+ * server did not spell out. The answer goes to the asker alone.
44
+ *
45
+ * @experimental New in 1.x and may change in a minor release.
46
+ */
47
+ export async function getServerVariables(
48
+ client: Client,
49
+ options?: CommandOptions,
50
+ ): Promise<Readonly<Record<string, string>>> {
51
+ const rows = await client.send({ command: "servergetvariables" }, options);
52
+ const answer = rows.find((row) =>
53
+ Object.keys(row).some((key) => key.startsWith("virtualserver_")),
54
+ );
55
+ if (answer === undefined) throw new NoDataError("servergetvariables");
56
+ return answer;
57
+ }
58
+
35
59
  /**
36
60
  * Subscribe to a channel: receive its clients' events and voice without
37
61
  * joining it.
@@ -12,7 +12,14 @@
12
12
  * round trip.
13
13
  */
14
14
 
15
- import { asServerID, type IconID, type ServerFamily, type ServerID } from "@honeybbq/teamspeak";
15
+ import {
16
+ asServerID,
17
+ HostMessageMode,
18
+ serverFamilyForVersion,
19
+ type IconID,
20
+ type ServerFamily,
21
+ type ServerID,
22
+ } from "@honeybbq/teamspeak";
16
23
  import { parseIconID, parseUint64 } from "../core/internal.js";
17
24
  import { uidAlgorithmForVersion, type UIDAlgorithm } from "./crypto/identity.js";
18
25
 
@@ -51,10 +58,10 @@ export interface ServerCapabilities {
51
58
  readonly hostMessage: string;
52
59
  /**
53
60
  * How the host message is to be shown (`virtualserver_hostmessage_mode`).
54
- * Compare it with `HostMessageMode`; a server may send a value the table
55
- * does not name.
61
+ * A value the `HostMessageMode` table does not name is passed through as the
62
+ * server sent it.
56
63
  */
57
- readonly hostMessageMode: number;
64
+ readonly hostMessageMode: HostMessageMode;
58
65
  }
59
66
 
60
67
  /**
@@ -70,14 +77,10 @@ export function parseServerCapabilities(
70
77
  const parsed = Number.parseInt(version, 10);
71
78
  const major = Number.isNaN(parsed) ? 0 : parsed;
72
79
 
73
- let family: ServerFamily = "unknown";
74
- if (major === 3) family = "ts3";
75
- else if (major >= 6) family = "ts6";
76
-
77
80
  return {
78
81
  version,
79
82
  major,
80
- family,
83
+ family: serverFamilyForVersion(version),
81
84
  uidAlgorithm: uidAlgorithmForVersion(version),
82
85
  name: params["virtualserver_name"] ?? "",
83
86
  iconID: parseIconID(params["virtualserver_icon_id"]),
@@ -100,7 +103,7 @@ export function unknownServerCapabilities(): ServerCapabilities {
100
103
  return parseServerCapabilities("");
101
104
  }
102
105
 
103
- function hostMessageMode(value: string | undefined): number {
106
+ function hostMessageMode(value: string | undefined): HostMessageMode {
104
107
  const parsed = Number.parseInt(value ?? "", 10);
105
- return Number.isNaN(parsed) ? 0 : parsed;
108
+ return (Number.isNaN(parsed) ? HostMessageMode.None : parsed) as HostMessageMode;
106
109
  }
@@ -16,7 +16,7 @@ import { callHook } from "./hooks.js";
16
16
  import { puzzleOf } from "./handshake/crypt-handshake.js";
17
17
  import {
18
18
  type ChannelID,
19
- type ClientEnterEvent,
19
+ type ClientEntry,
20
20
  type ClientID,
21
21
  type Codec,
22
22
  type KickedEvent,
@@ -67,7 +67,13 @@ import {
67
67
  import type { ClientVersion, CommandExecutor, CommandRequest } from "@honeybbq/teamspeak";
68
68
  import { handleNotification } from "../core/internal.js";
69
69
  import type { NotificationResult } from "../core/internal.js";
70
- import { parseChannel, parseCommand } from "../core/internal.js";
70
+ import {
71
+ parseChannel,
72
+ parseChannelGroup,
73
+ parseCommand,
74
+ parseServerGroup,
75
+ parseUint16,
76
+ } from "../core/internal.js";
71
77
  import { CommandThrottle } from "./throttle.js";
72
78
  import { splitCommandRows, sleep } from "../core/internal.js";
73
79
  import { isAutoNicknameMatch } from "./helpers.js";
@@ -146,7 +152,7 @@ export interface ClientInternals {
146
152
  nickname: string;
147
153
  clid: number;
148
154
  /** The clients this one knows of, as its events and `invokerGroups` read them. */
149
- readonly clients: ReadonlyMap<number, ClientEnterEvent>;
155
+ readonly clients: ReadonlyMap<number, ClientEntry>;
150
156
  capabilities: ServerCapabilities;
151
157
  /** Mark the attempt in progress connected. */
152
158
  markConnected(initServer?: Readonly<Record<string, string>>): void;
@@ -211,6 +217,27 @@ interface AttemptTrace {
211
217
  welcomeDone: boolean;
212
218
  /** The channel rows the welcome sequence has delivered so far. */
213
219
  channels: number;
220
+ /** Where the key exchange stands, before the shared secret exists. */
221
+ stage: "init1" | "puzzleSolving" | "puzzleAnswered";
222
+ /** The last Init1 step of the server's that was answered; -1 for none. */
223
+ init1Step: number;
224
+ }
225
+
226
+ /** What an attempt is waiting for now, for the report of an attempt that ended. */
227
+ function describeWaiting(trace: AttemptTrace, clientEkPending: boolean): string {
228
+ if (trace.phase === ConnectPhase.Open) {
229
+ return trace.target === "" ? "the server address to resolve" : "the connection to open";
230
+ }
231
+ if (trace.phase === ConnectPhase.Join) {
232
+ return clientEkPending
233
+ ? "the server's answer to clientek"
234
+ : "the server's answer to clientinit";
235
+ }
236
+ if (trace.stage === "puzzleSolving") return "the RSA puzzle to be solved";
237
+ if (trace.stage === "puzzleAnswered") return "the server's answer to the RSA puzzle";
238
+ return trace.init1Step < 0
239
+ ? "the server's first answer to init1"
240
+ : `the server's init1 step after step ${trace.init1Step}`;
214
241
  }
215
242
 
216
243
  /** A session that began with `sessionStart`, until its `sessionEnd`. */
@@ -401,13 +428,15 @@ export class Client implements CommandExecutor, AsyncDisposable {
401
428
  #throttle = new CommandThrottle();
402
429
  #cmdTrack = new CommandTracker(() => this.#clid);
403
430
  #viewStore: ViewStore;
404
- #clients: Map<number, ClientEnterEvent>;
431
+ #clients: Map<number, ClientEntry>;
405
432
  #attempt: ConnectAttempt = newConnectAttempt();
406
433
 
407
434
  #listeners = new Map<keyof EventMap, Subscription[]>();
408
435
  /** Deliveries waiting for their turn; see #emit. */
409
436
  #queue: Array<() => void> = [];
410
437
  #draining = false;
438
+ /** The group list rows of the command line being handled, by the name of the line. */
439
+ #groupLine: { readonly name: string; readonly rows: Array<Record<string, string>> } | undefined;
411
440
  #voiceDropped = 0;
412
441
  #voiceDropWarnedAt = -Infinity;
413
442
 
@@ -426,7 +455,11 @@ export class Client implements CommandExecutor, AsyncDisposable {
426
455
  this.#fileTransferSocketFactory = options.fileTransferSocketFactory;
427
456
  this.#reconnectOptions = options.reconnect;
428
457
  this.#trace = options.trace === undefined ? undefined : { ...options.trace };
429
- this.#viewStore = new ViewStore(this.#logger, () => this.#clid);
458
+ this.#viewStore = new ViewStore(
459
+ this.#logger,
460
+ () => this.#clid,
461
+ () => this.#scheduleDrain(),
462
+ );
430
463
  this.#clients = this.#viewStore.roster;
431
464
 
432
465
  this.#crypt = new Crypt(identity);
@@ -565,17 +598,27 @@ export class Client implements CommandExecutor, AsyncDisposable {
565
598
  sessionStarted: false,
566
599
  welcomeDone: false,
567
600
  channels: 0,
601
+ stage: "init1",
602
+ init1Step: -1,
568
603
  };
569
604
  attempt.trace = trace;
570
- attempt.onFail = (error) =>
605
+ attempt.onFail = (error) => {
606
+ const waitingFor = describeWaiting(trace, this.#handler.clientEkPending);
607
+ this.#logger.info("connection attempt ended", {
608
+ phase: trace.phase,
609
+ waitingFor,
610
+ error: String(error),
611
+ });
571
612
  this.#callHook(this.#trace?.attemptFailed, () => ({
572
613
  attempt: trace.attempt,
573
614
  reconnect: trace.reconnect,
574
615
  phase: trace.phase,
575
616
  error,
576
617
  target: trace.target,
618
+ waitingFor,
577
619
  durationMs: performance.now() - trace.startedAt,
578
620
  }));
621
+ };
579
622
 
580
623
  // The handshake may complete just as the signal fires, in which case
581
624
  // #failConnection leaves the session alone and the caller gets the
@@ -1362,9 +1405,30 @@ export class Client implements CommandExecutor, AsyncDisposable {
1362
1405
  const pType = p.typeFlagged & 0x0f;
1363
1406
  if (pType === 8 /* Init1 */) {
1364
1407
  if (this.#crypt.cryptoInitComplete) return;
1365
- const response = processInit1(this.#crypt, p.data);
1366
- if (response) {
1367
- this.#handler.sendPacket(PacketType.Init1, response, 0);
1408
+ const signal = this.#attempt.signal;
1409
+ const handler = this.#handler;
1410
+ const trace = this.#attempt.trace;
1411
+ const step = p.data[0] ?? 0x7f;
1412
+ const response = processInit1(this.#crypt, p.data, signal);
1413
+ if (response instanceof Promise) {
1414
+ // The puzzle: solved in slices, so the loop keeps running meanwhile.
1415
+ if (trace !== undefined) trace.stage = "puzzleSolving";
1416
+ response.then(
1417
+ (answer) => {
1418
+ if (answer && !signal.aborted) {
1419
+ handler.sendPacket(PacketType.Init1, answer, 0);
1420
+ if (trace !== undefined) trace.stage = "puzzleAnswered";
1421
+ }
1422
+ },
1423
+ (error: unknown) => {
1424
+ // An attempt that ended did so for its own reason; the abandoned
1425
+ // solve has nothing more to report.
1426
+ if (!signal.aborted) this.#handleReceiveError(error);
1427
+ },
1428
+ );
1429
+ } else if (response) {
1430
+ handler.sendPacket(PacketType.Init1, response, 0);
1431
+ if (trace !== undefined) trace.init1Step = step === 0x7f ? -1 : step;
1368
1432
  }
1369
1433
  return;
1370
1434
  }
@@ -1414,6 +1478,26 @@ export class Client implements CommandExecutor, AsyncDisposable {
1414
1478
  for (const row of splitCommandRows(trimmed)) {
1415
1479
  this.#handleCommandStr(row);
1416
1480
  }
1481
+ this.#applyGroupLine();
1482
+ }
1483
+ }
1484
+
1485
+ /**
1486
+ * A group list is a whole set, and the server sends it as one command line,
1487
+ * so it is applied once its last row has been handled.
1488
+ */
1489
+ #applyGroupLine(): void {
1490
+ const line = this.#groupLine;
1491
+ if (line === undefined) return;
1492
+ this.#groupLine = undefined;
1493
+ if (line.name === "notifyservergrouplist") {
1494
+ this.#viewStore.setServerGroups(
1495
+ line.rows.map(parseServerGroup).filter((group) => group.id !== 0n),
1496
+ );
1497
+ } else {
1498
+ this.#viewStore.setChannelGroups(
1499
+ line.rows.map(parseChannelGroup).filter((group) => group.id !== 0n),
1500
+ );
1417
1501
  }
1418
1502
  }
1419
1503
 
@@ -1487,8 +1571,20 @@ export class Client implements CommandExecutor, AsyncDisposable {
1487
1571
  this.#cmdTrack.offerCorrelated(cmd.name, cmd.params);
1488
1572
  }
1489
1573
  if (cmd.name === "notifyconnectioninforequest") this.#answerConnectionInfoRequest();
1574
+ if (cmd.name === "notifyservergrouplist" || cmd.name === "notifychannelgrouplist") {
1575
+ if (this.#groupLine?.name !== cmd.name) this.#applyGroupLine();
1576
+ this.#groupLine ??= { name: cmd.name, rows: [] };
1577
+ this.#groupLine.rows.push(cmd.params);
1578
+ } else if (cmd.name === "notifyserverupdated") {
1579
+ this.#viewStore.mergeServer(cmd.params);
1580
+ }
1581
+ // The roster entry goes with the notification, so it is read first.
1582
+ const leaving =
1583
+ cmd.name === "notifyclientleftview"
1584
+ ? this.#clients.get(parseUint16(cmd.params["clid"] ?? ""))
1585
+ : undefined;
1490
1586
  const result = handleNotification(cmd, this.#clid, this.#clients);
1491
- this.#processNotificationResult(result);
1587
+ this.#processNotificationResult(result, leaving);
1492
1588
  if (this.#listeners.get("notification")?.length || this.#eventMiddlewares.length > 0) {
1493
1589
  this.#emitServerEvent({
1494
1590
  name: "notification",
@@ -1513,6 +1609,7 @@ export class Client implements CommandExecutor, AsyncDisposable {
1513
1609
  // report a connection whose next command — clientinit with its password
1514
1610
  // hashes among them — goes out under that dummy key.
1515
1611
  if (this.#status === ClientStatus.Connecting && this.#crypt.cryptoInitComplete) {
1612
+ this.#viewStore.seedServer(cmd.params);
1516
1613
  handleInitServer(this.#internals, cmd.params);
1517
1614
  }
1518
1615
  break;
@@ -1569,7 +1666,7 @@ export class Client implements CommandExecutor, AsyncDisposable {
1569
1666
  }
1570
1667
  }
1571
1668
 
1572
- #processNotificationResult(result: NotificationResult): void {
1669
+ #processNotificationResult(result: NotificationResult, leaving?: ClientEntry): void {
1573
1670
  switch (result.kind) {
1574
1671
  case "clientEnter": {
1575
1672
  const info = result.info;
@@ -1598,7 +1695,7 @@ export class Client implements CommandExecutor, AsyncDisposable {
1598
1695
  break;
1599
1696
  }
1600
1697
  case "clientLeave": {
1601
- const event = result.event;
1698
+ const event = leaving === undefined ? result.event : { ...result.event, previous: leaving };
1602
1699
  this.#emitServerEvent({ name: "clientLeave", payload: event });
1603
1700
  if (!result.isSelf) break;
1604
1701
  if (event.reason === Reason.KickServer || event.reason === Reason.KickServerBan) {
@@ -1649,10 +1746,15 @@ export class Client implements CommandExecutor, AsyncDisposable {
1649
1746
  this.#viewStore.applyMoved(result.event);
1650
1747
  this.#emitServerEvent({ name: "channelMoved", payload: result.event });
1651
1748
  break;
1652
- case "channelDeleted":
1749
+ case "channelDeleted": {
1750
+ const previous = this.#viewStore.channelBeforeDeletion(result.event.channelID);
1653
1751
  this.#viewStore.applyDeleted(result.event);
1654
- this.#emitServerEvent({ name: "channelDeleted", payload: result.event });
1752
+ this.#emitServerEvent({
1753
+ name: "channelDeleted",
1754
+ payload: previous === undefined ? result.event : { ...result.event, previous },
1755
+ });
1655
1756
  break;
1757
+ }
1656
1758
  case "channelDescriptionChanged":
1657
1759
  this.#emitServerEvent({ name: "channelDescriptionChanged", payload: result.event });
1658
1760
  break;
@@ -1660,6 +1762,7 @@ export class Client implements CommandExecutor, AsyncDisposable {
1660
1762
  this.#emitServerEvent({ name: "channelPasswordChanged", payload: result.event });
1661
1763
  break;
1662
1764
  case "serverEdited":
1765
+ this.#viewStore.patchServer(result.event.changes);
1663
1766
  this.#emitServerEvent({ name: "serverEdited", payload: result.event });
1664
1767
  break;
1665
1768
  case "channelSubscribed":
@@ -1676,6 +1779,9 @@ export class Client implements CommandExecutor, AsyncDisposable {
1676
1779
  case "clientChatComposing":
1677
1780
  this.#emitServerEvent({ name: "clientChatComposing", payload: result.event });
1678
1781
  break;
1782
+ case "clientChatClosed":
1783
+ this.#emitServerEvent({ name: "clientChatClosed", payload: result.event });
1784
+ break;
1679
1785
  case "poked":
1680
1786
  this.#emitServerEvent({ name: "poked", payload: result.event });
1681
1787
  break;
@@ -1768,6 +1874,10 @@ export class Client implements CommandExecutor, AsyncDisposable {
1768
1874
  */
1769
1875
  #enqueue(delivery: () => void): void {
1770
1876
  this.#queue.push(delivery);
1877
+ this.#scheduleDrain();
1878
+ }
1879
+
1880
+ #scheduleDrain(): void {
1771
1881
  if (this.#draining) return;
1772
1882
  this.#draining = true;
1773
1883
  setImmediate(this.#drain);
@@ -1776,6 +1886,10 @@ export class Client implements CommandExecutor, AsyncDisposable {
1776
1886
  #drain = (): void => {
1777
1887
  try {
1778
1888
  while (this.#queue.length > 0) this.#queue.shift()!();
1889
+ // Everything handled so far is delivered: say once that the view moved.
1890
+ // Listeners cannot change the view, so this is the last word of the run.
1891
+ const revision = this.#viewStore.announce();
1892
+ if (revision !== undefined) this.#deliver("viewChanged", { revision });
1779
1893
  } finally {
1780
1894
  if (this.#queue.length > 0) setImmediate(this.#drain);
1781
1895
  else this.#draining = false;
@@ -1,6 +1,6 @@
1
1
  import { createHash, createECDH, randomBytes } from "node:crypto";
2
2
  import type { KeyObject } from "node:crypto";
3
- import { HandshakeError, FakeSignatureMismatchError } from "../errors.js";
3
+ import { HandshakeError, FakeSignatureMismatchError, PuzzleTooHardError } from "../errors.js";
4
4
  import type { Identity } from "./identity.js";
5
5
  import { identityPrivateKey, importPublicKey } from "./identity.js";
6
6
  import { EAX } from "./eax.js";
@@ -13,11 +13,25 @@ const PACKET_TYPE_MASK = 0x0f;
13
13
  const INIT1_MAC = Buffer.from("TS3INIT1");
14
14
 
15
15
  /**
16
- * The most squarings the Init1 puzzle may ask for. TS3 3.13 and TS6 6.0 both
17
- * ask for 10000; a level far beyond that is a server trying to pin the event
18
- * loop, since the squarings run synchronously.
16
+ * The most squarings the Init1 puzzle may ask for. A server raises its puzzle
17
+ * level while it is flooded with connections. Measured, TS3 3.13 and TS6 6.0
18
+ * both ask for 10000 when calm, 100000 at protection level 1 and 1000000 at
19
+ * level 2, the highest they reach; a level lasts about 75 seconds after the
20
+ * burst that raised it. A squaring takes about 0.3 microseconds here, so those
21
+ * take 3 ms, 30 ms and 300 ms. The cap is four times the highest level seen,
22
+ * 1.2 s of work here. The solve gives the event loop back every
23
+ * {@link SQUARINGS_PER_SLICE} squarings and stops when the connect is
24
+ * cancelled, so a level near the cap costs the caller at most what the caller
25
+ * allows the connect to take, and blocks nothing in the meantime; a level above
26
+ * it is refused with a {@link PuzzleTooHardError}.
19
27
  */
20
- export const MAX_RSA_CHALLENGE_LEVEL: number = 100_000;
28
+ export const MAX_RSA_CHALLENGE_LEVEL: number = 4_000_000;
29
+
30
+ /**
31
+ * How many squarings the solve does before it lets the event loop run: about
32
+ * 15 ms of work, so a timer or another connection waits no longer than that.
33
+ */
34
+ export const SQUARINGS_PER_SLICE = 50_000;
21
35
 
22
36
  export interface KeyNonce {
23
37
  key: Uint8Array;
@@ -69,10 +83,26 @@ export class Crypt {
69
83
  return this.#alpha;
70
84
  }
71
85
 
72
- solveRsaChallenge(data: Uint8Array, offset: number, level: number): Uint8Array {
73
- if (!Number.isInteger(level) || level < 0 || level > MAX_RSA_CHALLENGE_LEVEL) {
86
+ /**
87
+ * Answer the Init1 puzzle: square `x` modulo `n` `level` times, `x` and `n`
88
+ * being the two 64-byte numbers at `offset` in `data`. Rejects with a
89
+ * {@link PuzzleTooHardError} for a level above {@link MAX_RSA_CHALLENGE_LEVEL},
90
+ * with a {@link HandshakeError} for a level or modulus that is no puzzle, and
91
+ * with `signal`'s reason when it aborts, checked between slices of
92
+ * {@link SQUARINGS_PER_SLICE} squarings.
93
+ */
94
+ async solveRsaChallenge(
95
+ data: Uint8Array,
96
+ offset: number,
97
+ level: number,
98
+ signal?: AbortSignal,
99
+ ): Promise<Uint8Array> {
100
+ if (!Number.isInteger(level) || level < 0) {
74
101
  throw new HandshakeError(`RSA challenge level ${level} out of range`);
75
102
  }
103
+ if (level > MAX_RSA_CHALLENGE_LEVEL) {
104
+ throw new PuzzleTooHardError(level, MAX_RSA_CHALLENGE_LEVEL);
105
+ }
76
106
 
77
107
  const xBytes = data.slice(offset, offset + 64);
78
108
  const nBytes = data.slice(offset + 64, offset + 128);
@@ -81,9 +111,16 @@ export class Crypt {
81
111
  const n = bytesToBigInt(nBytes);
82
112
  if (n === 0n) throw new HandshakeError("RSA challenge modulus is zero");
83
113
 
84
- for (let i = 0; i < level; i++) {
85
- y = (y * y) % n;
114
+ for (let done = 0; done < level;) {
115
+ signal?.throwIfAborted();
116
+ const slice = level - done < SQUARINGS_PER_SLICE ? level - done : SQUARINGS_PER_SLICE;
117
+ for (let i = 0; i < slice; i++) {
118
+ y = (y * y) % n;
119
+ }
120
+ done += slice;
121
+ if (done < level) await new Promise<void>((resolve) => setImmediate(resolve));
86
122
  }
123
+ signal?.throwIfAborted();
87
124
 
88
125
  return bigIntToBytes(y, 64);
89
126
  }
@@ -13,8 +13,8 @@ const P256_SCALAR_SIZE = 32;
13
13
  const P256_UNCOMPRESSED_KEY_SIZE = 65;
14
14
  const P256_POINT_PREFIX = 0x04;
15
15
 
16
- /** The most a security level can be: SHA-1 is 160 bits wide. */
17
- const MAX_SECURITY_LEVEL = 160;
16
+ /** The highest security level there is: the level counts zero bits of a SHA-1 digest, which has 160. */
17
+ export const MAX_SECURITY_LEVEL = 160;
18
18
 
19
19
  let createIdentity: (privateKey: KeyObject, offset: bigint) => Identity;
20
20
  let privateKeyOf: (identity: Identity) => KeyObject;
@@ -5,6 +5,7 @@ export {
5
5
  generateIdentitySync,
6
6
  uidFromPublicKey,
7
7
  uidAlgorithmForVersion,
8
+ MAX_SECURITY_LEVEL,
8
9
  hash512,
9
10
  importPublicKey,
10
11
  } from "./identity.js";
@@ -121,6 +121,37 @@ export class HandshakeError extends TeamspeakError {
121
121
  }
122
122
  }
123
123
 
124
+ /**
125
+ * The server's Init1 puzzle asks for more squarings than this client will do:
126
+ * a server that is flooded raises the level, but not this far. `connect()`
127
+ * rejects with it, as with any {@link HandshakeError}, and nothing was solved.
128
+ */
129
+ export class PuzzleTooHardError extends HandshakeError {
130
+ /** {@inheritDoc @honeybbq/teamspeak!TeamspeakError.kind} */
131
+ static override readonly kind: string = "PuzzleTooHardError";
132
+ static {
133
+ // On the prototype, not the instance, as built-in errors do: an own `name`
134
+ // would be enumerable and show up in JSON.stringify and object spread.
135
+ Object.defineProperty(this.prototype, "name", {
136
+ value: "PuzzleTooHardError",
137
+ writable: true,
138
+ configurable: true,
139
+ enumerable: false,
140
+ });
141
+ }
142
+
143
+ /** The number of squarings the server asked for. */
144
+ readonly level: number;
145
+ /** The most this client does. */
146
+ readonly maxLevel: number;
147
+
148
+ constructor(level: number, maxLevel: number) {
149
+ super(`the server's RSA puzzle asks for ${level} squarings, more than the ${maxLevel} allowed`);
150
+ this.level = level;
151
+ this.maxLevel = maxLevel;
152
+ }
153
+ }
154
+
124
155
  /** An identity string `parseIdentity()` cannot read. */
125
156
  export class InvalidIdentityError extends TeamspeakError {
126
157
  /** {@inheritDoc @honeybbq/teamspeak!TeamspeakError.kind} */
@@ -1,7 +1,7 @@
1
1
  import { randomBytes } from "node:crypto";
2
2
  import { buildCommandOrdered } from "../../core/internal.js";
3
- import type { Crypt } from "../crypto/crypt.js";
4
- import { HandshakeError } from "../errors.js";
3
+ import { MAX_RSA_CHALLENGE_LEVEL, type Crypt } from "../crypto/crypt.js";
4
+ import { HandshakeError, PuzzleTooHardError } from "../errors.js";
5
5
 
6
6
  export const INIT_VERSION = 1566914096; // 3.5.0 [Stable]
7
7
 
@@ -9,6 +9,9 @@ const INIT_VERSION_LEN = 4;
9
9
  const INIT_TYPE_LEN = 1;
10
10
  const INIT_STEP_LEN = 21;
11
11
 
12
+ /** The RSA challenge each connection attempt, by its Crypt, is solving now. */
13
+ const solvingChallenges = new WeakMap<Crypt, Uint8Array>();
14
+
12
15
  /** The RSA challenge each connection attempt, by its Crypt, has answered. */
13
16
  const answeredChallenges = new WeakMap<
14
17
  Crypt,
@@ -33,8 +36,23 @@ export function puzzleOf(crypt: Crypt): { readonly level: number; readonly durat
33
36
  * Handle the TS3INIT1 handshake steps.
34
37
  * Returns the response bytes to send, or null if nothing should be sent.
35
38
  * Throws a HandshakeError for a step that cannot be answered.
39
+ *
40
+ * The puzzle step is the only one that takes time, so a challenge not answered
41
+ * before returns a promise of the response, which gives the event loop back
42
+ * while it solves and rejects with `signal`'s reason once that aborts. Nothing
43
+ * else the server sends is answered until it settles.
36
44
  */
37
- export function processInit1(crypt: Crypt, data: Uint8Array | null): Uint8Array | null {
45
+ export function processInit1(crypt: Crypt, data: null): Uint8Array;
46
+ export function processInit1(
47
+ crypt: Crypt,
48
+ data: Uint8Array | null,
49
+ signal?: AbortSignal,
50
+ ): Uint8Array | null | Promise<Uint8Array | null>;
51
+ export function processInit1(
52
+ crypt: Crypt,
53
+ data: Uint8Array | null,
54
+ signal?: AbortSignal,
55
+ ): Uint8Array | null | Promise<Uint8Array | null> {
38
56
  if (data === null || (data.length >= 1 && data[0] === 0x7f)) {
39
57
  return buildInit1StartPacket();
40
58
  }
@@ -48,7 +66,7 @@ export function processInit1(crypt: Crypt, data: Uint8Array | null): Uint8Array
48
66
  case 2:
49
67
  return buildInit1Step3Packet(data);
50
68
  case 3:
51
- return buildInit1Step4Packet(crypt, data);
69
+ return buildInit1Step4Packet(crypt, data, signal);
52
70
  case undefined:
53
71
  default:
54
72
  return null;
@@ -111,21 +129,43 @@ function buildInit1Step3Packet(data: Uint8Array): Uint8Array | null {
111
129
  return sendData;
112
130
  }
113
131
 
114
- function buildInit1Step4Packet(crypt: Crypt, data: Uint8Array): Uint8Array | null {
132
+ function buildInit1Step4Packet(
133
+ crypt: Crypt,
134
+ data: Uint8Array,
135
+ signal: AbortSignal | undefined,
136
+ ): Uint8Array | null | Promise<Uint8Array | null> {
115
137
  if (data.length !== INIT_TYPE_LEN + 64 + 64 + 4 + 100) return null;
116
138
  // One challenge per connection attempt, whose Crypt is its own. Each answer
117
- // costs up to a second of synchronous squarings, and a second would choose a
118
- // new alpha behind the clientinitiv already sent. The same challenge again
119
- // means the server did not get our answer, so it gets the same answer,
120
- // without solving anything; a different one gets none.
139
+ // can cost seconds of squarings, and a second would choose a new alpha
140
+ // behind the clientinitiv already sent. The same challenge again means the
141
+ // server did not get our answer, so it gets the same answer, without solving
142
+ // anything; a different one gets none. While one is being solved, all of
143
+ // them wait for it.
121
144
  const answered = answeredChallenges.get(crypt);
122
145
  if (answered !== undefined) {
123
146
  return Buffer.from(answered.challenge).equals(Buffer.from(data)) ? answered.answer : null;
124
147
  }
148
+ if (solvingChallenges.has(crypt)) return null;
125
149
 
126
150
  const level = new DataView(data.buffer, data.byteOffset).getUint32(1 + 128, false);
151
+ // A level too high is refused here, at once, before anything is solved.
152
+ if (level > MAX_RSA_CHALLENGE_LEVEL) throw new PuzzleTooHardError(level, MAX_RSA_CHALLENGE_LEVEL);
153
+
154
+ const challenge = Uint8Array.from(data);
155
+ solvingChallenges.set(crypt, challenge);
156
+ return solveInit1Challenge(crypt, challenge, level, signal).finally(() => {
157
+ solvingChallenges.delete(crypt);
158
+ });
159
+ }
160
+
161
+ async function solveInit1Challenge(
162
+ crypt: Crypt,
163
+ data: Uint8Array,
164
+ level: number,
165
+ signal: AbortSignal | undefined,
166
+ ): Promise<Uint8Array> {
127
167
  const solveStarted = performance.now();
128
- const y = crypt.solveRsaChallenge(data, 1, level);
168
+ const y = await crypt.solveRsaChallenge(data, 1, level, signal);
129
169
  const durationMs = performance.now() - solveStarted;
130
170
 
131
171
  const alphaB64 = Buffer.from(crypt.newAlpha()).toString("base64");
@@ -147,11 +187,6 @@ function buildInit1Step4Packet(crypt: Crypt, data: Uint8Array): Uint8Array | nul
147
187
  sendData.set(y.slice(0, 64), 5 + 232);
148
188
  sendData.set(cmdBytes, 5 + 232 + 64);
149
189
 
150
- answeredChallenges.set(crypt, {
151
- challenge: Uint8Array.from(data),
152
- answer: sendData,
153
- level,
154
- durationMs,
155
- });
190
+ answeredChallenges.set(crypt, { challenge: data, answer: sendData, level, durationMs });
156
191
  return sendData;
157
192
  }
@@ -12,7 +12,7 @@
12
12
  export { Client } from "./client.js";
13
13
  export { EventName, GroupWhisperType, GroupWhisperScope } from "./types.js";
14
14
 
15
- export type { ServerView, ViewReadyEvent, ViewStatus } from "./view.js";
15
+ export type { ServerView, ViewChangedEvent, ViewReadyEvent, ViewStatus } from "./view.js";
16
16
 
17
17
  export type {
18
18
  EventMap,
@@ -33,6 +33,7 @@ export type {
33
33
  export {
34
34
  FileTransferError,
35
35
  HandshakeError,
36
+ PuzzleTooHardError,
36
37
  InvalidAddressError,
37
38
  InvalidIdentityError,
38
39
  RemovedError,
@@ -93,5 +94,7 @@ export {
93
94
  generateIdentity,
94
95
  generateIdentitySync,
95
96
  uidFromPublicKey,
97
+ uidAlgorithmForVersion,
98
+ MAX_SECURITY_LEVEL,
96
99
  } from "./crypto/index.js";
97
100
  export type { UIDAlgorithm } from "./crypto/index.js";
@@ -136,6 +136,13 @@ export interface AttemptFailedInfo extends AttemptInfo {
136
136
  readonly error: unknown;
137
137
  /** The `host:port` being dialled; empty when the attempt failed before `resolveDone`. */
138
138
  readonly target: string;
139
+ /**
140
+ * What the attempt was waiting for when it ended, in words for a person or a
141
+ * log, such as `the server's answer to clientek`. It is finer than
142
+ * {@link AttemptFailedInfo.phase}, and its wording may change in any release:
143
+ * do not match on it.
144
+ */
145
+ readonly waitingFor: string;
139
146
  /** Milliseconds since `resolveStart`. */
140
147
  readonly durationMs: number;
141
148
  }