mirror of
https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak.git
synced 2026-12-05 21:12:49 +08:00
Add v3 batched downlink with tick-aligned timestamps, audio-clock playback and PLC; add adaptive Opus/PCM uplink and one-shot TURN relay retry. Expose frame size, automatic relay retry and Cloudflare ingress assumptions in the admin console, with persistence, i18n, docs and regression tests.
883 lines
33 KiB
TypeScript
883 lines
33 KiB
TypeScript
import { copyFileSync, existsSync, mkdirSync, readFileSync, unlinkSync } from "node:fs";
|
|
import { randomBytes } from "node:crypto";
|
|
import { dirname } from "node:path";
|
|
import { DatabaseSync } from "node:sqlite";
|
|
import type { AdminCredential } from "../security/admin-password.js";
|
|
import type { TeamSpeakProtocol } from "../server/teamspeak-adapter.js";
|
|
import { DEFAULT_WEBRTC_UDP_PORT_RANGE } from "../server/webrtc-config.js";
|
|
import type { VoiceProfileSetting } from "../shared/voice-profile.js";
|
|
|
|
export const DATABASE_SCHEMA_VERSION = 13;
|
|
const VOICE_SETTINGS_META_KEY = "voice_settings_v1";
|
|
export type AccessMode = "fixed" | "open";
|
|
|
|
export interface PersistedSettings {
|
|
siteName: string;
|
|
welcomeText: string;
|
|
welcomeTextEn: string;
|
|
welcomeTextDe: string;
|
|
welcomeTextRu: string;
|
|
welcomeTextJa: string;
|
|
accessMode: AccessMode;
|
|
tsHost: string;
|
|
tsPort: number;
|
|
tsTarget: string | null;
|
|
tsPasswordEncrypted: string | null;
|
|
detectedProtocol: TeamSpeakProtocol | null;
|
|
lastTestAt: string | null;
|
|
lastTestLatencyMs: number | null;
|
|
lastTestError: string | null;
|
|
webRtcEnabled: boolean;
|
|
webRtcPublicHost: string;
|
|
webRtcIpv6Enabled: boolean;
|
|
webRtcStunServer: string;
|
|
webRtcUdpStart: number;
|
|
webRtcUdpEnd: number;
|
|
/** Console-owned overrides; null inherits the environment baseline. */
|
|
voiceProfile: VoiceProfileSetting | null;
|
|
voiceTurnUrls: string | null;
|
|
voiceTurnSecretEncrypted: string | null;
|
|
voiceTurnTtlSeconds: number | null;
|
|
voiceOpusWs: boolean | null;
|
|
voiceJitterMaxMs: number | null;
|
|
voiceDownlinkFrameMs: 20 | 40 | null;
|
|
voiceAssumeCloudflare: boolean | null;
|
|
voiceAutoRelayRetry: boolean | null;
|
|
relayConfigured: boolean;
|
|
relayEnabled: boolean;
|
|
relayName: string;
|
|
relayHost: string;
|
|
relayPort: number;
|
|
relayTokenEncrypted: string | null;
|
|
updatedAt: string;
|
|
}
|
|
|
|
export interface SettingsUpdate {
|
|
siteName: string;
|
|
welcomeText: string;
|
|
welcomeTextEn?: string;
|
|
welcomeTextDe?: string;
|
|
welcomeTextRu?: string;
|
|
welcomeTextJa?: string;
|
|
accessMode: AccessMode;
|
|
tsHost: string;
|
|
tsPort: number;
|
|
tsTarget?: string | null;
|
|
tsPasswordEncrypted: string | null;
|
|
webRtcEnabled: boolean;
|
|
webRtcPublicHost?: string;
|
|
webRtcIpv6Enabled?: boolean;
|
|
webRtcStunServer?: string;
|
|
webRtcUdpStart?: number;
|
|
webRtcUdpEnd?: number;
|
|
voiceProfile?: VoiceProfileSetting | null;
|
|
voiceTurnUrls?: string | null;
|
|
voiceTurnSecretEncrypted?: string | null;
|
|
voiceTurnTtlSeconds?: number | null;
|
|
voiceOpusWs?: boolean | null;
|
|
voiceJitterMaxMs?: number | null;
|
|
voiceDownlinkFrameMs?: 20 | 40 | null;
|
|
voiceAssumeCloudflare?: boolean | null;
|
|
voiceAutoRelayRetry?: boolean | null;
|
|
relayConfigured: boolean;
|
|
relayEnabled: boolean;
|
|
relayName: string;
|
|
relayHost: string;
|
|
relayPort: number;
|
|
relayTokenEncrypted: string | null;
|
|
}
|
|
|
|
export interface PersistedRelayNode {
|
|
id: string;
|
|
name: string;
|
|
enabled: boolean;
|
|
host: string;
|
|
port: number;
|
|
voiceEndpoint: string;
|
|
tokenEncrypted: string | null;
|
|
createdAt: string;
|
|
updatedAt: string;
|
|
}
|
|
|
|
export interface ManagedInviteRecord {
|
|
id: string;
|
|
tokenHash: string;
|
|
targetHost: string;
|
|
targetPort: number;
|
|
targetText?: string | null;
|
|
serverPasswordEncrypted: string | null;
|
|
channel: string;
|
|
expiresAt: string;
|
|
maxUses: number;
|
|
useCount: number;
|
|
createdAt: string;
|
|
revokedAt: string | null;
|
|
}
|
|
|
|
export interface PersistedTsAdminSettings {
|
|
enabled: boolean;
|
|
transport: "web" | "ssh" | "tcp";
|
|
queryHost: string;
|
|
webQueryUrl: string;
|
|
apiKeyEncrypted: string | null;
|
|
serverId: number;
|
|
queryPort: number;
|
|
username: string;
|
|
passwordEncrypted: string | null;
|
|
hostKeyFingerprint: string;
|
|
updatedAt: string;
|
|
}
|
|
|
|
interface ManagedInviteRow extends Record<string, unknown> {
|
|
id: string;
|
|
token_hash: string;
|
|
target_host: string;
|
|
target_port: number;
|
|
target_text: string | null;
|
|
server_password_encrypted: string | null;
|
|
channel: string;
|
|
expires_at: string;
|
|
max_uses: number;
|
|
use_count: number;
|
|
created_at: string;
|
|
revoked_at: string | null;
|
|
}
|
|
|
|
interface SettingsRow extends Record<string, unknown> {
|
|
site_name: string;
|
|
welcome_text: string;
|
|
welcome_text_en: string;
|
|
welcome_text_de: string;
|
|
welcome_text_ru: string;
|
|
welcome_text_ja: string;
|
|
access_mode: string;
|
|
ts_host: string;
|
|
ts_port: number;
|
|
ts_target: string | null;
|
|
ts_password_encrypted: string | null;
|
|
detected_protocol: string | null;
|
|
last_test_at: string | null;
|
|
last_test_latency_ms: number | null;
|
|
last_test_error: string | null;
|
|
webrtc_enabled: number;
|
|
webrtc_public_host: string;
|
|
webrtc_ipv6_enabled: number;
|
|
webrtc_stun_server: string;
|
|
webrtc_udp_start: number;
|
|
webrtc_udp_end: number;
|
|
relay_configured: number;
|
|
relay_enabled: number;
|
|
relay_name: string;
|
|
relay_host: string;
|
|
relay_port: number;
|
|
relay_token_encrypted: string | null;
|
|
updated_at: string;
|
|
}
|
|
|
|
interface TsAdminSettingsRow extends Record<string, unknown> {
|
|
enabled: number;
|
|
transport: "web" | "ssh" | "tcp";
|
|
query_host: string;
|
|
web_query_url: string;
|
|
api_key_encrypted: string | null;
|
|
server_id: number;
|
|
query_port: number;
|
|
username: string;
|
|
password_encrypted: string | null;
|
|
host_key_fingerprint: string;
|
|
updated_at: string;
|
|
}
|
|
|
|
interface RelayNodeRow extends Record<string, unknown> {
|
|
id: string;
|
|
name: string;
|
|
enabled: number;
|
|
host: string;
|
|
port: number;
|
|
voice_endpoint: string;
|
|
token_encrypted: string | null;
|
|
created_at: string;
|
|
updated_at: string;
|
|
}
|
|
|
|
export class WebSpeakDatabase {
|
|
private readonly database: DatabaseSync;
|
|
|
|
constructor(private readonly path: string) {
|
|
mkdirSync(dirname(path), { recursive: true });
|
|
const existed = existsSync(path);
|
|
this.database = new DatabaseSync(path);
|
|
this.database.exec("PRAGMA foreign_keys = ON; PRAGMA journal_mode = WAL;");
|
|
this.migrate(existed);
|
|
}
|
|
|
|
saveWorkspaceInvite(tokenHash: string, encrypted: string, expiresAt: number, now = Date.now()): void {
|
|
this.database.prepare("DELETE FROM workspace_invites WHERE expires_at <= ?").run(now);
|
|
const count = this.database.prepare("SELECT COUNT(*) AS n FROM workspace_invites").get() as { n: number };
|
|
if (count.n >= 4096) throw new Error("INVITE_LIMIT_REACHED");
|
|
this.database.prepare("INSERT INTO workspace_invites(token_hash, payload_encrypted, expires_at) VALUES (?, ?, ?)").run(tokenHash, encrypted, expiresAt);
|
|
}
|
|
|
|
getWorkspaceInvite(tokenHash: string, now = Date.now()): string | null {
|
|
const row = this.database.prepare("SELECT payload_encrypted FROM workspace_invites WHERE token_hash = ? AND expires_at > ?").get(tokenHash, now) as { payload_encrypted: string } | undefined;
|
|
return row?.payload_encrypted ?? null;
|
|
}
|
|
|
|
close(): void {
|
|
this.database.close();
|
|
}
|
|
|
|
get schemaVersion(): number {
|
|
return Number((this.database.prepare("PRAGMA user_version").get() as { user_version: number }).user_version);
|
|
}
|
|
|
|
hasAdmin(): boolean {
|
|
return Boolean(this.database.prepare("SELECT 1 AS present FROM admin_credentials WHERE id = 1").get());
|
|
}
|
|
|
|
getAdminCredential(): AdminCredential | null {
|
|
const row = this.database.prepare("SELECT credential_json FROM admin_credentials WHERE id = 1").get() as { credential_json?: string } | undefined;
|
|
if (!row?.credential_json) return null;
|
|
const credential = JSON.parse(row.credential_json) as Partial<AdminCredential>;
|
|
return {
|
|
...credential,
|
|
version: 1,
|
|
username: typeof credential.username === "string" && credential.username ? credential.username : "admin",
|
|
mustChangePassword: credential.mustChangePassword === true,
|
|
} as AdminCredential;
|
|
}
|
|
|
|
initializeAdmin(credential: AdminCredential, settings: SettingsUpdate): void {
|
|
this.transaction(() => {
|
|
if (this.hasAdmin()) throw new Error("WebSpeak is already initialized");
|
|
const now = new Date().toISOString();
|
|
this.database.prepare(
|
|
"INSERT INTO admin_credentials (id, credential_json, created_at, updated_at) VALUES (1, ?, ?, ?)",
|
|
).run(JSON.stringify(credential), now, now);
|
|
this.writeSettings(settings, now);
|
|
this.insertAudit("ADMIN_INITIALIZED", { accessMode: settings.accessMode, target: `${settings.tsHost}:${settings.tsPort}` }, now);
|
|
});
|
|
}
|
|
|
|
updateAdminCredential(credential: AdminCredential): void {
|
|
const now = new Date().toISOString();
|
|
this.database.prepare(
|
|
"UPDATE admin_credentials SET credential_json = ?, updated_at = ? WHERE id = 1",
|
|
).run(JSON.stringify(credential), now);
|
|
}
|
|
|
|
getSettings(): PersistedSettings {
|
|
const row = this.database.prepare("SELECT * FROM settings WHERE id = 1").get() as SettingsRow;
|
|
const voice = this.readVoiceSettings();
|
|
return {
|
|
siteName: row.site_name,
|
|
welcomeText: row.welcome_text,
|
|
welcomeTextEn: row.welcome_text_en,
|
|
welcomeTextDe: row.welcome_text_de,
|
|
welcomeTextRu: row.welcome_text_ru,
|
|
welcomeTextJa: row.welcome_text_ja,
|
|
accessMode: row.access_mode === "open" ? "open" : "fixed",
|
|
tsHost: row.ts_host,
|
|
tsPort: row.ts_port,
|
|
tsTarget: row.ts_target,
|
|
tsPasswordEncrypted: row.ts_password_encrypted,
|
|
detectedProtocol: row.detected_protocol === "ts3" || row.detected_protocol === "ts6" ? row.detected_protocol : null,
|
|
lastTestAt: row.last_test_at,
|
|
lastTestLatencyMs: row.last_test_latency_ms,
|
|
lastTestError: row.last_test_error,
|
|
webRtcEnabled: row.webrtc_enabled === 1,
|
|
webRtcPublicHost: row.webrtc_public_host,
|
|
webRtcIpv6Enabled: row.webrtc_ipv6_enabled === 1,
|
|
webRtcStunServer: row.webrtc_stun_server,
|
|
webRtcUdpStart: row.webrtc_udp_start,
|
|
webRtcUdpEnd: row.webrtc_udp_end,
|
|
...voice,
|
|
relayConfigured: row.relay_configured === 1,
|
|
relayEnabled: row.relay_enabled === 1,
|
|
relayName: row.relay_name,
|
|
relayHost: row.relay_host,
|
|
relayPort: row.relay_port,
|
|
relayTokenEncrypted: row.relay_token_encrypted,
|
|
updatedAt: row.updated_at,
|
|
};
|
|
}
|
|
|
|
listRelayNodes(): PersistedRelayNode[] {
|
|
const rows = this.database.prepare(
|
|
"SELECT * FROM relay_nodes ORDER BY created_at ASC, id ASC",
|
|
).all() as RelayNodeRow[];
|
|
return rows.map((row) => ({
|
|
id: row.id,
|
|
name: row.name,
|
|
enabled: row.enabled === 1,
|
|
host: row.host,
|
|
port: row.port,
|
|
voiceEndpoint: row.voice_endpoint,
|
|
tokenEncrypted: row.token_encrypted,
|
|
createdAt: row.created_at,
|
|
updatedAt: row.updated_at,
|
|
}));
|
|
}
|
|
|
|
replaceRelayNodes(nodes: Array<Omit<PersistedRelayNode, "createdAt" | "updatedAt"> & { createdAt?: string; updatedAt?: string }>): void {
|
|
const now = new Date().toISOString();
|
|
this.transaction(() => {
|
|
this.database.exec("DELETE FROM relay_nodes");
|
|
const insert = this.database.prepare(
|
|
`INSERT INTO relay_nodes (id, name, enabled, host, port, voice_endpoint, token_encrypted, created_at, updated_at)
|
|
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)`,
|
|
);
|
|
for (const node of nodes) {
|
|
insert.run(
|
|
node.id,
|
|
node.name,
|
|
node.enabled ? 1 : 0,
|
|
node.host,
|
|
node.port,
|
|
node.voiceEndpoint,
|
|
node.tokenEncrypted,
|
|
node.createdAt ?? now,
|
|
node.updatedAt ?? now,
|
|
);
|
|
}
|
|
});
|
|
}
|
|
|
|
updateSettings(settings: SettingsUpdate, auditEvent = "SETTINGS_CHANGED"): void {
|
|
const now = new Date().toISOString();
|
|
this.transaction(() => {
|
|
this.writeSettings(settings, now);
|
|
this.insertAudit(auditEvent, { accessMode: settings.accessMode, target: `${settings.tsHost}:${settings.tsPort}` }, now);
|
|
});
|
|
}
|
|
|
|
recordConnectionTest(result: {
|
|
protocol: TeamSpeakProtocol | null;
|
|
latencyMs: number | null;
|
|
error: string | null;
|
|
}): void {
|
|
this.database.prepare(
|
|
`UPDATE settings
|
|
SET detected_protocol = ?, last_test_at = ?, last_test_latency_ms = ?, last_test_error = ?
|
|
WHERE id = 1`,
|
|
).run(result.protocol, new Date().toISOString(), result.latencyMs, result.error);
|
|
}
|
|
|
|
clearConnectionTest(): void {
|
|
this.database.exec(
|
|
"UPDATE settings SET detected_protocol = NULL, last_test_at = NULL, last_test_latency_ms = NULL, last_test_error = NULL WHERE id = 1",
|
|
);
|
|
}
|
|
|
|
createManagedInvite(record: Omit<ManagedInviteRecord, "createdAt" | "revokedAt" | "useCount">): ManagedInviteRecord {
|
|
const now = new Date().toISOString();
|
|
this.transaction(() => {
|
|
this.database.prepare(
|
|
`INSERT INTO managed_invites (
|
|
id, token_hash, target_host, target_port, target_text, server_password_encrypted,
|
|
channel, expires_at, max_uses, use_count, created_at, revoked_at
|
|
) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, 0, ?, NULL)`,
|
|
).run(
|
|
record.id,
|
|
record.tokenHash,
|
|
record.targetHost,
|
|
record.targetPort,
|
|
record.targetText ?? null,
|
|
record.serverPasswordEncrypted,
|
|
record.channel,
|
|
record.expiresAt,
|
|
record.maxUses,
|
|
now,
|
|
);
|
|
});
|
|
return { ...record, useCount: 0, createdAt: now, revokedAt: null };
|
|
}
|
|
|
|
listManagedInvites(): ManagedInviteRecord[] {
|
|
const rows = this.database.prepare(
|
|
"SELECT * FROM managed_invites ORDER BY created_at DESC",
|
|
).all() as ManagedInviteRow[];
|
|
return rows.map(mapManagedInviteRow);
|
|
}
|
|
|
|
getTsAdminSettings(): PersistedTsAdminSettings {
|
|
const row = this.database.prepare("SELECT * FROM ts_admin_settings WHERE id = 1").get() as TsAdminSettingsRow;
|
|
return {
|
|
enabled: row.enabled === 1,
|
|
transport: row.transport,
|
|
queryHost: row.query_host,
|
|
webQueryUrl: row.web_query_url,
|
|
apiKeyEncrypted: row.api_key_encrypted,
|
|
serverId: row.server_id,
|
|
queryPort: row.query_port,
|
|
username: row.username,
|
|
passwordEncrypted: row.password_encrypted,
|
|
hostKeyFingerprint: row.host_key_fingerprint,
|
|
updatedAt: row.updated_at,
|
|
};
|
|
}
|
|
|
|
updateTsAdminSettings(settings: Omit<PersistedTsAdminSettings, "updatedAt">): void {
|
|
const now = new Date().toISOString();
|
|
this.transaction(() => {
|
|
this.database.prepare(
|
|
`UPDATE ts_admin_settings
|
|
SET enabled = ?, transport = ?, query_host = ?, web_query_url = ?, api_key_encrypted = ?, server_id = ?,
|
|
query_port = ?, username = ?, password_encrypted = ?, host_key_fingerprint = ?, updated_at = ?
|
|
WHERE id = 1`,
|
|
).run(settings.enabled ? 1 : 0, settings.transport, settings.queryHost, settings.webQueryUrl, settings.apiKeyEncrypted, settings.serverId,
|
|
settings.queryPort, settings.username, settings.passwordEncrypted, settings.hostKeyFingerprint, now);
|
|
this.insertAudit("TS_ADMIN_SETTINGS_UPDATED", { enabled: settings.enabled, transport: settings.transport }, now);
|
|
});
|
|
}
|
|
|
|
getManagedInvite(tokenHash: string, now = Date.now()): ManagedInviteRecord | null {
|
|
const nowIso = new Date(now).toISOString();
|
|
const row = this.database.prepare(
|
|
`SELECT * FROM managed_invites
|
|
WHERE token_hash = ?
|
|
AND revoked_at IS NULL
|
|
AND expires_at > ?
|
|
AND (max_uses = 0 OR use_count < max_uses)`,
|
|
).get(tokenHash, nowIso) as ManagedInviteRow | undefined;
|
|
return row ? mapManagedInviteRow(row) : null;
|
|
}
|
|
|
|
revokeManagedInvite(id: string): boolean {
|
|
const result = this.database.prepare(
|
|
"UPDATE managed_invites SET revoked_at = ? WHERE id = ? AND revoked_at IS NULL",
|
|
).run(new Date().toISOString(), id) as { changes?: number | bigint };
|
|
return Number(result.changes ?? 0) === 1;
|
|
}
|
|
|
|
consumeManagedInvite(tokenHash: string, now = Date.now()): ManagedInviteRecord | null {
|
|
const nowIso = new Date(now).toISOString();
|
|
this.database.exec("BEGIN IMMEDIATE");
|
|
try {
|
|
const row = this.database.prepare(
|
|
`SELECT * FROM managed_invites
|
|
WHERE token_hash = ?
|
|
AND revoked_at IS NULL
|
|
AND expires_at > ?
|
|
AND (max_uses = 0 OR use_count < max_uses)`,
|
|
).get(tokenHash, nowIso) as ManagedInviteRow | undefined;
|
|
if (!row) {
|
|
this.database.exec("COMMIT");
|
|
return null;
|
|
}
|
|
const result = this.database.prepare(
|
|
`UPDATE managed_invites
|
|
SET use_count = use_count + 1
|
|
WHERE id = ? AND revoked_at IS NULL AND expires_at > ?
|
|
AND (max_uses = 0 OR use_count < max_uses)`,
|
|
).run(row.id, nowIso) as { changes?: number | bigint };
|
|
if (Number(result.changes ?? 0) !== 1) {
|
|
this.database.exec("COMMIT");
|
|
return null;
|
|
}
|
|
this.database.exec("COMMIT");
|
|
return { ...mapManagedInviteRow(row), useCount: row.use_count + 1 };
|
|
} catch (error) {
|
|
this.database.exec("ROLLBACK");
|
|
throw error;
|
|
}
|
|
}
|
|
|
|
exportBackup(): Buffer {
|
|
const exportPath = `${this.path}.export-${randomBytes(8).toString("hex")}.db`;
|
|
try {
|
|
const escapedPath = exportPath.replaceAll("'", "''");
|
|
this.database.exec(`VACUUM INTO '${escapedPath}'`);
|
|
return readFileSync(exportPath);
|
|
} finally {
|
|
try { unlinkSync(exportPath); } catch { /* best effort cleanup */ }
|
|
}
|
|
}
|
|
|
|
getMeta(key: string): string | null {
|
|
const row = this.database.prepare("SELECT value FROM metadata WHERE key = ?").get(key) as { value?: string } | undefined;
|
|
return row?.value ?? null;
|
|
}
|
|
|
|
setMeta(key: string, value: string): void {
|
|
this.database.prepare(
|
|
"INSERT INTO metadata (key, value) VALUES (?, ?) ON CONFLICT(key) DO UPDATE SET value = excluded.value",
|
|
).run(key, value);
|
|
}
|
|
|
|
nextVisitorNumber(): number {
|
|
let nextNumber = 1;
|
|
this.transaction(() => {
|
|
const currentValue = this.getMeta("visitor_count");
|
|
const current = currentValue ? Number.parseInt(currentValue, 10) : 0;
|
|
nextNumber = Number.isSafeInteger(current) && current >= 0 && current < Number.MAX_SAFE_INTEGER
|
|
? current + 1
|
|
: 1;
|
|
this.setMeta("visitor_count", String(nextNumber));
|
|
});
|
|
return nextNumber;
|
|
}
|
|
|
|
getVisitorCount(): number {
|
|
const value = this.getMeta("visitor_count");
|
|
const count = value ? Number.parseInt(value, 10) : 0;
|
|
return Number.isSafeInteger(count) && count >= 0 ? count : 0;
|
|
}
|
|
|
|
addAudit(event: string, details: Record<string, unknown> = {}): void {
|
|
this.insertAudit(event, details, new Date().toISOString());
|
|
}
|
|
|
|
recentAudit(limit = 8): Array<{ event: string; createdAt: string }> {
|
|
const normalizedLimit = Math.max(1, Math.min(50, Math.floor(limit)));
|
|
const rows = this.database.prepare(
|
|
"SELECT event, created_at FROM audit_events ORDER BY id DESC LIMIT ?",
|
|
).all(normalizedLimit) as Array<{ event: string; created_at: string }>;
|
|
return rows.map((row) => ({ event: row.event, createdAt: row.created_at }));
|
|
}
|
|
|
|
private migrate(existed: boolean): void {
|
|
let version = this.schemaVersion;
|
|
if (version > DATABASE_SCHEMA_VERSION) {
|
|
throw new Error(`Database schema ${version} is newer than this WebSpeak build`);
|
|
}
|
|
if (existed && version > 0) {
|
|
copyFileSync(this.path, `${this.path}.schema-${version}.bak`);
|
|
}
|
|
if (version === 0) {
|
|
this.transaction(() => {
|
|
this.database.exec(`
|
|
CREATE TABLE metadata (
|
|
key TEXT PRIMARY KEY,
|
|
value TEXT NOT NULL
|
|
);
|
|
CREATE TABLE admin_credentials (
|
|
id INTEGER PRIMARY KEY CHECK (id = 1),
|
|
credential_json TEXT NOT NULL,
|
|
created_at TEXT NOT NULL,
|
|
updated_at TEXT NOT NULL
|
|
);
|
|
CREATE TABLE settings (
|
|
id INTEGER PRIMARY KEY CHECK (id = 1),
|
|
site_name TEXT NOT NULL,
|
|
welcome_text TEXT NOT NULL,
|
|
access_mode TEXT NOT NULL CHECK (access_mode IN ('fixed', 'open')),
|
|
ts_host TEXT NOT NULL,
|
|
ts_port INTEGER NOT NULL CHECK (ts_port BETWEEN 1 AND 65535),
|
|
ts_password_encrypted TEXT,
|
|
detected_protocol TEXT CHECK (detected_protocol IS NULL OR detected_protocol IN ('ts3', 'ts6')),
|
|
last_test_at TEXT,
|
|
last_test_latency_ms INTEGER,
|
|
last_test_error TEXT,
|
|
updated_at TEXT NOT NULL
|
|
);
|
|
CREATE TABLE audit_events (
|
|
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
|
event TEXT NOT NULL,
|
|
details_json TEXT NOT NULL,
|
|
created_at TEXT NOT NULL
|
|
);
|
|
`);
|
|
const now = new Date().toISOString();
|
|
this.database.prepare(
|
|
`INSERT INTO settings (
|
|
id, site_name, welcome_text, access_mode, ts_host, ts_port,
|
|
ts_password_encrypted, detected_protocol, last_test_at,
|
|
last_test_latency_ms, last_test_error, updated_at
|
|
) VALUES (1, 'WebSpeak', '', 'fixed', '127.0.0.1', 9987, NULL, NULL, NULL, NULL, NULL, ?)`,
|
|
).run(now);
|
|
this.database.exec("PRAGMA user_version = 1");
|
|
});
|
|
version = 1;
|
|
}
|
|
if (version === 1) {
|
|
this.transaction(() => {
|
|
this.database.exec(`
|
|
CREATE TABLE managed_invites (
|
|
id TEXT PRIMARY KEY,
|
|
token_hash TEXT NOT NULL UNIQUE,
|
|
target_host TEXT NOT NULL,
|
|
target_port INTEGER NOT NULL CHECK (target_port BETWEEN 1 AND 65535),
|
|
server_password_encrypted TEXT,
|
|
channel TEXT NOT NULL DEFAULT '',
|
|
expires_at TEXT NOT NULL,
|
|
max_uses INTEGER NOT NULL CHECK (max_uses >= 0),
|
|
use_count INTEGER NOT NULL DEFAULT 0 CHECK (use_count >= 0),
|
|
created_at TEXT NOT NULL,
|
|
revoked_at TEXT
|
|
);
|
|
CREATE INDEX managed_invites_token_idx ON managed_invites(token_hash);
|
|
CREATE INDEX managed_invites_expiry_idx ON managed_invites(expires_at);
|
|
`);
|
|
this.database.exec("PRAGMA user_version = 2");
|
|
});
|
|
version = 2;
|
|
}
|
|
if (version === 2) {
|
|
this.transaction(() => {
|
|
this.database.exec(`
|
|
-- WebRTC media ports are stored with the administrator settings so the
|
|
-- same range is used by the gateway and shown in the admin console.
|
|
ALTER TABLE settings ADD COLUMN webrtc_enabled INTEGER NOT NULL DEFAULT 0 CHECK (webrtc_enabled IN (0, 1));
|
|
ALTER TABLE settings ADD COLUMN webrtc_public_host TEXT NOT NULL DEFAULT '';
|
|
ALTER TABLE settings ADD COLUMN webrtc_udp_start INTEGER NOT NULL DEFAULT 40000 CHECK (webrtc_udp_start BETWEEN 1 AND 65535);
|
|
ALTER TABLE settings ADD COLUMN webrtc_udp_end INTEGER NOT NULL DEFAULT 40099 CHECK (webrtc_udp_end BETWEEN 1 AND 65535);
|
|
`);
|
|
this.database.exec("PRAGMA user_version = 3");
|
|
});
|
|
version = 3;
|
|
}
|
|
if (version === 3) {
|
|
this.transaction(() => {
|
|
this.database.exec(`
|
|
ALTER TABLE settings ADD COLUMN welcome_text_en TEXT NOT NULL DEFAULT '';
|
|
`);
|
|
this.database.exec("PRAGMA user_version = 4");
|
|
});
|
|
version = 4;
|
|
}
|
|
if (version === 4) {
|
|
this.transaction(() => {
|
|
this.database.exec(`
|
|
ALTER TABLE settings ADD COLUMN relay_configured INTEGER NOT NULL DEFAULT 0 CHECK (relay_configured IN (0, 1));
|
|
ALTER TABLE settings ADD COLUMN relay_enabled INTEGER NOT NULL DEFAULT 0 CHECK (relay_enabled IN (0, 1));
|
|
ALTER TABLE settings ADD COLUMN relay_name TEXT NOT NULL DEFAULT '';
|
|
ALTER TABLE settings ADD COLUMN relay_host TEXT NOT NULL DEFAULT '';
|
|
ALTER TABLE settings ADD COLUMN relay_port INTEGER NOT NULL DEFAULT 39087 CHECK (relay_port BETWEEN 1 AND 65535);
|
|
ALTER TABLE settings ADD COLUMN relay_token_encrypted TEXT;
|
|
`);
|
|
this.database.exec("PRAGMA user_version = 5");
|
|
});
|
|
version = 5;
|
|
}
|
|
if (version === 5) {
|
|
this.transaction(() => {
|
|
this.database.exec(`
|
|
CREATE TABLE relay_nodes (
|
|
id TEXT PRIMARY KEY,
|
|
name TEXT NOT NULL,
|
|
enabled INTEGER NOT NULL DEFAULT 0 CHECK (enabled IN (0, 1)),
|
|
host TEXT NOT NULL,
|
|
port INTEGER NOT NULL CHECK (port BETWEEN 1 AND 65535),
|
|
token_encrypted TEXT,
|
|
created_at TEXT NOT NULL,
|
|
updated_at TEXT NOT NULL
|
|
);
|
|
CREATE INDEX relay_nodes_enabled_idx ON relay_nodes(enabled);
|
|
`);
|
|
const legacy = this.database.prepare(
|
|
`SELECT relay_configured, relay_enabled, relay_name, relay_host, relay_port, relay_token_encrypted
|
|
FROM settings WHERE id = 1`,
|
|
).get() as {
|
|
relay_configured?: number;
|
|
relay_enabled?: number;
|
|
relay_name?: string;
|
|
relay_host?: string;
|
|
relay_port?: number;
|
|
relay_token_encrypted?: string | null;
|
|
} | undefined;
|
|
if (legacy?.relay_configured === 1 && legacy.relay_host && legacy.relay_token_encrypted) {
|
|
const now = new Date().toISOString();
|
|
this.database.prepare(
|
|
`INSERT INTO relay_nodes (id, name, enabled, host, port, token_encrypted, created_at, updated_at)
|
|
VALUES ('relay-default', ?, ?, ?, ?, ?, ?, ?)`,
|
|
).run(
|
|
legacy.relay_name || "中继加速",
|
|
legacy.relay_enabled === 1 ? 1 : 0,
|
|
legacy.relay_host,
|
|
legacy.relay_port || 39087,
|
|
legacy.relay_token_encrypted,
|
|
now,
|
|
now,
|
|
);
|
|
}
|
|
this.database.exec("PRAGMA user_version = 6");
|
|
});
|
|
version = 6;
|
|
}
|
|
if (version === 6) {
|
|
this.transaction(() => {
|
|
this.database.exec(`
|
|
ALTER TABLE settings ADD COLUMN welcome_text_de TEXT NOT NULL DEFAULT '';
|
|
ALTER TABLE settings ADD COLUMN welcome_text_ru TEXT NOT NULL DEFAULT '';
|
|
ALTER TABLE settings ADD COLUMN welcome_text_ja TEXT NOT NULL DEFAULT '';
|
|
`);
|
|
this.database.exec("PRAGMA user_version = 7");
|
|
});
|
|
version = 7;
|
|
}
|
|
if (version === 7) {
|
|
this.transaction(() => {
|
|
this.database.exec(`
|
|
ALTER TABLE settings ADD COLUMN webrtc_ipv6_enabled INTEGER NOT NULL DEFAULT 0 CHECK (webrtc_ipv6_enabled IN (0, 1));
|
|
ALTER TABLE settings ADD COLUMN webrtc_stun_server TEXT NOT NULL DEFAULT '';
|
|
`);
|
|
this.database.exec("PRAGMA user_version = 8");
|
|
});
|
|
version = 8;
|
|
}
|
|
if (version === 8) {
|
|
this.transaction(() => {
|
|
this.database.exec(`
|
|
ALTER TABLE settings ADD COLUMN ts_target TEXT;
|
|
ALTER TABLE managed_invites ADD COLUMN target_text TEXT;
|
|
`);
|
|
this.database.exec("PRAGMA user_version = 9");
|
|
});
|
|
version = 9;
|
|
}
|
|
if (version === 9) {
|
|
this.transaction(() => {
|
|
this.database.exec(`
|
|
CREATE TABLE ts_admin_settings (
|
|
id INTEGER PRIMARY KEY CHECK (id = 1),
|
|
enabled INTEGER NOT NULL DEFAULT 0 CHECK (enabled IN (0, 1)),
|
|
query_port INTEGER NOT NULL DEFAULT 10022 CHECK (query_port BETWEEN 1 AND 65535),
|
|
username TEXT NOT NULL DEFAULT '',
|
|
password_encrypted TEXT,
|
|
host_key_fingerprint TEXT NOT NULL DEFAULT '',
|
|
updated_at TEXT NOT NULL
|
|
);
|
|
`);
|
|
this.database.prepare(
|
|
`INSERT INTO ts_admin_settings (id, enabled, query_port, username, password_encrypted, host_key_fingerprint, updated_at)
|
|
VALUES (1, 0, 10022, '', NULL, '', ?)`,
|
|
).run(new Date().toISOString());
|
|
this.database.exec("PRAGMA user_version = 10");
|
|
});
|
|
version = 10;
|
|
}
|
|
if (version === 10) {
|
|
this.transaction(() => {
|
|
this.database.exec("ALTER TABLE relay_nodes ADD COLUMN voice_endpoint TEXT NOT NULL DEFAULT ''");
|
|
this.database.exec("PRAGMA user_version = 11");
|
|
});
|
|
version = 11;
|
|
}
|
|
if (version === 11) {
|
|
this.transaction(() => {
|
|
this.database.exec(`
|
|
ALTER TABLE ts_admin_settings ADD COLUMN transport TEXT NOT NULL DEFAULT 'web' CHECK (transport IN ('web', 'ssh', 'tcp'));
|
|
ALTER TABLE ts_admin_settings ADD COLUMN query_host TEXT NOT NULL DEFAULT '';
|
|
ALTER TABLE ts_admin_settings ADD COLUMN web_query_url TEXT NOT NULL DEFAULT '';
|
|
ALTER TABLE ts_admin_settings ADD COLUMN api_key_encrypted TEXT;
|
|
ALTER TABLE ts_admin_settings ADD COLUMN server_id INTEGER NOT NULL DEFAULT 0 CHECK (server_id BETWEEN 0 AND 4294967295);
|
|
UPDATE ts_admin_settings SET transport = 'ssh' WHERE enabled = 1 OR password_encrypted IS NOT NULL OR host_key_fingerprint <> '';
|
|
PRAGMA user_version = 12;
|
|
`);
|
|
});
|
|
version = 12;
|
|
}
|
|
if (version === 12) {
|
|
this.transaction(() => {
|
|
this.database.exec(`CREATE TABLE workspace_invites (
|
|
token_hash TEXT PRIMARY KEY,
|
|
payload_encrypted TEXT NOT NULL,
|
|
expires_at INTEGER NOT NULL
|
|
); CREATE INDEX workspace_invites_expiry ON workspace_invites(expires_at);
|
|
PRAGMA user_version = 13;`);
|
|
});
|
|
}
|
|
}
|
|
|
|
/** Optional settings must survive a code-only rollback to the 0.3.3 schema. */
|
|
private readVoiceSettings(): Pick<PersistedSettings, "voiceProfile" | "voiceTurnUrls" | "voiceTurnSecretEncrypted" | "voiceTurnTtlSeconds" | "voiceOpusWs" | "voiceJitterMaxMs" | "voiceDownlinkFrameMs" | "voiceAssumeCloudflare" | "voiceAutoRelayRetry"> {
|
|
let value: Record<string, unknown> = {};
|
|
try {
|
|
const parsed: unknown = JSON.parse(this.getMeta(VOICE_SETTINGS_META_KEY) ?? "{}");
|
|
if (parsed && typeof parsed === "object" && !Array.isArray(parsed)) value = parsed as Record<string, unknown>;
|
|
} catch { /* A malformed optional value inherits the deployment defaults. */ }
|
|
return {
|
|
voiceProfile: value.voiceProfile === "legacy" || value.voiceProfile === "adaptive" || value.voiceProfile === "auto"
|
|
? value.voiceProfile : null,
|
|
voiceTurnUrls: typeof value.voiceTurnUrls === "string" ? value.voiceTurnUrls : null,
|
|
voiceTurnSecretEncrypted: typeof value.voiceTurnSecretEncrypted === "string" ? value.voiceTurnSecretEncrypted : null,
|
|
voiceTurnTtlSeconds: Number.isInteger(value.voiceTurnTtlSeconds) && Number(value.voiceTurnTtlSeconds) >= 300 && Number(value.voiceTurnTtlSeconds) <= 86400
|
|
? Number(value.voiceTurnTtlSeconds) : null,
|
|
voiceOpusWs: typeof value.voiceOpusWs === "boolean" ? value.voiceOpusWs : null,
|
|
voiceJitterMaxMs: Number.isInteger(value.voiceJitterMaxMs) && Number(value.voiceJitterMaxMs) >= 80 && Number(value.voiceJitterMaxMs) <= 500
|
|
? Number(value.voiceJitterMaxMs) : null,
|
|
voiceDownlinkFrameMs: value.voiceDownlinkFrameMs === 20 || value.voiceDownlinkFrameMs === 40
|
|
? value.voiceDownlinkFrameMs : null,
|
|
voiceAssumeCloudflare: typeof value.voiceAssumeCloudflare === "boolean" ? value.voiceAssumeCloudflare : null,
|
|
voiceAutoRelayRetry: typeof value.voiceAutoRelayRetry === "boolean" ? value.voiceAutoRelayRetry : null,
|
|
};
|
|
}
|
|
|
|
private writeSettings(settings: SettingsUpdate, now: string): void {
|
|
this.database.prepare(
|
|
`UPDATE settings SET
|
|
site_name = ?, welcome_text = ?, welcome_text_en = ?, welcome_text_de = ?, welcome_text_ru = ?, welcome_text_ja = ?, access_mode = ?, ts_host = ?, ts_port = ?, ts_target = ?,
|
|
ts_password_encrypted = ?, webrtc_enabled = ?, webrtc_public_host = ?, webrtc_ipv6_enabled = ?, webrtc_stun_server = ?, webrtc_udp_start = ?,
|
|
webrtc_udp_end = ?, relay_configured = ?, relay_enabled = ?, relay_name = ?,
|
|
relay_host = ?, relay_port = ?, relay_token_encrypted = ?, updated_at = ?
|
|
WHERE id = 1`,
|
|
).run(
|
|
settings.siteName,
|
|
settings.welcomeText,
|
|
settings.welcomeTextEn ?? "",
|
|
settings.welcomeTextDe ?? "",
|
|
settings.welcomeTextRu ?? "",
|
|
settings.welcomeTextJa ?? "",
|
|
settings.accessMode,
|
|
settings.tsHost,
|
|
settings.tsPort,
|
|
settings.tsTarget ?? null,
|
|
settings.tsPasswordEncrypted,
|
|
settings.webRtcEnabled ? 1 : 0,
|
|
settings.webRtcPublicHost ?? "",
|
|
settings.webRtcIpv6Enabled ? 1 : 0,
|
|
settings.webRtcStunServer ?? "",
|
|
settings.webRtcUdpStart ?? DEFAULT_WEBRTC_UDP_PORT_RANGE[0],
|
|
settings.webRtcUdpEnd ?? DEFAULT_WEBRTC_UDP_PORT_RANGE[1],
|
|
settings.relayConfigured ? 1 : 0,
|
|
settings.relayEnabled ? 1 : 0,
|
|
settings.relayName,
|
|
settings.relayHost,
|
|
settings.relayPort,
|
|
settings.relayTokenEncrypted,
|
|
now,
|
|
);
|
|
// writeSettings is called within the caller's settings transaction. Older
|
|
// binaries ignore this key and keep it intact when updating other fields.
|
|
this.setMeta(VOICE_SETTINGS_META_KEY, JSON.stringify({
|
|
...this.readVoiceSettings(),
|
|
...Object.fromEntries(Object.entries(settings).filter(([key, value]) => key.startsWith("voice") && value !== undefined)),
|
|
}));
|
|
}
|
|
|
|
private insertAudit(event: string, details: Record<string, unknown>, now: string): void {
|
|
this.database.prepare(
|
|
"INSERT INTO audit_events (event, details_json, created_at) VALUES (?, ?, ?)",
|
|
).run(event, JSON.stringify(details), now);
|
|
}
|
|
|
|
private transaction(action: () => void): void {
|
|
this.database.exec("BEGIN IMMEDIATE");
|
|
try {
|
|
action();
|
|
this.database.exec("COMMIT");
|
|
} catch (error) {
|
|
this.database.exec("ROLLBACK");
|
|
throw error;
|
|
}
|
|
}
|
|
}
|
|
|
|
function mapManagedInviteRow(row: ManagedInviteRow): ManagedInviteRecord {
|
|
return {
|
|
id: row.id,
|
|
tokenHash: row.token_hash,
|
|
targetHost: row.target_host,
|
|
targetPort: row.target_port,
|
|
targetText: row.target_text,
|
|
serverPasswordEncrypted: row.server_password_encrypted,
|
|
channel: row.channel,
|
|
expiresAt: row.expires_at,
|
|
maxUses: row.max_uses,
|
|
useCount: row.use_count,
|
|
createdAt: row.created_at,
|
|
revokedAt: row.revoked_at,
|
|
};
|
|
}
|