mirror of
https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak.git
synced 2026-12-02 19:42:51 +08:00
refactor: share admin contracts and isolate page styles
This commit is contained in:
1 parent
e2f0a43762
commit
f0712fa3fc
26 files changed
+2231
-1733
No files matched your search
@@ -261,7 +261,7 @@ export function createAdminRouter(options: AdminRouterOptions): Router {
|
||||
options.getActiveSessions(),
|
||||
options.getPeakSessions(),
|
||||
options.startedAt,
|
||||
) as unknown as AdminOverview;
|
||||
);
|
||||
response.json({
|
||||
generatedAt: new Date().toISOString(),
|
||||
gateway: {
|
||||
@@ -288,7 +288,7 @@ export function createAdminRouter(options: AdminRouterOptions): Router {
|
||||
options.getActiveSessions(),
|
||||
options.getPeakSessions(),
|
||||
options.startedAt,
|
||||
) as unknown as AdminOverview;
|
||||
);
|
||||
const report = {
|
||||
generatedAt: new Date().toISOString(),
|
||||
gateway: {
|
||||
@@ -688,17 +688,6 @@ function readStructuredLogs(logFile: string): StructuredLogEntry[] {
|
||||
return entries.sort((left, right) => Date.parse(left.timestamp ?? "") - Date.parse(right.timestamp ?? ""));
|
||||
}
|
||||
|
||||
interface AdminOverview {
|
||||
gateway: { uptimeSeconds: number };
|
||||
teamSpeak: {
|
||||
target: string;
|
||||
status: string;
|
||||
lastTestAt: string | null;
|
||||
latencyMs: number | null;
|
||||
lastError: string | null;
|
||||
};
|
||||
}
|
||||
|
||||
function logLevelName(level: unknown): string {
|
||||
if (level === 10) return "DEBUG";
|
||||
if (level === 30) return "INFO";
|
||||
|
||||
@@ -1,3 +1,6 @@
|
||||
import type { AdminSettingsInput, RelayNodeInput, ManagedInviteInput } from "../shared/admin-inputs.js";
|
||||
export type { AdminSettingsInput, RelayNodeInput, ManagedInviteInput } from "../shared/admin-inputs.js";
|
||||
import type { AdminOverview, AdminSettings } from "../shared/admin-responses.js";
|
||||
import { createHash, randomBytes } from "node:crypto";
|
||||
import { existsSync } from "node:fs";
|
||||
import type { Logger } from "../logger.js";
|
||||
@@ -13,50 +16,12 @@ import { DEFAULT_ACCELERATION_RELAY_PORT, type ConfiguredAccelerationRelay } fro
|
||||
import { DEFAULT_WEBRTC_UDP_PORT_RANGE, WEBRTC_UDP_PORT_MAX, WEBRTC_UDP_PORT_MIN } from "../server/webrtc-config.js";
|
||||
import { DEFAULT_WELCOME_TEXTS, resolveWelcomeTexts } from "../site-copy.js";
|
||||
|
||||
export interface AdminSettingsInput {
|
||||
target: string;
|
||||
serverPassword?: string;
|
||||
passwordAction?: "keep" | "replace" | "remove";
|
||||
accessMode: AccessMode;
|
||||
siteName: string;
|
||||
welcomeText: string;
|
||||
welcomeTextEn?: string;
|
||||
welcomeTextDe?: string;
|
||||
welcomeTextRu?: string;
|
||||
welcomeTextJa?: string;
|
||||
webRtcEnabled: boolean;
|
||||
webRtcUdpStart?: number;
|
||||
webRtcUdpEnd?: number;
|
||||
relaySettingsAction?: "keep" | "replace" | "remove";
|
||||
relayEnabled?: boolean;
|
||||
relayName?: string;
|
||||
relayTarget?: string;
|
||||
relayToken?: string;
|
||||
relayTokenAction?: "keep" | "replace" | "remove";
|
||||
relayNodes?: RelayNodeInput[];
|
||||
}
|
||||
|
||||
export interface RelayNodeInput {
|
||||
id?: string;
|
||||
name: string;
|
||||
target: string;
|
||||
enabled: boolean;
|
||||
token?: string;
|
||||
tokenAction?: "keep" | "replace" | "remove";
|
||||
}
|
||||
|
||||
export interface ConnectionPolicy {
|
||||
defaultTarget: TeamSpeakTarget;
|
||||
serverPassword: string;
|
||||
accessMode: AccessMode;
|
||||
}
|
||||
|
||||
export interface ManagedInviteInput {
|
||||
channel: string;
|
||||
expiresInHours: number;
|
||||
maxUses: number;
|
||||
}
|
||||
|
||||
export interface ManagedInviteView {
|
||||
id: string;
|
||||
target: string;
|
||||
@@ -136,7 +101,7 @@ export class AdminService {
|
||||
};
|
||||
}
|
||||
|
||||
getAdminSettings(): Record<string, unknown> {
|
||||
getAdminSettings(): AdminSettings {
|
||||
const settings = this.database.getSettings();
|
||||
return {
|
||||
target: formatTeamSpeakTarget({ host: settings.tsHost, port: settings.tsPort }),
|
||||
@@ -276,7 +241,7 @@ export class AdminService {
|
||||
}
|
||||
}
|
||||
|
||||
getOverview(activeSessions: number, peakSessions: number, startedAt: number): Record<string, unknown> {
|
||||
getOverview(activeSessions: number, peakSessions: number, startedAt: number): AdminOverview {
|
||||
const settings = this.database.getSettings();
|
||||
return {
|
||||
gateway: {
|
||||
|
||||
@@ -4,6 +4,7 @@ import { createAudioFlowStats, snapshotAudioStats, type AudioFlowStats } from ".
|
||||
export type { AudioFlowStats } from "./audio-stats.js";
|
||||
import { mapChannelTree, normalizeDirectorySnapshot, avatarDataUrl } from "./directory-view.js";
|
||||
import type { ServerMessage } from "../shared/server-messages.js";
|
||||
import { parseWebRtcClientMessage } from "../shared/webrtc.js";
|
||||
import type { ChannelInfo } from "../shared/voice-models.js";
|
||||
import type { ChannelMember as SharedChannelMember, ServerEvent as SharedServerEvent } from "../shared/voice-models.js";
|
||||
import { WebSocketServer, WebSocket } from "ws";
|
||||
@@ -722,8 +723,8 @@ export class VoiceBridge {
|
||||
}
|
||||
|
||||
const rawMessage = typeof data === "string" ? data : data.toString("utf-8");
|
||||
const webRtcOffer = parseWebRtcOffer(rawMessage);
|
||||
if (webRtcOffer) {
|
||||
const webRtcMessage = parseWebRtcClientMessage(rawMessage);
|
||||
if (webRtcMessage?.type === "webrtcOffer") {
|
||||
if (this.getWebRtcOptions()?.enabled !== true) {
|
||||
sendProtocolError(sendJson, "WEBRTC_DISABLED", "WebRTC 音频传输未启用");
|
||||
return;
|
||||
@@ -732,10 +733,11 @@ export class VoiceBridge {
|
||||
sendProtocolError(sendJson, "SESSION_NOT_READY", "TeamSpeak 会话尚未就绪");
|
||||
return;
|
||||
}
|
||||
void this.handleWebRtcOffer(entry!, webRtcOffer, sendJson);
|
||||
const { sdp, muted, accompanimentActive } = webRtcMessage.payload;
|
||||
void this.handleWebRtcOffer(entry!, { ...sdp, muted, accompanimentActive }, sendJson);
|
||||
return;
|
||||
}
|
||||
if (isWebRtcStopMessage(rawMessage)) {
|
||||
if (webRtcMessage?.type === "webrtcStop") {
|
||||
void this.stopWebRtc(entry!);
|
||||
return;
|
||||
}
|
||||
@@ -1074,35 +1076,6 @@ function sendProtocolError(sendJson: (message: ServerMessage) => void, code: str
|
||||
sendJson({ type: "error", error: { code, message, recoverable: false } });
|
||||
}
|
||||
|
||||
function parseWebRtcOffer(raw: string): WebRtcSessionDescription | null {
|
||||
let value: unknown;
|
||||
try { value = JSON.parse(raw); } catch { return null; }
|
||||
if (!isRecord(value) || value.type !== "webrtcOffer" || !isRecord(value.payload) || !isRecord(value.payload.sdp)) return null;
|
||||
const description = value.payload.sdp;
|
||||
if (description.type !== "offer" || typeof description.sdp !== "string" || description.sdp.length > 256 * 1024) return null;
|
||||
if (value.payload.muted !== undefined && typeof value.payload.muted !== "boolean") return null;
|
||||
if (value.payload.accompanimentActive !== undefined && typeof value.payload.accompanimentActive !== "boolean") return null;
|
||||
return {
|
||||
type: "offer",
|
||||
sdp: description.sdp,
|
||||
muted: value.payload.muted === true,
|
||||
accompanimentActive: value.payload.accompanimentActive === true,
|
||||
};
|
||||
}
|
||||
|
||||
function isWebRtcStopMessage(raw: string): boolean {
|
||||
try {
|
||||
const value: unknown = JSON.parse(raw);
|
||||
return isRecord(value) && value.type === "webrtcStop";
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
function isRecord(value: unknown): value is Record<string, unknown> {
|
||||
return Boolean(value) && typeof value === "object" && !Array.isArray(value);
|
||||
}
|
||||
|
||||
function isChannelRecord(value: unknown): value is { id: string; name: string } {
|
||||
return Boolean(value) && typeof value === "object" && typeof (value as { id?: unknown }).id === "string" && typeof (value as { name?: unknown }).name === "string";
|
||||
}
|
||||
@@ -9,6 +9,8 @@ import type { Logger as LoggerType } from "../logger.js";
|
||||
import type { TSVoiceData } from "./ts-client.js";
|
||||
import { WEBRTC_UDP_PORT_RANGE } from "./webrtc-config.js";
|
||||
import { OpusEncoder } from "./opus-codec.js";
|
||||
import type { WebRtcSessionDescription } from "../shared/webrtc.js";
|
||||
export type { WebRtcSessionDescription } from "../shared/webrtc.js";
|
||||
|
||||
export { DEFAULT_WEBRTC_UDP_PORT_RANGE, WEBRTC_UDP_PORT_RANGE } from "./webrtc-config.js";
|
||||
|
||||
@@ -35,13 +37,6 @@ export interface WebRtcAudioOptions {
|
||||
udpPortRange?: [number, number];
|
||||
}
|
||||
|
||||
export interface WebRtcSessionDescription {
|
||||
type: "offer" | "answer";
|
||||
sdp: string;
|
||||
muted?: boolean;
|
||||
accompanimentActive?: boolean;
|
||||
}
|
||||
|
||||
export interface WebRtcAudioSessionOptions {
|
||||
connectionId: string;
|
||||
publicHost?: string;
|
||||
|
||||
@@ -0,0 +1,37 @@
|
||||
export interface AdminSettingsInput {
|
||||
target: string;
|
||||
serverPassword?: string;
|
||||
passwordAction?: "keep" | "replace" | "remove";
|
||||
accessMode: "fixed" | "open";
|
||||
siteName: string;
|
||||
welcomeText: string;
|
||||
welcomeTextEn?: string;
|
||||
welcomeTextDe?: string;
|
||||
welcomeTextRu?: string;
|
||||
welcomeTextJa?: string;
|
||||
webRtcEnabled: boolean;
|
||||
webRtcUdpStart?: number;
|
||||
webRtcUdpEnd?: number;
|
||||
relaySettingsAction?: "keep" | "replace" | "remove";
|
||||
relayEnabled?: boolean;
|
||||
relayName?: string;
|
||||
relayTarget?: string;
|
||||
relayToken?: string;
|
||||
relayTokenAction?: "keep" | "replace" | "remove";
|
||||
relayNodes?: RelayNodeInput[];
|
||||
}
|
||||
|
||||
export interface RelayNodeInput {
|
||||
id?: string;
|
||||
name: string;
|
||||
target: string;
|
||||
enabled: boolean;
|
||||
token?: string;
|
||||
tokenAction?: "keep" | "replace" | "remove";
|
||||
}
|
||||
|
||||
export interface ManagedInviteInput {
|
||||
channel: string;
|
||||
expiresInHours: number;
|
||||
maxUses: number;
|
||||
}
|
||||
@@ -0,0 +1,102 @@
|
||||
/** Runtime-checked browser projections of the administration API. */
|
||||
export type AdminResponseReader<T> = (value: unknown) => T;
|
||||
type Reader = AdminResponseReader<unknown>;
|
||||
|
||||
function invalid(): never { throw new Error("INVALID_ADMIN_RESPONSE"); }
|
||||
function record(value: unknown): Record<string, unknown> {
|
||||
return value !== null && typeof value === "object" && !Array.isArray(value) ? value as Record<string, unknown> : invalid();
|
||||
}
|
||||
const text: AdminResponseReader<string> = value => typeof value === "string" ? value : invalid();
|
||||
const number: AdminResponseReader<number> = value => typeof value === "number" && Number.isFinite(value) ? value : invalid();
|
||||
const boolean: AdminResponseReader<boolean> = value => typeof value === "boolean" ? value : invalid();
|
||||
const nonempty: AdminResponseReader<string> = value => text(value).length > 0 ? text(value) : invalid();
|
||||
const nullable = <T>(read: AdminResponseReader<T>): AdminResponseReader<T | null> => value => value === null ? null : read(value);
|
||||
const optional = <T>(read: AdminResponseReader<T>): AdminResponseReader<T | undefined> => value => value === undefined ? undefined : read(value);
|
||||
const array = <T>(read: AdminResponseReader<T>): AdminResponseReader<T[]> => value => Array.isArray(value) ? value.map(read) : invalid();
|
||||
const choice = <T extends string | boolean>(...values: T[]): AdminResponseReader<T> => value => values.includes(value as T) ? value as T : invalid();
|
||||
function object<T extends Record<string, Reader>>(fields: T): AdminResponseReader<{ [K in keyof T]: ReturnType<T[K]> }> {
|
||||
return value => {
|
||||
const source = record(value);
|
||||
// Project only declared fields, so response extensions cannot overwrite form state.
|
||||
return Object.fromEntries(Object.entries(fields).map(([key, read]) => [key, read(source[key])])) as { [K in keyof T]: ReturnType<T[K]> };
|
||||
};
|
||||
}
|
||||
|
||||
const auditEvent = object({ event: text, createdAt: text });
|
||||
const relayNode = object({ id: text, name: text, enabled: boolean, target: text, hasToken: boolean });
|
||||
const welcomeTexts = object({ zh: text, en: text, de: text, ru: text, ja: text });
|
||||
const settings = object({
|
||||
target: text, hasPassword: boolean, accessMode: choice("fixed", "open"), siteName: text,
|
||||
welcomeText: text, welcomeTextEn: text, welcomeTextDe: text, welcomeTextRu: text, welcomeTextJa: text,
|
||||
welcomeDefaults: welcomeTexts, lastTestAt: nullable(text), lastTestLatencyMs: nullable(number), lastTestError: nullable(text),
|
||||
webRtcEnabled: boolean, webRtcUdpStart: number, webRtcUdpEnd: number,
|
||||
relayConfigured: boolean, relayEnabled: boolean, relayName: text, relayTarget: text, hasRelayToken: boolean,
|
||||
relayNodes: array(relayNode), internalPort: number, updatedAt: text,
|
||||
});
|
||||
const teamSpeak = object({ target: text, status: text, lastTestAt: nullable(text), latencyMs: nullable(number), lastError: nullable(text) });
|
||||
const overview = object({
|
||||
gateway: object({ status: text, version: text, uptimeSeconds: number }), teamSpeak,
|
||||
sessions: object({ active: number, peak: number, limit: number }),
|
||||
recentEvents: array(auditEvent), legacyConfigImported: boolean,
|
||||
});
|
||||
const session = object({
|
||||
id: text, nickname: text, target: text, state: text, createdAt: text,
|
||||
ageSeconds: number, tsClientId: nullable(number), channelId: nullable(text), memberCount: number,
|
||||
});
|
||||
const invite = object({
|
||||
id: text, target: text, channel: text, expiresAt: text, maxUses: number,
|
||||
useCount: number, createdAt: text, revokedAt: nullable(text), status: choice("active", "expired", "exhausted", "revoked"),
|
||||
});
|
||||
const logContext: AdminResponseReader<Record<string, string | number | boolean>> = value => Object.fromEntries(
|
||||
Object.entries(record(value)).map(([key, entry]) => [key, typeof entry === "string" || typeof entry === "boolean" ? entry : number(entry)]),
|
||||
);
|
||||
const logEntry = object({ timestamp: nullable(text), level: text, message: text, context: logContext });
|
||||
const connection = object({
|
||||
id: text, nickname: text, clientIp: text, target: text, relayName: nullable(text), relayTarget: nullable(text),
|
||||
startedAt: text, connectedAt: nullable(text), disconnectedAt: nullable(text), durationSeconds: nullable(number),
|
||||
status: choice("active", "connecting", "disconnected", "failed"), reason: nullable(text), failureDetail: nullable(text),
|
||||
});
|
||||
const skin = object({
|
||||
id: text, name: text, version: text, author: text, license: text, minAppVersion: text, installedAt: number,
|
||||
description: optional(text), previewUrl: optional(text), previewMimeType: optional(text),
|
||||
builtIn: optional(boolean), enabled: optional(boolean), previewKind: optional(choice("day", "night", "illusia")),
|
||||
});
|
||||
const sessionStatus = object({ authenticated: boolean, mustChangePassword: optional(boolean), csrfToken: optional(text) });
|
||||
|
||||
export const adminResponses = {
|
||||
session(value: unknown) {
|
||||
const result = sessionStatus(value);
|
||||
if (result.authenticated && (!result.csrfToken || result.mustChangePassword === undefined)) invalid();
|
||||
return result;
|
||||
},
|
||||
login: object({ ok: choice(true), csrfToken: nonempty, mustChangePassword: boolean }),
|
||||
ok: object({ ok: choice(true) }),
|
||||
overview,
|
||||
settings,
|
||||
savedSettings: object({ ok: choice(true), settings }),
|
||||
sessions: object({ sessions: array(session) }),
|
||||
invites: object({ invites: array(invite) }),
|
||||
createdInvite: object({ ok: choice(true), token: nonempty, invite }),
|
||||
audit: object({ events: array(auditEvent) }),
|
||||
logs: object({ available: boolean, entries: array(logEntry), sessions: array(connection) }),
|
||||
diagnostics: object({
|
||||
gateway: object({ version: text, node: text, platform: text, arch: text }),
|
||||
database: object({ schemaVersion: number }), sessions: object({ created: number }),
|
||||
}),
|
||||
skins: object({ skins: array(skin), defaultSkinId: text }),
|
||||
defaultSkin: object({ ok: choice(true), defaultSkinId: text }),
|
||||
updatedSkin: object({ ok: choice(true), skin, defaultSkinId: text }),
|
||||
uploadedSkin: object({ ok: choice(true), skin }),
|
||||
probe: object({
|
||||
ok: boolean, checkType: choice("network", "protocol"), passwordVerified: boolean,
|
||||
latencyMs: number, serverName: nullable(text), requiresPassword: boolean,
|
||||
packetLossPercent: optional(number), attempts: optional(number), successfulAttempts: optional(number), errorCode: optional(text),
|
||||
}),
|
||||
};
|
||||
|
||||
export type AdminSettings = ReturnType<typeof settings>;
|
||||
export type AdminOverview = ReturnType<typeof overview>;
|
||||
export type AdminSession = ReturnType<typeof session>;
|
||||
export type ManagedInvite = ReturnType<typeof invite>;
|
||||
export type AdminLog = ReturnType<typeof logEntry>;
|
||||
export type AdminConnectionRecord = ReturnType<typeof connection>;
|
||||
@@ -1,10 +1,8 @@
|
||||
import type { ChannelMember, ChannelInfo, ServerEvent, VoiceAudioBridgeStats } from "./voice-models.js";
|
||||
import { normalizeScreenShareIceServers, parseScreenShareSignal, type ScreenShareIceServer, type ScreenSharePeerSignal, type ScreenShareStreamDescription, type ScreenShareViewerDescription } from "./screen-share.js";
|
||||
|
||||
export interface SessionDescription {
|
||||
type: "offer" | "answer";
|
||||
sdp: string;
|
||||
}
|
||||
import { isSessionDescription, type SessionDescription } from "./webrtc.js";
|
||||
export type { SessionDescription } from "./webrtc.js";
|
||||
|
||||
type Message<T extends string, Fields = object> = { type: T } & Fields;
|
||||
type Request = { requestId?: string };
|
||||
@@ -133,7 +131,7 @@ const valid: Record<ServerMessage["type"], (message: RecordValue) => boolean> =
|
||||
webrtcError: m => optional(m.code, text) && optional(m.detail, text),
|
||||
audioError: m => optional(m.code, text) && optional(m.detail, text),
|
||||
whisperTargets: m => arrayOf(m.targetIds, clientId) && boolean(m.active),
|
||||
webrtcAnswer: m => isRecord(m.payload) && isRecord(m.payload.sdp) && m.payload.sdp.type === "answer" && text(m.payload.sdp.sdp) && m.payload.sdp.sdp.length <= 256 * 1024,
|
||||
webrtcAnswer: m => isRecord(m.payload) && isSessionDescription(m.payload.sdp, "answer"),
|
||||
voiceActivity: m => arrayOf(m.clientIds, clientId),
|
||||
commandCompleted: m => text(m.requestId),
|
||||
screenShareCompleted: m => text(m.requestId),
|
||||
|
||||
@@ -0,0 +1,36 @@
|
||||
import assert from "node:assert/strict";
|
||||
import test from "node:test";
|
||||
import { isSessionDescription, MAX_VOICE_SDP_LENGTH, parseWebRtcClientMessage, type WebRtcClientMessage } from "./webrtc.js";
|
||||
import { parseServerMessage } from "./server-messages.js";
|
||||
|
||||
test("voice offer flags survive JSON transport and legacy omissions retain their defaults", () => {
|
||||
const message: WebRtcClientMessage = { type: "webrtcOffer", payload: { sdp: { type: "offer", sdp: "v=0\r\n" }, muted: true, accompanimentActive: true } };
|
||||
assert.deepEqual(parseWebRtcClientMessage(JSON.stringify(message)), message);
|
||||
assert.deepEqual(parseWebRtcClientMessage(JSON.stringify({ type: "webrtcOffer", payload: { sdp: message.payload.sdp } })), {
|
||||
...message, payload: { ...message.payload, muted: false, accompanimentActive: false },
|
||||
});
|
||||
assert.deepEqual(parseWebRtcClientMessage('{"type":"webrtcStop"}'), { type: "webrtcStop" });
|
||||
assert.deepEqual(parseWebRtcClientMessage('{"type":"webrtcStop","payload":17}'), { type: "webrtcStop" });
|
||||
});
|
||||
|
||||
test("malformed voice controls remain unrecognized instead of bypassing ordinary error handling", () => {
|
||||
const sdp = { type: "offer", sdp: "v=0" };
|
||||
for (const value of [null, [], { type: "other" }, { type: "webrtcOffer" },
|
||||
{ type: "webrtcOffer", payload: { sdp: { ...sdp, type: "answer" } } },
|
||||
{ type: "webrtcOffer", payload: { sdp, muted: 1 } },
|
||||
{ type: "webrtcOffer", payload: { sdp, accompanimentActive: "true" } },
|
||||
{ type: "webrtcOffer", payload: { sdp: { ...sdp, sdp: null } } },
|
||||
]) assert.equal(parseWebRtcClientMessage(JSON.stringify(value)), null);
|
||||
assert.equal(parseWebRtcClientMessage("{"), null);
|
||||
});
|
||||
|
||||
test("offer and answer validation share the same SDP boundary without removing legacy empty strings", () => {
|
||||
for (const length of [0, MAX_VOICE_SDP_LENGTH, MAX_VOICE_SDP_LENGTH + 1]) {
|
||||
const sdp = "a".repeat(length);
|
||||
const accepted = length <= MAX_VOICE_SDP_LENGTH;
|
||||
assert.equal(Boolean(parseWebRtcClientMessage(JSON.stringify({ type: "webrtcOffer", payload: { sdp: { type: "offer", sdp } } }))), accepted);
|
||||
assert.equal(Boolean(parseServerMessage({ type: "webrtcAnswer", payload: { sdp: { type: "answer", sdp } } })), accepted);
|
||||
assert.equal(isSessionDescription({ type: "answer", sdp }, "answer"), accepted);
|
||||
}
|
||||
assert.equal(isSessionDescription({ type: "offer", sdp: "v=0" }, "answer"), false);
|
||||
});
|
||||
@@ -0,0 +1,45 @@
|
||||
/** Browser-safe voice negotiation contract; screen sharing has its own signaling. */
|
||||
export interface SessionDescription {
|
||||
type: "offer" | "answer";
|
||||
sdp: string;
|
||||
}
|
||||
|
||||
export interface WebRtcSessionDescription extends SessionDescription {
|
||||
muted?: boolean;
|
||||
accompanimentActive?: boolean;
|
||||
}
|
||||
|
||||
export type WebRtcClientMessage =
|
||||
| { type: "webrtcOffer"; payload: {
|
||||
sdp: SessionDescription & { type: "offer" };
|
||||
muted?: boolean;
|
||||
accompanimentActive?: boolean;
|
||||
} }
|
||||
| { type: "webrtcStop" };
|
||||
|
||||
export const MAX_VOICE_SDP_LENGTH = 256 * 1024;
|
||||
|
||||
function isRecord(value: unknown): value is Record<string, unknown> {
|
||||
return Boolean(value) && typeof value === "object" && !Array.isArray(value);
|
||||
}
|
||||
|
||||
export function isSessionDescription<T extends SessionDescription["type"]>(value: unknown, type: T): value is SessionDescription & { type: T } {
|
||||
return isRecord(value) && value.type === type && typeof value.sdp === "string" && value.sdp.length <= MAX_VOICE_SDP_LENGTH;
|
||||
}
|
||||
|
||||
/** Null preserves the gateway's existing fallback to ordinary command errors. */
|
||||
export function parseWebRtcClientMessage(raw: string): WebRtcClientMessage | null {
|
||||
let value: unknown;
|
||||
try { value = JSON.parse(raw); } catch { return null; }
|
||||
if (!isRecord(value)) return null;
|
||||
// Older clients send no payload. Ignore extra fields as the old parser did.
|
||||
if (value.type === "webrtcStop") return { type: "webrtcStop" };
|
||||
if (value.type !== "webrtcOffer" || !isRecord(value.payload) || !isSessionDescription(value.payload.sdp, "offer")) return null;
|
||||
if (value.payload.muted !== undefined && typeof value.payload.muted !== "boolean") return null;
|
||||
if (value.payload.accompanimentActive !== undefined && typeof value.payload.accompanimentActive !== "boolean") return null;
|
||||
return { type: "webrtcOffer", payload: {
|
||||
sdp: { type: "offer", sdp: value.payload.sdp.sdp },
|
||||
muted: value.payload.muted === true,
|
||||
accompanimentActive: value.payload.accompanimentActive === true,
|
||||
} };
|
||||
}
|
||||
Reference in new issue
Block a user