mirror of
https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak.git
synced 2026-12-03 12:02:50 +08:00
feat: add GitHub skin store and organize instance administration
Adopt the pinned published TeamSpeak SDK and direct relay routing. Add optional TeamSpeak Query administration with encrypted credentials and separate WebSpeak access, site, operations and skin management. Distribute Discord Voice through the GitHub skin index, preserve skin state during updates, and correct KAAK scaling and screen fullscreen. Validation: 831 tests; backend and frontend builds; five-language UI checks from narrow screens through 4K and local Query fixture actions.
This commit is contained in:
1 parent
180bfeb52f
commit
0af3236c30
95 files changed
+7678
-709
No files matched your search
@@ -30,6 +30,8 @@ export interface AccelerationRelayOptions {
|
||||
export interface ConfiguredAccelerationRelay extends AccelerationRelayOptions {
|
||||
id: string;
|
||||
name: string;
|
||||
/** HTTPS origin of the WebSpeak voice gateway on this relay node. */
|
||||
voiceEndpoint?: string;
|
||||
}
|
||||
|
||||
export interface AccelerationTarget {
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import assert from "node:assert/strict";
|
||||
import test from "node:test";
|
||||
import type { DirectoryClientInfo, DirectorySnapshot } from "@echosixhiya/teamspeak-client";
|
||||
import type { DirectoryClientInfo, DirectorySnapshot } from "./teamspeak-sdk.js";
|
||||
import { DirectorySynchronizer } from "./directory-sync.js";
|
||||
|
||||
function member(id: number, channelID = 1n, overrides: Partial<DirectoryClientInfo> = {}): DirectoryClientInfo {
|
||||
@@ -31,6 +31,15 @@ test("partial snapshots retain earlier clients and state omitted by a later snap
|
||||
assert.deepEqual(directory.getSnapshot()?.clients, [member(1, 2n, { inputMuted: true }), member(2), member(3)]);
|
||||
});
|
||||
|
||||
test("complete SDK views remove unsubscribed clients instead of retaining them as partial welcome data", () => {
|
||||
const directory = new DirectorySynchronizer();
|
||||
directory.applySnapshot({ ...snapshot(member(1), member(2)), complete: true });
|
||||
directory.applySnapshot({ ...snapshot(member(1, 1n, { inputMuted: true })), complete: true });
|
||||
assert.deepEqual(directory.getSnapshot()?.clients, [member(1, 1n, { inputMuted: true })]);
|
||||
directory.applySnapshot({ ...snapshot(member(1), member(2, 2n)), complete: true });
|
||||
assert.deepEqual(directory.getSnapshot()?.clients.map(client => client.id), [1, 2]);
|
||||
});
|
||||
|
||||
test("a stale partial snapshot cannot bring back a departed client before an explicit rejoin", () => {
|
||||
const directory = new DirectorySynchronizer();
|
||||
directory.applySnapshot(snapshot(member(1), member(2)));
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import type { ClientInfo, DirectoryClientInfo } from "@echosixhiya/teamspeak-client";
|
||||
import type { ClientInfo, DirectoryClientInfo } from "./teamspeak-sdk.js";
|
||||
import type { TSDirectorySnapshot } from "./ts-client.js";
|
||||
|
||||
type DirectoryDelta =
|
||||
@@ -28,6 +28,9 @@ export class DirectorySynchronizer {
|
||||
|
||||
applySnapshot(snapshot: TSDirectorySnapshot): void {
|
||||
this.snapshot = { channels: snapshot.channels.slice(), clients: [] };
|
||||
// A native SDK view is the complete visible roster. In particular, an
|
||||
// unsubscribe removes clients without individual leave notifications.
|
||||
if (snapshot.complete) this.clients.clear();
|
||||
for (const client of snapshot.clients) {
|
||||
if (this.departedClientIds.has(client.id)) continue;
|
||||
const previous = this.clients.get(client.id);
|
||||
|
||||
@@ -0,0 +1,97 @@
|
||||
import assert from "node:assert/strict";
|
||||
import { mkdtemp, rm } from "node:fs/promises";
|
||||
import { createServer as createPortProbe } from "node:net";
|
||||
import os from "node:os";
|
||||
import path from "node:path";
|
||||
import test from "node:test";
|
||||
import { AdminService, type AdminSettingsInput } from "../admin/admin-service.js";
|
||||
import type { Logger } from "../logger.js";
|
||||
import { WebSpeakDatabase } from "../persistence/database.js";
|
||||
import { JoinTicketStore } from "./join-ticket.js";
|
||||
import { createWebServer } from "./server.js";
|
||||
import { createVoiceGatewayServer } from "./voice-gateway.js";
|
||||
|
||||
const noop = () => {};
|
||||
const logger: Logger = { debug: noop, info: noop, warn: noop, error: noop, child: () => logger };
|
||||
|
||||
test("ingress keeps the page origin and delegates the voice ticket to the selected relay", async (context) => {
|
||||
const directory = await mkdtemp(path.join(os.tmpdir(), "webspeak-relay-delegation-"));
|
||||
const database = new WebSpeakDatabase(path.join(directory, "webspeak.db"));
|
||||
const relayPort = await availablePort();
|
||||
const ingressPort = await availablePort();
|
||||
const relayToken = "integration-test-relay-token";
|
||||
const relayEndpoint = `http://127.0.0.1:${relayPort}`;
|
||||
const relay = createVoiceGatewayServer({
|
||||
host: "127.0.0.1",
|
||||
port: relayPort,
|
||||
sharedToken: relayToken,
|
||||
logger,
|
||||
webRtc: { enabled: false },
|
||||
});
|
||||
const service = new AdminService(
|
||||
database,
|
||||
Buffer.alloc(32, 7),
|
||||
logger,
|
||||
path.join(directory, "missing-config.json"),
|
||||
async () => ({ ok: true, protocol: "ts3", latencyMs: 1, serverName: "Test", requiresPassword: false }),
|
||||
);
|
||||
const localTickets = new JoinTicketStore();
|
||||
const ingress = createWebServer({
|
||||
port: ingressPort,
|
||||
adminService: service,
|
||||
voiceBridgeOptions: { joinTickets: localTickets, acceleration: () => service.getAccelerationRelayOptions() },
|
||||
logger,
|
||||
});
|
||||
context.after(async () => {
|
||||
await ingress.stop();
|
||||
await relay.stop();
|
||||
database.close();
|
||||
await rm(directory, { recursive: true, force: true });
|
||||
});
|
||||
|
||||
await service.initialize();
|
||||
const settings: AdminSettingsInput = {
|
||||
target: "203.0.113.20#9987",
|
||||
accessMode: "fixed",
|
||||
siteName: "WebSpeak",
|
||||
welcomeText: "",
|
||||
webRtcEnabled: false,
|
||||
relayNodes: [{
|
||||
id: "de-relay",
|
||||
name: "Germany relay",
|
||||
target: "relay.example.com#39087",
|
||||
voiceEndpoint: relayEndpoint,
|
||||
enabled: true,
|
||||
token: relayToken,
|
||||
tokenAction: "replace",
|
||||
}],
|
||||
};
|
||||
service.updateSettings(settings);
|
||||
await relay.start();
|
||||
await ingress.start();
|
||||
|
||||
const origin = `http://127.0.0.1:${ingressPort}`;
|
||||
const response = await fetch(`${origin}/api/join-ticket`, {
|
||||
method: "POST",
|
||||
headers: { origin, "content-type": "application/json" },
|
||||
body: JSON.stringify({ nickname: "Tester", accelerated: true }),
|
||||
});
|
||||
assert.equal(response.status, 201);
|
||||
assert.equal(response.headers.get("cache-control"), "no-store");
|
||||
const result = await response.json() as { ticket?: string; voiceEndpoint?: string };
|
||||
assert.ok(result.ticket);
|
||||
assert.equal(result.voiceEndpoint, relayEndpoint);
|
||||
assert.equal(localTickets.consume(result.ticket!), null);
|
||||
});
|
||||
|
||||
async function availablePort(): Promise<number> {
|
||||
const socket = createPortProbe();
|
||||
await new Promise<void>((resolve, reject) => {
|
||||
socket.once("error", reject);
|
||||
socket.listen(0, "127.0.0.1", resolve);
|
||||
});
|
||||
const address = socket.address();
|
||||
assert.ok(address && typeof address !== "string");
|
||||
await new Promise<void>((resolve, reject) => socket.close((error) => error ? reject(error) : resolve()));
|
||||
return address.port;
|
||||
}
|
||||
+41
-4
@@ -12,9 +12,10 @@ import { createAdminRouter } from "../admin/admin-router.js";
|
||||
import type { AdminService } from "../admin/admin-service.js";
|
||||
import { AdminSessionStore } from "../admin/admin-session.js";
|
||||
import { isSafeOpenTargetForPrefill, resolveSafeOpenTarget, TeamSpeakTargetResolutionError } from "../security/open-target-policy.js";
|
||||
import { identityFromString } from "@echosixhiya/teamspeak-client";
|
||||
import { parseIdentity } from "@honeybbq/teamspeak/client";
|
||||
import { JoinRateLimiter } from "./join-rate-limit.js";
|
||||
import type { ConfiguredAccelerationRelay } from "./acceleration-relay.js";
|
||||
import { createVoiceGatewayAuthHeaders, type DelegatedVoiceSession } from "./voice-gateway-auth.js";
|
||||
import type { SkinRegistry } from "../admin/skin-registry.js";
|
||||
import { resolveVisitorTotal } from "./visitor-count.js";
|
||||
|
||||
@@ -171,7 +172,7 @@ export function createWebServer(options: WebServerOptions): WebServer {
|
||||
let identity: string | undefined;
|
||||
if (requestedIdentity) {
|
||||
try {
|
||||
identityFromString(requestedIdentity);
|
||||
parseIdentity(requestedIdentity);
|
||||
identity = requestedIdentity;
|
||||
} catch {
|
||||
// A stale/corrupt local identity must not block a normal ephemeral join.
|
||||
@@ -235,13 +236,29 @@ export function createWebServer(options: WebServerOptions): WebServer {
|
||||
serverPassword = consumedInvite.serverPassword;
|
||||
}
|
||||
|
||||
const ticket = options.voiceBridgeOptions.joinTickets.create({
|
||||
const sessionPayload: DelegatedVoiceSession = {
|
||||
target,
|
||||
serverPassword,
|
||||
nickname,
|
||||
...(channel ? { channel } : {}),
|
||||
...(identity ? { identity, rememberIdentity: true } : body.rememberIdentity === true ? { rememberIdentity: true } : {}),
|
||||
...(accelerationRequested ? { accelerated: true, ...(requestedRelayId ? { accelerationRelayId: requestedRelayId } : {}) } : {}),
|
||||
};
|
||||
const selectedRelay = accelerationRequested
|
||||
? requestedRelayId ? acceleration.find((relay) => relay.id === requestedRelayId) : acceleration[0]
|
||||
: undefined;
|
||||
if (selectedRelay?.voiceEndpoint) {
|
||||
try {
|
||||
const ticket = await createRemoteVoiceTicket(selectedRelay, sessionPayload);
|
||||
response.status(201).json({ ok: true, ticket, voiceEndpoint: selectedRelay.voiceEndpoint });
|
||||
return;
|
||||
} catch (error: unknown) {
|
||||
logger.warn({ relayId: selectedRelay.id, err: error instanceof Error ? error.message : String(error) }, "Relay voice gateway ticket request failed; using legacy UDP acceleration");
|
||||
}
|
||||
}
|
||||
|
||||
const ticket = options.voiceBridgeOptions.joinTickets.create({
|
||||
...sessionPayload,
|
||||
...(accelerationRequested && selectedRelay ? { accelerated: true, accelerationRelayId: selectedRelay.id } : {}),
|
||||
});
|
||||
response.status(201).json({ ok: true, ticket });
|
||||
});
|
||||
@@ -298,6 +315,26 @@ function resolveAccelerationOptions(
|
||||
return Array.isArray(value) ? value : [value];
|
||||
}
|
||||
|
||||
async function createRemoteVoiceTicket(relay: ConfiguredAccelerationRelay, payload: DelegatedVoiceSession): Promise<string> {
|
||||
const endpoint = new URL("/api/relay/voice-ticket", relay.voiceEndpoint);
|
||||
const response = await fetch(endpoint, {
|
||||
method: "POST",
|
||||
headers: {
|
||||
"content-type": "application/json",
|
||||
...createVoiceGatewayAuthHeaders(relay.token, payload),
|
||||
},
|
||||
body: JSON.stringify(payload),
|
||||
signal: AbortSignal.timeout(5_000),
|
||||
cache: "no-store",
|
||||
});
|
||||
if (!response.ok) throw new Error(`Relay voice gateway returned HTTP ${response.status}`);
|
||||
const result: unknown = await response.json().catch(() => null);
|
||||
if (!isRecord(result) || result.ok !== true || typeof result.ticket !== "string" || result.ticket.length < 16) {
|
||||
throw new Error("Relay voice gateway returned an invalid ticket");
|
||||
}
|
||||
return result.ticket;
|
||||
}
|
||||
|
||||
function isRecord(value: unknown): value is Record<string, unknown> {
|
||||
return Boolean(value) && typeof value === "object" && !Array.isArray(value);
|
||||
}
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
import assert from "node:assert/strict";
|
||||
import test, { type TestContext } from "node:test";
|
||||
import { EventEmitter } from "node:events";
|
||||
import type { ClientInfo } from "@echosixhiya/teamspeak-client";
|
||||
import type { ClientInfo } from "./teamspeak-sdk.js";
|
||||
import type { ServerMessage } from "../shared/server-messages.js";
|
||||
import { SessionEventCoordinator, type SessionDirectoryState } from "./session-events.js";
|
||||
import type { TSDirectorySnapshot } from "./ts-client.js";
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import type { ClientInfo } from "@echosixhiya/teamspeak-client";
|
||||
import type { ClientInfo } from "./teamspeak-sdk.js";
|
||||
import type { EventEmitter } from "node:events";
|
||||
import type { WebSpeakError } from "../errors.js";
|
||||
import type { ChannelInfo, ChannelMember } from "../shared/voice-models.js";
|
||||
|
||||
@@ -1,10 +1,5 @@
|
||||
import {
|
||||
Client as TeamSpeakClient,
|
||||
generateIdentity,
|
||||
type ClientOptions,
|
||||
type Identity,
|
||||
} from "@echosixhiya/teamspeak-client";
|
||||
import { WebSpeakTeamSpeakResolver } from "./teamspeak-resolver.js";
|
||||
import { generateIdentitySync } from "@honeybbq/teamspeak/client";
|
||||
import { TeamSpeakSdkClient, type Identity, type TeamSpeakClientOptions } from "./teamspeak-sdk.js";
|
||||
import type { Logger } from "../logger.js";
|
||||
import { normalizeTeamSpeakError } from "../errors.js";
|
||||
import { formatTeamSpeakTarget, teamSpeakTargetKey, type TeamSpeakTarget } from "../domain/teamspeak-target.js";
|
||||
@@ -75,7 +70,7 @@ export interface TeamSpeakAdapterOptions {
|
||||
* successfully observed server generation for later connections.
|
||||
*/
|
||||
export class TeamSpeakAdapter {
|
||||
readonly client: TeamSpeakClient;
|
||||
readonly client: TeamSpeakSdkClient;
|
||||
readonly identity: Identity;
|
||||
private detectedProtocol: TeamSpeakProtocol | null = null;
|
||||
|
||||
@@ -84,9 +79,8 @@ export class TeamSpeakAdapter {
|
||||
private readonly logger: Logger,
|
||||
private readonly protocolCache: EndpointProtocolCache = endpointProtocolCache,
|
||||
) {
|
||||
this.identity = options.identity ?? generateIdentity(8);
|
||||
const clientOptions: ClientOptions = {
|
||||
resolver: new WebSpeakTeamSpeakResolver(),
|
||||
this.identity = options.identity ?? generateIdentitySync(8);
|
||||
const clientOptions: TeamSpeakClientOptions = {
|
||||
serverPassword: options.serverPassword,
|
||||
defaultChannel: options.defaultChannel,
|
||||
defaultChannelPassword: options.channelPassword,
|
||||
@@ -97,7 +91,7 @@ export class TeamSpeakAdapter {
|
||||
error: (msg: string) => this.logger.error(msg),
|
||||
},
|
||||
};
|
||||
this.client = new TeamSpeakClient(
|
||||
this.client = new TeamSpeakSdkClient(
|
||||
this.identity,
|
||||
formatTeamSpeakTarget(options.target),
|
||||
options.nickname,
|
||||
@@ -112,14 +106,14 @@ export class TeamSpeakAdapter {
|
||||
const cachedProtocol = this.protocolCache.get(this.target);
|
||||
this.logger.info({ target: formatTeamSpeakTarget(this.target), cachedProtocol }, "Connecting through TeamSpeak adapter");
|
||||
try {
|
||||
await this.client.connect();
|
||||
await this.client.waitConnected(AbortSignal.timeout(TEAM_SPEAK_CONNECT_TIMEOUT_MS));
|
||||
await this.client.connect({ signal: AbortSignal.timeout(TEAM_SPEAK_CONNECT_TIMEOUT_MS) });
|
||||
} catch (error: unknown) {
|
||||
await this.client.disconnect().catch(() => undefined);
|
||||
throw normalizeTeamSpeakError(error);
|
||||
}
|
||||
|
||||
const observedProtocol = await this.detectProtocol();
|
||||
const family = this.client.serverFamily;
|
||||
const observedProtocol = family === "ts3" || family === "ts6" ? family : null;
|
||||
this.detectedProtocol = observedProtocol ?? cachedProtocol ?? null;
|
||||
if (observedProtocol) this.protocolCache.set(this.target, observedProtocol);
|
||||
}
|
||||
@@ -136,19 +130,6 @@ export class TeamSpeakAdapter {
|
||||
}
|
||||
}
|
||||
|
||||
private async detectProtocol(): Promise<TeamSpeakProtocol | null> {
|
||||
try {
|
||||
const rows = await this.client.execCommandWithResponse("version", 3000);
|
||||
const versionText = rows
|
||||
.flatMap((row) => Object.values(row))
|
||||
.filter((value): value is string => typeof value === "string")
|
||||
.join(" ");
|
||||
return detectTeamSpeakProtocol(versionText);
|
||||
} catch {
|
||||
// Version discovery is an optimization; connection success is enough to proceed.
|
||||
return null;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
export function detectTeamSpeakProtocol(versionText: string): TeamSpeakProtocol | null {
|
||||
|
||||
@@ -130,11 +130,11 @@ test("schema 8 settings and invites survive the nickname migration", async (cont
|
||||
});
|
||||
database.close();
|
||||
const legacy = new DatabaseSync(file);
|
||||
legacy.exec("ALTER TABLE settings DROP COLUMN ts_target; ALTER TABLE managed_invites DROP COLUMN target_text; PRAGMA user_version = 8;");
|
||||
legacy.exec("DROP TABLE ts_admin_settings; ALTER TABLE relay_nodes DROP COLUMN voice_endpoint; ALTER TABLE settings DROP COLUMN ts_target; ALTER TABLE managed_invites DROP COLUMN target_text; PRAGMA user_version = 8;");
|
||||
legacy.close();
|
||||
const migrated = new WebSpeakDatabase(file);
|
||||
try {
|
||||
assert.equal(migrated.schemaVersion, 9);
|
||||
assert.equal(migrated.schemaVersion, 12);
|
||||
assert.equal(migrated.getSettings().tsHost, "127.0.0.1");
|
||||
assert.equal(migrated.getSettings().tsTarget, null);
|
||||
const invite = migrated.consumeManagedInvite("legacy-token");
|
||||
|
||||
@@ -1,82 +1,54 @@
|
||||
import assert from "node:assert/strict";
|
||||
import test from "node:test";
|
||||
import type { AddrResolver, ResolvedAddr } from "@echosixhiya/teamspeak-client";
|
||||
import { WebSpeakTeamSpeakResolver } from "./teamspeak-resolver.js";
|
||||
import { resolveLocalTeamSpeakAlias } from "./teamspeak-resolver.js";
|
||||
|
||||
function fixedResolver(result: ResolvedAddr[], onResolve?: (signal?: AbortSignal) => void): AddrResolver {
|
||||
return {
|
||||
resolve: async (_address, signal) => {
|
||||
onResolve?.(signal);
|
||||
return result;
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
test("private short hostnames use local DNS directly without cloud nickname discovery", async () => {
|
||||
let baseCalls = 0;
|
||||
const resolver = new WebSpeakTeamSpeakResolver({
|
||||
localLookup: async (hostname) => {
|
||||
assert.equal(hostname, "teamspeak");
|
||||
return [{ address: "172.18.0.6", family: 4 }];
|
||||
},
|
||||
baseResolver: {
|
||||
resolve: async () => {
|
||||
baseCalls++;
|
||||
return [];
|
||||
},
|
||||
test("private short hostnames resolve locally before upstream discovery", async () => {
|
||||
let lookedUp = "";
|
||||
const address = await resolveLocalTeamSpeakAlias("teamspeak", {
|
||||
lookup: async (hostname) => {
|
||||
lookedUp = hostname;
|
||||
return [
|
||||
{ address: "203.0.113.4", family: 4 },
|
||||
{ address: "172.18.0.6", family: 4 },
|
||||
];
|
||||
},
|
||||
});
|
||||
|
||||
const result = await resolver.resolve("teamspeak:9988");
|
||||
assert.equal(result[0]?.addr, "172.18.0.6:9988");
|
||||
assert.equal(result[0]?.source, "Direct");
|
||||
assert.equal(baseCalls, 0);
|
||||
assert.equal(lookedUp, "teamspeak");
|
||||
assert.equal(address, "172.18.0.6");
|
||||
});
|
||||
|
||||
test("undotted nickname discovery is bounded and falls back to the direct host", async () => {
|
||||
let baseSignal: AbortSignal | undefined;
|
||||
const resolver = new WebSpeakTeamSpeakResolver({
|
||||
localLookup: async () => [],
|
||||
baseResolver: {
|
||||
resolve: async (_address, signal) => {
|
||||
baseSignal = signal;
|
||||
return new Promise<ResolvedAddr[]>(() => undefined);
|
||||
},
|
||||
},
|
||||
localAliasLookupTimeoutMs: 20,
|
||||
nicknameLookupTimeoutMs: 25,
|
||||
});
|
||||
|
||||
const result = await resolver.resolve("teamspeak:9987");
|
||||
assert.equal(result[0]?.addr, "teamspeak:9987");
|
||||
assert.equal(result[0]?.source, "Direct");
|
||||
assert.equal(baseSignal?.aborted, true);
|
||||
});
|
||||
|
||||
test("dotted hostnames preserve the SDK resolver path", async () => {
|
||||
const expected: ResolvedAddr[] = [{ addr: "voice.example.com:9987", source: "Direct", expiry: new Date(0) }];
|
||||
test("public and dotted names are left to the upstream resolver", async () => {
|
||||
let lookupCalls = 0;
|
||||
let baseCalls = 0;
|
||||
const resolver = new WebSpeakTeamSpeakResolver({
|
||||
localLookup: async () => {
|
||||
assert.equal(await resolveLocalTeamSpeakAlias("public-alias", {
|
||||
lookup: async () => {
|
||||
lookupCalls++;
|
||||
return [];
|
||||
return [{ address: "203.0.113.4", family: 4 }];
|
||||
},
|
||||
baseResolver: fixedResolver(expected, () => { baseCalls++; }),
|
||||
});
|
||||
|
||||
assert.deepEqual(await resolver.resolve("voice.example.com:9987"), expected);
|
||||
assert.equal(lookupCalls, 0);
|
||||
assert.equal(baseCalls, 1);
|
||||
}), undefined);
|
||||
assert.equal(await resolveLocalTeamSpeakAlias("voice.example.com", {
|
||||
lookup: async () => {
|
||||
lookupCalls++;
|
||||
return [{ address: "10.0.0.2", family: 4 }];
|
||||
},
|
||||
}), undefined);
|
||||
assert.equal(lookupCalls, 1);
|
||||
});
|
||||
|
||||
test("DNS resolution failures continue through bounded nickname discovery", async () => {
|
||||
const expected: ResolvedAddr[] = [{ addr: "public.example.com:9987", source: "Nickname", expiry: new Date(0) }];
|
||||
const resolver = new WebSpeakTeamSpeakResolver({
|
||||
localLookup: async () => { throw new Error("ENOTFOUND"); },
|
||||
baseResolver: fixedResolver(expected),
|
||||
nicknameLookupTimeoutMs: 100,
|
||||
test("a slow local lookup is bounded and falls through to upstream DNS", async () => {
|
||||
const result = await resolveLocalTeamSpeakAlias("teamspeak", {
|
||||
lookup: async () => new Promise(() => undefined),
|
||||
timeoutMs: 20,
|
||||
});
|
||||
assert.equal(result, undefined);
|
||||
});
|
||||
|
||||
assert.deepEqual(await resolver.resolve("public-alias"), expected);
|
||||
test("aborting a local lookup preserves the connection cancellation", async () => {
|
||||
const controller = new AbortController();
|
||||
const failure = new Error("connect cancelled");
|
||||
const pending = resolveLocalTeamSpeakAlias("teamspeak", {
|
||||
lookup: async () => new Promise(() => undefined),
|
||||
signal: controller.signal,
|
||||
});
|
||||
controller.abort(failure);
|
||||
await assert.rejects(pending, failure);
|
||||
});
|
||||
@@ -1,90 +1,15 @@
|
||||
import { lookup } from "node:dns/promises";
|
||||
import { isIP } from "node:net";
|
||||
import { Resolver as TeamSpeakResolver } from "@echosixhiya/teamspeak-client/discovery";
|
||||
import type { AddrResolver, ResolvedAddr } from "@echosixhiya/teamspeak-client";
|
||||
import { formatTeamSpeakTarget, parseTeamSpeakTarget } from "../domain/teamspeak-target.js";
|
||||
|
||||
const LOCAL_ALIAS_LOOKUP_TIMEOUT_MS = 1_000;
|
||||
const NICKNAME_LOOKUP_TIMEOUT_MS = 3_000;
|
||||
|
||||
type LocalAddress = { address: string; family: number };
|
||||
type LocalLookup = (hostname: string) => Promise<LocalAddress[]>;
|
||||
|
||||
interface WebSpeakTeamSpeakResolverOptions {
|
||||
baseResolver?: AddrResolver;
|
||||
localLookup?: LocalLookup;
|
||||
localAliasLookupTimeoutMs?: number;
|
||||
nicknameLookupTimeoutMs?: number;
|
||||
}
|
||||
|
||||
/**
|
||||
* Keep TeamSpeak nickname discovery for normal names, while allowing an
|
||||
* internal short hostname (for example a Docker Compose service name) to use
|
||||
* the local resolver directly. Bound cloud nickname discovery so a network
|
||||
* black hole cannot prevent the SDK's direct-host fallback indefinitely.
|
||||
* Resolve an internal short hostname before the upstream SDK's SRV/TSDNS and
|
||||
* optional nickname resolution. Public hosts are left to the SDK's resolver.
|
||||
*/
|
||||
export class WebSpeakTeamSpeakResolver implements AddrResolver {
|
||||
private readonly baseResolver: AddrResolver;
|
||||
private readonly localLookup: LocalLookup;
|
||||
private readonly localAliasLookupTimeoutMs: number;
|
||||
private readonly nicknameLookupTimeoutMs: number;
|
||||
|
||||
constructor(options: WebSpeakTeamSpeakResolverOptions = {}) {
|
||||
this.baseResolver = options.baseResolver ?? new TeamSpeakResolver();
|
||||
this.localLookup = options.localLookup ?? ((hostname) => lookup(hostname, { all: true, verbatim: true }));
|
||||
this.localAliasLookupTimeoutMs = options.localAliasLookupTimeoutMs ?? LOCAL_ALIAS_LOOKUP_TIMEOUT_MS;
|
||||
this.nicknameLookupTimeoutMs = options.nicknameLookupTimeoutMs ?? NICKNAME_LOOKUP_TIMEOUT_MS;
|
||||
}
|
||||
|
||||
async resolve(address: string, signal?: AbortSignal): Promise<ResolvedAddr[]> {
|
||||
if (signal?.aborted) throw signal.reason ?? new Error("TeamSpeak address resolution was aborted");
|
||||
|
||||
let target;
|
||||
try {
|
||||
target = parseTeamSpeakTarget(address);
|
||||
} catch {
|
||||
return this.resolveBase(address, signal);
|
||||
}
|
||||
|
||||
const { host, port } = target;
|
||||
if (isIP(host) || host === "localhost" || host.includes(".")) {
|
||||
return this.resolveBase(address, signal);
|
||||
}
|
||||
|
||||
const localAddress = await resolveLocalTeamSpeakAlias(host, {
|
||||
lookup: this.localLookup, timeoutMs: this.localAliasLookupTimeoutMs, signal,
|
||||
});
|
||||
if (localAddress) {
|
||||
return [directAddress(localAddress, port)];
|
||||
}
|
||||
|
||||
const baseResults = await this.resolveBaseWithTimeout(address, signal);
|
||||
return baseResults?.length ? baseResults : [directAddress(host, port)];
|
||||
}
|
||||
|
||||
private resolveBase(address: string, signal?: AbortSignal): Promise<ResolvedAddr[]> {
|
||||
return this.baseResolver.resolve(address, signal);
|
||||
}
|
||||
|
||||
private async resolveBaseWithTimeout(address: string, signal?: AbortSignal): Promise<ResolvedAddr[] | null> {
|
||||
const timeoutController = new AbortController();
|
||||
const combinedSignal = signal ? AbortSignal.any([signal, timeoutController.signal]) : timeoutController.signal;
|
||||
try {
|
||||
return await raceWithTimeout(
|
||||
Promise.resolve().then(() => this.baseResolver.resolve(address, combinedSignal)),
|
||||
this.nicknameLookupTimeoutMs,
|
||||
signal,
|
||||
);
|
||||
} catch (error: unknown) {
|
||||
if (signal?.aborted) throw signal.reason ?? error;
|
||||
return null;
|
||||
} finally {
|
||||
timeoutController.abort(new Error("TeamSpeak nickname lookup timed out"));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/** Keep Docker/service names local before attempting public nickname discovery. */
|
||||
export async function resolveLocalTeamSpeakAlias(
|
||||
host: string,
|
||||
options: { lookup?: LocalLookup; timeoutMs?: number; signal?: AbortSignal } = {},
|
||||
@@ -102,14 +27,6 @@ export async function resolveLocalTeamSpeakAlias(
|
||||
return addresses?.find(({ address }) => isPrivateNetworkAddress(address))?.address;
|
||||
}
|
||||
|
||||
function directAddress(host: string, port: number): ResolvedAddr {
|
||||
return {
|
||||
addr: formatTeamSpeakTarget({ host, port }),
|
||||
source: "Direct",
|
||||
expiry: new Date(0),
|
||||
};
|
||||
}
|
||||
|
||||
function isPrivateNetworkAddress(address: string): boolean {
|
||||
const version = isIP(address);
|
||||
if (version === 4) {
|
||||
|
||||
@@ -0,0 +1,136 @@
|
||||
import assert from "node:assert/strict";
|
||||
import { EventEmitter } from "node:events";
|
||||
import { setImmediate as nextTurn } from "node:timers/promises";
|
||||
import test from "node:test";
|
||||
import { asChannelGroupID, asChannelID, asClientID, asUID, avatarFileName, type Channel, type ClientEntry } from "@honeybbq/teamspeak";
|
||||
import { Client, generateIdentitySync, type ServerView } from "@honeybbq/teamspeak/client";
|
||||
import { TeamSpeakSdkClient, type DirectorySnapshot } from "./teamspeak-sdk.js";
|
||||
|
||||
const identity = generateIdentitySync(8);
|
||||
const uid = "AAAAAAAAAAAAAAAAAAAAAAAAAAA=";
|
||||
function channel(id = 1): Channel {
|
||||
return { id: asChannelID(BigInt(id)), parentID: asChannelID(0n), order: asChannelID(0n), name: "Lobby",
|
||||
description: "", hasPassword: true, maxClients: 12, isMaxClientsUnlimited: false } as Channel;
|
||||
}
|
||||
function member(id = 1): ClientEntry {
|
||||
return { id: asClientID(id), nickname: `Member ${id}`, uid: asUID(uid), channelID: asChannelID(1n), type: 0,
|
||||
serverGroups: [], isAway: true, awayMessage: "Away", isInputMuted: true, isOutputMuted: false,
|
||||
isChannelCommander: true, avatar: "avatar-hash", isRecording: false, isTalker: false,
|
||||
channelGroupID: asChannelGroupID(0n), createdAt: undefined, lastConnectedAt: undefined, idleTimeMs: undefined };
|
||||
}
|
||||
|
||||
function fixture() {
|
||||
const sdk = new TeamSpeakSdkClient(identity, "127.0.0.1:9987", "Test", {});
|
||||
const native = Object.assign(new EventEmitter(), {
|
||||
view: {
|
||||
status: "live", revision: 1,
|
||||
channels: new Map([[asChannelID(1n), channel()]]),
|
||||
clients: new Map([[asClientID(1), member()]]),
|
||||
serverName: "Shanghai", serverIconID: undefined, serverBannerImageURL: "https://example.invalid/banner",
|
||||
server: { virtualserver_welcomemessage: "Welcome" },
|
||||
whenReady: async (_options?: { signal?: AbortSignal }) => {},
|
||||
},
|
||||
serverCapabilities: { family: "ts6", welcomeMessage: "Old welcome" },
|
||||
queries: [] as string[],
|
||||
async exec(command: string) { this.queries.push(command); throw new Error("insufficient client permissions (code 2568)"); },
|
||||
});
|
||||
const state = sdk as unknown as { sdkClient: Client | null; attachUpstreamEvents(client: Client): void };
|
||||
state.sdkClient = native as unknown as Client;
|
||||
state.attachUpstreamEvents(native as unknown as Client);
|
||||
return { sdk, native, state };
|
||||
}
|
||||
|
||||
test("ordinary-client directories and avatar metadata use the live view without list permissions", async () => {
|
||||
const { sdk, native } = fixture();
|
||||
assert.deepEqual(await sdk.listDirectoryChannels(), [{ id: 1n, parentID: 0n, order: 0n, name: "Lobby", description: "",
|
||||
passwordProtected: true, maxClients: 12, maxClientsLimited: true }]);
|
||||
assert.deepEqual(await sdk.listDirectoryClients(), [{ id: 1, nickname: "Member 1", uid, channelID: 1n, type: 0,
|
||||
serverGroups: [], away: true, awayMessage: "Away", inputMuted: true, outputMuted: false, channelCommander: true }]);
|
||||
assert.deepEqual(await sdk.getClientAvatarMetadata(1), { uid, cacheKey: "avatar-hash", path: `/${avatarFileName(uid)}` });
|
||||
assert.equal(await sdk.getClientAvatarMetadata(2), null);
|
||||
assert.deepEqual(sdk.serverInfo, { name: "Shanghai", iconId: null, hostBannerGfxUrl: "https://example.invalid/banner", welcomeMessage: "Welcome" });
|
||||
assert.equal(sdk.serverFamily, "ts6");
|
||||
assert.deepEqual(native.queries, []);
|
||||
});
|
||||
|
||||
test("live-view snapshots include channel edits and remove clients that went out of view", () => {
|
||||
const { sdk, native } = fixture();
|
||||
const snapshots: DirectorySnapshot[] = [];
|
||||
sdk.on("directorySnapshot", snapshot => snapshots.push(snapshot));
|
||||
native.emit("viewReady");
|
||||
native.emit("viewChanged");
|
||||
assert.equal(snapshots.length, 1, "an unchanged revision does not duplicate the directory");
|
||||
assert.equal(snapshots[0]?.complete, true);
|
||||
native.view.clients.clear();
|
||||
native.view.channels.set(asChannelID(1n), { ...channel(), name: "Renamed", hasPassword: false, maxClients: 20 });
|
||||
native.view.revision++;
|
||||
native.emit("viewChanged");
|
||||
assert.equal(snapshots.at(-1)?.channels[0]?.name, "Renamed");
|
||||
assert.equal(snapshots.at(-1)?.channels[0]?.passwordProtected, false);
|
||||
assert.equal(snapshots.at(-1)?.channels[0]?.maxClients, 20);
|
||||
assert.deepEqual(snapshots.at(-1)?.clients, []);
|
||||
assert.equal(snapshots[0]?.clients.length, 1, "earlier snapshots stay independent");
|
||||
native.view.status = "stale";
|
||||
native.view.revision++;
|
||||
native.emit("viewChanged");
|
||||
assert.equal(snapshots.length, 2, "a stale view cannot initialize a session");
|
||||
});
|
||||
|
||||
test("member status changes use the SDK's current record and retired views cannot publish", async () => {
|
||||
const { sdk, native, state } = fixture();
|
||||
const updates: unknown[] = [];
|
||||
const snapshots: unknown[] = [];
|
||||
sdk.on("clientUpdated", update => updates.push(update));
|
||||
sdk.on("directorySnapshot", snapshot => snapshots.push(snapshot));
|
||||
native.view.clients.set(asClientID(1), { ...member(), isInputMuted: false, isOutputMuted: true, isAway: false });
|
||||
native.emit("clientUpdated", { clientID: asClientID(1), changes: { isInputMuted: false } });
|
||||
assert.equal((updates[0] as { info: { inputMuted: boolean } }).info.inputMuted, false);
|
||||
assert.equal((updates[0] as { info: { outputMuted: boolean } }).info.outputMuted, true);
|
||||
state.sdkClient = null;
|
||||
native.emit("viewChanged");
|
||||
native.emit("clientUpdated", { clientID: asClientID(1) });
|
||||
assert.equal(updates.length, 1);
|
||||
assert.equal(snapshots.length, 0);
|
||||
state.sdkClient = native as unknown as Client;
|
||||
native.view.status = "stale";
|
||||
await assert.rejects(sdk.listDirectoryChannels(), /view is not ready/);
|
||||
});
|
||||
|
||||
test("connect waits for the welcome view and propagates its connection deadline", async t => {
|
||||
const { native } = fixture();
|
||||
native.view.status = "loading";
|
||||
let welcome!: () => void;
|
||||
let observedSignal: AbortSignal | undefined;
|
||||
native.view.whenReady = options => {
|
||||
observedSignal = options?.signal;
|
||||
return new Promise<void>(resolve => { welcome = resolve; });
|
||||
};
|
||||
t.mock.method(Client.prototype, "connect", async () => {});
|
||||
t.mock.getter(Client.prototype, "view", () => native.view as unknown as ServerView);
|
||||
const sdk = new TeamSpeakSdkClient(identity, "127.0.0.1:9987", "Test", {});
|
||||
const controller = new AbortController();
|
||||
let connected = false;
|
||||
const snapshots: DirectorySnapshot[] = [];
|
||||
sdk.on("directorySnapshot", snapshot => snapshots.push(snapshot));
|
||||
const pending = sdk.connect({ signal: controller.signal }).then(() => { connected = true; });
|
||||
await nextTurn();
|
||||
assert.equal(connected, false, "handshake success alone is not a usable directory");
|
||||
assert.equal(observedSignal, controller.signal);
|
||||
native.view.status = "live";
|
||||
welcome();
|
||||
await pending;
|
||||
assert.equal(connected, true);
|
||||
assert.equal(snapshots.length, 1);
|
||||
assert.equal(snapshots[0]?.clients[0]?.id, 1);
|
||||
});
|
||||
|
||||
test("an interrupted welcome rejects connect instead of leaving initialization pending", async t => {
|
||||
const { native } = fixture();
|
||||
const failure = new Error("welcome connection deadline");
|
||||
native.view.status = "loading";
|
||||
native.view.whenReady = async options => { options?.signal?.throwIfAborted(); };
|
||||
t.mock.method(Client.prototype, "connect", async () => {});
|
||||
t.mock.getter(Client.prototype, "view", () => native.view as unknown as ServerView);
|
||||
const sdk = new TeamSpeakSdkClient(identity, "127.0.0.1:9987", "Test", {});
|
||||
await assert.rejects(sdk.connect({ signal: AbortSignal.abort(failure) }), error => error === failure);
|
||||
});
|
||||
@@ -0,0 +1,339 @@
|
||||
import { EventEmitter } from "node:events";
|
||||
import type { Writable } from "node:stream";
|
||||
import {
|
||||
asChannelID,
|
||||
asClientID,
|
||||
avatarFileName,
|
||||
initFileDownload,
|
||||
moveClient,
|
||||
pokeClient,
|
||||
sendChannelMessage,
|
||||
sendPrivateMessage,
|
||||
sendServerMessage,
|
||||
type Channel,
|
||||
type ClientEntry,
|
||||
type Codec,
|
||||
type CommandExecutor,
|
||||
type FileDownloadInfo,
|
||||
type ServerFamily,
|
||||
} from "@honeybbq/teamspeak";
|
||||
import { Client, type ClientOptions, type Identity } from "@honeybbq/teamspeak/client";
|
||||
import { resolveLocalTeamSpeakAlias } from "./teamspeak-resolver.js";
|
||||
import { formatTeamSpeakTarget, parseTeamSpeakTarget } from "../domain/teamspeak-target.js";
|
||||
|
||||
export type { Identity };
|
||||
export type TeamSpeakClientOptions = Pick<ClientOptions, "serverPassword" | "defaultChannel" | "defaultChannelPassword" | "logger">;
|
||||
|
||||
export interface ClientInfo {
|
||||
id: number;
|
||||
nickname: string;
|
||||
uid: string;
|
||||
serverGroups: string[];
|
||||
channelID: bigint;
|
||||
type: number;
|
||||
}
|
||||
|
||||
export interface DirectoryClientInfo extends ClientInfo {
|
||||
away?: boolean;
|
||||
awayMessage?: string;
|
||||
inputMuted?: boolean;
|
||||
outputMuted?: boolean;
|
||||
channelCommander?: boolean;
|
||||
}
|
||||
|
||||
export interface DirectoryChannelInfo {
|
||||
id: bigint;
|
||||
parentID: bigint;
|
||||
order: bigint;
|
||||
name: string;
|
||||
description: string;
|
||||
passwordProtected?: boolean;
|
||||
maxClients?: number;
|
||||
maxClientsLimited?: boolean;
|
||||
}
|
||||
|
||||
export interface DirectorySnapshot {
|
||||
channels: DirectoryChannelInfo[];
|
||||
clients: DirectoryClientInfo[];
|
||||
/** The SDK's live view replaces the visible roster, including unsubscribed clients. */
|
||||
complete?: boolean;
|
||||
}
|
||||
|
||||
export interface RawNotification {
|
||||
name: string;
|
||||
params: Record<string, string>;
|
||||
}
|
||||
|
||||
export interface VoiceData {
|
||||
clientId: number;
|
||||
codec: number;
|
||||
data: Uint8Array;
|
||||
}
|
||||
|
||||
export interface TextMessage {
|
||||
invokerName: string;
|
||||
invokerUID: string;
|
||||
message: string;
|
||||
invokerGroups: readonly bigint[] | undefined;
|
||||
targetMode: number;
|
||||
targetID: bigint;
|
||||
invokerID: number;
|
||||
}
|
||||
|
||||
export interface ServerInfo {
|
||||
name: string;
|
||||
iconId: number | null;
|
||||
hostBannerGfxUrl: string | null;
|
||||
welcomeMessage: string;
|
||||
}
|
||||
|
||||
/**
|
||||
* A narrow compatibility boundary for WebSpeak's old fork-specific SDK events.
|
||||
* Wire I/O and command execution are provided by the upstream 1.0 client; this
|
||||
* class only translates names and shapes that WebSpeak already consumes.
|
||||
*/
|
||||
export class TeamSpeakSdkClient extends EventEmitter implements CommandExecutor {
|
||||
private sdkClient: Client | null = null;
|
||||
private directoryRevision = -1;
|
||||
|
||||
constructor(
|
||||
private readonly identity: Identity,
|
||||
private readonly address: string,
|
||||
private readonly nickname: string,
|
||||
private readonly options: TeamSpeakClientOptions,
|
||||
) {
|
||||
super();
|
||||
}
|
||||
|
||||
get status(): string | number {
|
||||
return this.sdkClient?.status ?? 0;
|
||||
}
|
||||
|
||||
get serverInfo(): ServerInfo | null {
|
||||
const client = this.sdkClient;
|
||||
return client
|
||||
? {
|
||||
name: client.view.serverName,
|
||||
iconId: client.view.serverIconID ?? null,
|
||||
hostBannerGfxUrl: client.view.serverBannerImageURL ?? null,
|
||||
welcomeMessage: client.view.server.virtualserver_welcomemessage ?? client.serverCapabilities.welcomeMessage,
|
||||
}
|
||||
: null;
|
||||
}
|
||||
|
||||
get serverFamily(): ServerFamily {
|
||||
return this.sdkClient?.serverCapabilities.family ?? "unknown";
|
||||
}
|
||||
|
||||
async connect(options: { signal?: AbortSignal } = {}): Promise<void> {
|
||||
this.directoryRevision = -1;
|
||||
const target = parseTeamSpeakTarget(this.address);
|
||||
const localAlias = await resolveLocalTeamSpeakAlias(target.host, { signal: options.signal });
|
||||
const address = localAlias ? formatTeamSpeakTarget({ host: localAlias, port: target.port }) : this.address;
|
||||
const client = new Client(this.identity, address, this.nickname, {
|
||||
...this.options,
|
||||
// Preserve TeamSpeak nickname addresses. The upstream resolver bounds
|
||||
// the full SRV/TSDNS/nickname lookup and falls back to the given address.
|
||||
nicknameLookup: true,
|
||||
});
|
||||
this.sdkClient = client;
|
||||
this.attachUpstreamEvents(client);
|
||||
await client.connect(options);
|
||||
// connect() accepts the session before the welcome directory is complete.
|
||||
// Share its cancellation/deadline instead of waiting forever for a snapshot.
|
||||
await client.view.whenReady(options);
|
||||
this.publishDirectory(client);
|
||||
}
|
||||
|
||||
async disconnect(): Promise<void> {
|
||||
await this.sdkClient?.disconnect();
|
||||
}
|
||||
|
||||
async send(request: Parameters<CommandExecutor["send"]>[0], options?: Parameters<CommandExecutor["send"]>[1]) {
|
||||
return this.requireClient().send(request, options);
|
||||
}
|
||||
|
||||
async exec(command: string, options?: { signal?: AbortSignal; timeoutMs?: number }) {
|
||||
return this.requireClient().exec(command, options);
|
||||
}
|
||||
|
||||
clientID(): number {
|
||||
return Number(this.sdkClient?.clientID ?? 0);
|
||||
}
|
||||
|
||||
channelID(): bigint {
|
||||
return this.sdkClient?.channelID ?? 0n;
|
||||
}
|
||||
|
||||
async execCommand(command: string, timeoutMs?: number): Promise<void> {
|
||||
await this.requireClient().exec(command, timeoutMs === undefined ? undefined : { timeoutMs });
|
||||
}
|
||||
|
||||
async execCommandWithResponse(command: string, timeoutMs?: number): Promise<Record<string, string>[]> {
|
||||
return this.requireClient().exec(command, timeoutMs === undefined ? undefined : { timeoutMs });
|
||||
}
|
||||
|
||||
sendVoice(data: Uint8Array, codec: number): void {
|
||||
this.requireClient().sendVoice(data, codec as Codec);
|
||||
}
|
||||
|
||||
sendWhisper(data: Uint8Array, clientIds: number[], codec: number): void {
|
||||
this.requireClient().sendWhisper(data, { clients: clientIds.map(asClientID) }, codec as Codec);
|
||||
}
|
||||
|
||||
async fileTransferInitDownload(channelID: bigint, path: string, password: string): Promise<FileDownloadInfo> {
|
||||
return initFileDownload(this, asChannelID(channelID), path, { password });
|
||||
}
|
||||
|
||||
async downloadFileData(host: string, info: FileDownloadInfo, destination: Writable): Promise<void> {
|
||||
await this.requireClient().downloadFileData(host, info, destination);
|
||||
}
|
||||
|
||||
async listDirectoryChannels(): Promise<DirectoryChannelInfo[]> {
|
||||
return this.readDirectory().channels;
|
||||
}
|
||||
|
||||
async listDirectoryClients(): Promise<DirectoryClientInfo[]> {
|
||||
return this.readDirectory().clients;
|
||||
}
|
||||
|
||||
async getClientAvatarMetadata(clientId: number): Promise<{ uid: string; cacheKey: string; path: string } | null> {
|
||||
const info = this.requireClient().view.clients.get(asClientID(clientId));
|
||||
if (!info?.uid || !info.avatar) return null;
|
||||
return { uid: info.uid, cacheKey: info.avatar, path: `/${avatarFileName(info.uid)}` };
|
||||
}
|
||||
|
||||
private readDirectory(): DirectorySnapshot {
|
||||
const view = this.requireClient().view;
|
||||
if (view.status !== "live") throw new Error("TeamSpeak directory view is not ready");
|
||||
return {
|
||||
channels: [...view.channels.values()].map(toDirectoryChannel),
|
||||
clients: [...view.clients.values()].map(toDirectoryClient),
|
||||
complete: true,
|
||||
};
|
||||
}
|
||||
|
||||
private publishDirectory(client: Client): void {
|
||||
if (this.sdkClient !== client || client.view.status !== "live" || client.view.revision === this.directoryRevision) return;
|
||||
this.directoryRevision = client.view.revision;
|
||||
this.emit("directorySnapshot", this.readDirectory());
|
||||
}
|
||||
|
||||
private requireClient(): Client {
|
||||
if (!this.sdkClient) throw new Error("TeamSpeak session is not ready");
|
||||
return this.sdkClient;
|
||||
}
|
||||
|
||||
private attachUpstreamEvents(client: Client): void {
|
||||
const isCurrent = () => this.sdkClient === client;
|
||||
client.on("viewReady", () => this.publishDirectory(client));
|
||||
client.on("viewChanged", () => this.publishDirectory(client));
|
||||
client.on("voiceData", (event) => {
|
||||
if (!isCurrent()) return;
|
||||
this.emit("voiceData", { clientId: Number(event.clientID), codec: event.codec, data: event.data } satisfies VoiceData);
|
||||
});
|
||||
client.on("textMessage", (event) => {
|
||||
if (!isCurrent()) return;
|
||||
this.emit("textMessage", {
|
||||
...event,
|
||||
invokerGroups: event.invokerGroups,
|
||||
targetID: BigInt(event.targetID),
|
||||
invokerID: Number(event.invokerID),
|
||||
} satisfies TextMessage);
|
||||
});
|
||||
client.on("poked", (event) => { if (isCurrent()) this.emit("poked", event); });
|
||||
client.on("clientEnter", (event) => {
|
||||
if (!isCurrent()) return;
|
||||
this.emit("clientEnter", toDirectoryClient(event));
|
||||
});
|
||||
client.on("clientUpdated", (event) => {
|
||||
if (!isCurrent()) return;
|
||||
const info = client.view.clients.get(event.clientID);
|
||||
if (info) this.emit("clientUpdated", { info: toDirectoryClient(info) });
|
||||
});
|
||||
client.on("clientLeave", (event) => {
|
||||
if (!isCurrent()) return;
|
||||
const id = Number(event.clientID);
|
||||
this.emit("clientLeave", {
|
||||
id,
|
||||
reasonID: event.reason,
|
||||
reasonMsg: event.reasonMessage,
|
||||
targetID: id,
|
||||
});
|
||||
});
|
||||
client.on("clientMoved", (event) => {
|
||||
if (!isCurrent()) return;
|
||||
const id = Number(event.clientID);
|
||||
this.emit("clientMoved", {
|
||||
id,
|
||||
targetChannelID: BigInt(event.targetChannelID),
|
||||
reasonID: event.reason,
|
||||
invokerID: Number(event.invokerID),
|
||||
invokerUID: event.invokerUID,
|
||||
invokerName: event.invokerName,
|
||||
});
|
||||
});
|
||||
client.on("kicked", (event) => { if (isCurrent()) this.emit("kicked", event.reasonMessage); });
|
||||
client.on("disconnected", (event) => { if (isCurrent()) this.emit("disconnected", event.error); });
|
||||
client.on("notification", (event) => {
|
||||
if (!isCurrent()) return;
|
||||
const notification = { name: event.name, params: { ...event.params } } satisfies RawNotification;
|
||||
this.emit("rawNotification", notification);
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
export async function listChannelsCompat(client: TeamSpeakSdkClient): Promise<DirectoryChannelInfo[]> {
|
||||
return client.listDirectoryChannels();
|
||||
}
|
||||
|
||||
export async function listClientsCompat(client: TeamSpeakSdkClient): Promise<DirectoryClientInfo[]> {
|
||||
return client.listDirectoryClients();
|
||||
}
|
||||
|
||||
export async function moveClientCompat(client: TeamSpeakSdkClient, clientId: number, channelId: bigint, password?: string): Promise<void> {
|
||||
await moveClient(client, asClientID(clientId), asChannelID(channelId), { password });
|
||||
}
|
||||
|
||||
export async function sendTextMessageCompat(client: TeamSpeakSdkClient, mode: number, targetId: bigint, message: string): Promise<void> {
|
||||
if (mode === 1) await sendPrivateMessage(client, asClientID(Number(targetId)), message);
|
||||
else if (mode === 2) await sendChannelMessage(client, message);
|
||||
else await sendServerMessage(client, message);
|
||||
}
|
||||
|
||||
export async function pokeCompat(client: TeamSpeakSdkClient, clientId: number, message: string): Promise<void> {
|
||||
await pokeClient(client, asClientID(clientId), message);
|
||||
}
|
||||
|
||||
export type { Channel, ClientEntry };
|
||||
|
||||
function toDirectoryChannel(channel: Channel): DirectoryChannelInfo {
|
||||
return {
|
||||
id: BigInt(channel.id),
|
||||
parentID: BigInt(channel.parentID),
|
||||
order: BigInt(channel.order),
|
||||
name: channel.name,
|
||||
description: channel.description,
|
||||
passwordProtected: channel.hasPassword,
|
||||
...(Number.isInteger(channel.maxClients) && channel.maxClients >= 0 && channel.maxClients <= 65_535
|
||||
&& typeof channel.isMaxClientsUnlimited === "boolean"
|
||||
? { maxClients: channel.maxClients, maxClientsLimited: !channel.isMaxClientsUnlimited }
|
||||
: {}),
|
||||
};
|
||||
}
|
||||
|
||||
function toDirectoryClient(entry: ClientEntry): DirectoryClientInfo {
|
||||
return {
|
||||
id: Number(entry.id),
|
||||
nickname: entry.nickname,
|
||||
uid: entry.uid,
|
||||
serverGroups: entry.serverGroups.map(String),
|
||||
channelID: BigInt(entry.channelID),
|
||||
type: entry.type,
|
||||
...(entry.isAway !== undefined ? { away: entry.isAway } : {}),
|
||||
...(entry.awayMessage !== undefined ? { awayMessage: entry.awayMessage } : {}),
|
||||
...(entry.isInputMuted !== undefined ? { inputMuted: entry.isInputMuted } : {}),
|
||||
...(entry.isOutputMuted !== undefined ? { outputMuted: entry.isOutputMuted } : {}),
|
||||
...(entry.isChannelCommander !== undefined ? { channelCommander: entry.isChannelCommander } : {}),
|
||||
};
|
||||
}
|
||||
@@ -3,6 +3,7 @@ import test from "node:test";
|
||||
import { EventEmitter } from "node:events";
|
||||
import { setImmediate as nextTurn } from "node:timers/promises";
|
||||
import type { Writable } from "node:stream";
|
||||
import type { CommandRequest } from "@honeybbq/teamspeak";
|
||||
import pino from "pino";
|
||||
import { TSClient } from "./ts-client.js";
|
||||
|
||||
@@ -22,10 +23,24 @@ class SdkStub extends EventEmitter {
|
||||
name: "兄弟们的teamspeak", iconId: 123456, hostBannerGfxUrl: null, welcomeMessage: "",
|
||||
};
|
||||
inputUpdate = async (_command: string): Promise<void> => {};
|
||||
async send(request: CommandRequest) {
|
||||
const command = [request.command, ...(request.params ?? []).map(([key, value]) => `${key}=${String(value ?? "")}`)].join(" ");
|
||||
this.inputCommands.push(command);
|
||||
await this.inputUpdate(command);
|
||||
return [];
|
||||
}
|
||||
async execCommand(command: string) { this.inputCommands.push(command); await this.inputUpdate(command); }
|
||||
clientID() { return 1; }
|
||||
channelID() { return 1n; }
|
||||
async listDirectoryChannels() { return [{ id: 1n, parentID: 0n, order: 0n, name: "Lobby", description: "", passwordProtected: true }]; }
|
||||
async listDirectoryClients() { return [{ id: 1, nickname: "Test", uid: "self", channelID: 1n, type: 0, serverGroups: [] as string[], inputMuted: true }]; }
|
||||
initialized = 0;
|
||||
downloaded = 0;
|
||||
metadata = async () => rows;
|
||||
async getClientAvatarMetadata() {
|
||||
const [info] = await this.metadata();
|
||||
return info ? { uid: info.client_unique_identifier, cacheKey: info.client_flag_avatar, path: `/avatar_${info.client_base64HashClientUID}` } : null;
|
||||
}
|
||||
transfer = async () => transfer;
|
||||
download = async (destination: Writable) => { destination.write(Buffer.from("GIF89a")); };
|
||||
execCommandWithResponse(command = "") {
|
||||
@@ -50,6 +65,34 @@ function fixture() {
|
||||
return { client, sdk, state };
|
||||
}
|
||||
|
||||
test("normal startup publishes the subscribed native directory without privileged list queries", async () => {
|
||||
const f = fixture();
|
||||
f.state.connected = false;
|
||||
const state = f.client as unknown as { adapter: { connect(): Promise<void> } };
|
||||
state.adapter = { connect: async () => {} };
|
||||
const snapshots: Array<{ complete?: boolean; clients: Array<{ id: number; inputMuted?: boolean }> }> = [];
|
||||
f.client.on("directorySnapshot", snapshot => snapshots.push(snapshot));
|
||||
await f.client.connect();
|
||||
assert.equal(f.client.isConnected(), true);
|
||||
assert.equal(snapshots.at(-1)?.complete, true);
|
||||
assert.equal(snapshots.at(-1)?.clients[0]?.id, 1);
|
||||
assert.equal(snapshots.at(-1)?.clients[0]?.inputMuted, true);
|
||||
assert.deepEqual(f.sdk.inputCommands, ["channelsubscribeall"]);
|
||||
});
|
||||
|
||||
test("a missing native view fails startup instead of leaving a connected session without a directory", async () => {
|
||||
const f = fixture();
|
||||
f.state.connected = false;
|
||||
const state = f.client as unknown as { adapter: { connect(): Promise<void> } };
|
||||
state.adapter = { connect: async () => {} };
|
||||
f.sdk.listDirectoryChannels = async () => { throw new Error("TeamSpeak directory view is not ready"); };
|
||||
let published = false;
|
||||
f.client.on("connected", () => { published = true; });
|
||||
await assert.rejects(f.client.connect(), /view is not ready/);
|
||||
assert.equal(f.client.isConnected(), false);
|
||||
assert.equal(published, false);
|
||||
});
|
||||
|
||||
test("stream commands wait for server acknowledgement and propagate refusals", async () => {
|
||||
const f = fixture();
|
||||
const ack = deferred<void>();
|
||||
|
||||
+45
-79
@@ -1,20 +1,26 @@
|
||||
import { EventEmitter } from "node:events";
|
||||
import { Writable } from "node:stream";
|
||||
import {
|
||||
Client as TS3FullClient,
|
||||
clientMove as tsClientMove,
|
||||
listChannels as tsListChannels,
|
||||
listClients as tsListClients,
|
||||
poke as tsPoke,
|
||||
sendTextMessage as tsSendTextMessage,
|
||||
generateIdentity,
|
||||
type Identity,
|
||||
type VoiceData,
|
||||
type DirectoryClientInfo,
|
||||
type DirectorySnapshot,
|
||||
type RawNotification,
|
||||
type TextMessage,
|
||||
} from "@echosixhiya/teamspeak-client";
|
||||
generateIdentitySync,
|
||||
} from "@honeybbq/teamspeak/client";
|
||||
import type {
|
||||
ClientInfo,
|
||||
DirectoryChannelInfo,
|
||||
DirectoryClientInfo,
|
||||
DirectorySnapshot,
|
||||
Identity,
|
||||
RawNotification,
|
||||
TextMessage,
|
||||
VoiceData,
|
||||
} from "./teamspeak-sdk.js";
|
||||
import {
|
||||
listChannelsCompat as tsListChannels,
|
||||
listClientsCompat as tsListClients,
|
||||
moveClientCompat as tsClientMove,
|
||||
pokeCompat as tsPoke,
|
||||
sendTextMessageCompat as tsSendTextMessage,
|
||||
TeamSpeakSdkClient,
|
||||
} from "./teamspeak-sdk.js";
|
||||
import type { Logger } from "../logger.js";
|
||||
import { describeTeamSpeakError, normalizeTeamSpeakError, normalizeTeamSpeakKickedReason } from "../errors.js";
|
||||
import { TeamSpeakAdapter, type TeamSpeakProtocol } from "./teamspeak-adapter.js";
|
||||
@@ -23,8 +29,6 @@ import { createAccelerationRelayClient, type AccelerationRelayClient, type Accel
|
||||
import {
|
||||
applyChannelCapacityNotification,
|
||||
applyChannelPasswordProtectionNotification,
|
||||
parseChannelCapacities,
|
||||
parseChannelPasswordProtections,
|
||||
type ChannelCapacity,
|
||||
type ChannelPasswordProtection,
|
||||
} from "./channel-capacity.js";
|
||||
@@ -69,7 +73,7 @@ const MAX_SERVER_ICON_BYTES = 128 * 1024;
|
||||
const MAX_SERVER_BANNER_URL_LENGTH = 2_048;
|
||||
const MAX_SERVER_WELCOME_MESSAGE_LENGTH = 4_096;
|
||||
|
||||
export type TSDirectoryChannel = DirectorySnapshot["channels"][number] & Partial<ChannelCapacity> & Partial<ChannelPasswordProtection>;
|
||||
export type TSDirectoryChannel = DirectoryChannelInfo & Partial<ChannelCapacity> & Partial<ChannelPasswordProtection>;
|
||||
export type TSDirectorySnapshot = Omit<DirectorySnapshot, "channels"> & { channels: TSDirectoryChannel[] };
|
||||
export type TSDirectoryClient = DirectoryClientInfo;
|
||||
export type TSRawNotification = RawNotification;
|
||||
@@ -102,7 +106,7 @@ export function toTSChatMessage(msg: TextMessage): TSChatMessage {
|
||||
}
|
||||
|
||||
export class TSClient extends EventEmitter {
|
||||
private client: TS3FullClient | null = null;
|
||||
private client: TeamSpeakSdkClient | null = null;
|
||||
private adapter: TeamSpeakAdapter | null = null;
|
||||
private logger: Logger;
|
||||
private readonly identity: Identity;
|
||||
@@ -125,7 +129,7 @@ export class TSClient extends EventEmitter {
|
||||
constructor(private options: TSClientOptions, logger: Logger) {
|
||||
super();
|
||||
this.logger = logger.child({ nickname: options.nickname });
|
||||
this.identity = options.identity ?? generateIdentity(8);
|
||||
this.identity = options.identity ?? generateIdentitySync(8);
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -199,47 +203,16 @@ export class TSClient extends EventEmitter {
|
||||
err: error instanceof Error ? error.message : String(error),
|
||||
}, "Could not subscribe to all TeamSpeak channels");
|
||||
}
|
||||
// Directory snapshots are dispatched through two setImmediate layers in
|
||||
// the SDK. Let both flush before reconciling with a direct client-protocol
|
||||
// snapshot so the gateway's first connected state contains every member.
|
||||
await new Promise<void>((resolve) => setImmediate(resolve));
|
||||
await new Promise<void>((resolve) => setImmediate(resolve));
|
||||
|
||||
// TS6 can finish the welcome event stream before it has exposed every
|
||||
// existing client to a newly connected session. Pull one authoritative
|
||||
// snapshot through this same client protocol session so users who joined
|
||||
// earlier are visible immediately as well. Realtime events continue to
|
||||
// keep the snapshot current after this reconciliation.
|
||||
try {
|
||||
const [channels, clients] = await Promise.all([
|
||||
tsListChannels(client),
|
||||
tsListClients(client),
|
||||
]);
|
||||
try {
|
||||
// The high-level SDK directory type intentionally omits channel limit
|
||||
// metadata. Its raw client-protocol rows still include the public
|
||||
// maximum-client properties, so retain those without another SDK API.
|
||||
// TeamSpeak only includes channel flag fields (including the public
|
||||
// password-required bit) when the client asks for flags explicitly.
|
||||
const rows = await client.execCommandWithResponse("channellist -flags", 5_000);
|
||||
const capacities = parseChannelCapacities(rows);
|
||||
for (const [id, capacity] of capacities) this.channelCapacities.set(id, capacity);
|
||||
for (const [id, passwordProtected] of parseChannelPasswordProtections(rows)) {
|
||||
this.channelPasswordProtection.set(id, passwordProtected);
|
||||
}
|
||||
} catch (error: unknown) {
|
||||
this.logger.warn({ err: error instanceof Error ? error.message : String(error) }, "Could not read TeamSpeak channel limits");
|
||||
}
|
||||
this.emit("directorySnapshot", {
|
||||
channels: this.applyChannelMetadata(channels),
|
||||
clients,
|
||||
});
|
||||
} catch (error: unknown) {
|
||||
this.logger.warn({
|
||||
failureCode: "DIRECTORY_SNAPSHOT_UNAVAILABLE",
|
||||
failureDetail: error instanceof Error ? error.message : String(error),
|
||||
}, "TeamSpeak directory snapshot unavailable");
|
||||
}
|
||||
// The upstream live view contains the welcome and subscription data,
|
||||
// including channel limits and member status. Reading it needs no list
|
||||
// permissions; a failure must fail initialization instead of parking the
|
||||
// browser in `syncing` forever.
|
||||
const [channels, clients] = await Promise.all([tsListChannels(client), tsListClients(client)]);
|
||||
this.emit("directorySnapshot", {
|
||||
channels: this.applyChannelMetadata(channels),
|
||||
clients,
|
||||
complete: true,
|
||||
} satisfies TSDirectorySnapshot);
|
||||
|
||||
const connectedChannelId = client.channelID();
|
||||
if (this.preferredChannelId === 0n) {
|
||||
@@ -284,9 +257,9 @@ export class TSClient extends EventEmitter {
|
||||
/**
|
||||
* Load a visible client's TeamSpeak avatar through the client protocol.
|
||||
*
|
||||
* TeamSpeak does not include the avatar bytes in directory notifications.
|
||||
* `clientinfo` exposes the avatar marker and the per-identity filename; the
|
||||
* file itself is then read through the normal TeamSpeak file-transfer port.
|
||||
* The SDK's live view supplies the avatar marker and identity. Its public
|
||||
* avatar filename helper handles TS3/TS6 identities; the image is read
|
||||
* through the normal TeamSpeak file-transfer port.
|
||||
* A missing permission, missing avatar, blocked file-transfer port, or an
|
||||
* oversized image is intentionally reported as `null` so the web client can
|
||||
* keep its generated initial avatar.
|
||||
@@ -297,18 +270,11 @@ export class TSClient extends EventEmitter {
|
||||
if (!Number.isInteger(clientId) || clientId <= 0 || clientId > 65535) throw new Error("Invalid TeamSpeak client id");
|
||||
const generation = this.connectionGeneration;
|
||||
const isCurrent = () => this.client === client && this.connected && this.connectionGeneration === generation;
|
||||
const rows = await client.execCommandWithResponse(`clientinfo clid=${clientId}`, 5_000);
|
||||
const info = await client.getClientAvatarMetadata(clientId);
|
||||
if (!isCurrent()) return null;
|
||||
const info = rows.find((row) => {
|
||||
if (expectedUid && row.client_unique_identifier !== expectedUid) return false;
|
||||
return typeof row.client_flag_avatar === "string" && typeof row.client_base64HashClientUID === "string";
|
||||
});
|
||||
if (!info) return null;
|
||||
const cacheKey = info.client_flag_avatar?.trim() ?? "";
|
||||
const avatarFileKey = info.client_base64HashClientUID?.trim() ?? "";
|
||||
if (!cacheKey || !/^[A-Za-z0-9+/=_-]{8,256}$/.test(avatarFileKey)) return null;
|
||||
|
||||
const transfer = await client.fileTransferInitDownload(0n, `/avatar_${avatarFileKey}`, "");
|
||||
if (!info || expectedUid && info.uid !== expectedUid) return null;
|
||||
const cacheKey = info.cacheKey;
|
||||
const transfer = await client.fileTransferInitDownload(0n, info.path, "");
|
||||
if (!isCurrent()) return null;
|
||||
const size = Number(transfer.size);
|
||||
if (!Number.isSafeInteger(size) || size <= 0 || size > MAX_CLIENT_AVATAR_BYTES) return null;
|
||||
@@ -380,7 +346,7 @@ export class TSClient extends EventEmitter {
|
||||
return data;
|
||||
}
|
||||
|
||||
private attachClientListeners(client: TS3FullClient): void {
|
||||
private attachClientListeners(client: TeamSpeakSdkClient): void {
|
||||
client.on("voiceData", (data: VoiceData) => {
|
||||
if (this.client !== client) return;
|
||||
this.emit("voiceData", {
|
||||
@@ -390,12 +356,12 @@ export class TSClient extends EventEmitter {
|
||||
} as TSVoiceData);
|
||||
});
|
||||
|
||||
// The SDK exposes the directory that TeamSpeak sends during the normal
|
||||
// client welcome sequence. The connect path also reconciles this event
|
||||
// stream with a complete client-protocol snapshot.
|
||||
// The SDK publishes its native live view after the welcome and whenever
|
||||
// the visible channels or members change.
|
||||
client.on("directorySnapshot", (snapshot) => {
|
||||
if (this.client !== client) return;
|
||||
this.emit("directorySnapshot", {
|
||||
complete: snapshot.complete,
|
||||
channels: this.applyChannelMetadata(snapshot.channels),
|
||||
clients: snapshot.clients.slice(),
|
||||
});
|
||||
@@ -625,7 +591,7 @@ export class TSClient extends EventEmitter {
|
||||
}
|
||||
|
||||
getIdentityString(): string {
|
||||
return this.identity.toString();
|
||||
return this.identity.export();
|
||||
}
|
||||
|
||||
getChannelId(): bigint {
|
||||
|
||||
@@ -79,7 +79,7 @@ async function fixture(t: TestContext, overrides: {
|
||||
if (overrides.waitForFirstMessage !== false) await first;
|
||||
const entries = (bridge as unknown as { entries: Map<string, {
|
||||
id: string; ws: WebSocket; audio: AudioFlowStats; webrtc: WebRtcAudioSession | null;
|
||||
isAlive: boolean; avatarCache: Map<string, string | null>;
|
||||
isAlive: boolean; lastPongAt: number; missedHeartbeats: number; avatarCache: Map<string, string | null>;
|
||||
members: Map<number, { id: number; uid: string }>; eventLog: unknown[];
|
||||
}> }).entries;
|
||||
return { bridge, sdk, socket, messages, entries, wss };
|
||||
@@ -304,6 +304,44 @@ async function avatarFixture(t: TestContext) {
|
||||
return { ...f, calls, release: () => release(avatar), entry: [...f.entries.values()][0]! };
|
||||
}
|
||||
|
||||
test("a single missed WebSocket heartbeat is retried and a pong resets the miss count", { timeout: 5_000 }, async t => {
|
||||
const f = await fixture(t);
|
||||
const entry = [...f.entries.values()][0]!;
|
||||
const bridge = f.bridge as unknown as { checkHeartbeats(): void };
|
||||
// Suppress the network ping so this test can advance heartbeat ticks directly.
|
||||
entry.ws.ping = (() => {}) as typeof entry.ws.ping;
|
||||
|
||||
bridge.checkHeartbeats();
|
||||
assert.equal(entry.isAlive, false);
|
||||
bridge.checkHeartbeats();
|
||||
assert.equal(entry.missedHeartbeats, 1);
|
||||
assert.equal(entry.ws.readyState, WebSocket.OPEN);
|
||||
|
||||
const previousPongAt = entry.lastPongAt;
|
||||
entry.ws.emit("pong", Buffer.alloc(0));
|
||||
assert.equal(entry.isAlive, true);
|
||||
assert.equal(entry.missedHeartbeats, 0);
|
||||
assert.ok(entry.lastPongAt >= previousPongAt);
|
||||
});
|
||||
|
||||
test("two consecutive missed WebSocket heartbeats terminate the stale session", { timeout: 5_000 }, async t => {
|
||||
const f = await fixture(t);
|
||||
const entry = [...f.entries.values()][0]!;
|
||||
const bridge = f.bridge as unknown as { checkHeartbeats(): void };
|
||||
entry.ws.ping = (() => {}) as typeof entry.ws.ping;
|
||||
|
||||
const closed = once(f.socket, "close");
|
||||
bridge.checkHeartbeats();
|
||||
bridge.checkHeartbeats();
|
||||
assert.equal(entry.ws.readyState, WebSocket.OPEN);
|
||||
assert.equal(entry.missedHeartbeats, 1);
|
||||
|
||||
bridge.checkHeartbeats();
|
||||
await closed;
|
||||
await nextTurn();
|
||||
assert.equal(f.bridge.getActiveCount(), 0);
|
||||
});
|
||||
|
||||
test("avatar completion after teardown cannot refill the cache or start another SDK request", { timeout: 5_000 }, async t => {
|
||||
const f = await avatarFixture(t);
|
||||
await f.bridge.terminateSession(f.entry.id);
|
||||
|
||||
@@ -3,7 +3,7 @@ import test from "node:test";
|
||||
import { setImmediate as nextTurn } from "node:timers/promises";
|
||||
import type { IncomingMessage } from "node:http";
|
||||
import pino from "pino";
|
||||
import { VoiceBridge, createTrustedProxies, resolveClientIp } from "./voice-bridge.js";
|
||||
import { VoiceBridge, createTrustedProxies, resolveClientIp, resolveWebRtcPublicHost } from "./voice-bridge.js";
|
||||
import { JoinTicketStore } from "./join-ticket.js";
|
||||
import { createAudioFlowStats } from "./audio-stats.js";
|
||||
import { SessionAudioTransport } from "./session-audio.js";
|
||||
@@ -164,6 +164,16 @@ test("a current peer construction failure reports a recoverable negotiation erro
|
||||
assert.deepEqual(f.messages, [{ type: "webrtcError", code: "WEBRTC_NEGOTIATION_FAILED" }]);
|
||||
});
|
||||
|
||||
test("WebRTC candidates use the voice gateway host when the page Origin belongs to another gateway", () => {
|
||||
const request = {
|
||||
headers: {
|
||||
origin: "https://ingress.example.com",
|
||||
host: "voice-relay.example.com:3041",
|
||||
},
|
||||
} as IncomingMessage;
|
||||
assert.equal(resolveWebRtcPublicHost(request), "voice-relay.example.com");
|
||||
});
|
||||
|
||||
test("initial accompaniment updates TeamSpeak before creating a muted mixer and resets on stop", async () => {
|
||||
const f = fixture();
|
||||
const inputs: Array<[string, boolean]> = [];
|
||||
|
||||
+66
-15
@@ -12,7 +12,7 @@ import { WebSocketServer, WebSocket } from "ws";
|
||||
import type { IncomingMessage, Server } from "node:http";
|
||||
import { randomUUID } from "node:crypto";
|
||||
import { BlockList, isIP } from "node:net";
|
||||
import { identityFromString } from "@echosixhiya/teamspeak-client";
|
||||
import { parseIdentity } from "@honeybbq/teamspeak/client";
|
||||
import { TSClient, type TSClientOptions } from "./ts-client.js";
|
||||
import type { Logger as LoggerType } from "../logger.js";
|
||||
import { clientConnectionFailureCode, describeTeamSpeakError, normalizeTeamSpeakError } from "../errors.js";
|
||||
@@ -29,6 +29,17 @@ import { OpusEncoder } from "./opus-codec.js";
|
||||
import { avatarDataUrl } from "./directory-view.js";
|
||||
|
||||
const HEARTBEAT_INTERVAL_MS = 30_000;
|
||||
const MAX_MISSED_HEARTBEATS = 2;
|
||||
const MAX_LOGGED_WEBSOCKET_CLOSE_REASON_LENGTH = 160;
|
||||
|
||||
function sanitizeWebSocketCloseReason(reason: Buffer): string {
|
||||
return reason.toString("utf8")
|
||||
.replace(/[\u0000-\u001f\u007f]/g, " ")
|
||||
.replace(/\s+/g, " ")
|
||||
.trim()
|
||||
.slice(0, MAX_LOGGED_WEBSOCKET_CLOSE_REASON_LENGTH);
|
||||
}
|
||||
|
||||
function publicFailureDetail(error: ReturnType<typeof normalizeTeamSpeakError>): string | undefined {
|
||||
const serverMessage = error.diagnostics.serverMessage?.trim();
|
||||
const serverId = error.diagnostics.id?.trim();
|
||||
@@ -86,6 +97,8 @@ interface WebClientEntry extends SessionDirectoryState {
|
||||
eventLog: ServerEvent[];
|
||||
audioTransport: SessionAudioTransport | null;
|
||||
isAlive: boolean;
|
||||
lastPongAt: number;
|
||||
missedHeartbeats: number;
|
||||
reconnectTimer: ReturnType<typeof setTimeout> | null;
|
||||
audio: AudioFlowStats;
|
||||
webrtc: WebRtcAudioSession | null;
|
||||
@@ -161,7 +174,7 @@ export class VoiceBridge {
|
||||
const webrtcPublicHost = resolveWebRtcPublicHost(req);
|
||||
let identity;
|
||||
try {
|
||||
identity = connection.identity ? identityFromString(connection.identity) : undefined;
|
||||
identity = connection.identity ? parseIdentity(connection.identity) : undefined;
|
||||
} catch {
|
||||
// Send a structured failure before the close so the browser can tell
|
||||
// an invalid remembered identity apart from a real connection failure.
|
||||
@@ -235,6 +248,8 @@ export class VoiceBridge {
|
||||
whisperTargetIds: new Set(),
|
||||
whisperActive: false,
|
||||
isAlive: true,
|
||||
lastPongAt: Date.now(),
|
||||
missedHeartbeats: 0,
|
||||
reconnectTimer: null,
|
||||
audio: createAudioFlowStats(),
|
||||
webrtc: null,
|
||||
@@ -536,7 +551,12 @@ export class VoiceBridge {
|
||||
});
|
||||
entry.events = events;
|
||||
|
||||
ws.on("pong", () => { if (entry) entry.isAlive = true; });
|
||||
ws.on("pong", () => {
|
||||
if (!entry) return;
|
||||
entry.isAlive = true;
|
||||
entry.lastPongAt = Date.now();
|
||||
entry.missedHeartbeats = 0;
|
||||
});
|
||||
ws.on("message", (data: Buffer | string, isBinary: boolean) => {
|
||||
if (this.entries.get(entryId) !== entry) return;
|
||||
if (isBinary) {
|
||||
@@ -588,8 +608,19 @@ export class VoiceBridge {
|
||||
void handleCommand(entry!, command, sendJson);
|
||||
});
|
||||
|
||||
ws.on("close", () => {
|
||||
this.logger.info({ entryId }, "WebSocket closed");
|
||||
ws.on("close", (code, reason) => {
|
||||
const closedAt = Date.now();
|
||||
this.logger.info({
|
||||
entryId,
|
||||
closeCode: code,
|
||||
closeReason: sanitizeWebSocketCloseReason(reason),
|
||||
abnormalClose: code === 1006,
|
||||
...(entry ? {
|
||||
lastPongAt: new Date(entry.lastPongAt).toISOString(),
|
||||
lastPongAgeMs: Math.max(0, closedAt - entry.lastPongAt),
|
||||
missedHeartbeats: entry.missedHeartbeats,
|
||||
} : {}),
|
||||
}, "WebSocket closed");
|
||||
void this.teardown(entryId, "websocket-close");
|
||||
});
|
||||
|
||||
@@ -712,6 +743,9 @@ export class VoiceBridge {
|
||||
target: formatTeamSpeakTarget(entry.target),
|
||||
...(entry.accelerationRelay ? { relayName: entry.accelerationRelay.name, relayTarget: entry.accelerationRelay.target } : {}),
|
||||
reason,
|
||||
lastPongAt: new Date(entry.lastPongAt).toISOString(),
|
||||
lastPongAgeMs: Math.max(0, Date.now() - entry.lastPongAt),
|
||||
missedHeartbeats: entry.missedHeartbeats,
|
||||
...(entry.connectionFailureCode ? { failureCode: entry.connectionFailureCode } : {}),
|
||||
durationSeconds: Math.max(0, Math.floor((Date.now() - entry.session.createdAt) / 1000)),
|
||||
audio: { ...entry.audio },
|
||||
@@ -720,19 +754,33 @@ export class VoiceBridge {
|
||||
|
||||
private startHeartbeat(): void {
|
||||
if (this.heartbeatTimer) clearInterval(this.heartbeatTimer);
|
||||
this.heartbeatTimer = setInterval(() => {
|
||||
for (const entry of this.entries.values()) {
|
||||
if (entry.ws.readyState !== WebSocket.OPEN) continue;
|
||||
if (!entry.isAlive) {
|
||||
this.heartbeatTimer = setInterval(() => this.checkHeartbeats(), HEARTBEAT_INTERVAL_MS);
|
||||
this.heartbeatTimer.unref?.();
|
||||
}
|
||||
|
||||
private checkHeartbeats(): void {
|
||||
for (const entry of this.entries.values()) {
|
||||
if (entry.ws.readyState !== WebSocket.OPEN) continue;
|
||||
if (!entry.isAlive) {
|
||||
entry.missedHeartbeats += 1;
|
||||
const lastPongAgeMs = Math.max(0, Date.now() - entry.lastPongAt);
|
||||
const timedOut = entry.missedHeartbeats >= MAX_MISSED_HEARTBEATS;
|
||||
this.logger.warn({
|
||||
entryId: entry.id,
|
||||
missedHeartbeats: entry.missedHeartbeats,
|
||||
maxMissedHeartbeats: MAX_MISSED_HEARTBEATS,
|
||||
lastPongAt: new Date(entry.lastPongAt).toISOString(),
|
||||
lastPongAgeMs,
|
||||
}, timedOut ? "WebSocket heartbeat timed out" : "WebSocket heartbeat missed; retrying");
|
||||
if (timedOut) {
|
||||
entry.ws.terminate();
|
||||
void this.teardown(entry.id, "heartbeat-timeout");
|
||||
continue;
|
||||
}
|
||||
entry.isAlive = false;
|
||||
entry.ws.ping();
|
||||
}
|
||||
}, HEARTBEAT_INTERVAL_MS);
|
||||
this.heartbeatTimer.unref?.();
|
||||
entry.isAlive = false;
|
||||
entry.ws.ping();
|
||||
}
|
||||
}
|
||||
|
||||
private resolveConnection(url: URL): JoinTicketPayload | null {
|
||||
@@ -845,11 +893,14 @@ export class VoiceBridge {
|
||||
}
|
||||
}
|
||||
|
||||
function resolveWebRtcPublicHost(request: IncomingMessage): string | undefined {
|
||||
export function resolveWebRtcPublicHost(request: IncomingMessage): string | undefined {
|
||||
const origin = firstHeader(request.headers.origin);
|
||||
const forwardedHost = firstHeader(request.headers["x-forwarded-host"]);
|
||||
const directHost = firstHeader(request.headers.host);
|
||||
for (const candidate of [origin, forwardedHost, directHost]) {
|
||||
// The page can be hosted on the ingress gateway while its voice socket is
|
||||
// connected to a different relay node. ICE candidates must name the socket's
|
||||
// gateway, not the page's Origin.
|
||||
for (const candidate of [forwardedHost, directHost, origin]) {
|
||||
const host = normalizeWebRtcHost(candidate);
|
||||
if (host) return host;
|
||||
}
|
||||
|
||||
@@ -0,0 +1,47 @@
|
||||
import assert from "node:assert/strict";
|
||||
import test from "node:test";
|
||||
import { createVoiceGatewayAuthHeaders, parseDelegatedVoiceSession, VoiceGatewayRequestVerifier } from "./voice-gateway-auth.js";
|
||||
|
||||
const secret = "relay-auth-secret-long-enough";
|
||||
const payload = {
|
||||
target: { host: "ts.example.invalid", port: 9987 },
|
||||
nickname: "Browser user",
|
||||
serverPassword: "secret",
|
||||
rememberIdentity: true,
|
||||
};
|
||||
|
||||
test("voice gateway request authentication is canonical, time-limited and single-use", () => {
|
||||
const now = 1_800_000_000_000;
|
||||
const headers = createVoiceGatewayAuthHeaders(secret, payload, now, "a".repeat(32));
|
||||
const verifier = new VoiceGatewayRequestVerifier();
|
||||
|
||||
assert.equal(verifier.verify(secret, {
|
||||
timestamp: headers["x-webspeak-relay-timestamp"],
|
||||
nonce: headers["x-webspeak-relay-nonce"],
|
||||
signature: headers["x-webspeak-relay-signature"],
|
||||
}, { serverPassword: "secret", nickname: "Browser user", rememberIdentity: true, target: { port: 9987, host: "ts.example.invalid" } }, now), true);
|
||||
assert.equal(verifier.verify(secret, {
|
||||
timestamp: headers["x-webspeak-relay-timestamp"],
|
||||
nonce: headers["x-webspeak-relay-nonce"],
|
||||
signature: headers["x-webspeak-relay-signature"],
|
||||
}, payload, now), false, "replayed nonces must be rejected");
|
||||
|
||||
const stale = createVoiceGatewayAuthHeaders(secret, payload, now - 31_000, "b".repeat(32));
|
||||
assert.equal(verifier.verify(secret, {
|
||||
timestamp: stale["x-webspeak-relay-timestamp"],
|
||||
nonce: stale["x-webspeak-relay-nonce"],
|
||||
signature: stale["x-webspeak-relay-signature"],
|
||||
}, payload, now), false, "old signed requests must expire");
|
||||
});
|
||||
|
||||
test("delegated voice session parser accepts only bounded TeamSpeak session data", () => {
|
||||
assert.deepEqual(parseDelegatedVoiceSession(payload), {
|
||||
target: { host: "ts.example.invalid", port: 9987 },
|
||||
serverPassword: "secret",
|
||||
nickname: "Browser user",
|
||||
rememberIdentity: true,
|
||||
});
|
||||
assert.equal(parseDelegatedVoiceSession({ ...payload, target: { host: "127.0.0.1/path", port: 9987 } }), null);
|
||||
assert.equal(parseDelegatedVoiceSession({ ...payload, nickname: "" }), null);
|
||||
assert.equal(parseDelegatedVoiceSession({ ...payload, serverPassword: "x".repeat(513) }), null);
|
||||
});
|
||||
@@ -0,0 +1,111 @@
|
||||
import { createHmac, randomBytes, timingSafeEqual } from "node:crypto";
|
||||
import type { TeamSpeakTarget } from "../domain/teamspeak-target.js";
|
||||
|
||||
const MAX_CLOCK_SKEW_MS = 30_000;
|
||||
const NONCE_TTL_MS = MAX_CLOCK_SKEW_MS * 2;
|
||||
const MAX_NONCES = 10_000;
|
||||
|
||||
export interface DelegatedVoiceSession {
|
||||
target: TeamSpeakTarget;
|
||||
serverPassword: string;
|
||||
nickname: string;
|
||||
channel?: string;
|
||||
identity?: string;
|
||||
rememberIdentity?: boolean;
|
||||
}
|
||||
|
||||
export interface VoiceGatewayAuthHeaders {
|
||||
"x-webspeak-relay-timestamp": string;
|
||||
"x-webspeak-relay-nonce": string;
|
||||
"x-webspeak-relay-signature": string;
|
||||
}
|
||||
|
||||
export function createVoiceGatewayAuthHeaders(
|
||||
secret: string,
|
||||
body: unknown,
|
||||
now = Date.now(),
|
||||
nonce = randomBytes(16).toString("hex"),
|
||||
): VoiceGatewayAuthHeaders {
|
||||
const timestamp = String(now);
|
||||
return {
|
||||
"x-webspeak-relay-timestamp": timestamp,
|
||||
"x-webspeak-relay-nonce": nonce,
|
||||
"x-webspeak-relay-signature": signature(secret, timestamp, nonce, body),
|
||||
};
|
||||
}
|
||||
|
||||
/** Verifies short-lived, one-use requests from a configured gateway. */
|
||||
export class VoiceGatewayRequestVerifier {
|
||||
private readonly usedNonces = new Map<string, number>();
|
||||
|
||||
verify(
|
||||
secret: string,
|
||||
headers: { timestamp: string | undefined; nonce: string | undefined; signature: string | undefined },
|
||||
body: unknown,
|
||||
now = Date.now(),
|
||||
): boolean {
|
||||
if (secret.length < 16 || !headers.timestamp || !headers.nonce || !headers.signature) return false;
|
||||
if (!/^\d{10,16}$/.test(headers.timestamp) || !/^[a-f\d]{32}$/i.test(headers.nonce) || !/^[a-f\d]{64}$/i.test(headers.signature)) return false;
|
||||
const timestamp = Number(headers.timestamp);
|
||||
if (!Number.isSafeInteger(timestamp) || Math.abs(now - timestamp) > MAX_CLOCK_SKEW_MS) return false;
|
||||
|
||||
this.prune(now);
|
||||
if (this.usedNonces.has(headers.nonce) || this.usedNonces.size >= MAX_NONCES) return false;
|
||||
|
||||
const expected = Buffer.from(signature(secret, headers.timestamp, headers.nonce, body), "hex");
|
||||
const received = Buffer.from(headers.signature, "hex");
|
||||
if (expected.length !== received.length || !timingSafeEqual(expected, received)) return false;
|
||||
|
||||
this.usedNonces.set(headers.nonce, timestamp + NONCE_TTL_MS);
|
||||
return true;
|
||||
}
|
||||
|
||||
private prune(now: number): void {
|
||||
for (const [nonce, expiresAt] of this.usedNonces) {
|
||||
if (expiresAt <= now) this.usedNonces.delete(nonce);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
export function parseDelegatedVoiceSession(value: unknown): DelegatedVoiceSession | null {
|
||||
if (!isRecord(value) || !isRecord(value.target)) return null;
|
||||
const { host, port } = value.target;
|
||||
if (typeof host !== "string" || host.length < 1 || host.length > 253 || /[\s\u0000-\u001f\u007f\/#@?]/.test(host)) return null;
|
||||
if (typeof port !== "number" || !Number.isInteger(port) || port < 1 || port > 65535) return null;
|
||||
if (typeof value.serverPassword !== "string" || value.serverPassword.length > 512) return null;
|
||||
if (typeof value.nickname !== "string" || !value.nickname.trim() || value.nickname.length > 30) return null;
|
||||
if (value.channel !== undefined && (typeof value.channel !== "string" || value.channel.length > 100)) return null;
|
||||
if (value.identity !== undefined && (typeof value.identity !== "string" || value.identity.length > 8192)) return null;
|
||||
if (value.rememberIdentity !== undefined && typeof value.rememberIdentity !== "boolean") return null;
|
||||
|
||||
return {
|
||||
target: { host, port },
|
||||
serverPassword: value.serverPassword,
|
||||
nickname: value.nickname.trim(),
|
||||
...(typeof value.channel === "string" && value.channel ? { channel: value.channel } : {}),
|
||||
...(typeof value.identity === "string" && value.identity ? { identity: value.identity } : {}),
|
||||
...(value.rememberIdentity === true ? { rememberIdentity: true } : {}),
|
||||
};
|
||||
}
|
||||
|
||||
function signature(secret: string, timestamp: string, nonce: string, body: unknown): string {
|
||||
return createHmac("sha256", Buffer.from(secret, "utf8"))
|
||||
.update(timestamp)
|
||||
.update("\n")
|
||||
.update(nonce)
|
||||
.update("\n")
|
||||
.update(canonicalJson(body))
|
||||
.digest("hex");
|
||||
}
|
||||
|
||||
function canonicalJson(value: unknown): string {
|
||||
if (value === null || typeof value !== "object") return JSON.stringify(value) ?? "null";
|
||||
if (Array.isArray(value)) return `[${value.map(canonicalJson).join(",")}]`;
|
||||
const record = value as Record<string, unknown>;
|
||||
const fields = Object.keys(record).filter(key => record[key] !== undefined).sort();
|
||||
return `{${fields.map(key => `${JSON.stringify(key)}:${canonicalJson(record[key])}`).join(",")}}`;
|
||||
}
|
||||
|
||||
function isRecord(value: unknown): value is Record<string, unknown> {
|
||||
return value !== null && typeof value === "object" && !Array.isArray(value);
|
||||
}
|
||||
@@ -0,0 +1,49 @@
|
||||
import assert from "node:assert/strict";
|
||||
import test from "node:test";
|
||||
import pino from "pino";
|
||||
import { createVoiceGatewayServer } from "./voice-gateway.js";
|
||||
import { createVoiceGatewayAuthHeaders } from "./voice-gateway-auth.js";
|
||||
|
||||
test("voice relay gateway issues a one-time join ticket only for signed session requests", async t => {
|
||||
const sharedToken = "relay-shared-token-that-is-long-enough";
|
||||
const gateway = createVoiceGatewayServer({
|
||||
host: "127.0.0.1",
|
||||
port: 0,
|
||||
sharedToken,
|
||||
logger: pino({ enabled: false }),
|
||||
webRtc: { enabled: true },
|
||||
});
|
||||
const address = await gateway.start();
|
||||
t.after(() => gateway.stop());
|
||||
const url = `http://127.0.0.1:${address.port}/api/relay/voice-ticket`;
|
||||
const payload = {
|
||||
target: { host: "voice.example.invalid", port: 9987 },
|
||||
serverPassword: "secret",
|
||||
nickname: "Visitor",
|
||||
rememberIdentity: true,
|
||||
};
|
||||
const headers = createVoiceGatewayAuthHeaders(sharedToken, payload);
|
||||
const request = () => fetch(url, {
|
||||
method: "POST",
|
||||
headers: { "content-type": "application/json", ...headers },
|
||||
body: JSON.stringify(payload),
|
||||
});
|
||||
|
||||
const accepted = await request();
|
||||
assert.equal(accepted.status, 201);
|
||||
const body = await accepted.json() as { ok?: boolean; ticket?: string };
|
||||
assert.equal(body.ok, true);
|
||||
assert.equal(typeof body.ticket, "string");
|
||||
assert.ok((body.ticket?.length ?? 0) >= 32);
|
||||
assert.equal(accepted.headers.get("cache-control"), "no-store");
|
||||
assert.equal((await request()).status, 401, "the signed request nonce cannot be replayed");
|
||||
|
||||
const invalidPayload = { ...payload, nickname: "" };
|
||||
const invalidHeaders = createVoiceGatewayAuthHeaders(sharedToken, invalidPayload);
|
||||
const invalid = await fetch(url, {
|
||||
method: "POST",
|
||||
headers: { "content-type": "application/json", ...invalidHeaders },
|
||||
body: JSON.stringify(invalidPayload),
|
||||
});
|
||||
assert.equal(invalid.status, 400);
|
||||
});
|
||||
@@ -0,0 +1,91 @@
|
||||
import { createServer } from "node:http";
|
||||
import express from "express";
|
||||
import { VoiceBridge, type VoiceBridgeOptions } from "./voice-bridge.js";
|
||||
import { JoinTicketStore } from "./join-ticket.js";
|
||||
import { parseDelegatedVoiceSession, VoiceGatewayRequestVerifier } from "./voice-gateway-auth.js";
|
||||
import type { Logger } from "../logger.js";
|
||||
import type { WebRtcAudioOptions } from "./webrtc-audio.js";
|
||||
import type { ScreenShareIceServer } from "./screen-share.js";
|
||||
|
||||
export interface VoiceGatewayServerOptions {
|
||||
host: string;
|
||||
port: number;
|
||||
sharedToken: string;
|
||||
logger: Logger;
|
||||
webRtc: WebRtcAudioOptions;
|
||||
screenShareIceServers?: ScreenShareIceServer[];
|
||||
trustedProxies?: readonly string[];
|
||||
}
|
||||
|
||||
export interface VoiceGatewayServer {
|
||||
start(): Promise<{ host: string; port: number }>;
|
||||
stop(): Promise<void>;
|
||||
}
|
||||
|
||||
export function createVoiceGatewayServer(options: VoiceGatewayServerOptions): VoiceGatewayServer {
|
||||
if (options.sharedToken.trim().length < 16) throw new Error("Voice gateway token must contain at least 16 characters");
|
||||
const app = express();
|
||||
app.use(express.json({ limit: "16kb" }));
|
||||
const tickets = new JoinTicketStore();
|
||||
const verifier = new VoiceGatewayRequestVerifier();
|
||||
const voiceBridgeOptions: VoiceBridgeOptions = {
|
||||
joinTickets: tickets,
|
||||
webRtc: options.webRtc,
|
||||
screenShareIceServers: options.screenShareIceServers,
|
||||
trustedProxies: options.trustedProxies,
|
||||
};
|
||||
const bridge = new VoiceBridge(voiceBridgeOptions, options.logger);
|
||||
const server = createServer(app);
|
||||
|
||||
app.get("/health", (_request, response) => response.json({ status: "ok", role: "voice-gateway" }));
|
||||
app.post("/api/relay/voice-ticket", (request, response) => {
|
||||
response.setHeader("Cache-Control", "no-store");
|
||||
if (!request.is("application/json")) {
|
||||
response.status(415).json({ ok: false, code: "JSON_REQUIRED" });
|
||||
return;
|
||||
}
|
||||
const authenticated = verifier.verify(options.sharedToken, {
|
||||
timestamp: request.get("x-webspeak-relay-timestamp"),
|
||||
nonce: request.get("x-webspeak-relay-nonce"),
|
||||
signature: request.get("x-webspeak-relay-signature"),
|
||||
}, request.body);
|
||||
if (!authenticated) {
|
||||
response.status(401).json({ ok: false, code: "RELAY_AUTH_REJECTED" });
|
||||
return;
|
||||
}
|
||||
const session = parseDelegatedVoiceSession(request.body);
|
||||
if (!session) {
|
||||
response.status(400).json({ ok: false, code: "RELAY_SESSION_INVALID" });
|
||||
return;
|
||||
}
|
||||
response.status(201).json({ ok: true, ticket: tickets.create(session) });
|
||||
});
|
||||
|
||||
bridge.attach(server);
|
||||
|
||||
return {
|
||||
start(): Promise<{ host: string; port: number }> {
|
||||
return new Promise((resolve, reject) => {
|
||||
const onError = (error: Error): void => {
|
||||
server.off("listening", onListening);
|
||||
reject(error);
|
||||
};
|
||||
const onListening = (): void => {
|
||||
server.off("error", onError);
|
||||
const address = server.address();
|
||||
resolve({ host: options.host, port: typeof address === "object" && address ? address.port : options.port });
|
||||
};
|
||||
server.once("error", onError);
|
||||
server.once("listening", onListening);
|
||||
server.listen(options.port, options.host);
|
||||
});
|
||||
},
|
||||
async stop(): Promise<void> {
|
||||
await bridge.shutdown();
|
||||
await new Promise<void>((resolve) => {
|
||||
if (!server.listening) { resolve(); return; }
|
||||
server.close(() => resolve());
|
||||
});
|
||||
},
|
||||
};
|
||||
}
|
||||
Reference in new issue
Block a user