@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
@@ -2,13 +2,14 @@ import {
2
2
  AlreadyConnectedError,
3
3
  ClientStatus,
4
4
  CommandTimeoutError,
5
+ ErrorCode,
5
6
  NotConnectedError,
6
7
  Reason,
7
8
  ServerError,
8
9
  TeamspeakError,
9
10
  backoffDelay,
10
11
  noopLogger,
11
- type ClientEnterEvent,
12
+ type ClientEntry,
12
13
  type CommandExecutor,
13
14
  type CommandMiddleware,
14
15
  type CommandOptions,
@@ -17,6 +18,7 @@ import {
17
18
  type Listener,
18
19
  type Logger,
19
20
  type ReconnectOptions,
21
+ serverFamilyForVersion,
20
22
  type ServerEventMap,
21
23
  type ServerFamily,
22
24
  type ServerID,
@@ -32,10 +34,11 @@ import {
32
34
  parseServerError,
33
35
  resolveBackoffPolicy,
34
36
  } from "../core/internal.js";
35
- import type { QueryTransport } from "./transport.js";
37
+ import type { QueryTransport, QueryTransportStats } from "./transport.js";
36
38
  import { connectTcp } from "./tcp.js";
37
39
  import { connectSsh } from "./ssh.js";
38
40
  import { WebQueryTransport } from "./web.js";
41
+ import { GuestAccessError, QueryAuthError } from "./errors.js";
39
42
  import {
40
43
  assertEventsSupported,
41
44
  normalizeQueryOptions,
@@ -152,7 +155,7 @@ export class QueryClient implements CommandExecutor, AsyncDisposable {
152
155
  * 0 until it is known.
153
156
  */
154
157
  #clid = 0;
155
- #clients = new Map<number, ClientEnterEvent>();
158
+ #clients = new Map<number, ClientEntry>();
156
159
 
157
160
  #reconnectOptions: ReconnectOptions | undefined;
158
161
  #reconnecting = false;
@@ -229,12 +232,32 @@ export class QueryClient implements CommandExecutor, AsyncDisposable {
229
232
  return this.#version;
230
233
  }
231
234
 
235
+ /**
236
+ * What the current connection reports about itself: its kind, where it
237
+ * points, when it opened and how many bytes went each way, for a metrics
238
+ * exporter. Read-only. A client with no connection, and a `custom` transport
239
+ * that keeps no counts, report no kind, an empty address, no open time and
240
+ * zero bytes. A reconnection starts the counts again.
241
+ *
242
+ * @experimental Part of the entry, which may change in a minor release.
243
+ */
244
+ get stats(): QueryTransportStats {
245
+ return (
246
+ this.#transport?.stats?.() ?? {
247
+ connectedAt: undefined,
248
+ transport: undefined,
249
+ address: "",
250
+ bytesSent: 0,
251
+ bytesReceived: 0,
252
+ }
253
+ );
254
+ }
255
+
232
256
  /**
233
257
  * The transport carrying this connection, or `undefined` when there is none.
234
258
  *
235
259
  * Read-only, and the transport is the interface the client itself talks
236
- * over — counts of what went out and came in, and which connection it is,
237
- * can be read from it for metrics. The socket underneath is not exposed:
260
+ * over. The socket underneath is not exposed:
238
261
  * a caller that needs it supplies the seam instead (the `connect` option of
239
262
  * a `tcp` transport, or `connection` of an `ssh` one), where it is theirs to
240
263
  * keep.
@@ -259,11 +282,11 @@ export class QueryClient implements CommandExecutor, AsyncDisposable {
259
282
  // ---- Connection -----------------------------------------------------------
260
283
 
261
284
  /**
262
- * Connect and set the session up: open the transport, then `login` (raw TCP
263
- * only), `use`, `version`, the notification registrations, and one client
285
+ * Connect and set the session up: open the transport, then `login` (the raw
286
+ * TCP transport's `login` option), `use`, `version`, the notification registrations, and one client
264
287
  * list.
265
288
  *
266
- * The `login` and `server` options are applied here rather than left to the
289
+ * The transport's `login` and the `server` option are applied here rather than left to the
267
290
  * caller so that a reconnection is the same session as the first connection
268
291
  * was.
269
292
  *
@@ -318,6 +341,33 @@ export class QueryClient implements CommandExecutor, AsyncDisposable {
318
341
  * the same session the first connection was.
319
342
  */
320
343
  async #establish(signal: AbortSignal | undefined, generation: number): Promise<void> {
344
+ try {
345
+ await this.#establishSession(signal, generation);
346
+ } catch (error) {
347
+ throw this.#guestRefusal(error) ?? error;
348
+ }
349
+ }
350
+
351
+ /**
352
+ * The refusal of a guest connection by a server with no guest access, as
353
+ * itself: 5124 over WebQuery, a failed `guest` authentication over SSH.
354
+ */
355
+ #guestRefusal(error: unknown): GuestAccessError | undefined {
356
+ const transport = this.#options.transport;
357
+ if (transport.kind === "web" && transport.apiKey === undefined) {
358
+ if (error instanceof ServerError && error.code === ErrorCode.APIKeyMissing) {
359
+ return new GuestAccessError(error, error.code);
360
+ }
361
+ } else if (
362
+ transport.kind === "ssh" &&
363
+ (transport.connect as { guest?: unknown }).guest === true
364
+ ) {
365
+ if (error instanceof QueryAuthError) return new GuestAccessError(error);
366
+ }
367
+ return undefined;
368
+ }
369
+
370
+ async #establishSession(signal: AbortSignal | undefined, generation: number): Promise<void> {
321
371
  const transport = await this.#openTransport(signal);
322
372
  // Given up on while the transport was being opened: it is closed rather
323
373
  // than installed, and the caller hears that nothing is connected.
@@ -349,12 +399,13 @@ export class QueryClient implements CommandExecutor, AsyncDisposable {
349
399
  transport.onLine = (line) => this.#handleLine(line);
350
400
  transport.onClose = (error) => this.#handleClose(error);
351
401
 
352
- const { login, server, nickname, eventCategories } = this.#options;
402
+ const { transport: resolvedTransport, server, nickname, eventCategories } = this.#options;
403
+ const login = resolvedTransport.kind === "tcp" ? resolvedTransport.login : undefined;
353
404
  if (login !== undefined) await this.login(login.name, login.password, { signal });
354
405
  // Not `use()`: this session learns who it is, and who is there, once, below.
355
406
  if (server !== undefined) await this.#select(server, { nickname, signal });
356
407
  this.#version = await this.#getVersion(signal);
357
- this.#serverFamily = serverFamilyOf(this.#version);
408
+ this.#serverFamily = serverFamilyForVersion(this.#version);
358
409
  // Like the version, a failure here fails the connect: a client that cannot
359
410
  // tell which one it is would miss its own kick without saying so.
360
411
  await this.#learnSelf(signal);
@@ -446,7 +497,7 @@ export class QueryClient implements CommandExecutor, AsyncDisposable {
446
497
  * server refuses the command; over SSH the session is logged in already.
447
498
  *
448
499
  * Public because a caller driving the client by hand needs it: `connect()`
449
- * runs it from the `login` option, and this is the same `login` command.
500
+ * runs it from the tcp transport's `login` option, and this is the same `login` command.
450
501
  *
451
502
  * On TeamSpeak 3 a failed login gets the caller's IP address banned for 600
452
503
  * seconds, so a retry loop on a wrong password locks itself out of every
@@ -990,6 +1041,7 @@ export class QueryClient implements CommandExecutor, AsyncDisposable {
990
1041
  case "channelUnsubscribed":
991
1042
  case "pluginCommand":
992
1043
  case "clientChatComposing":
1044
+ case "clientChatClosed":
993
1045
  // Neither a TeamSpeak 3 ServerQuery connection nor a TeamSpeak 6 one over
994
1046
  // SSH is sent these (measured), so a query client does not offer them.
995
1047
  // Should a server send one, the clients it knows are still kept current
@@ -1239,15 +1291,6 @@ function serverIDOf(server: ResolvedQueryOptions["server"]): ServerID | number |
1239
1291
  return server !== undefined && "id" in server ? server.id : undefined;
1240
1292
  }
1241
1293
 
1242
- /** Which server generation a `version` string names. */
1243
- function serverFamilyOf(version: string): ServerFamily {
1244
- const major = Number.parseInt(version, 10);
1245
- if (Number.isNaN(major)) return "unknown";
1246
- if (major === 3) return "ts3";
1247
- if (major >= 6) return "ts6";
1248
- return "unknown";
1249
- }
1250
-
1251
1294
  /** Sleep, or wake early once `signal` aborts. Resolves either way, never rejects. */
1252
1295
  function sleep(ms: number, signal: AbortSignal): Promise<void> {
1253
1296
  if (ms <= 0 || signal.aborted) return Promise.resolve();
@@ -106,3 +106,40 @@ export class QueryAuthError extends TeamspeakError {
106
106
  this.username = username;
107
107
  }
108
108
  }
109
+
110
+ /**
111
+ * A connection made with `guest: true` was refused because the server offers
112
+ * no guest access. TeamSpeak 3 has none, and a TeamSpeak 6 server started with
113
+ * guest access off refuses the same way.
114
+ *
115
+ * Over WebQuery the server answers a request without an api key with 5124
116
+ * (`ErrorCode.APIKeyMissing`); over SSH it fails the `guest` user's
117
+ * authentication. The server's own error is kept as `cause`, and over WebQuery
118
+ * its code as {@link GuestAccessError.code}, so the refusal can still be
119
+ * matched by number.
120
+ *
121
+ * @experimental Part of the `@honeybbq/teamspeak/query` entry, which may
122
+ * change in a minor release.
123
+ */
124
+ export class GuestAccessError extends TeamspeakError {
125
+ /** {@inheritDoc @honeybbq/teamspeak!TeamspeakError.kind} */
126
+ static override readonly kind: string = "GuestAccessError";
127
+ static {
128
+ Object.defineProperty(this.prototype, "name", {
129
+ value: "GuestAccessError",
130
+ writable: true,
131
+ configurable: true,
132
+ enumerable: false,
133
+ });
134
+ }
135
+
136
+ /** The server's error code when it sent one (5124 over WebQuery); `undefined` over SSH. */
137
+ readonly code: number | undefined;
138
+
139
+ constructor(cause: Error, code?: number) {
140
+ super(`the server does not offer guest access (TeamSpeak 3 has none): ${cause.message}`, {
141
+ cause,
142
+ });
143
+ this.code = code;
144
+ }
145
+ }
@@ -4,7 +4,8 @@
4
4
  * ServerQuery is the administrative interface to a TeamSpeak server: the voice
5
5
  * protocol's commands, plus the ones only an administrator can run. This entry
6
6
  * runs the same typed commands as `@honeybbq/teamspeak`,
7
- * over raw TCP (10011), SSH (10022) or TeamSpeak 6's HTTP WebQuery (10080).
7
+ * over raw TCP (10011, TeamSpeak 3), SSH (10022) or WebQuery, the HTTP interface
8
+ * of TeamSpeak 3 (3.12 and later) and TeamSpeak 6 (10080).
8
9
  *
9
10
  * Only what belongs to ServerQuery is exported here. The typed commands, ids
10
11
  * and errors every client shares come from `@honeybbq/teamspeak`.
@@ -30,13 +31,18 @@ export type {
30
31
  QueryTransportOptions,
31
32
  } from "./client.js";
32
33
 
33
- export type { QueryTransport } from "./transport.js";
34
+ export type { QueryTransport, QueryTransportStats } from "./transport.js";
34
35
 
35
36
  // Reconnection: the client's default retry decision, and the shared options.
36
37
  export { defaultShouldRetry } from "./reconnect.js";
37
38
 
38
39
  // Errors unique to ServerQuery.
39
- export { MissingDependencyError, QueryAuthError, SshHostKeyError } from "./errors.js";
40
+ export {
41
+ GuestAccessError,
42
+ MissingDependencyError,
43
+ QueryAuthError,
44
+ SshHostKeyError,
45
+ } from "./errors.js";
40
46
 
41
47
  // The transports each `transport` kind builds on, for a caller that wants one
42
48
  // directly or that is writing its own `custom` opener.
@@ -27,6 +27,13 @@ export type QueryTransportOptions =
27
27
  * {@link TcpOptions.connect}.
28
28
  */
29
29
  readonly connect?: TcpConnector | undefined;
30
+ /**
31
+ * The query account to log in as, sent as a `login` command once the
32
+ * connection is open, and again on every reconnect. Left out, the
33
+ * session starts unauthenticated. SSH and WebQuery carry their
34
+ * credentials in their own arm.
35
+ */
36
+ readonly login?: { readonly name: string; readonly password: string } | undefined;
30
37
  }
31
38
  | ({
32
39
  /**
@@ -37,11 +44,19 @@ export type QueryTransportOptions =
37
44
  readonly kind: "ssh";
38
45
  } & SshConnectOptions)
39
46
  | ({
40
- /** TeamSpeak 6's HTTP WebQuery. */
47
+ /** WebQuery, the HTTP interface of TeamSpeak 3 (3.12 and later) and TeamSpeak 6. */
41
48
  readonly kind: "web";
42
- /** The server's base URL, such as `http://127.0.0.1:10080`. */
49
+ /**
50
+ * The server's base URL, such as `http://127.0.0.1:10080` or
51
+ * `https://ts.example.com:10443`.
52
+ */
43
53
  readonly url: string;
44
- /** The `fetch` to use; a small one over `node:http` by default. */
54
+ /**
55
+ * The `fetch` to use; by default a small one over `node:http` or
56
+ * `node:https` by the URL's scheme, verifying an HTTPS certificate
57
+ * against Node's trust store. For a private CA, pass a `fetch` that
58
+ * trusts it, or start Node with `NODE_EXTRA_CA_CERTS`.
59
+ */
45
60
  readonly fetch?: typeof fetch | undefined;
46
61
  } & WebCredentials)
47
62
  | {
@@ -60,7 +75,10 @@ export type QueryTransportOptions =
60
75
  * `servernotifyregister`.
61
76
  *
62
77
  * `bans` is not registered by default: TeamSpeak 3 refuses it with 1539,
63
- * which would fail the registration of every category after it.
78
+ * which would fail the registration of every category after it. `tokenused`
79
+ * is not registered by default either: both servers accept it (measured) and
80
+ * then send `notifytokenused`, which carries a privilege key and has no typed
81
+ * event, so it reaches `notification` only.
64
82
  */
65
83
  export type QueryEventCategory =
66
84
  | "server"
@@ -68,7 +86,8 @@ export type QueryEventCategory =
68
86
  | "textserver"
69
87
  | "textchannel"
70
88
  | "textprivate"
71
- | "bans";
89
+ | "bans"
90
+ | "tokenused";
72
91
 
73
92
  /**
74
93
  * Which notification categories to register for.
@@ -88,7 +107,8 @@ export type QueryEventCategory =
88
107
  * | `server` | `serverEdited` |
89
108
  * | `channel` (registered for every channel) | `channelCreated`, `channelEdited`, `channelMoved`, `channelDeleted`, `channelDescriptionChanged`, `channelPasswordChanged`, `clientEnter`, `clientLeave`, `clientMoved` |
90
109
  * | `textserver`, `textchannel`, `textprivate` | `textMessage`, for the server, the channel and private messages |
91
- * | `bans` | none |
110
+ * | `bans` | `banUpdated` |
111
+ * | `tokenused` | none (`notification` only) |
92
112
  *
93
113
  * Leaving a category out leaves its events out: `{ categories: ["textprivate"] }`
94
114
  * delivers no channel event. The voice client's events about clients' updates,
@@ -101,12 +121,6 @@ export type QueryEventsOption = boolean | { readonly categories?: readonly Query
101
121
  export interface QueryClientOptions {
102
122
  /** How to reach the server. Required: a client cannot connect without one. */
103
123
  readonly transport: QueryTransportOptions;
104
- /**
105
- * The query account to log in as, sent as a `login` command after the
106
- * transport is opened. Raw TCP only: SSH logs in as the session's account,
107
- * and WebQuery's api key is the login, so giving this with either throws.
108
- */
109
- readonly login?: { readonly name: string; readonly password: string } | undefined;
110
124
  /**
111
125
  * The virtual server to select with `use`, by id or by voice port. Over
112
126
  * WebQuery the transport answers `use` itself, by addressing that server in
@@ -150,9 +164,6 @@ export const DEFAULT_EVENT_CATEGORIES: readonly QueryEventCategory[] = Object.fr
150
164
  "textprivate",
151
165
  ]);
152
166
 
153
- /** The kinds whose own handshake is the login, so there is no `login` to send. */
154
- const LOGIN_HANDLED_BY_TRANSPORT: ReadonlySet<ResolvedTransport["kind"]> = new Set(["ssh", "web"]);
155
-
156
167
  const CATEGORIES: ReadonlySet<string> = new Set([
157
168
  "server",
158
169
  "channel",
@@ -160,6 +171,7 @@ const CATEGORIES: ReadonlySet<string> = new Set([
160
171
  "textchannel",
161
172
  "textprivate",
162
173
  "bans",
174
+ "tokenused",
163
175
  ]);
164
176
 
165
177
  /** A transport with its defaults filled, and its fields copied. */
@@ -169,6 +181,7 @@ export type ResolvedTransport =
169
181
  readonly host: string;
170
182
  readonly port: number;
171
183
  readonly connect: TcpConnector | undefined;
184
+ readonly login: { readonly name: string; readonly password: string } | undefined;
172
185
  }
173
186
  | {
174
187
  readonly kind: "ssh";
@@ -187,7 +200,6 @@ export type ResolvedTransport =
187
200
  /** Options with their defaults filled and their fields copied. */
188
201
  export interface ResolvedQueryOptions {
189
202
  readonly transport: ResolvedTransport;
190
- readonly login: { readonly name: string; readonly password: string } | undefined;
191
203
  readonly server: { readonly id: ServerID | number } | { readonly port: number } | undefined;
192
204
  readonly nickname: string | undefined;
193
205
  /** The categories the caller asked to register for; `events: false` leaves this empty. */
@@ -261,6 +273,11 @@ function transportOptions(transport: unknown): ResolvedTransport {
261
273
  throw new TypeError("transport is an object");
262
274
  }
263
275
  const options = transport as Record<string, unknown>;
276
+ if (options["login"] !== undefined && options["kind"] !== "tcp") {
277
+ throw new TypeError(
278
+ `transport.login belongs to the "tcp" transport; the ${String(options["kind"])} transport carries its own credentials`,
279
+ );
280
+ }
264
281
  switch (options["kind"]) {
265
282
  case "tcp": {
266
283
  const host = nonEmpty(options["host"], "transport.host");
@@ -269,11 +286,24 @@ function transportOptions(transport: unknown): ResolvedTransport {
269
286
  if (connect !== undefined && typeof connect !== "function") {
270
287
  throw new TypeError("transport.connect is a function");
271
288
  }
289
+ const login = options["login"];
290
+ if (login !== undefined) {
291
+ if (typeof login !== "object" || login === null) {
292
+ throw new TypeError("transport.login is { name, password }");
293
+ }
294
+ const { name, password } = login as Record<string, unknown>;
295
+ nonEmpty(name, "transport.login.name");
296
+ if (typeof password !== "string") {
297
+ throw new TypeError("transport.login.password is a string");
298
+ }
299
+ }
272
300
  return {
273
301
  kind: "tcp",
274
302
  host,
275
303
  port: raw < 0 ? 10011 : raw,
276
304
  connect: connect as TcpConnector | undefined,
305
+ login:
306
+ login === undefined ? undefined : { ...(login as { name: string; password: string }) },
277
307
  };
278
308
  }
279
309
  case "ssh": {
@@ -394,11 +424,14 @@ export function assertEventsSupported(resolved: ResolvedQueryOptions): void {
394
424
  * hearing about before a connection is attempted.
395
425
  */
396
426
  export function normalizeQueryOptions(options: QueryClientOptions): ResolvedQueryOptions {
397
- const transport = transportOptions(options.transport);
398
- const login = options.login;
399
- if (login !== undefined && typeof login !== "object") {
400
- throw new TypeError("login is { name, password }");
427
+ // Plain JavaScript can still pass the old top-level `login`; dropping it
428
+ // quietly would leave the caller unauthenticated and believing otherwise.
429
+ if ((options as { login?: unknown }).login !== undefined) {
430
+ throw new TypeError(
431
+ "login is no longer a client option: give it to the tcp transport, as transport.login",
432
+ );
401
433
  }
434
+ const transport = transportOptions(options.transport);
402
435
  const server = options.server;
403
436
  if (server !== undefined) {
404
437
  if (typeof server !== "object" || server === null) {
@@ -422,21 +455,8 @@ export function normalizeQueryOptions(options: QueryClientOptions): ResolvedQuer
422
455
  if (commandMiddleware !== undefined && !Array.isArray(commandMiddleware)) {
423
456
  throw new TypeError("commandMiddleware is an array");
424
457
  }
425
- if (login !== undefined && LOGIN_HANDLED_BY_TRANSPORT.has(transport.kind)) {
426
- // The SSH session is the query account already, and WebQuery's api key is
427
- // the login; neither leaves a `login` to send, and the server refuses the
428
- // command on both. A silently dropped option would leave the caller
429
- // believing they had logged in.
430
- throw new TypeError(
431
- `login is not sent over the ${transport.kind} transport, which logs in by itself`,
432
- );
433
- }
434
-
435
458
  const resolved: ResolvedQueryOptions = {
436
459
  transport,
437
- // Kept for `custom` too: its opener is the caller's, and most of them wrap
438
- // one of the built-in transports, `tcp` among them.
439
- login: login === undefined ? undefined : { ...login },
440
460
  server: server === undefined ? undefined : { ...server },
441
461
  nickname,
442
462
  eventCategories: eventCategories(options.events),
package/src/query/ssh.ts CHANGED
@@ -251,7 +251,9 @@ export interface SshDialTarget {
251
251
  * `whoami` answer, `serverinfo` and the like are refused with 2568, and
252
252
  * `servernotifyregister` is the Guest group's permission to give or withhold,
253
253
  * so pass `events: false` to a `QueryClient` that should not register for any.
254
- * A server started with `--query-ssh-allow-guest=0` refuses the login with a
254
+ * A server that offers no guest access (TeamSpeak 3 has none, and TeamSpeak 6
255
+ * can be started with `--query-ssh-allow-guest=0`) fails the login, which a
256
+ * `QueryClient` reports as a `GuestAccessError` whose `cause` is the
255
257
  * {@link QueryAuthError}.
256
258
  *
257
259
  * @experimental Part of the `@honeybbq/teamspeak/query` entry, which may
@@ -536,7 +538,12 @@ export async function connectSsh(options: SshOptions): Promise<StreamTransport>
536
538
  // stream closes with it.
537
539
  ssh.on("error", (failure) => channel.emit("error", failure));
538
540
  channel.once("close", () => ssh.end());
539
- resolve(new StreamTransport(channel, () => ssh.end()));
541
+ resolve(
542
+ new StreamTransport(channel, () => ssh.end(), {
543
+ transport: "ssh",
544
+ address: `${login === undefined ? "" : `${login.username}@`}${host}:${port}`,
545
+ }),
546
+ );
540
547
  });
541
548
  };
542
549
 
@@ -1,5 +1,5 @@
1
1
  import { LineReader } from "./lines.js";
2
- import type { QueryTransport } from "./transport.js";
2
+ import type { QueryTransport, QueryTransportStats } from "./transport.js";
3
3
 
4
4
  /**
5
5
  * The part of a duplex byte stream a line transport uses. A `node:net` socket
@@ -18,6 +18,9 @@ export interface QueryStream {
18
18
  on(event: "close", listener: () => void): unknown;
19
19
  }
20
20
 
21
+ /** How long `close()` waits for the server to end the session after `quit`. */
22
+ const QUIT_WAIT_MS = 1_000;
23
+
21
24
  /**
22
25
  * A {@link QueryTransport} over a byte stream: raw TCP, or an SSH shell.
23
26
  *
@@ -37,15 +40,27 @@ export class StreamTransport implements QueryTransport {
37
40
  #banner = 2;
38
41
  #closing = false;
39
42
  #ended = false;
43
+ /** Wakes a `close()` that is waiting for the server to end the session. */
44
+ #onEnded: (() => void) | undefined;
40
45
  #error: Error | undefined;
46
+ #identity: { readonly transport: "tcp" | "ssh"; readonly address: string } | undefined;
47
+ #openedAt = new Date();
48
+ #bytesSent = 0;
49
+ #bytesReceived = 0;
41
50
 
42
51
  /**
43
52
  * `onEnd` runs once the stream is closed, to release what the stream sits
44
- * on: an SSH session's connection, say.
53
+ * on: an SSH session's connection, say. `identity` says which kind of
54
+ * connection this is and where it points, for {@link StreamTransport.stats}.
45
55
  */
46
- constructor(stream: QueryStream, onEnd?: () => void) {
56
+ constructor(
57
+ stream: QueryStream,
58
+ onEnd?: () => void,
59
+ identity?: { readonly transport: "tcp" | "ssh"; readonly address: string },
60
+ ) {
47
61
  this.#stream = stream;
48
62
  this.#onEnd = onEnd;
63
+ this.#identity = identity;
49
64
  stream.on("data", (chunk) => this.#handleData(chunk));
50
65
  stream.on("error", (error) => {
51
66
  this.#error = error;
@@ -56,23 +71,65 @@ export class StreamTransport implements QueryTransport {
56
71
  send(line: string): Promise<void> {
57
72
  if (this.#ended) return Promise.reject(new Error("the query connection is closed"));
58
73
  return new Promise((resolve, reject) => {
59
- this.#stream.write(`${line}\n`, (error) => (error ? reject(error) : resolve()));
74
+ this.#stream.write(`${line}\n`, (error) => {
75
+ if (error) reject(error);
76
+ else {
77
+ this.#bytesSent += Buffer.byteLength(line) + 1;
78
+ resolve();
79
+ }
80
+ });
60
81
  });
61
82
  }
62
83
 
63
- close(): Promise<void> {
64
- if (this.#ended) return Promise.resolve();
84
+ stats(): QueryTransportStats {
85
+ return {
86
+ connectedAt: this.#openedAt,
87
+ transport: this.#identity?.transport,
88
+ address: this.#identity?.address ?? "",
89
+ bytesSent: this.#bytesSent,
90
+ bytesReceived: this.#bytesReceived,
91
+ };
92
+ }
93
+
94
+ /**
95
+ * Say `quit`, give the server a moment to end the session, and close.
96
+ *
97
+ * Ending the connection without it is not always noticed: a TeamSpeak 3
98
+ * server can keep an SSH session, and its slot among the few each address
99
+ * gets, long after the client has gone. `quit` is the command that ends a
100
+ * session, and the server answers it by closing the stream.
101
+ */
102
+ async close(): Promise<void> {
103
+ if (this.#ended) return;
65
104
  this.#closing = true;
105
+ // Whatever the server still says, it is no longer anyone's answer.
106
+ this.onLine = null;
107
+ const closed = new Promise<void>((resolve) => {
108
+ this.#onEnded = resolve;
109
+ });
110
+ const said = await this.send("quit").then(
111
+ () => true,
112
+ () => false,
113
+ );
114
+ if (said) {
115
+ let timer: NodeJS.Timeout | undefined;
116
+ const patience = new Promise<void>((resolve) => {
117
+ timer = setTimeout(resolve, QUIT_WAIT_MS);
118
+ });
119
+ await Promise.race([closed, patience]);
120
+ clearTimeout(timer);
121
+ }
122
+ if (this.#ended) return;
66
123
  // Ending the stream is not enough to hear it close. An SSH session channel
67
124
  // is half-open, so `end()` sends EOF and stops there without reporting
68
125
  // 'close', and the hook that releases the connection underneath would never
69
126
  // run; the close is owed here as well as from the stream's own event.
70
127
  this.#stream.end();
71
128
  this.#handleClose();
72
- return Promise.resolve();
73
129
  }
74
130
 
75
131
  #handleData(chunk: Uint8Array): void {
132
+ this.#bytesReceived += chunk.byteLength;
76
133
  for (const line of this.#reader.push(chunk)) {
77
134
  if (this.#banner > 0) {
78
135
  this.#banner--;
@@ -85,6 +142,7 @@ export class StreamTransport implements QueryTransport {
85
142
  #handleClose(): void {
86
143
  if (this.#ended) return;
87
144
  this.#ended = true;
145
+ this.#onEnded?.();
88
146
  this.#onEnd?.();
89
147
  this.onClose?.(this.#closing ? undefined : this.#error);
90
148
  }
package/src/query/tcp.ts CHANGED
@@ -43,7 +43,7 @@ export async function connectTcp(options: TcpOptions): Promise<StreamTransport>
43
43
  signal?.throwIfAborted();
44
44
  const stream = await connect(host, port);
45
45
  await opened(stream, signal);
46
- return new StreamTransport(stream);
46
+ return new StreamTransport(stream, undefined, { transport: "tcp", address: `${host}:${port}` });
47
47
  }
48
48
 
49
49
  /** A connected `node:net` socket, with whole lines sent as they are written. */